Full Code of shernshiou/node-uber for AI

master d00e150a4591 cached
78 files
241.5 KB
60.8k tokens
12 symbols
1 requests
Download .txt
Showing preview only (261K chars total). Download the full file or copy to clipboard to get everything.
Repository: shernshiou/node-uber
Branch: master
Commit: d00e150a4591
Files: 78
Total size: 241.5 KB

Directory structure:
gitextract_dcrhj7s8/

├── .codeclimate.yml
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .travis.yml
├── LICENSE
├── README-Nodeback.md
├── README.md
├── examples/
│   ├── auth-get-products-async.js
│   └── auth-get-products.js
├── gulpfile.js
├── index.js
├── lib/
│   ├── Uber.js
│   └── resources/
│       ├── drivers/
│       │   ├── PartnerPayments.js
│       │   ├── PartnerProfile.js
│       │   └── PartnerTrips.js
│       └── riders/
│           ├── Estimates.js
│           ├── Payment.js
│           ├── Places.js
│           ├── Products.js
│           ├── Requests.js
│           └── User.js
├── package.json
└── test/
    ├── allTests.js
    ├── auth/
    │   ├── oauth.js
    │   └── oauthAsync.js
    ├── common.js
    ├── drivers/
    │   ├── payments.js
    │   ├── paymentsAsync.js
    │   ├── profile.js
    │   ├── profileAsync.js
    │   ├── trips.js
    │   └── tripsAsync.js
    ├── general.js
    ├── replies/
    │   ├── auth/
    │   │   ├── token.json
    │   │   ├── tokenExpired.json
    │   │   ├── tokenNoPlaces.json
    │   │   ├── tokenNoProfile.json
    │   │   ├── tokenNoRefresh.json
    │   │   ├── tokenNoRequest.json
    │   │   └── tokenRefreshed.json
    │   ├── drivers/
    │   │   ├── partnerPayments.json
    │   │   ├── partnerProfile.json
    │   │   └── partnerTrips.json
    │   ├── geocoder/
    │   │   ├── locationA.json
    │   │   ├── locationB.json
    │   │   ├── locationC.json
    │   │   └── locationEmpty.json
    │   └── riders/
    │       ├── history.json
    │       ├── paymentMethod.json
    │       ├── placeHome.json
    │       ├── placeWork.json
    │       ├── price.json
    │       ├── product.json
    │       ├── productDetail.json
    │       ├── profile.json
    │       ├── profilePromoError.json
    │       ├── profilePromoSuccess.json
    │       ├── requestAccept.json
    │       ├── requestCreate.json
    │       ├── requestEstimate.json
    │       ├── requestFareExpired.json
    │       ├── requestMap.json
    │       ├── requestReceipt.json
    │       ├── requestSurge.json
    │       └── time.json
    └── riders/
        ├── estimates.js
        ├── estimatesAsync.js
        ├── payment-methods.js
        ├── payment-methodsAsync.js
        ├── places.js
        ├── placesAsync.js
        ├── products.js
        ├── productsAsync.js
        ├── requests.js
        ├── requestsAsync.js
        ├── user.js
        └── userAsync.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .codeclimate.yml
================================================
---
engines:
  duplication:
    enabled: true
    config:
      languages:
      - ruby
      - javascript
      - python
      - php
  eslint:
    enabled: true
  fixme:
    enabled: true
ratings:
  paths:
  - "**.inc"
  - "**.js"
  - "**.jsx"
  - "**.module"
  - "**.php"
  - "**.py"
  - "**.rb"
exclude_paths:
- test/


================================================
FILE: .eslintignore
================================================
**/*{.,-}min.js


================================================
FILE: .eslintrc
================================================
env:
  amd: true
  browser: true
  es6: true
  jquery: true
  node: true

# http://eslint.org/docs/rules/
rules:
  # Possible Errors
  comma-dangle: [2, never]
  no-cond-assign: 2
  no-console: 0
  no-constant-condition: 2
  no-control-regex: 2
  no-debugger: 2
  no-dupe-args: 2
  no-dupe-keys: 2
  no-duplicate-case: 2
  no-empty: 2
  no-empty-character-class: 2
  no-ex-assign: 2
  no-extra-boolean-cast: 2
  no-extra-parens: 0
  no-extra-semi: 2
  no-func-assign: 2
  no-inner-declarations: [2, functions]
  no-invalid-regexp: 2
  no-irregular-whitespace: 2
  no-negated-in-lhs: 2
  no-obj-calls: 2
  no-regex-spaces: 2
  no-sparse-arrays: 2
  no-unexpected-multiline: 2
  no-unreachable: 2
  use-isnan: 2
  valid-jsdoc: 0
  valid-typeof: 2

  # Best Practices
  accessor-pairs: 2
  block-scoped-var: 0
  complexity: [2, 7]
  consistent-return: 0
  curly: 0
  default-case: 0
  dot-location: 0
  dot-notation: 0
  eqeqeq: 2
  guard-for-in: 2
  no-alert: 2
  no-caller: 2
  no-case-declarations: 2
  no-div-regex: 2
  no-else-return: 0
  no-empty-pattern: 2
  no-eq-null: 2
  no-eval: 2
  no-extend-native: 2
  no-extra-bind: 2
  no-fallthrough: 2
  no-floating-decimal: 0
  no-implicit-coercion: 0
  no-implied-eval: 2
  no-invalid-this: 0
  no-iterator: 2
  no-labels: 0
  no-lone-blocks: 2
  no-loop-func: 2
  no-magic-number: 0
  no-multi-spaces: 0
  no-multi-str: 0
  no-native-reassign: 2
  no-new-func: 2
  no-new-wrappers: 2
  no-new: 2
  no-octal-escape: 2
  no-octal: 2
  no-proto: 2
  no-redeclare: 2
  no-return-assign: 2
  no-script-url: 2
  no-self-compare: 2
  no-sequences: 0
  no-throw-literal: 0
  no-unused-expressions: 2
  no-useless-call: 2
  no-useless-concat: 2
  no-void: 2
  no-warning-comments: 0
  no-with: 2
  radix: 2
  vars-on-top: 0
  wrap-iife: 2
  yoda: 0

  # Strict
  strict: 0

  # Variables
  init-declarations: 0
  no-catch-shadow: 2
  no-delete-var: 2
  no-label-var: 2
  no-shadow-restricted-names: 2
  no-shadow: 0
  no-undef-init: 2
  no-undef: 0
  no-undefined: 0
  no-unused-vars: 0
  no-use-before-define: 0

  # Node.js and CommonJS
  callback-return: 2
  handle-callback-err: 2
  no-mixed-requires: 0
  no-new-require: 0
  no-path-concat: 2
  no-process-exit: 2
  no-restricted-modules: 0
  no-sync: 0

  # Stylistic Issues
  array-bracket-spacing: 0
  block-spacing: 0
  brace-style: 0
  camelcase: 0
  comma-spacing: 0
  comma-style: 0
  computed-property-spacing: 0
  consistent-this: 0
  eol-last: 0
  func-names: 0
  func-style: 0
  id-length: 0
  id-match: 0
  indent: 0
  jsx-quotes: 0
  key-spacing: 0
  linebreak-style: 0
  lines-around-comment: 0
  max-depth: 0
  max-len: 0
  max-nested-callbacks: 0
  max-params: 0
  max-statements: [2, 30]
  new-cap: 0
  new-parens: 0
  newline-after-var: 0
  no-array-constructor: 0
  no-bitwise: 0
  no-continue: 0
  no-inline-comments: 0
  no-lonely-if: 0
  no-mixed-spaces-and-tabs: 0
  no-multiple-empty-lines: 0
  no-negated-condition: 0
  no-nested-ternary: 0
  no-new-object: 0
  no-plusplus: 0
  no-restricted-syntax: 0
  no-spaced-func: 0
  no-ternary: 0
  no-trailing-spaces: 0
  no-underscore-dangle: 0
  no-unneeded-ternary: 0
  object-curly-spacing: 0
  one-var: 0
  operator-assignment: 0
  operator-linebreak: 0
  padded-blocks: 0
  quote-props: 0
  quotes: 0
  require-jsdoc: 0
  semi-spacing: 0
  semi: 0
  sort-vars: 0
  space-after-keywords: 0
  space-before-blocks: 0
  space-before-function-paren: 0
  space-before-keywords: 0
  space-in-parens: 0
  space-infix-ops: 0
  space-return-throw-case: 0
  space-unary-ops: 0
  spaced-comment: 0
  wrap-regex: 0

  # ECMAScript 6
  arrow-body-style: 0
  arrow-parens: 0
  arrow-spacing: 0
  constructor-super: 0
  generator-star-spacing: 0
  no-arrow-condition: 0
  no-class-assign: 0
  no-const-assign: 0
  no-dupe-class-members: 0
  no-this-before-super: 0
  no-var: 0
  object-shorthand: 0
  prefer-arrow-callback: 0
  prefer-const: 0
  prefer-reflect: 0
  prefer-spread: 0
  prefer-template: 0
  require-yield: 0


================================================
FILE: .gitignore
================================================
################################################
## Dependencies
################################################
node_modules

################################################
## Nodejs Common Files
################################################
lib-cov
*.seed
*.log
*.out
*.pid
npm-debug.log

################################################
## Secret
################################################
.key.json

################################################
# Miscellaneous
################################################
*~
*#
.DS_STORE
.netbeans
nbproject
.idea
.node_history

################################################
## Instanbul Code Coverage Reports
################################################
coverage


================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
  - "6.10"
  - "6.9"
  - "4.8"
  - "4.4.1"
  - "4.2"
addons:
  code_climate:
    repo_token: 6131e0b97abea823e9a41cc90736f0c2fdbe5d6b442ce0603f7f131aea6b35c3
after_script:
  - codeclimate-test-reporter < coverage/lcov.info


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2016 Shern Shiou Tan, Alexander Graebe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README-Nodeback.md
================================================
# Initialization

In order to use this module, you have to import it in your application first:

```javasctipt
var Uber = require('node-uber');
```

Next, initialize the Uber object with the keys you obtained from the [Uber developer dashboard](https://developer.uber.com/dashboard):

```javasctipt
var uber = new Uber({
  client_id: 'CLIENT_ID',
  client_secret: 'CLIENT_SECRET',
  server_token: 'SERVER_TOKEN',
  redirect_uri: 'REDIRECT URL',
  name: 'APP_NAME',
  language: 'en_US', // optional, defaults to en_US
  sandbox: true // optional, defaults to false
});
```

> **Note**: For all available `language` options check out the [Localization page of the API](https://developer.uber.com/docs/localization).

# Authenticating

To make HTTP calls, you need to create an authenticated session with the API. User-specific operations require you to use a OAuth 2 bearer token with specific [scopes](https://developer.uber.com/docs/scopes). Jump to the [method overview section](https://github.com/shernshiou/node-uber#method-overview) to identify required scopes for methods. General operations can use a simple server-token authentication.

## Step one: Authorize

To obtain an OAuth 2 bearer token, you have to authorize your application with the required scope. Available scopes are: `history`, `history_lite`, `profile`, `request`, `all_trips`, and `places`.

To do so, you are initially required to redirect your user to an authorization URL. You can generate the authorization URL using `uber.getAuthorizeUrl`. In case you are using [Express](http://expressjs.com/), your route definition could look as follows:

```javascript
app.get('/api/login', function(request, response) {
  var url = uber.getAuthorizeUrl(['history','profile', 'request', 'places']);
  response.redirect(url);
});
```

The URL will lead to a page where your user will be required to login and approve access to his/her Uber account. In case that step was successful, Uber will issue an HTTP 302 redirect to the redirect_uri defined in the [Uber developer dashboard](https://developer.uber.com/dashboard). On that redirect, you will receive an authorization code, which is single use and expires in 10 minutes.

## Step two: Receive redirect and get an access token

To complete the authorization you now need to receive the callback and convert the given authorization code into an OAuth access token. You can accomplish that using `uber.authorization`. This method will retrieve and store the access_token, refresh_token, authorized scopes, and token expiration date within the uber object for consecutive requests.

Using Express, you could achieve that as follows:

```javascript
 app.get('/api/callback', function(request, response) {
    uber.authorization({
      authorization_code: request.query.code
    }, function(err, res) {
      if (err) {
        console.error(err);
      } else {
        // store the user id and associated properties:
        // access_token = res[0], refresh_token = res[1], scopes = res[2]),and token expiration date = res[3]
        console.log('New access_token retrieved: ' + res[0]);
        console.log('... token allows access to scopes: ' + res[2]);
        console.log('... token is valid until: ' + res[3]);
        console.log('... after token expiration, re-authorize using refresh_token: ' + res[1]);

        // redirect the user back to your actual app
        response.redirect('/web/index.html');
      }
    });
});
```

## Step three: Make HTTP requests to available resources

Now that you are authenticated, you can issue requests using provided methods.

For instance, to obtain a list of available Uber products for a specific location, you can use `uber.products.getAllForLocation`.

In case you are using Express, your route definition could look as follows:

```javascript
app.get('/api/products', function(request, response) {
  // extract the query from the request URL
  var query = url.parse(request.url, true).query;

  // if no query params sent, respond with Bad Request
  if (!query || !query.lat || !query.lng) {
    response.sendStatus(400);
  } else {
    uber.products.getAllForLocation(query.lat, query.lng, function(err, res) {
      if (err) {
        console.error(err);
        response.sendStatus(500);
      } else {
        response.json(res);
      }
    });
  }
});
```

### Optional: Revoke user access (token)

If your users decide to disconnect or revoke access to their Uber accounts, you can use the `uber.revokeToken` method. This will invalidate either `access_token` or `refresh_token`. Note that per [RFC7009](https://tools.ietf.org/html/rfc7009), revoke will return success for any string you pass into the function provided the client_id and client_secret are correct. This includes previously revoked tokens and invalid tokens.

```javascript
uber.revokeToken('My_access_token');
```

# Method Overview

## [Riders API](https://developer.uber.com/docs/riders/introduction)

HTTP Method | Endpoint                          | Auth Method           | Required Scope                                 | Methods
----------- | --------------------------------- | --------------------- | ---------------------------------------------- | ---------------------------------------
GET         | /v1.2/products                      | OAuth or server_token |                                                | products.getAllForAddress
GET         | /v1.2/products                      | OAuth or server_token |                                                | products.getAllForLocation
GET         | /v1.2/products/{product_id}         | OAuth or server_token |                                                | products.getByID
PUT         | /v1.2/sandbox/products/{product_id} | OAuth or server_token | (Sandbox mode)                                 | products.setSurgeMultiplierByID
PUT         | /v1.2/sandbox/products/{product_id} | OAuth or server_token | (Sandbox mode)                                 | products.setDriversAvailabilityByID
GET         | /v1.2/estimates/price               | OAuth or server_token |                                                | estimates.getPriceForRoute
GET         | /v1.2/estimates/price               | OAuth or server_token |                                                | estimates.getPriceForRouteByAddress
GET         | /v1.2/estimates/time                | OAuth or server_token |                                                | estimates.getETAForAddress
GET         | /v1.2/estimates/time                | OAuth or server_token |                                                | estimates.getETAForLocation
GET         | /v1.2/history                       | OAuth                 | history or history_lite                        | user.getHistory
GET         | /v1.2/me                            | OAuth                 | profile                                        | user.getProfile
PATCH       | /v1.2/me                            | OAuth                 | profile                                        | user.applyPromo
POST        | /v1.2/requests                      | OAuth                 | request (privileged)                           | requests.create
GET         | /v1.2/requests/current              | OAuth                 | request (privileged) or all_trips (privileged) | requests.getCurrent
PATCH       | /v1.2/requests/current              | OAuth                 | request (privileged)                           | requests.updateCurrent
DELETE      | /v1.2/requests/current              | OAuth                 | request (privileged)                           | requests.deleteCurrent
POST        | /v1.2/requests/estimate             | OAuth                 | request (privileged)                           | requests.getEstimates
GET         | /v1.2/requests/{request_id}         | OAuth                 | request (privileged)                           | requests.getByID
PATCH       | /v1.2/requests/{request_id}         | OAuth                 | request (privileged)                           | requests.updateByID
PUT         | /v1.2/sandbox/requests/{request_id} | OAuth                 | request (privileged & Sandbox mode )           | requests.setStatusByID
DELETE      | /v1.2/requests/{request_id}         | OAuth                 | request (privileged)                           | requests.deleteByID
GET         | /v1.2/requests/{request_id}/map     | OAuth                 | request (privileged)                           | requests.getMapByID
GET         | /v1.2/requests/{request_id}/receipt | OAuth                 | request_receipt (privileged)                   | requests.getReceiptByID
GET         | /v1.2/places/{place_id}             | OAuth                 | places                                         | places.getHome and places.getWork
PUT         | /v1.2/places/{place_id}             | OAuth                 | places                                         | places.updateHome and places.updateWork
GET         | /v1.2/payment-methods                | OAuth                 | request (privileged)                           | payment.getMethods

## [Drivers API](https://developer.uber.com/docs/drivers)

HTTP Method | Endpoint           | Auth Method | Required Scope   | Methods
----------- | ------------------ | ----------- | ---------------- | ---------------------------
GET         | /v1/partners/me       | OAuth       | partner.accounts | partnerprofile.getProfile
GET         | /v1/partners/payments | OAuth       | partner.payments | partnerpayments.getPayments
GET         | /v1/partners/trips    | OAuth       | partner.trips    | partnertrips.getTrips
# Endpoint Details

## Authorization (OAuth 2.0)

### Generate Authorize URL

After getting the authorize url, the user will be redirected to the redirect url with authorization code used in the next function.

```javascript
uber.getAuthorizeUrl(parameter);
```

#### Parameter

- Array of scopes

#### Example

```javascript
uber.getAuthorizeUrl(['history','profile', 'request', 'places']);
```

### Authorize

Used to convert authorization code or refresh token into access token.

```javascript
uber.authorization(parameter, callback);
```

#### Parameter

- JS Object with attribute `authorization_code` OR `refresh_token`

#### Example

> _Note:_ The callback return parameters changed with v1.0.0! This change was necessary to introduce promise-based callbacks.

> ```javascript
> uber.authorization({ refresh_token: 'REFRESH_TOKEN' },
>   function (err, res) {
>     if (err) console.error(err);
>     else {
>       // store the user id and associated properties:
>       // access_token = res[0], refresh_token = res[1], scopes = res[2]),and token expiration date = res[3]
>       console.log('New access_token retrieved: ' + res[0]);
>       console.log('... token allows access to scopes: ' + res[2]);
>       console.log('... token is valid until: ' + res[3]);
>       console.log('... after token expiration, re-authorize using refresh_token: ' + res[1]);
>     }
>   });
> ```

## /products

The product endpoint can be accessed either with an OAuth `access_token` or simply with the `server_token` because it is not user-specific. It has, therefore, no required scope for access.

### [Get available products for address](https://developer.uber.com/docs/v1-products)

This method utilizes [geocoder](https://github.com/wyattdanger/geocoder) to retrieve the coordinates for an address using Google as the provider. It uses the first element of the response. In other words, the coordinates represent what the Google algorithm provides with most confidence value.

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

```javascript
uber.products.getAllForAddress(address, callback);
```

#### Example

```javascript
uber.products.getAllForAddress('1455 Market St, San Francisco, CA 94103, US', function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get available products for location](https://developer.uber.com/docs/v1-products)

```javascript
uber.products.getAllForLocation(latitude, longitude, callback);
```

#### Example

```javascript
uber.products.getAllForLocation(3.1357169, 101.6881501, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get product details by product_id](https://developer.uber.com/docs/v1-products-details)

```javascript
uber.products.getByID(product_id, callback);
```

#### Example

```javascript
uber.products.getByID('d4abaae7-f4d6-4152-91cc-77523e8165a4', function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Set driver's availability by product_id](https://developer.uber.com/docs/sandbox)

```javascript
uber.products.setDriversAvailabilityByID(product_id, availability, callback);
```

> **Note**: This method is only allowed in Sandbox mode.

#### Parameter

- availability (boolean) will force requests to return a `no_drivers_available` error if set to false

#### Example

```javascript
uber.products.setDriversAvailabilityByID('d4abaae7-f4d6-4152-91cc-77523e8165a4', false, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Set surge multiplier by product_id](https://developer.uber.com/docs/sandbox)

```javascript
uber.products.setSurgeMultiplierByID(product_id, multiplier, callback);
```

> **Note**: This method is only allowed in Sandbox mode.

#### Parameter

- multiplier (float) will force two stage confirmation for requests if > 2.0

#### Example

```javascript
uber.products.setSurgeMultiplierByID('d4abaae7-f4d6-4152-91cc-77523e8165a4', 2.2, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

## /estimates

The estimates endpoint can be accessed either with an OAuth `access_token` or simply with the `server_token` because it is not user-specific. It has, therefore, no required scope for access.

### [Get price estimates for specific address](https://developer.uber.com/docs/v1-estimates-price)

This method utilizes [geocoder](https://github.com/wyattdanger/geocoder) to retrieve the coordinates for an address using Google as the provider. It uses the first element of the response. In other words, the coordinates represent what the Google algorithm provides with most confidence value.

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

> ```javascript
> uber.estimates.getPriceForRouteByAddress(start_address, end_address, [, seats], callback);
> ```

`seats` defaults to 2, which is also the maximum value for this parameter.

#### Example

```javascript
uber.estimates.getPriceForRouteByAddress(
  '1455 Market St, San Francisco, CA 94103, US',
  '2675 Middlefield Rd, Palo Alto, CA 94306, US',
  function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get price estimates for specific route](https://developer.uber.com/docs/v1-estimates-price)

```javascript
uber.estimates.getPriceForRoute(start_latitude, start_longitude, end_latitude, end_longitude [, seats], callback);
```

`seats` defaults to 2, which is also the maximum value for this parameter.

#### Example

```javascript
uber.estimates.getPriceForRoute(3.1357169, 101.6881501, 3.0833, 101.6500, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get ETA for address](https://developer.uber.com/docs/v1-estimates-time)

This method utilizes [geocoder](https://github.com/wyattdanger/geocoder) to retrieve the coordinates for an address using Google as the provider. It uses the first element of the response. In other words, the coordinates represent what the Google algorithm provides with most confidence value.

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

```javascript
uber.estimates.getETAForAddress(address, [, product_id], callback);
```

#### Example

```javascript
uber.estimates.getETAForAddress('455 Market St, San Francisco, CA 94103, US', function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get ETA for location](https://developer.uber.com/docs/v1-estimates-time)

```javascript
uber.estimates.getETAForLocation(latitude, longitude [, product_id], callback);
```

#### Example

```javascript
uber.estimates.getETAForLocation(3.1357169, 101.6881501, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

## /history

The history endpoint can be accessed ONLY with an OAuth `access_token` authorized with either the `history` or `history_lite` (without city information) scope.

### [Get user activity](https://developer.uber.com/docs/v12-history)

```javascript
uber.user.getHistory(offset, limit, callback);
```

`offset` defaults to 0 and `limit` defaults to 5 with a maximum value of 50.

#### Example

```javascript
uber.user.getHistory(0, 5, function(err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

## /me

The me endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `profile` scope.

### [Get user profile](https://developer.uber.com/docs/v1-me)

```javascript
uber.user.getProfile(callback);
```

#### Example

```javascript
uber.user.getProfile(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

#### [Apply promo code to user account](https://developer.uber.com/docs/riders/references/api/v1.2/me-patch)

```javascript
uber.user.applyPromo(code);
```

##### Parameter

- user promotion code (string)

##### Example

```javascript
uber.user.applyPromo('FREE_RIDEZ', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

## /requests

The requests endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `request` scope.

### [Create new request](https://developer.uber.com/docs/v1-requests)

```javascript
uber.requests.create(parameter, callback);
```

#### Parameter

- JS Object with at least the following attributes:
  - `start_latitude` & `start_longitude` OR `start_place_id`
  - `end_latitude` & `end_longitude` OR `end_place_id`
  -  The key for the upfront fare of a ride (`fare_id`)
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

#### Example

```javascript
uber.requests.create({
  "fare_id": "d30e732b8bba22c9cdc10513ee86380087cb4a6f89e37ad21ba2a39f3a1ba960",
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
  "start_latitude": 37.761492,
  "start_longitude": -122.423941,
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
}, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get current request](https://developer.uber.com/docs/v1-requests-current)

> **Note**: By default, only details about trips your app requested will be returned. This endpoint can be used with the scope `all_trips` to get all trips irrespective of which application initiated them.

```javascript
uber.requests.getCurrent(callback);
```

#### Example

```javascript
uber.requests.getCurrent(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Update current request](https://developer.uber.com/docs/v1-requests-current-patch)

```javascript
uber.requests.updateCurrent(parameter, callback);
```

#### Parameter

- JS Object with attributes to be updated (only destination-related attributes enabled)
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

#### Example

```javascript
uber.requests.updateCurrent({
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
}, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Delete current request](https://developer.uber.com/docs/v1-requests-current-delete)

```javascript
uber.requests.deleteCurrent(callback);
```

#### Example

```javascript
uber.requests.deleteCurrent(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Get estimates](https://developer.uber.com/docs/v1-requests-estimate)

```javascript
uber.requests.getEstimates(parameter, callback);
```

#### Parameter

- JS Object with at least the following attributes:
  - `start_latitude` & `start_longitude` OR `start_place_id`
  - `end_latitude` & `end_longitude` OR `end_place_id`
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

#### Example

```javascript
uber.requests.getEstimates({
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
  "start_latitude": 37.761492,
  "start_longitude": -122.423941,
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
}, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Get request by request_id](https://developer.uber.com/docs/v1-requests-details)

```javascript
uber.requests.getByID(request_id, callback);
```

#### Example

```javascript
uber.requests.getByID('17cb78a7-b672-4d34-a288-a6c6e44d5315', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Update request by request_id](https://developer.uber.com/docs/v1-requests-patch)

```javascript
uber.requests.updateByID(request_id, parameter, callback);
```

#### Parameter

- JS Object with attributes to be updated (only destination-related attributes enabled)
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

#### Example

```javascript
uber.requests.updateByID('17cb78a7-b672-4d34-a288-a6c6e44d5315', {
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
}, function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Set request status by request_id](https://developer.uber.com/docs/sandbox)

```javascript
uber.requests.setStatusByID(request_id, status, callback);
```

> **Note**: This method is only allowed in Sandbox mode. Check out the [documentation](https://developer.uber.com/docs/sandbox) for valid status properties.

#### Example

```javascript
uber.requests.setStatusByID('17cb78a7-b672-4d34-a288-a6c6e44d5315', 'accepted', function (err, res) {
  if (err) console.error(err);
  else console.log(res);
});
```

### [Delete request by request_id](https://developer.uber.com/docs/v1-requests-cancel)

```javascript
uber.requests.deleteByID(request_id, callback);
```

#### Example

```javascript
uber.requests.deleteByID('17cb78a7-b672-4d34-a288-a6c6e44d5315', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Get request map by request_id](https://developer.uber.com/docs/v1-requests-map)

```javascript
uber.requests.getMapByID(request_id, callback);
```

Unless the referenced request is in status `accepted`, a 404 error will be returned.

#### Example

```javascript
uber.requests.getMapByID('17cb78a7-b672-4d34-a288-a6c6e44d5315', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Get request receipt by request_id](https://developer.uber.com/docs/v1-requests-receipt)

> **Note**: This endpoint requires OAuth authentication with the scope `request_receipt`

```javascript
uber.requests.getReceiptByID(request_id, callback);
```

The referenced request must be in status `completed`.

#### Example

```javascript
uber.requests.getReceiptByID('17cb78a7-b672-4d34-a288-a6c6e44d5315', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

## /places

The places endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `places` scope.

> **Note**: As of right now, only two place_ids are allowed: `home` and `work`.

### [Get home address](https://developer.uber.com/docs/v1-places-get)

```javascript
uber.places.getHome(callback);
```

#### Example

```javascript
uber.places.getHome(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Get work address](https://developer.uber.com/docs/v1-places-get)

```javascript
uber.places.getWork(callback);
```

#### Example

```javascript
uber.places.getWork(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Update home address](https://developer.uber.com/docs/v1-places-put)

```javascript
uber.places.updateHome(address, callback);
```

#### Example

```javascript
uber.places.updateHome('685 Market St, San Francisco, CA 94103, USA', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Update work address](https://developer.uber.com/docs/v1-places-put)

```javascript
uber.places.updateWork(address, callback);
```

#### Example

```javascript
uber.places.updateWork('1455 Market St, San Francisco, CA 94103, USA', function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

## /payment-methods

The payment-methods endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `request` scope.

### [Get available payment methods](https://developer.uber.com/docs/v1-payment-methods)

```javascript
uber.payment.getMethods(callback);
```

#### Example

```javascript
uber.payment.getMethods(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

## /partners

The partners endpoints (Driver API) can be accessed ONLY with an OAuth `access_token` authorized with [the respective scopes](https://developer.uber.com/docs/drivers/guides/scopes) (`partner.accounts`, `partner.trips`, or `partner.payments`).

### [Get driver profile](https://developer.uber.com/docs/drivers/references/api/v1/partners-me-get)

```javascript
uber.partnerprofile.getProfile(callback);
```

#### Example

```javascript
uber.partnerprofile.getProfile(function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Get driver payments](https://developer.uber.com/docs/drivers/references/api/v1/partners-payments-get)

```javascript
uber.partnerpayments.getPayments(offset, limit, from_time, to_time, callback);
```

##### Parameter

- offset for payments list (sorted by creation time). Defaults to `0`
- limit of payments list. Defaults to `5`
- minimum Unix timestamp for filtered payments list
- maximum Unix timestamp for filtered payments list

#### Example

```javascript
uber.partnerpayments.getPayments(0, 50, 1451606400, 1505160819, function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```

### [Get driver trips](https://developer.uber.com/docs/drivers/references/api/v1/partners-trips-get)

```javascript
uber.partnertrips.getTrips(offset, limit, from_time, to_time, callback);
```

##### Parameter

- offset for trips list (sorted by creation time). Defaults to `0`
- limit of trips list. Defaults to `5`
- minimum Unix timestamp for filtered trips list
- maximum Unix timestamp for filtered trips list

#### Example

```javascript
uber.partnertrips.getTrips(0, 50, 1451606400, 1505160819, function (err, res) {
  if (err) console.log(err);
  else console.log(res);
});
```


================================================
FILE: README.md
================================================
[![Join the chat at https://gitter.im/shernshiou/node-uber](https://badges.gitter.im/shernshiou/node-uber.svg)](https://gitter.im/shernshiou/node-uber?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org) [![build status](https://img.shields.io/travis/shernshiou/node-uber.svg?style=flat-square)](https://travis-ci.org/shernshiou/node-uber) [![Dependency Status](https://david-dm.org/shernshiou/node-uber.svg?style=flat-square)](https://david-dm.org/shernshiou/node-uber) [![devDependency Status](https://david-dm.org/shernshiou/node-uber/dev-status.svg)](https://david-dm.org/shernshiou/node-uber#info=devDependencies) [![Code Climate](https://codeclimate.com/github/shernshiou/node-uber/badges/gpa.svg)](https://codeclimate.com/github/shernshiou/node-uber) [![Test Coverage](https://codeclimate.com/github/shernshiou/node-uber/badges/coverage.svg)](https://codeclimate.com/github/shernshiou/node-uber/coverage)

# Uber Rides Node.js Wrapper

This projects helps you to make HTTP requests to the Uber Rides API.

## Installation

Before you begin, you need to register your app in the [Uber developer dashboard](https://developer.uber.com/dashboard). Notice that the app gets a client ID, secret, and server token required for authenticating with the API.

After registering your application, you need to install this module in your Node.js project:

```sh
npm install node-uber
```

## Initialization

In order to use this module, you have to import it in your application first:

```javasctipt
var Uber = require('node-uber');
```

Next, initialize the Uber object with the keys you obtained from the [Uber developer dashboard](https://developer.uber.com/dashboard):

```javasctipt
var uber = new Uber({
  client_id: 'CLIENT_ID',
  client_secret: 'CLIENT_SECRET',
  server_token: 'SERVER_TOKEN',
  redirect_uri: 'REDIRECT URL',
  name: 'APP_NAME',
  language: 'en_US', // optional, defaults to en_US
  sandbox: true, // optional, defaults to false
  proxy: 'PROXY URL' // optional, defaults to none
});
```

> **Note**: For all available `language` options check out the [Localization page of the API](https://developer.uber.com/docs/localization).

## Authenticating

To make HTTP calls, you need to create an authenticated session with the API. User-specific operations require you to use a OAuth 2 bearer token with specific [scopes](https://developer.uber.com/docs/scopes). Jump to the [method overview section](https://github.com/shernshiou/node-uber#method-overview) to identify required scopes for methods. General operations can use a simple server-token authentication.

### Step one: Authorize

To obtain an OAuth 2 bearer token, you have to authorize your application with the required scope. Available scopes are: `history`, `history_lite`, `profile`, `request`, `all_trips`, and `places`.

To do so, you are initially required to redirect your user to an authorization URL. You can generate the authorization URL using `uber.getAuthorizeUrl`. In case you are using [Express](http://expressjs.com/), your route definition could look as follows:

```javascript
app.get('/api/login', function(request, response) {
  var url = uber.getAuthorizeUrl(['history','profile', 'request', 'places']);
  response.redirect(url);
});
```

The URL will lead to a page where your user will be required to login and approve access to his/her Uber account. In case that step was successful, Uber will issue an HTTP 302 redirect to the redirect_uri defined in the [Uber developer dashboard](https://developer.uber.com/dashboard). On that redirect, you will receive an authorization code, which is single use and expires in 10 minutes.

### Step two: Receive redirect and get an access token

To complete the authorization you now need to receive the callback and convert the given authorization code into an OAuth access token. You can accomplish that using `uber.authorizationAsync`. This method will retrieve and store the access_token, refresh_token, authorized scopes, and token expiration date within the uber object for consecutive requests.

Using Express, you could achieve that as follows:

```javascript
 app.get('/api/callback', function(request, response) {
    uber.authorizationAsync({authorization_code: request.query.code})
    .spread(function(access_token, refresh_token, authorizedScopes, tokenExpiration) {
      // store the user id and associated access_token, refresh_token, scopes and token expiration date
      console.log('New access_token retrieved: ' + access_token);
      console.log('... token allows access to scopes: ' + authorizedScopes);
      console.log('... token is valid until: ' + tokenExpiration);
      console.log('... after token expiration, re-authorize using refresh_token: ' + refresh_token);

      // redirect the user back to your actual app
      response.redirect('/web/index.html');
    })
    .error(function(err) {
      console.error(err);
    });
});
```

> **Nodeback**: Looking for nodeback-style methods? Check out the [nodeback-readme](README-Nodeback.md).

### Step three: Make HTTP requests to available resources

Now that you are authenticated, you can issue requests using provided methods.

For instance, to obtain a list of available Uber products for a specific location, you can use `uber.products.getAllForLocationAsync`.

In case you are using Express, your route definition could look as follows:

```javascript
app.get('/api/products', function(request, response) {
  // extract the query from the request URL
  var query = url.parse(request.url, true).query;

  // if no query params sent, respond with Bad Request
  if (!query || !query.lat || !query.lng) {
    response.sendStatus(400);
  } else {
    uber.products.getAllForLocationAsync(query.lat, query.lng)
    .then(function(res) {
        response.json(res);
    })
    .error(function(err) {
      console.error(err);
      response.sendStatus(500);
    });
  }
});
```

### Optional: Revoke user access (token)

If your users decide to disconnect or revoke access to their Uber accounts, you can use the `uber.revokeTokenAsync` method. This will invalidate either `access_token` or `refresh_token`. Note that per [RFC7009](https://tools.ietf.org/html/rfc7009), revoke will return success for any string you pass into the function provided the client_id and client_secret are correct. This includes previously revoked tokens and invalid tokens.

```javascript
uber.revokeTokenAsync('My_access_token');
```

## Method Overview

> **Nodeback**: Looking for nodeback-style methods? Check out the [nodeback-readme](README-Nodeback.md).

## [Riders API](https://developer.uber.com/docs/riders/introduction)

HTTP Method | Endpoint                          | Auth Method           | Required Scope                                 | Methods
----------- | --------------------------------- | --------------------- | ---------------------------------------------- | -------------------------------------------------
GET         | /v1.2/products                      | OAuth or server_token |                                                | products.getAllForAddressAsync
GET         | /v1.2/products                      | OAuth or server_token |                                                | products.getAllForLocationAsync
GET         | /v1.2/products/{product_id}         | OAuth or server_token |                                                | products.getByIDAsync
PUT         | /v1.2/sandbox/products/{product_id} | OAuth or server_token | (Sandbox mode)                                 | products.setSurgeMultiplierByIDAsync
PUT         | /v1.2/sandbox/products/{product_id} | OAuth or server_token | (Sandbox mode)                                 | products.setDriversAvailabilityByIDAsync
GET         | /v1.2/estimates/price               | OAuth or server_token |                                                | estimates.getPriceForRouteAsync
GET         | /v1.2/estimates/price               | OAuth or server_token |                                                | estimates.getPriceForRouteByAddressAsync
GET         | /v1.2/estimates/time                | OAuth or server_token |                                                | estimates.getETAForAddressAsync
GET         | /v1.2/estimates/time                | OAuth or server_token |                                                | estimates.getETAForLocationAsync
GET         | /v1.2/history                     | OAuth                 | history or history_lite                        | user.getHistoryAsync
GET         | /v1.2/me                            | OAuth                 | profile                                        | user.getProfileAsync
PATCH       | /v1.2/me                          | OAuth                 | profile                                        | user.applyPromoAsync
POST        | /v1.2/requests                      | OAuth                 | request (privileged)                           | requests.createAsync
GET         | /v1.2/requests/current              | OAuth                 | request (privileged) or all_trips (privileged) | requests.getCurrentAsync
PATCH       | /v1.2/requests/current              | OAuth                 | request (privileged)                           | requests.updateCurrentAsync
DELETE      | /v1.2/requests/current              | OAuth                 | request (privileged)                           | requests.deleteCurrentAsync
POST        | /v1.2/requests/estimate             | OAuth                 | request (privileged)                           | requests.getEstimatesAsync
GET         | /v1.2/requests/{request_id}         | OAuth                 | request (privileged)                           | requests.getByIDAsync
PATCH       | /v1.2/requests/{request_id}         | OAuth                 | request (privileged)                           | requests.updateByIDAsync
PUT         | /v1.2/sandbox/requests/{request_id} | OAuth                 | request (privileged & Sandbox mode )           | requests.setStatusByIDAsync
DELETE      | /v1.2/requests/{request_id}         | OAuth                 | request (privileged)                           | requests.deleteByIDAsync
GET         | /v1.2/requests/{request_id}/map     | OAuth                 | request (privileged)                           | requests.getMapByIDAsync
GET         | /v1.2/requests/{request_id}/receipt | OAuth                 | request_receipt (privileged)                   | requests.getReceiptByIDAsync
GET         | /v1.2/places/{place_id}             | OAuth                 | places                                         | places.getHomeAsync and places.getWorkAsync
PUT         | /v1.2/places/{place_id}             | OAuth                 | places                                         | places.updateHomeAsync and places.updateWorkAsync
GET         | /v1.2/payment-methods                | OAuth                 | request (privileged)                           | payment.getMethodsAsync

## [Drivers API](https://developer.uber.com/docs/drivers)

HTTP Method | Endpoint           | Auth Method | Required Scope   | Methods
----------- | ------------------ | ----------- | ---------------- | --------------------------------
GET         | /v1/partners/me       | OAuth       | partner.accounts | partnerprofile.getProfileAsync
GET         | /v1/partners/payments | OAuth       | partner.payments | partnerpayments.getPaymentsAsync
GET         | /v1/partners/trips    | OAuth       | partner.trips    | partnertrips.getTripsAsync

## Endpoint Details

### Authorization (OAuth 2.0)

#### Generate Authorize URL

After getting the authorize url, the user will be redirected to the redirect url with authorization code used in the next function.

```javascript
uber.getAuthorizeUrl(parameter);
```

##### Parameter

- Array of scopes

##### Example

```javascript
uber.getAuthorizeUrl(['history','profile', 'request', 'places']);
```

#### Authorize

Used to convert authorization code or refresh token into access token.

```javascript
uber.authorizationAsync(parameter);
```

##### Parameter

- JS Object with attribute `authorization_code` OR `refresh_token`

##### Example: Just access_token

```javascript
uber.authorizationAsync({ refresh_token: 'REFRESH_TOKEN' })
  .then(function(access_token) { console.log(access_token); })
  .error(function(err) { console.error(err); });
});
```

##### Example: All properties

```javascript
uber.authorizationAsync({ refresh_token: 'REFRESH_TOKEN' })
.spread(function(access_token, refresh_token, authorizedScopes, tokenExpiration) {
  // store the user id and associated access_token, refresh_token, scopes and token expiration date
  console.log('New access_token retrieved: ' + access_token);
  console.log('... token allows access to scopes: ' + authorizedScopes);
  console.log('... token is valid until: ' + tokenExpiration);
  console.log('... after token expiration, re-authorize using refresh_token: ' + refresh_token);
})
  .error(function(err) { console.error(err); });
});
```

### /products

The product endpoint can be accessed either with an OAuth `access_token` or simply with the `server_token` because it is not user-specific. It has, therefore, no required scope for access.

#### [Get available products for address](https://developer.uber.com/docs/v1-products)

This method utilizes [geocoder](https://github.com/wyattdanger/geocoder) to retrieve the coordinates for an address using Google as the provider. It uses the first element of the response. In other words, the coordinates represent what the Google algorithm provides with most confidence value.

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

```javascript
uber.products.getAllForAddressAsync(address);
```

##### Example

```javascript
uber.products.getAllForAddressAsync('1455 Market St, San Francisco, CA 94103, US')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get available products for location](https://developer.uber.com/docs/v1-products)

```javascript
uber.products.getAllForLocationAsync(latitude, longitude);
```

##### Example

```javascript
uber.products.getAllForLocationAsync(3.1357169, 101.6881501)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get product details by product_id](https://developer.uber.com/docs/v1-products-details)

```javascript
uber.products.getByIDAsync(product_id);
```

##### Example

```javascript
uber.products.getByIDAsync('d4abaae7-f4d6-4152-91cc-77523e8165a4')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Set driver's availability by product_id](https://developer.uber.com/docs/sandbox)

```javascript
uber.products.setDriversAvailabilityByIDAsync(product_id, availability);
```

> **Note**: This method is only allowed in Sandbox mode.

##### Parameter

- availability (boolean) will force requests to return a `no_drivers_available` error if set to false

##### Example

```javascript
uber.products.setDriversAvailabilityByIDAsync('d4abaae7-f4d6-4152-91cc-77523e8165a4', false)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Set surge multiplier by product_id](https://developer.uber.com/docs/sandbox)

```javascript
uber.products.setSurgeMultiplierByIDAsync(product_id, multiplier);
```

> **Note**: This method is only allowed in Sandbox mode.

##### Parameter

- multiplier (float) will force two stage confirmation for requests if > 2.0

##### Example

```javascript
uber.products.setSurgeMultiplierByIDAsync('d4abaae7-f4d6-4152-91cc-77523e8165a4', 2.2)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /estimates

The estimates endpoint can be accessed either with an OAuth `access_token` or simply with the `server_token` because it is not user-specific. It has, therefore, no required scope for access.

#### [Get price estimates for specific address](https://developer.uber.com/docs/v1-estimates-price)

This method utilizes [geocoder](https://github.com/wyattdanger/geocoder) to retrieve the coordinates for an address using Google as the provider. It uses the first element of the response. In other words, the coordinates represent what the Google algorithm provides with most confidence value.

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

> ```javascript
> uber.estimates.getPriceForRouteByAddressAsync(start_address, end_address, [, seats]);
> ```

`seats` defaults to 2, which is also the maximum value for this parameter.

##### Example

```javascript
uber.estimates.getPriceForRouteByAddressAsync(
  '1455 Market St, San Francisco, CA 94103, US',
  '2675 Middlefield Rd, Palo Alto, CA 94306, US')
  .then(function(res) { console.log(res); })
  .error(function(err) { console.error(err); });
```

#### [Get price estimates for specific route](https://developer.uber.com/docs/v1-estimates-price)

```javascript
uber.estimates.getPriceForRouteAsync(start_latitude, start_longitude, end_latitude, end_longitude [, seats]);
```

`seats` defaults to 2, which is also the maximum value for this parameter.

##### Example

```javascript
uber.estimates.getPriceForRouteAsync(3.1357169, 101.6881501, 3.0833, 101.6500)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get ETA for address](https://developer.uber.com/docs/v1-estimates-time)

This method utilizes [geocoder](https://github.com/wyattdanger/geocoder) to retrieve the coordinates for an address using Google as the provider. It uses the first element of the response. In other words, the coordinates represent what the Google algorithm provides with most confidence value.

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

```javascript
uber.estimates.getETAForAddressAsync(address, [, product_id]);
```

##### Example

```javascript
uber.estimates.getETAForAddressAsync('455 Market St, San Francisco, CA 94103, US')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
});
```

#### [Get ETA for location](https://developer.uber.com/docs/v1-estimates-time)

```javascript
uber.estimates.getETAForLocationAsync(latitude, longitude [, product_id]);
```

##### Example

```javascript
uber.estimates.getETAForLocationAsync(3.1357169, 101.6881501)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /history

The history endpoint can be accessed ONLY with an OAuth `access_token` authorized with either the `history` or `history_lite` (without city information) scope.

#### [Get user activity](https://developer.uber.com/docs/v12-history)

```javascript
uber.user.getHistoryAsync(offset, limit);
```

`offset` defaults to 0 and `limit` defaults to 5 with a maximum value of 50.

##### Example

```javascript
uber.user.getHistoryAsync(0, 5)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /me

The me endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `profile` scope.

#### [Get user profile](https://developer.uber.com/docs/v1-me)

```javascript
uber.user.getProfileAsync();
```

##### Example

```javascript
uber.user.getProfileAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Apply promo code to user account](https://developer.uber.com/docs/riders/references/api/v1.2/me-patch)

```javascript
uber.user.applyPromoAsync(code);
```

##### Parameter

- user promotion code (string)

##### Example

```javascript
uber.user.applyPromoAsync('FREE_RIDEZ')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /requests

The requests endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `request` scope.

#### [Create new request](https://developer.uber.com/docs/v1-requests)

```javascript
uber.requests.createAsync(parameter);
```

##### Parameter

- JS Object with at least the following attributes:
  - `start_latitude` & `start_longitude` OR `start_place_id`
  - `end_latitude` & `end_longitude` OR `end_place_id`
  -  The key for the upfront fare of a ride (`fare_id`)
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

##### Example

```javascript
uber.requests.createAsync({
  "fare_id": "d30e732b8bba22c9cdc10513ee86380087cb4a6f89e37ad21ba2a39f3a1ba960",
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
  "start_latitude": 37.761492,
  "start_longitude": -122.423941,
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
})
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get current request](https://developer.uber.com/docs/v1-requests-current)

> **Note**: By default, only details about trips your app requested will be returned. This endpoint can be used with the scope `all_trips` to get all trips irrespective of which application initiated them.

```javascript
uber.requests.getCurrentAsync();
```

##### Example

```javascript
uber.requests.getCurrentAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Update current request](https://developer.uber.com/docs/v1-requests-current-patch)

```javascript
uber.requests.updateCurrentAsync(parameter);
```

##### Parameter

- JS Object with attributes to be updated (only destination-related attributes enabled)
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

##### Example

```javascript
uber.requests.updateCurrentAsync({
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
})
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Delete current request](https://developer.uber.com/docs/v1-requests-current-delete)

```javascript
uber.requests.deleteCurrentAsync();
```

##### Example

```javascript
uber.requests.deleteCurrentAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get estimates](https://developer.uber.com/docs/v1-requests-estimate)

```javascript
uber.requests.getEstimatesAsync(parameter);
```

##### Parameter

- JS Object with at least the following attributes:
  - `start_latitude` & `start_longitude` OR `start_place_id`
  - `end_latitude` & `end_longitude` OR `end_place_id`
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

##### Example

```javascript
uber.requests.getEstimatesAsync({
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
  "start_latitude": 37.761492,
  "start_longitude": -122.423941,
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
})
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get request by request_id](https://developer.uber.com/docs/v1-requests-details)

```javascript
uber.requests.getByIDAsync(request_id);
```

##### Example

```javascript
uber.requests.getByIDAsync('17cb78a7-b672-4d34-a288-a6c6e44d5315')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Update request by request_id](https://developer.uber.com/docs/v1-requests-patch)

```javascript
uber.requests.updateByIDAsync(request_id, parameter);
```

##### Parameter

- JS Object with attributes to be updated (only destination-related attributes enabled)
- You can provide `startAddress` instead of `start_latitude` & `start_longitude` and `endAddress` instead of `end_latitude` & `end_longitude` thanks to [geocoder](https://github.com/wyattdanger/geocoder)

> **Note**: To ensure correct coordinates you should provide the complete address, including city, ZIP code, state, and country.

##### Example

```javascript
uber.requests.updateByIDAsync('17cb78a7-b672-4d34-a288-a6c6e44d5315', {
  "end_latitude": 37.775393,
  "end_longitude": -122.417546
})
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Set request status by request_id](https://developer.uber.com/docs/sandbox)

```javascript
uber.requests.setStatusByIDAsync(request_id, status);
```

> **Note**: This method is only allowed in Sandbox mode. Check out the [documentation](https://developer.uber.com/docs/sandbox) for valid status properties.

##### Example

```javascript
uber.requests.setStatusByIDAsync('17cb78a7-b672-4d34-a288-a6c6e44d5315', 'accepted')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Delete request by request_id](https://developer.uber.com/docs/v1-requests-cancel)

```javascript
uber.requests.deleteByIDAsync(request_id);
```

##### Example

```javascript
uber.requests.deleteByIDAsync('17cb78a7-b672-4d34-a288-a6c6e44d5315')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get request map by request_id](https://developer.uber.com/docs/v1-requests-map)

```javascript
uber.requests.getMapByIDAsync(request_id);
```

Unless the referenced request is in status `accepted`, a 404 error will be returned.

##### Example

```javascript
uber.requests.getMapByIDAsync('17cb78a7-b672-4d34-a288-a6c6e44d5315')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get request receipt by request_id](https://developer.uber.com/docs/v1-requests-receipt)

> **Note**: This endpoint requires OAuth authentication with the scope `request_receipt`

```javascript
uber.requests.getReceiptByIDAsync(request_id);
```

The referenced request must be in status `completed`.

##### Example

```javascript
uber.requests.getReceiptByIDAsync('17cb78a7-b672-4d34-a288-a6c6e44d5315')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /places

The places endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `places` scope.

> **Note**: As of right now, only two place_ids are allowed: `home` and `work`.

#### [Get home address](https://developer.uber.com/docs/v1-places-get)

```javascript
uber.places.getHomeAsync();
```

##### Example

```javascript
uber.places.getHomeAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get work address](https://developer.uber.com/docs/v1-places-get)

```javascript
uber.places.getWorkAsync();
```

##### Example

```javascript
uber.places.getWorkAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Update home address](https://developer.uber.com/docs/v1-places-put)

```javascript
uber.places.updateHomeAsync(address);
```

##### Example

```javascript
uber.places.updateHomeAsync('685 Market St, San Francisco, CA 94103, USA')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Update work address](https://developer.uber.com/docs/v1-places-put)

```javascript
uber.places.updateWorkAsync(address);
```

##### Example

```javascript
uber.places.updateWorkAsync('1455 Market St, San Francisco, CA 94103, USA')
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /payment-methods

The payment-methods endpoint can be accessed ONLY with an OAuth `access_token` authorized with the `request` scope.

#### [Get available payment methods](https://developer.uber.com/docs/v1-payment-methods)

```javascript
uber.payment.getMethodsAsync();
```

##### Example

```javascript
uber.payment.getMethodsAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

### /partners

The partners endpoints (Driver API) can be accessed ONLY with an OAuth `access_token` authorized with [the respective scopes](https://developer.uber.com/docs/drivers/guides/scopes) (`partner.accounts`, `partner.trips`, or `partner.payments`).

#### [Get driver profile](https://developer.uber.com/docs/drivers/references/api/v1/partners-me-get)

```javascript
uber.partnerprofile.getProfileAsync();
```

##### Example

```javascript
uber.partnerprofile.getProfileAsync()
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get driver payments](https://developer.uber.com/docs/drivers/references/api/v1/partners-payments-get)

```javascript
uber.partnerpayments.getPaymentsAsync(offset, limit, from_time, to_time);
```

##### Parameter

- offset for payments list (sorted by creation time). Defaults to `0`
- limit of payments list. Defaults to `5`
- minimum Unix timestamp for filtered payments list
- maximum Unix timestamp for filtered payments list

##### Example

```javascript
uber.partnerpayments.getPaymentsAsync(0, 50, 1451606400, 1505160819)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

#### [Get driver trips](https://developer.uber.com/docs/drivers/references/api/v1/partners-trips-get)

```javascript
uber.partnertrips.getTripsAsync(offset, limit, from_time, to_time);
```

##### Parameter

- offset for trips list (sorted by creation time). Defaults to `0`
- limit of trips list. Defaults to `5`
- minimum Unix timestamp for filtered trips list
- maximum Unix timestamp for filtered trips list

##### Example

```javascript
uber.partnertrips.getTripsAsync(0, 50, 1451606400, 1505160819)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
```

## Test

You can execute all existing tests using script `test/allTests.js`. These tests include linting, code coverage, and unit tests.

```sh
npm test
```

In case you would like to contribute to this project, please ensure that all the tests pass before you create a PR. We have strict code style and code coverage (>= 95%) requirements.

## Version History

The change-log can be found in the [Wiki: Version History](https://github.com/shernshiou/node-uber/wiki/Version-History).


================================================
FILE: examples/auth-get-products-async.js
================================================
var Uber = require('node-uber');

// create new Uber instance
var uber = new Uber({
    client_id: 'YOUR CLIENT ID',
    client_secret: 'YOUR CLIENT SECRET',
    server_token: 'YOUR SERVER TOKEN',
    redirect_uri: 'http://localhost/callback',
    name: 'nodejs uber wrapper',
    language: 'en_US',
    sandbox: true
});

// get authorization URL
var authURL = uber.getAuthorizeUrl(['history', 'profile', 'request', 'places']);

// redirect user to the authURL

// the authorizarion_code will be provided via the callback after logging in using the authURL
uber.authorizationAsync({
        authorization_code: 'YOUR AUTH CODE'
    })
    .spread(function(access_token, refresh_token, authorizedScopes, tokenExpiration) {
        // store the user id and associated access_token, refresh_token, scopes and token expiration date
        console.log('New access_token retrieved: ' + access_token);
        console.log('... token allows access to scopes: ' + authorizedScopes);
        console.log('... token is valid until: ' + tokenExpiration);
        console.log('... after token expiration, re-authorize using refresh_token: ' + refresh_token);

        // chain the promise to retrive all products for location
        return uber.products.getAllForLocationAsync(3.1357169, 101.6881501);
    })
    .then(function(res) {
        // response with all products
        console.log(res);
    })
    .error(function(err) {
        console.error(err);
    });


================================================
FILE: examples/auth-get-products.js
================================================
var Uber = require('node-uber');

// create new Uber instance
var uber = new Uber({
    client_id: 'YOUR CLIENT ID',
    client_secret: 'YOUR CLIENT SECRET',
    server_token: 'YOUR SERVER TOKEN',
    redirect_uri: 'http://localhost/callback',
    name: 'nodejs uber wrapper',
    language: 'en_US',
    sandbox: true
});

// get authorization URL
var authURL = uber.getAuthorizeUrl(['history', 'profile', 'request', 'places']);

// redirect user to the authURL

// the authorizarion_code will be provided via the callback after logging in using the authURL
uber.authorization({
    authorization_code: 'YOUR AUTH CODE'
}, function(err, res) {
    if (err) {
        console.error(err);
    } else {
        // store the user id and associated properties:
        // access_token = res[0], refresh_token = res[1], scopes = res[2]),and token expiration date = res[3]
        console.log('New access_token retrieved: ' + res[0]);
        console.log('... token allows access to scopes: ' + res[2]);
        console.log('... token is valid until: ' + res[3]);
        console.log('... after token expiration, re-authorize using refresh_token: ' + res[1]);

        uber.products.getAllForLocation(3.1357169, 101.6881501, function(err, res) {
            if (err) console.error(err);
            else console.log(res);
        });
    }
});


================================================
FILE: gulpfile.js
================================================
var gulp = require('gulp'),
    mocha = require('gulp-mocha'),
    istanbul = require('gulp-istanbul'),
    eslint = require('gulp-eslint');

gulp.task('lint', function() {
    // ESLint ignores files with "node_modules" paths.
    // So, it's best to have gulp ignore the directory as well.
    // Also, Be sure to return the stream from the task;
    // Otherwise, the task may end before the stream has finished.
    return gulp.src(['**/*.js', '!node_modules/**', '!coverage/**'])
        // eslint() attaches the lint output to the "eslint" property
        // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failAfterError last.
        .pipe(eslint.failAfterError());
});

gulp.task('pre-test', function() {
    return gulp.src(['lib/**/*.js'])
        // Covering files
        .pipe(istanbul({
            includeUntested: true
        }))
        // Force `require` to return covered files
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function() {
    return gulp.src(['test/**/*.js'])
        .pipe(mocha({
            reporter: 'spec',
            //useColors: false,
            timeout: 5000
        }))
        // Creating the reports after tests ran
        .pipe(istanbul.writeReports())
        // Enforce a coverage of at least 95%
        .pipe(istanbul.enforceThresholds({
            thresholds: {
                global: 95
            }
        }));
});

gulp.task('default', ['lint', 'pre-test', 'test']);


================================================
FILE: index.js
================================================
module.exports = require('./lib/Uber');


================================================
FILE: lib/Uber.js
================================================
var request = require('request');
var qs = require('querystring');
var OAuth = require('oauth');
var util = require('util');
var Promise = require('bluebird');
var NodeGeocoder = require('node-geocoder');
var ProxyAgent = require('proxy-agent');

var resources = {
  Estimates: require('./resources/riders/Estimates'),
  Products: require('./resources/riders/Products'),
  User: require('./resources/riders/User'),
  Requests: require('./resources/riders/Requests'),
  Places: require('./resources/riders/Places'),
  Payment: require('./resources/riders/Payment'),
  PartnerPayments: require('./resources/drivers/PartnerPayments'),
  PartnerProfile: require('./resources/drivers/PartnerProfile'),
  PartnerTrips: require('./resources/drivers/PartnerTrips')
};

function Uber(options) {
  this.sandbox = options.sandbox
    ? options.sandbox
    : false;
  this.defaults = {
    client_id: options.client_id,
    client_secret: options.client_secret,
    server_token: options.server_token,
    redirect_uri: options.redirect_uri,
    name: options.name,
    base_url: this.sandbox
      ? 'https://sandbox-api.uber.com/'
      : 'https://api.uber.com/',
    base_version: 'v1.2',
    language: options.language
      ? options.language
      : 'en_US',
    authorize_url: 'https://login.uber.com/oauth/v2/authorize',
    access_token_url: 'https://login.uber.com/oauth/v2/token',
    revoke_token_url: 'https://login.uber.com/oauth/v2/revoke',
    proxy: options.proxy
      ? options.proxy
      : ''
  };

  this.oauth2 = new OAuth.OAuth2(this.defaults.client_id, this.defaults.client_secret, '', this.defaults.authorize_url, this.defaults.access_token_url);

  this.geocoder = NodeGeocoder({
    provider: "google",
    apiKey: options.google_maps_api_key
  });

  if (this.defaults.proxy) {
    this.oauth2.setAgent(new ProxyAgent(this.defaults.proxy));
  }
  this.oauth2.useAuthorizationHeaderforGET(true);

  this.resources = resources;
  this.access_token = options.access_token;
  this.refresh_token = options.refresh_token;
  this.tokenExpiration = '';
  this.authorizedScopes = '';

  this._initResources();
}

module.exports = Uber;

Uber.prototype._initResources = function _initResources() {
  for (var name in this.resources) {
    if ({}.hasOwnProperty.call(this.resources, name)) {
      this[name.toLowerCase()] = Promise.promisifyAll(new resources[name](this));
    }
  }
};

Uber.prototype.getCoordinatesForAddress = function getCoordinatesForAddress(address, callback) {
  this.geocoder.geocode(address, function (err, data) {
    if (err || data.length === 0) {
      return callback((err
        ? err
        : new Error('No coordinates found for: "' + address + '"')), {
          lat: '',
          lng: ''
        });
    }

    const result = { lat: data[0].latitude, lng: data[0].longitude };
    callback(null, result);
  });
};

Uber.prototype.replaceAddressWithCoordinates = function
  replaceAddressWithCoordinates(params, addressField, latField, lngField, callback) {
  if (this.hasOwnNestedProperty(params, addressField) && !this.getNestedProperty(params, latField) && !this.getNestedProperty(params, lngField)) {
    // get coordinates from address
    this.getCoordinatesForAddress(this.getNestedProperty(params, addressField), function (err, data) {
      if (err) {
        return callback(err);
      }

      console.log(data)
      this.removeNestedProperty(params, addressField);
      this.setNestedProperty(params, latField, data.lat);
      this.setNestedProperty(params, lngField, data.lng);

      return callback(null, params);
    }.bind(this));
  } else {
    return callback(null, params);
  }
};

Uber.prototype.getAuthorizeUrl = function getAuthorizeUrl(scope) {
  if (!Array.isArray(scope)) {
    return new Error('Scope is not an array');
  }
  if (scope.length === 0) {
    return new Error('Scope is empty');
  }

  return this.oauth2.getAuthorizeUrl({ response_type: 'code', redirect_uri: this.defaults.redirect_uri, scope: scope.join(' ') });
};

Uber.prototype.authorization = function authorization(options, callback) {
  var self = this;
  var grantType = '';
  var code = '';
  var nD = null;

  if (options.hasOwnProperty('authorization_code')) {
    grantType = 'authorization_code';
    code = options.authorization_code;
  } else if (options.hasOwnProperty('refresh_token')) {
    grantType = 'refresh_token';
    code = options.refresh_token;
  } else {
    return callback(new Error('No authorization_code or refresh_token'));
  }

  this.oauth2.getOAuthAccessToken(code, {
    client_id: this.defaults.client_id,
    client_secret: this.defaults.client_secret,
    redirect_uri: this.defaults.redirect_uri,
    grant_type: grantType
  }, function (err, access_token, refresh_token, results) {
    if (err) {
      return callback(err);
    } else {
      self.access_token = access_token;
      self.refresh_token = refresh_token;
      // store auth scopes
      self.authorizedScopes = results.scope;
      // store expiration date
      nD = new Date();
      // expires value indicates seconds
      nD.setSeconds(nD.getSeconds() + results.expires_in);
      self.tokenExpiration = nD;
      return callback(null, [self.access_token, self.refresh_token, self.authorizedScopes, self.tokenExpiration]);
    }
  });

  return self;
};

Uber.prototype.authorizationAsync = Promise.promisify(Uber.prototype.authorization);

Uber.prototype.delete = function (options, callback) {
  return this.modifierMethodHelper(options, callback, 'delete');
};

Uber.prototype.patch = function patch(options, callback) {
  return this.modifierMethodHelper(options, callback, 'patch');
};

Uber.prototype.post = function post(options, callback) {
  return this.modifierMethodHelper(options, callback, 'post');
};

Uber.prototype.put = function put(options, callback) {
  return this.modifierMethodHelper(options, callback, 'put');
};

Uber.prototype.modifierMethodExecute = function modifierMethodExecute(method, params, callback) {
  if (this.defaults.proxy) {
    params.agent = new ProxyAgent(this.defaults.proxy);
  }

  switch (method) {
    case 'delete':
      request.delete(params, callback);
      break;
    case 'post':
      request.post(params, callback);
      break;
    case 'put':
      request.put(params, callback);
      break;
    case 'patch':
      request.patch(params, callback);
      break;
  }
};

Uber.prototype.modifierMethodHelper = function modifierMethodHelper(options, callback, method) {
  var access_type;
  var self = this;
  var localCallback = function localCallback(err, data, res) {
    // shared callback between put, post, patch, and delete requests
    if (err || data.statusCode >= 400) {
      return callback(((err)
        ? err
        : 'HTTP Response with error code: ' + data.statusCode), data);
    } else {
      return callback(null, res);
    }
  };
  var refreshCallback = function refreshCallback() {
    if (!self.checkScopes(options)) {
      return callback(new Error('Required scope not found'));
    }

    // remove scope parameter from options
    delete options.scope;

    var params = {
      url: self.getRequestURL(options.version, options.url),
      json: true,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': access_type,
        'Accept-Language': self.defaults.language
      },
      body: ((options.params)
        ? options.params
        : '')
    };

    self.modifierMethodExecute(method, params, localCallback);

    return self;
  };
  if (options && options.server_token) {
    access_type = 'Token ' + this.defaults.server_token;
    refreshCallback();
  } else {
    if (!this.access_token) {
      return callback(new Error('Invalid access token'));
    } else {
      // defaults to OAuth with access_token
      // auto renew if required
      if (this.isTokenStale()) {
        this.authorization({
          refresh_token: this.refresh_token
        }, function (err, res) {
          if (err) {
            return callback(err);
          } else {
            access_type = 'Bearer ' + res[0];
            refreshCallback();
          }
        });
      } else {
        access_type = 'Bearer ' + this.access_token;
        refreshCallback();
      }
    }
  }
};

Uber.prototype.createAccessHeader = function createAccessHeader(server_token) {
  var access_type;

  if (server_token) {
    access_type = 'Token ' + this.defaults.server_token;
  } else {
    if (this.access_token) {
      access_type = 'Bearer ' + this.access_token;
    }
  }

  return access_type;
};

Uber.prototype.get = function get(options, callback) {
  var access_type = this.createAccessHeader(options.server_token);
  if (!access_type) {
    return callback(new Error('Invalid access token'), 'A valid access token is required for this request');
  }
  var url = this.getRequestURL(options.version, options.url);

  if (!this.checkScopes(options)) {
    return callback(new Error('Required scope not found'));
  }

  // remove scope parameter from options
  delete options.scope;

  // add all further option params
  if (options.params) {
    url += '?' + qs.stringify(options.params);
  }

  var reqOptions = {
    url: url,
    json: true,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': access_type,
      'Accept-Language': this.defaults.language
    }
  };
  if (this.defaults.proxy) {
    reqOptions.agent = new ProxyAgent(this.defaults.proxy);
  }

  request.get(reqOptions, function (err, data, res) {
    if (err || data.statusCode >= 400) {
      return callback((err
        ? err
        : data), res);
    } else {
      return callback(null, res);
    }
  });

  return this;
};

Uber.prototype.checkScopes = function checkScopes(options) {
  if (!options || !options.scope) {
    // checking scopes is not relevant
    return true;
  }

  // check if options.scope is array
  if (options.scope && Array === options.scope.constructor) {
    var regExp;
    for (var i = 0; i < options.scope.length; i++) {
      // regEx is required to avoid mismatch between
      // request and request_receipt
      regExp = new RegExp('\\b' + options.scope[i] + '\\b', 'gi');
      if (regExp.test(this.authorizedScopes)) {
        return true;
      }
    }
    return false;
  } else {
    if (this.authorizedScopes.indexOf(options.scope) > -1) {
      return true;
    } else {
      return false;
    }
  }
};

Uber.prototype.revokeToken = function revokeToken(token, callback) {
  if (typeof token !== "string" || token.length === 0) {
    return callback(new Error('Passed token is not acceptable'));
  }

  request.post(this.defaults.revoke_token_url, {
    form: {
      client_id: this.defaults.client_id,
      client_secret: this.defaults.client_secret,
      token: token
    }
  }, function (err, res, body) {
    if (err) {
      return callback(err);
    }

    return callback(null, res);
  });
};

Uber.prototype.revokeTokenAsync = Promise.promisify(Uber.prototype.revokeToken);

Uber.prototype.clearTokens = function clearTokens() {
  this.access_token = null;
  this.refresh_token = null;
  this.tokenExpiration = null;
  this.authorizedScopes = null;
};

Uber.prototype.setTokens = function setTokens(access_token, refresh_token, tokenExpiration, authorizedScopes) {
  this.access_token = access_token;
  this.refresh_token = refresh_token;
  this.tokenExpiration = tokenExpiration;
  this.authorizedScopes = authorizedScopes;
}

Uber.prototype.isNumeric = function isNumeric(input) {
  return (!input || isNaN(input))
    ? false
    : true;
};

Uber.prototype.hasOwnNestedProperty = function hasOwnNestedProperty(obj, key) {
  return key.split('.').every(function (x) {
    if (typeof obj !== 'object' || obj === null || !(x in obj))
      return false;
    obj = obj[x];
    return true;
  });
};

Uber.prototype.getNestedProperty = function getNestedProperty(obj, key) {
  return key.split(".").reduce(function (o, x) {
    return (typeof o === 'undefined' || o === null)
      ? o
      : o[x];
  }, obj);
};

Uber.prototype.removeNestedProperty = function removeNestedProperty(obj, key) {
  var props = key.split('.');
  var propName = props[props.length - 1];
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      if (p === propName) {
        delete obj[p];
      } else if (typeof obj[p] === 'object') {
        this.removeNestedProperty(obj[p], propName);
      }
    }
  }
  return obj;
};

Uber.prototype.setNestedProperty = function setNestedProperty(obj, key, value) {
  var schema = obj;
  var pList = key.split('.');
  var len = pList.length;
  for (var i = 0; i < len - 1; i++) {
    var elem = pList[i];
    schema = schema[elem];
  }

  schema[pList[len - 1]] = value;
};

Uber.prototype.getRequestURL = function getRequestURL(version, url) {
  return this.defaults.base_url + (version
    ? version
    : this.defaults.base_version) + '/' + url;
};

Uber.prototype.isTokenStale = function isTokenStale() {
  var nD = new Date();
  var threshold = 500;
  nD.setSeconds(nD.getSeconds() + threshold);
  return nD > this.tokenExpiration;
};

Uber.prototype.isSurge = function isSurge(err) {
  return err.hasOwnProperty('surge_confirmation');
};


================================================
FILE: lib/resources/drivers/PartnerPayments.js
================================================
function PartnerPayments(uber) {
  this._uber = uber;
  this.path = 'partners/payments';
  this.requiredScope = 'partner.payments';
}

module.exports = PartnerPayments;

PartnerPayments.prototype.getPayments = function getPayments(off, lim, from, to, callback) {
  var newOffset = off || 0;
  // ensure query limit is set. Maximum is 50. Default is 5.
  var newLimit = (lim)
    ? Math.min(lim, 50)
    : 5;

  var params = {
    offset: newOffset,
    limit: newLimit
  };

  if (parseInt(from, 10) > 0) {
    params['from_time'] = from;
  }

  if (parseInt(to, 10) > 0) {
    params['to_time'] = to;
  }

  return this._uber.get({
    url: this.path,
    version: 'v1',
    params: params,
    scope: this.requiredScope
  }, callback);
};


================================================
FILE: lib/resources/drivers/PartnerProfile.js
================================================
function PartnerProfile(uber) {
  this._uber = uber;
  this.path = 'partners/me';
  this.requiredScope = 'partner.accounts';
}

module.exports = PartnerProfile;

PartnerProfile.prototype.getProfile = function getProfile(callback) {
  return this._uber.get({
    url: this.path,
    version: 'v1',
    scope: this.requiredScope
  }, callback);
};


================================================
FILE: lib/resources/drivers/PartnerTrips.js
================================================
function PartnerTrips(uber) {
  this._uber = uber;
  this.path = 'partners/trips';
  this.requiredScope = 'partner.trips';
}

module.exports = PartnerTrips;

PartnerTrips.prototype.getTrips = function getTrips(off, lim, from, to, callback) {
  var newOffset = off || 0;
  // ensure query limit is set. Maximum is 50. Default is 5.
  var newLimit = (lim)
    ? Math.min(lim, 50)
    : 5;

  var params = {
    offset: newOffset,
    limit: newLimit
  };

  if (parseInt(from, 10) > 0) {
    params['from_time'] = from;
  }

  if (parseInt(to, 10) > 0) {
    params['to_time'] = to;
  }

  return this._uber.get({
    url: this.path,
    version: 'v1',
    params: params,
    scope: this.requiredScope
  }, callback);
};


================================================
FILE: lib/resources/riders/Estimates.js
================================================
function Estimates(uber) {
    this._uber = uber;
    this.path = 'estimates';
}

module.exports = Estimates;

Estimates.prototype.getPriceForRouteByAddress = function getPriceForRouteByAddress(startAddress, endAddress, seats, callback) {
    this._uber.getCoordinatesForAddress(startAddress, function(err, startData) {
        if(err) {
            // check first if seats (optional) is provided
            return (typeof seats === 'function' ? seats(err) : callback(err));
        }

        this._uber.getCoordinatesForAddress(endAddress, function(err2, endData) {
            if(err2) {
                return (typeof seats === 'function' ? seats(err2) : callback(err2));
            }

            return this.getPriceForRoute(
                startData.lat,
                startData.lng,
                endData.lat,
                endData.lng,
                seats,
                callback
            );
        }.bind(this));
    }.bind(this));
};

Estimates.prototype.getPriceForRoute = function getPriceForRoute(startLat,
    startLon, endLat, endLon, seats, callback) {
    // seats is optional
    if (typeof seats === 'function') {
        callback = seats;
        // set to the default of 2 seats
        seats = 2;
    }

    if (!startLat || !startLon) {
        return callback(new Error('Invalid starting point latitude & longitude'));
    }

    if (!endLat || !endLon) {
        return callback(new Error('Invalid ending point latitude & longitude'));
    }

    if (!this._uber.isNumeric(seats)) {
        seats = 2;
    }

    return this._uber.get({
        url: this.path + '/price',
        params: {
            start_latitude: startLat,
            start_longitude: startLon,
            end_latitude: endLat,
            end_longitude: endLon,
            seat_count: seats
        },
        server_token: true
    }, callback);
};

Estimates.prototype.getETAForAddress = function getETAForAddress(address, id, callback) {
    this._uber.getCoordinatesForAddress(address, function(err, data) {
        if(err) {
            // check first if ID (optional) is provided
            return (typeof id === 'function' ? id(err) : callback(err));
        }

        return this.getETAForLocation(
            data.lat,
            data.lng,
            id,
            callback
        );
    }.bind(this));
};

Estimates.prototype.getETAForLocation = function getETAForLocation(lat, lon, id, callback) {
    if (typeof id === 'function') {
        callback = id;
        id = undefined;
    }

    if (!lat || !lon) {
        return callback(new Error('Invalid latitude & longitude'));
    }

    // add optional product_id in case it's set
    var par = (id && id !== '') ? {
        start_latitude: lat,
        start_longitude: lon,
        product_id: id
    } : {
        start_latitude: lat,
        start_longitude: lon
    };

    return this._uber.get({
        url: this.path + '/time',
        params: par,
        server_token: true
    }, callback);
};


================================================
FILE: lib/resources/riders/Payment.js
================================================
function Payment(uber) {
    this._uber = uber;
    this.path = 'payment-methods';
    this.requiredScope = 'request';
}

module.exports = Payment;

Payment.prototype.getMethods = function getMethods(callback) {
    return this._uber.get({
        url: this.path,
        scope: this.requiredScope
    }, callback);
};


================================================
FILE: lib/resources/riders/Places.js
================================================
function Places(uber) {
  this._uber = uber;
  this.path = 'places';
  this.requiredScope = 'places';
}

module.exports = Places;

Places.prototype.getByID = function getByID(id, callback) {
  if (!id) {
    return callback(new Error('Invalid place_id'));
  }

  // as long as only two ids are allowed
  if (id !== 'home' && id !== 'work') {
    return callback(new Error('place_id needs to be either "home" or "work"'));
  }

  var options = {
    url: this.path + '/' + id,
    scope: this.requiredScope
  };

  return this._uber.get(options, callback);
};

Places.prototype.getHome = function getHome(callback) {
  return this.getByID('home', callback);
};

Places.prototype.getWork = function getWork(callback) {
  return this.getByID('work', callback);
};

Places.prototype.updateByID = function updateByID(id, newAddress, callback) {
  if (!id) {
    return callback(new Error('Invalid place_id'));
  }

  // as long as only two ids are allowed
  if (id !== 'home' && id !== 'work') {
    return callback(new Error('place_id needs to be either "home" or "work"'));
  }

  if (!newAddress) {
    return callback(new Error('Invalid address'));
  }

  return this._uber.put({
    url: this.path + '/' + id,
    params: { address: newAddress },
    scope: this.requiredScope
  }, callback);
};

Places.prototype.updateHome = function updateHome(newAddress, callback) {
  return this.updateByID('home', newAddress, callback);
};

Places.prototype.updateWork = function updateWork(newAddress, callback) {
  return this.updateByID('work', newAddress, callback);
};


================================================
FILE: lib/resources/riders/Products.js
================================================
function Products(uber) {
    this._uber = uber;
    this.path = 'products';
}

module.exports = Products;

Products.prototype.getAllForAddress = function getAllForAddress(address, callback) {
    this._uber.getCoordinatesForAddress(address, function(err, data) {
        if(err) {
            return callback(err);
        }

        return this.getAllForLocation(
            data.lat,
            data.lng,
            callback
        );
    }.bind(this));
};

Products.prototype.getAllForLocation = function getAllForLocation(lat, lon, callback) {
    if (!lat || !lon) {
        return callback(new Error('Invalid latitude & longitude'));
    }

    return this._uber.get({
        url: this.path,
        params: {
            latitude: lat,
            longitude: lon
        },
        server_token: true
    }, callback);
};

Products.prototype.getByID = function getByID(id, callback) {
    if (!id) {
        return callback(new Error('Missing product_id parameter'));
    }

    return this._uber.get({
        url: this.path + '/' + id,
        server_token: true
    }, callback);
};

Products.prototype.setSurgeMultiplierByID = function setSurgeMultiplierByID(id, multiplier, callback) {
    if (!id) {
        return callback(new Error('Invalid product_id'));
    }

    if (this._uber.sandbox) {
        if (!this._uber.isNumeric(multiplier)) {
            return callback(new Error('Invalid surge multiplier'));
        } else {
            return this._uber.put({
                // this is required only for the PUT method
                url: 'sandbox/' + this.path + '/' + id,
                params: {
                    surge_multiplier: parseFloat(multiplier)
                },
                server_token: true
            }, callback);
        }
    } else {
        return callback(new Error('Setting surge multiplier is only allowed in Sandbox mode'));
    }
};

Products.prototype.setDriversAvailabilityByID = function setDriversAvailabilityByID(id, availability, callback) {
    if (!id) {
        return callback(new Error('Invalid product_id'));
    }

    if (this._uber.sandbox) {
        if (typeof availability !== 'boolean') {
            return callback(new Error('Availability needs to be a boolean'));
        } else {
            return this._uber.put({
                // this is required only for the PUT method
                url: 'sandbox/' + this.path + '/' + id,
                params: {
                    drivers_available: availability
                },
                server_token: true
            }, callback);
        }
    } else {
        return callback(new Error('Setting driver`s availability is only allowed in Sandbox mode'));
    }
};


================================================
FILE: lib/resources/riders/Requests.js
================================================
function Requests(uber) {
    this._uber = uber;
    this.path = 'requests';
    this.requiredScope = ['request', 'all_trips', 'request_receipt'];
}

module.exports = Requests;

Requests.prototype.create = function create(parameters, callback) {
    var self = this;
    if (!parameters) {
        return callback(new Error('Invalid parameters'));
    }
    function localCallback(err, res) {
        if (!err) {
            return callback(err, res);
        } else if (!res) {
            return callback(err, res);
        }
        else if (res.statusCode === 409 && res.body.hasOwnProperty('meta')) {
            var meta = res.body.meta;
            if (meta.hasOwnProperty('surge_confirmation')) {
                var serr = {};
                serr.message = err;
                serr.surge_confirmation = meta.surge_confirmation;
                parameters.surge_confirmation_id = meta.surge_confirmation.surge_confirmation_id;
                self._uber.currentRequestParameters = parameters;
                return callback(serr, res);
            } else {
                return callback(err, res);
            }
        }
    }
    // replace addresses with node-geocoder coordinates if provided
    this._uber
        .replaceAddressWithCoordinates(
            parameters,
            'startAddress',
            'start_latitude',
            'start_longitude',
            function(startErr, startData) {
                if (startErr) {
                    return callback(startErr);
                }

                this._uber
                    .replaceAddressWithCoordinates(
                        startData,
                        'endAddress',
                        'end_latitude',
                        'end_longitude',
                        function(endErr, endData) {
                            if (endErr) {
                                return callback(endErr);
                            }
                            return this._uber.post({
                                url: this.path,
                                params: endData,
                                scope: this.requiredScope[0]
                            }, localCallback);
                        }.bind(this)
                    );
            }.bind(this)
        );
};

Requests.prototype.acceptSurgeForLastRequest = function acceptSurgeForLastRequest(callback) {
  if (! this._uber.hasOwnProperty('currentRequestParameters')) {
      return callback('No active request found for this session', null);
  } else {
      var params = JSON.parse(JSON.stringify(this._uber.currentRequestParameters));
      // invalidate session
      delete this._uber.currentRequestParameters;
      return this._uber.post({
          url: this.path,
          params: params,
          scope: this.requiredScope[0]
      }, callback);
  }
};

Requests.prototype.getCurrent = function getCurrent(callback) {
    return this.getByID('current', callback);
};

Requests.prototype.getByID = function getByID(id, callback) {
    if (!id) {
        return callback(new Error('Invalid request_id'));
    }

    return this._uber.get({
        url: this.path + '/' + id,
        scope: [this.requiredScope[0], this.requiredScope[1]]
    }, callback);
};

Requests.prototype.getMapByID = function getMapByID(id, callback) {
    if (!id) {
        return callback(new Error('Invalid request_id'));
    }

    return this._uber.get({
        url: this.path + '/' + id + '/map',
        scope: this.requiredScope[0]
    }, callback);
};

Requests.prototype.getReceiptByID = function getReceiptByID(id, callback) {
    if (!id) {
        return callback(new Error('Invalid request_id'));
    }

    return this._uber.get({
        url: this.path + '/' + id + '/receipt',
        scope: this.requiredScope[2]
    }, callback);
};

Requests.prototype.updateCurrent = function updateCurrent(parameters, callback) {
    if (!parameters) {
        return callback(new Error('Invalid parameters'));
    }

    return this.updateByID('current', parameters, callback);
};

Requests.prototype.updateByID = function updateByID(id, parameters, callback) {
    if (!id) {
        return callback(new Error('Invalid request_id'));
    }

    if (!parameters) {
        return callback(new Error('Invalid parameters'));
    }

    // replace addresses with node-geocoder coordinates if provided
    this._uber
        .replaceAddressWithCoordinates(
            parameters,
            'startAddress',
            'start_latitude',
            'start_longitude',
            function(startErr, startData) {
                if (startErr) {
                    return callback(startErr);
                }

                this._uber
                    .replaceAddressWithCoordinates(
                        startData,
                        'endAddress',
                        'end_latitude',
                        'end_longitude',
                        function(endErr, endData) {
                            if (endErr) {
                                return callback(endErr);
                            }

                            return this._uber.patch({
                                url: this.path + '/' + id,
                                params: endData,
                                scope: this.requiredScope[0]
                            }, callback);
                        }.bind(this)
                    );
            }.bind(this)
        );
};

Requests.prototype.setStatusByID = function setStatusByID(id, newSatus, callback) {
    if (!this._uber.sandbox) {
        return callback(new Error('PUT method for requests is only allowed in Sandbox mode'));
    }

    if (!id) {
        return callback(new Error('Invalid request_id'));
    }

    if (!newSatus) {
        return callback(new Error('Invalid status'));
    }

    return this._uber.put({
            // this is required only for the PUT method
            url: 'sandbox/' + this.path + '/' + id,
            params: {
                status: newSatus
            },
            scope: this.requiredScope[0]
        },
        callback);
};

Requests.prototype.deleteCurrent = function deleteCurrent(callback) {
    return this.deleteByID('current', callback);
};

Requests.prototype.deleteByID = function deleteByID(id, callback) {
    if (!id) {
        return callback(new Error('Invalid request_id'));
    }

    return this._uber.delete({
        url: this.path + '/' + id,
        scope: this.requiredScope[0]
    }, callback);
};

Requests.prototype.getEstimates = function getEstimates(parameters, callback) {
    if (!parameters) {
        return callback(new Error('Invalid parameters'));
    }

    // replace addresses with node-geocoder coordinates if provided
    this._uber
        .replaceAddressWithCoordinates(
            parameters,
            'startAddress',
            'start_latitude',
            'start_longitude',
            function(startErr, startData) {
                if (startErr) {
                    return callback(startErr);
                }

                this._uber
                    .replaceAddressWithCoordinates(
                        startData,
                        'endAddress',
                        'end_latitude',
                        'end_longitude',
                        function(endErr, endData) {
                            if (endErr) {
                                return callback(endErr);
                            }

                            return this._uber.post({
                                url: this.path + '/estimate',
                                params: endData,
                                scope: this.requiredScope[0]
                            }, callback);
                        }.bind(this)
                    );
            }.bind(this)
        );
};


================================================
FILE: lib/resources/riders/User.js
================================================
function User(uber) {
  this._uber = uber;
  this.path = ['me', 'history'];
  this.requiredScope = ['profile', 'history', 'history_lite'];
}

module.exports = User;

User.prototype.getHistory = function getHistory(off, lim, callback) {
  var newOffset = off || 0;
  // ensure query limit is set. Maximum is 50. Default is 5.
  var newLimit = (lim) ? Math.min(lim, 50) : 5;

  return this._uber.get({
    url: this.path[1],
    params: { offset: newOffset, limit: newLimit },
    scope: [this.requiredScope[1], this.requiredScope[2]]
  }, callback);
};

User.prototype.getProfile = function getProfile(callback) {
  return this._uber.get({
    url: this.path[0],
    scope: this.requiredScope[0]
  }, callback);
};

User.prototype.applyPromo = function applyPromo(promo, callback) {
  return this._uber.patch({
    url: this.path[0],
    params: { applied_promotion_codes: promo },
    scope: this.requiredScope[0]
  }, callback);
}


================================================
FILE: package.json
================================================
{
  "name": "node-uber",
  "version": "2.0.0",
  "description": "A Node.js wrapper for Uber API",
  "main": "index.js",
  "scripts": {
    "test": "gulp"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/shernshiou/node-uber.git"
  },
  "author": {
    "name": "Shern Shiou Tan",
    "email": "shernshiou@gmail.com",
    "url": "http://blog.shernshiou.com"
  },
  "contributors": [
    {
      "name": "Alexander Graebe",
      "email": "alex.graebe@gmail.com",
      "url": "https://twitter.com/agraebe"
    }
  ],
  "license": "MIT",
  "dependencies": {
    "bluebird": "^3.4.7",
    "node-geocoder": "^3.22.0",
    "oauth": "^0.9.15",
    "proxy-agent": "^2.0.0",
    "request": "^2.79.0"
  },
  "devDependencies": {
    "chai": "^4.1.2",
    "codeclimate-test-reporter": "^0.5.0",
    "gulp": "^3.9.1",
    "gulp-eslint": "^4.0.0",
    "gulp-istanbul": "^1.1.2",
    "gulp-mocha": "^3.0.1",
    "gulp-util": "^3.0.8",
    "istanbul": "^0.4.5",
    "mocha": "^3.5.3",
    "nock": "^9.0.14",
    "sinon": "^3.2.1",
    "sinon-chai": "^2.13.0",
    "superagent": "^3.6.0"
  },
  "engines": {
    "node": ">6.10",
    "npm": ">3.10.10"
  }
}


================================================
FILE: test/allTests.js
================================================
var common = require("./common"),
    nock = common.nock,
    jp = common.jsonReplyPath,
    key = common.key,
    jr = common.jsonReply,
    ac = common.authCode,
    acNP = common.authCodeNoProfile,
    acNPl = common.authCodeNoPlaces,
    acNR = common.authCodeNoRequest,
    acTE = common.authCodeTokenExpired,
    acTR = common.authCodeTokenRefresh,
    acTNR = common.authCodeTokenNoRefresh,
    acRTE = common.authCodeRefreshTokenError,
    rPC = common.requestProductCreate,
    rPS = common.requestProductSurge,
    rSC = common.requestSurgeConfirmationID,
    rPSOE = common.requestProductSomeOtherError;
function importTest(name, path) {
    describe(name, function() {
        before(function() {
            defineNocks();
        });
        require(path);
    });
}

describe("Running all tests ...", function() {
    importTest("Uber client general tests", './general');
    // Auth
    importTest("OAuth2 authorization methods", './auth/oauth');
    importTest("OAuth2 authorization methods (Async)", './auth/oauthAsync');
    // Riders
    importTest("/Estimates", './riders/estimates');
    importTest("/Estimates (Async)", './riders/estimatesAsync');
    importTest("/Payment-Methods", './riders/payment-methods');
    importTest("/Payment-Methods (Async)", './riders/payment-methodsAsync');
    importTest("/Places", './riders/places');
    importTest("/Places (Async)", './riders/placesAsync');
    importTest("/Products", './riders/products');
    importTest("/Products (Async)", './riders/productsAsync');
    importTest("/Requests", './riders/requests');
    importTest("/Requests (Async)", './riders/requestsAsync');
    importTest("/User", './riders/user');
    importTest("/User (Async)", './riders/userAsync');
    // Drivers
    importTest("/Partners/Me", './drivers/profile');
    importTest("/Partner/Me (Async)", './drivers/profileAsync');
    importTest("/Partners/Payments", './drivers/payments');
    importTest("/Partner/Payments (Async)", './drivers/paymentsAsync');
    importTest("/Partners/Trips", './drivers/trips');
    importTest("/Partner/Trips (Async)", './drivers/tripsAsync');
});

defineNocks = function() {
    // Login
    nock('https://login.uber.com')
        .persist()
        .post('/oauth/v2/revoke')
        .reply(200)
        .post('/oauth/v2/token', {
            code: ''
        })
        .reply(500)
        .post('/oauth/v2/token', {
            code: ac
        })
        .replyWithFile(200, jp('auth/token'))
        .post('/oauth/v2/token', {
            refresh_token: ac
        })
        .replyWithFile(200, jp('auth/token'))
        .post('/oauth/v2/token', {
            code: acNP
        })
        .replyWithFile(200, jp('auth/tokenNoProfile'))
        .post('/oauth/v2/token', {
            code: acNPl
        })
        .replyWithFile(200, jp('auth/tokenNoPlaces'))
        .post('/oauth/v2/token', {
            code: acNR
        })
        .replyWithFile(200, jp('auth/tokenNoRequest'))
        .post('/oauth/v2/token', {
            code: acTE
        })
        .replyWithFile(200, jp('auth/tokenExpired'))
        .post('/oauth/v2/token', {
            refresh_token: acTR
        })
        .replyWithFile(200, jp('auth/tokenRefreshed'))
        .post('/oauth/v2/token', {
            code: acTNR
        })
        .replyWithFile(200, jp('auth/tokenNoRefresh'))
        .post('/oauth/v2/token', {
            refresh_token: acRTE
        })
        .reply(500);

    // Endpoints accessible with OAuth2 Token
    nock('https://api.uber.com', {
            reqheaders: {
                'Authorization': 'Bearer ' + jr('auth/token').access_token
            }
        })
        .persist()
        // Payment-Methods
        .get('/v1.2/payment-methods')
        .replyWithFile(200, jp('riders/paymentMethod'))
        // Places
        .get('/v1.2/places/home')
        .replyWithFile(200, jp('riders/placeHome'))
        .put('/v1.2/places/home')
        .replyWithFile(200, jp('riders/placeHome'))
        .get('/v1.2/places/work')
        .replyWithFile(200, jp('riders/placeWork'))
        .put('/v1.2/places/work')
        .replyWithFile(200, jp('riders/placeWork'))
        .get('/v1.2/places/shop')
        .reply(404)
        .put('/v1.2/places/shop')
        .reply(404)
        // User
        .get('/v1.2/me')
        .replyWithFile(200, jp('riders/profile'))
        .patch('/v1.2/me', {
            applied_promotion_codes: 'FREE_RIDEZ'
        })
        .replyWithFile(200, jp('riders/profilePromoSuccess'))
        .patch('/v1.2/me', {
            applied_promotion_codes: 'already-used-code'
        })
        .replyWithFile(400, jp('riders/profilePromoError'))
        .get(function(uri) {
            var parts = uri.split('/v1.2/history?offset=0&limit=');
            if (parts.length !== 2) {
                return false;
            }
            // range should be between 1 and 50
            return (parts[1] > 0 && parts[1] <= 50);
        })
        .replyWithFile(200, jp('riders/history'))
        // Requests
        .get('/v1.2/requests/current')
        .replyWithFile(200, jp('riders/requestAccept'))
        .post('/v1.2/requests', {
            product_id : rPC
        })
        .replyWithFile(200, jp('riders/requestCreate'))
        .post('/v1.2/requests', {
            product_id : rPS,
            surge_confirmation_id : rSC
        })
        .replyWithFile(200, jp('riders/requestCreate'))
        .post('/v1.2/requests', {
            product_id : rPS
        })
        .replyWithFile(409, jp('riders/requestSurge'))
        .post('/v1.2/requests', {
            product_id : rPSOE
        })
        .replyWithFile(409, jp('riders/requestFareExpired'))
        .patch('/v1.2/requests/current')
        .reply(204)
        .delete('/v1.2/requests/current')
        .reply(204)
        .post('/v1.2/requests/estimate')
        .replyWithFile(200, jp('riders/requestEstimate'))
        .get('/v1.2/requests/17cb78a7-b672-4d34-a288-a6c6e44d5315')
        .replyWithFile(200, jp('riders/requestAccept'))
        .patch('/v1.2/requests/abcd')
        .reply(404)
        .get('/v1.2/requests/abcd')
        .reply(404)
        .patch('/v1.2/requests/17cb78a7-b672-4d34-a288-a6c6e44d5315')
        .reply(204)
        .delete('/v1.2/requests/17cb78a7-b672-4d34-a288-a6c6e44d5315')
        .reply(204)
        .get('/v1.2/requests/17cb78a7-b672-4d34-a288-a6c6e44d5315/map')
        .replyWithFile(200, jp('riders/requestMap'))
        .get('/v1.2/requests/17cb78a7-b672-4d34-a288-a6c6e44d5315/receipt')
        .replyWithFile(200, jp('riders/requestReceipt'))
        // Driver Partners
        .get('/v1/partners/me')
        .replyWithFile(200, jp('drivers/partnerProfile'))
        .get('/v1/partners/payments?offset=0&limit=5&from_time=1451606400&to_time=1505160819')
        .replyWithFile(200, jp('drivers/partnerPayments'))
        .get('/v1/partners/payments?offset=0&limit=50&from_time=1451606400&to_time=1505160819')
        .replyWithFile(200, jp('drivers/partnerPayments'))
        .get('/v1/partners/payments?offset=0&limit=5')
        .replyWithFile(200, jp('drivers/partnerPayments'))
        .get('/v1/partners/trips?offset=0&limit=5&from_time=1451606400&to_time=1505160819')
        .replyWithFile(200, jp('drivers/partnerTrips'))
        .get('/v1/partners/trips?offset=0&limit=50&from_time=1451606400&to_time=1505160819')
        .replyWithFile(200, jp('drivers/partnerTrips'))
        .get('/v1/partners/trips?offset=0&limit=5')
        .replyWithFile(200, jp('drivers/partnerTrips'));


    // Endpoints accessible with server_token
    nock('https://api.uber.com', {
            reqheaders: {
                'Authorization': 'Token ' + key.server_token
            }
        })
        .persist()
        //Estimates
        .get('/v1.2/estimates/price?start_latitude=3.1357169&start_longitude=101.6881501&end_latitude=3.0831659&end_longitude=101.6505078&seat_count=2')
        .replyWithFile(200, jp('riders/price'))
        .get(function(uri) {
            return uri.indexOf('v1.2/estimates/time?start_latitude=3.1357169&start_longitude=101.6881501') >= 0;
        })
        .replyWithFile(200, jp('riders/time'))
        // Products
        .get('/v1.2/products?latitude=3.1357169&longitude=101.6881501')
        .replyWithFile(200, jp('riders/product'))
        .get('/v1.2/products/d4abaae7-f4d6-4152-91cc-77523e8165a4')
        .replyWithFile(200, jp('riders/productDetail'));

    // Endpoints for sandbox mode with server_token
    nock('https://sandbox-api.uber.com', {
            reqheaders: {
                'Authorization': 'Token ' + key.server_token
            }
        })
        .persist()
        .put('/v1.2/sandbox/products/d4abaae7-f4d6-4152-91cc-77523e8165a4', {
            surge_multiplier: 2.2
        })
        .reply(204)
        .put('/v1.2/sandbox/products/d4abaae7-f4d6-4152-91cc-77523e8165a4', {
            drivers_available: false
        })
        .reply(204);

    // Endpoints for sandbox mode with OAuth2 Token
    nock('https://sandbox-api.uber.com', {
            reqheaders: {
                'Authorization': 'Bearer ' + jr('auth/token').access_token
            }
        })
        .persist()
        .put('/v1.2/sandbox/requests/17cb78a7-b672-4d34-a288-a6c6e44d5315', {
            status: 'accepted'
        })
        .reply(204);

    // Geocoder
    nock('http://maps.googleapis.com')
        .persist()
        .get('/maps/api/geocode/json?sensor=false&address=A')
        .replyWithFile(200, jp('geocoder/locationA'))
        .get('/maps/api/geocode/json?sensor=false&address=B')
        .replyWithFile(200, jp('geocoder/locationB'))
        .get('/maps/api/geocode/json?sensor=false&address=C')
        .replyWithFile(200, jp('geocoder/locationC'))
        .get('/maps/api/geocode/json?sensor=false&address=%20')
        .replyWithFile(200, jp('geocoder/locationEmpty'));
};


================================================
FILE: test/auth/oauth.js
================================================
var common = require('../common'),
  should = common.should,
  qs = common.qs,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acTE = common.authCodeTokenExpired,
  acTNR = common.authCodeTokenNoRefresh;

describe('OAuth2 authorization url', function() {
  it('generate OAuth2 correct authorization url', function(done) {
    var allScopes = [
      'profile',
      'history',
      'places',
      'request',
      'request_receipt',
      'all_trips',
      'partner.payments',
      'partner.accounts',
      'partner.trips'
    ];
    var url = uber.getAuthorizeUrl(allScopes),
      sampleUrl = uber.defaults.authorize_url + '?' + qs.stringify({response_type: 'code', redirect_uri: uber.defaults.redirect_uri, scope: allScopes.join(' '), client_id: uber.defaults.client_id});
    url.should.equal(sampleUrl);
    done();
  });

  it('should return error if scope is not an array', function(done) {
    uber.getAuthorizeUrl().message.should.equal('Scope is not an array');
    done();
  });

  it('should return error if scope is not an empty array', function(done) {
    uber.getAuthorizeUrl([]).message.should.equal('Scope is empty');
    done();
  });
});

describe('Exchange authorization code into access token', function() {
  it('should be able to get access token and refresh token using authorization code', function(done) {
    uber.authorization({
      authorization_code: ac
    }, function(err, res) {
      should.not.exist(err);
      res[0].should.equal(reply('auth/token').access_token);
      res[1].should.equal(reply('auth/token').refresh_token);
      uber.access_token.should.equal(reply('auth/token').access_token);
      uber.refresh_token.should.equal(reply('auth/token').refresh_token);
      done();
    });
  });

  it('should able to get access token and refresh token using refresh token', function(done) {
    uber.authorization({
      refresh_token: 'x8Y6dF2qA6iKaTKlgzVfFvyYoNrlkp'
    }, function(err, res) {
      should.not.exist(err);
      res[0].should.equal(reply('auth/token').access_token);
      res[1].should.equal(reply('auth/token').refresh_token);
      uber.access_token.should.equal(reply('auth/token').access_token);
      uber.refresh_token.should.equal(reply('auth/token').refresh_token);
      done();
    });
  });

  it('should return error if there is no authorization_code or refresh_token', function(done) {
    uber.authorization({}, function(err, access_token, refresh_token) {
      err.message.should.equal('No authorization_code or refresh_token');
      done();
    });
  });

  it('should return error if uber auth service not reachable', function(done) {
    uber.authorization({
      authorization_code: ''
    }, function(err, access_token, refresh_token) {
      err.statusCode.should.equal(500);
      done();
    });
  });
});

describe('Auto refresh token whenever it is expired', function() {
  it('should be able to recognize an expired token and then auto refresh the token ', function(done) {
    uber.authorization({
      authorization_code: acTE
    }, function(err, res) {
      should.not.exist(err);
      uber.requests.create({
        product_id: 'a1111c8c-c720-46c3-8534-2fcdd730040d',
        start_latitude: 37.761492,
        start_longitude: -122.423941,
        end_latitude: 37.775393,
        end_longitude: -122.417546
      }, function(err, res) {
        should.not.exist(err);
        uber.tokenExpiration.should.be.above(new Date());
        done();
      });
    });
  });
  it('should return an error if the uber server is not available while refreshing token', function(done) {
    uber.authorization({
      authorization_code: acTNR
    }, function(err, res) {
      should.not.exist(err);
      uber.requests.create({
        product_id: 'a1111c8c-c720-46c3-8534-2fcdd730040d',
        start_latitude: 37.761492,
        start_longitude: -122.423941,
        end_latitude: 37.775393,
        end_longitude: -122.417546
      }, function(err, res) {
        should.exist(err);
        err.statusCode.should.equal(500);
        done();
      });
    });
  });
});

describe('Multi-user handling', function() {
  it('should set Uber tokens', function(done) {
    uber.setTokens(reply('auth/token').access_token, reply('auth/token').refresh_token, reply('auth/token').expires_in, reply('auth/token').scope);

    uber.access_token.should.equal(reply('auth/token').access_token);
    uber.refresh_token.should.equal(reply('auth/token').refresh_token);
    uber.tokenExpiration.should.equal(reply('auth/token').expires_in);
    uber.authorizedScopes.should.equal(reply('auth/token').scope);
    done();
  });

  it('should clear Uber tokens', function(done) {
    uber.setTokens(reply('auth/token').access_token, reply('auth/token').refresh_token, reply('auth/token').expires_in, reply('auth/token').scope);

    uber.clearTokens();

    should.not.exist(uber.access_token);
    should.not.exist(uber.refresh_token);
    should.not.exist(uber.tokenExpiration);
    should.not.exist(uber.authorizedScopes);

    done();
  });
});

describe('OAuth2 revokeToken', function() {
  it('should return error if token is empty', function(done) {
    uber.revokeToken('', function(err, res) {
      should.exist(err);
      done();
    });
  });

  it('should return error if token is not a string', function(done) {
    uber.revokeToken({
      a: 1
    }, function(err, res) {
      should.exist(err);
      done();
    });
  });

  it('should return success if token is revoked', function(done) {
    uber.revokeToken('my_access_token', function(err, res) {
      should.not.exist(err);
      should.exist(res);
      done();
    });
  });
});


================================================
FILE: test/auth/oauthAsync.js
================================================
var common = require('../common'),
  should = common.should,
  qs = common.qs,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acTE = common.authCodeTokenExpired,
  acTNR = common.authCodeTokenNoRefresh;

describe('Exchange authorization code into access token', function() {
  it('should be able to get access token and refresh token using authorization code', function(done) {
    uber.authorizationAsync({authorization_code: ac}).spread(function(access_token, refresh_token) {
      access_token.should.equal(reply('auth/token').access_token);
      refresh_token.should.equal(reply('auth/token').refresh_token);
      uber.access_token.should.equal(reply('auth/token').access_token);
      uber.refresh_token.should.equal(reply('auth/token').refresh_token);
    }).error(function(err) {
      should.not.exist(err);
    });
    done();
  });

  it('should able to get access token and refresh token using refresh token', function(done) {
    uber.authorizationAsync({refresh_token: 'x8Y6dF2qA6iKaTKlgzVfFvyYoNrlkp'}).spread(function(access_token, refresh_token) {
      access_token.should.equal(reply('auth/token').access_token);
      refresh_token.should.equal(reply('auth/token').refresh_token);
      uber.access_token.should.equal(reply('auth/token').access_token);
      uber.refresh_token.should.equal(reply('auth/token').refresh_token);
    }).error(function(err) {
      should.not.exist(err);
    });
    done();
  });

  it('should return error if there is no authorization_code or refresh_token', function(done) {
    uber.authorizationAsync({}).then(function(access_token, refresh_token) {
      should.not.exist(access_token);
      should.not.exist(refresh_token);
    }).error(function(err) {
      err.message.should.equal('No authorization_code or refresh_token');
    });
    done();
  });
});

describe('Auto refresh token whenever it is expired', function() {
  it('should be able to recognize an expired token and then auto refresh the token ', function(done) {
    uber.authorizationAsync({authorization_code: acTE}).then(function() {
      return uber.requests.createAsync({product_id: 'a1111c8c-c720-46c3-8534-2fcdd730040d', start_latitude: 37.761492, start_longitude: -122.423941, end_latitude: 37.775393, end_longitude: -122.417546});
    }).then(function(res) {
      res.should.deep.equal(reply('riders/requestCreate'));
      uber.tokenExpiration.should.be.above(new Date());
      done();
    });
  });
  it('should return an error if the uber server is not available while refreshing token', function(done) {
    uber.authorizationAsync({authorization_code: acTNR}).then(function() {
      return uber.requests.createAsync({product_id: 'a1111c8c-c720-46c3-8534-2fcdd730040d', start_latitude: 37.761492, start_longitude: -122.423941, end_latitude: 37.775393, end_longitude: -122.417546});
    }).then(function(res) {
      should.not.exist(res);
    }).error(function(err) {
      should.exist(err);
      err.statusCode.should.equal(500);
      done();
    });
  });
});

describe('OAuth2 revokeTokenAsync', function() {
  it('should return error if token is empty', function(done) {
    uber.revokeTokenAsync('').then(function(res) {
      should.not.exist(res);
    }).error(function(err) {
      should.exist(err);
      done();
    });
  });

  it('should return error if token is not a string', function(done) {
    uber.revokeTokenAsync({a: 1}).then(function(res) {
      should.not.exist(res);
    }).error(function(err) {
      should.exist(err);
      done();
    });
  });

  it('should return success if token is revoked', function(done) {
    uber.revokeTokenAsync('my_access_token').then(function(res) {
      should.exist(res);
    }).error(function(err) {
      should.not.exist(err);
      done();
    });
    done();
  });
});


================================================
FILE: test/common.js
================================================
var chai = require('chai'),
    nock = require('nock'),
    request = require('superagent'),
    should = chai.should(),
    qs = require('querystring'),
    Uber = require('../lib/Uber'),
    path = require('path'),
    fs = require('fs');

var key = {
    "client_id": "CLIENTIDCLIENTIDCLIENTIDCLIENT",
    "client_secret": "CLIENTSECRETCLIENTSECRETCLIENTSECRETCLIE",
    "server_token": "SERVERTOKENSERVERTOKENSERVERTOKENSERVERT",
    "redirect_uri": "http://localhost/callback",
    "google_maps_api_key": process.env.GOOGLE_MAPS_API_KEY,
    "name": "nodejs uber wrapper",
    "language": "en_US"
};

var uber = new Uber(key);

// uber instance for Sandbox mode
key.sandbox = true;
var uber_sandbox = new Uber(key);

// JSON path for reply files
jsonReplyPath = function(filename) {
    return path.join(__dirname, '/replies/' + filename + '.json');
}

// Load JSON file from replies folder for assertions
jsonReply = function(path) {
    return JSON.parse(fs.readFileSync(this.jsonReplyPath(path), 'utf8'));
}

exports.chai = chai;
exports.nock = nock;
exports.request = request;
exports.should = should;
exports.qs = qs;
exports.uber = uber;
exports.uber_sandbox = uber_sandbox;
exports.key = key;
exports.jsonReplyPath = jsonReplyPath;
exports.jsonReply = jsonReply;
exports.authCode = 'x8Y6dF2qA6iKaTKlgzVfFvyYoNrlkp';
exports.authCodeNoProfile = 'h6Y6dF2qA6iKaTKlgzVfFvyYoNrLK3';
exports.authCodeNoPlaces = 'j1P6dF2qA6iKaTKlgzVfFvyYoNrhU1';
exports.authCodeNoRequest = 'a0P6dK3oA6iKaTKlgzVfFvyYoNrfG5';
exports.authCodeTokenExpired = 'h0P6dK3aA6iKaTK4gzVfFvyYoNrfG5';
exports.authCodeTokenNoRefresh = 'm0P6dK3aTPiKaTK4gzVfFvyYoNrfG5';
exports.authCodeRefreshTokenError = 'Zxkcv8qdSRRseIVlshydoQ4wnZBehr';
exports.authCodeTokenRefresh = 'Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr';
exports.requestProductCreate = 'a1111c8c-c720-46c3-8534-2fcdd730040d';
exports.requestProductSurge = 'a1111c8c-c720-8150-8534-2fcdd730040d';
exports.requestProductSomeOtherError = 'a2341c8c-c720-8150-8534-2fcdd730040d';
exports.requestSurgeConfirmationID = 'e100a670';

================================================
FILE: test/drivers/payments.js
================================================
var common = require("../common"),
  should = common.should,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acNP = common.authCodeNoProfile;

it('should get driver partner payments after authentication', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnerpayments.getPayments(0, 50, 1451606400, 1505160819, function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerPayments'));
      done();
    });
  });
});

it('should get driver partner payments after authentication, even with a too high limit', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnerpayments.getPayments(0, 99, 1451606400, 1505160819, function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerPayments'));
      done();
    });
  });
});

it('should get driver partner payments after authentication without required parameters', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnerpayments.getPayments(null, null, null, null, function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerPayments'));
      done();
    });
  });
});

it('should return invalid access token error when no token found', function(done) {
  uber.clearTokens();
  uber.partnerpayments.getPayments(null, null, null, null, function(err, res) {
    err.message.should.equal('Invalid access token');
    done();
  });
});


================================================
FILE: test/drivers/paymentsAsync.js
================================================
var common = require("../common"),
  should = common.should,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acNP = common.authCodeNoProfile;

it('should get driver partner payments after authentication', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnerpayments.getPaymentsAsync(0, 50, 1451606400, 1505160819);
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerPayments'));
    done();
  });
});

it('should get driver partner payments after authentication, even with a too high limit', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnerpayments.getPaymentsAsync(0, 99, 1451606400, 1505160819);
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerPayments'));
    done();
  });
});

it('should get driver partner payments after authentication without required parameters', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnerpayments.getPaymentsAsync(null, null, null, null);
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerPayments'));
    done();
  });
});

it('should return invalid access token error when no token found', function(done) {
  uber.clearTokens();
  uber.partnerpayments.getPaymentsAsync(null, null, null, null).error(function(err) {
    err.message.should.equal('Invalid access token');
    done();
  });
});


================================================
FILE: test/drivers/profile.js
================================================
var common = require("../common"),
  should = common.should,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acNP = common.authCodeNoProfile;

it('should return invalid access token error when no token found', function(done) {
  uber.clearTokens();
  uber.partnerprofile.getProfile(function(err, res) {
    err.message.should.equal('Invalid access token');
    done();
  });
});

it('should get partner profile after authentication', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnerprofile.getProfile(function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerProfile'));
      done();
    });
  });
});

it('should return error for partner profile with missing partner.accounts scope', function(done) {
  uber.authorization({
    authorization_code: acNP
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnerprofile.getProfile(function(err, res) {
      err.message.should.equal('Required scope not found');
      done();
    });
  });
});


================================================
FILE: test/drivers/profileAsync.js
================================================
var common = require("../common"),
  should = common.should,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acNP = common.authCodeNoProfile;

it('should return invalid access token error when no token found', function(done) {
  uber.clearTokens();
  uber.partnerprofile.getProfileAsync().error(function(err) {
    err.message.should.equal('Invalid access token');
    done();
  });
});

it('should get partner profile after authentication', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnerprofile.getProfileAsync();
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerProfile'));
    done();
  });
});

it('should return error for partner profile with missing partner.accounts scope', function(done) {
  uber.authorizationAsync({authorization_code: acNP}).then(function() {
    return uber.partnerprofile.getProfileAsync();
  }).error(function(err) {
    err.message.should.equal('Required scope not found');
    done();
  });
});


================================================
FILE: test/drivers/trips.js
================================================
var common = require("../common"),
  should = common.should,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acNP = common.authCodeNoProfile;

it('should get driver partner trips after authentication', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnertrips.getTrips(0, 50, 1451606400, 1505160819, function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerTrips'));
      done();
    });
  });
});

it('should get driver partner trips after authentication, even with a too high limit', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnertrips.getTrips(0, 99, 1451606400, 1505160819, function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerTrips'));
      done();
    });
  });
});

it('should get driver partner trips after authentication without required parameters', function(done) {
  uber.authorization({
    authorization_code: ac
  }, function(err, accessToken, refreshToken) {
    should.not.exist(err);
    uber.partnertrips.getTrips(null, null, null, null, function(err, res) {
      should.not.exist(err);
      res.should.deep.equal(reply('drivers/partnerTrips'));
      done();
    });
  });
});

it('should return invalid access token error when no token found', function(done) {
  uber.clearTokens();
  uber.partnertrips.getTrips(null, null, null, null, function(err, res) {
    err.message.should.equal('Invalid access token');
    done();
  });
});


================================================
FILE: test/drivers/tripsAsync.js
================================================
var common = require("../common"),
  should = common.should,
  uber = common.uber,
  reply = common.jsonReply,
  ac = common.authCode,
  acNP = common.authCodeNoProfile;

it('should get driver partner trips after authentication', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnertrips.getTripsAsync(0, 50, 1451606400, 1505160819);
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerTrips'));
    done();
  });
});

it('should get driver partner trips after authentication, even with a too high limit', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnertrips.getTripsAsync(0, 99, 1451606400, 1505160819);
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerTrips'));
    done();
  });
});

it('should get driver partner trips after authentication without required parameters', function(done) {
  uber.authorizationAsync({authorization_code: ac}).then(function() {
    return uber.partnertrips.getTripsAsync(null, null, null, null);
  }).then(function(res) {
    res.should.deep.equal(reply('drivers/partnerTrips'));
    done();
  });
});

it('should return invalid access token error when no token found', function(done) {
  uber.clearTokens();
  uber.partnertrips.getTripsAsync(null, null, null, null).error(function(err) {
    err.message.should.equal('Invalid access token');
    done();
  });
});


================================================
FILE: test/general.js
================================================
var common = require("./common"),
    key = common.key,
    uber = common.uber;

it('should load the key from a key.json', function(done) {
    key.should.have.property('client_id');
    key.should.have.property('client_secret');
    key.should.have.property('server_token');
    key.should.have.property('redirect_uri');
    key.should.have.property('name');
    key.should.have.property('language');
    done();
});

it('should initiate Uber client with the key', function(done) {
    uber.should.have.property('defaults');
    uber.defaults.language.should.equal(key.language);
    uber.defaults.client_id.should.equal(key.client_id);
    uber.defaults.client_secret.should.equal(key.client_secret);
    uber.defaults.server_token.should.equal(key.server_token);
    uber.defaults.redirect_uri.should.equal(key.redirect_uri);
    uber.defaults.base_url.should.equal('https://api.uber.com/');
    uber.defaults.authorize_url.should.equal('https://login.uber.com/oauth/v2/authorize');
    uber.defaults.access_token_url.should.equal('https://login.uber.com/oauth/v2/token');
    uber.should.have.property('oauth2');
    done();
});


================================================
FILE: test/replies/auth/token.json
================================================
{
    "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
    "token_type": "Bearer",
    "expires_in": 2592000,
    "refresh_token": "Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr",
    "scope": "profile, history, places, request, request_receipt, all_trips, partner.payments, partner.accounts, partner.trips"
}


================================================
FILE: test/replies/auth/tokenExpired.json
================================================
{
  "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
  "token_type": "Bearer",
  "expires_in": -100,
  "refresh_token": "Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr",
  "scope": "profile history places request request_receipt"
}


================================================
FILE: test/replies/auth/tokenNoPlaces.json
================================================
{
    "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
    "token_type": "Bearer",
    "expires_in": 2592000,
    "refresh_token": "Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr",
    "scope": "profile history request request_receipt"
}


================================================
FILE: test/replies/auth/tokenNoProfile.json
================================================
{
    "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
    "token_type": "Bearer",
    "expires_in": 2592000,
    "refresh_token": "Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr",
    "scope": "history places request request_receipt"
}


================================================
FILE: test/replies/auth/tokenNoRefresh.json
================================================
{
  "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
  "token_type": "Bearer",
  "expires_in": -100,
  "refresh_token": "Zxkcv8qdSRRseIVlshydoQ4wnZBehr",
  "scope": "profile history places request request_receipt"
}


================================================
FILE: test/replies/auth/tokenNoRequest.json
================================================
{
    "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
    "token_type": "Bearer",
    "expires_in": 2592000,
    "refresh_token": "Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr",
    "scope": "profile history places request_receipt"
}


================================================
FILE: test/replies/auth/tokenRefreshed.json
================================================
{
  "access_token": "EE1IDxytP04tJ767GbjH7ED9PpGmYvL",
  "token_type": "Bearer",
  "expires_in": 2592000,
  "refresh_token": "Zx8fJ8qdSRRseIVlsGgtgQ4wnZBehr",
  "scope": "profile history places request request_receipt"
}


================================================
FILE: test/replies/drivers/partnerPayments.json
================================================
{
  "count": 1200,
  "limit": 1,
  "payments": [
    {
      "payment_id": "5cb8304c-f3f0-4a46-b6e3-b55e020750d7",
      "category": "fare",
      "event_time": 1502842757,
      "trip_id": "5cb8304c-f3f0-4a46-b6e3-b55e020750d7",
      "cash_collected": 0,
      "amount": 4.12,
      "driver_id": "8LvWuRAq2511gmr8EMkovekFNa2848lyMaQevIto-aXmnK9oKNRtfTxYLgPq9OSt8EzAu5pDB7XiaQIrcp-zXgOA5EyK4h00U6D1o7aZpXIQah--U77Eh7LEBiksj2rahB==",
      "breakdown": {
        "other": 4.16,
        "toll": 1,
        "service_fee": -1.04
      },
      "rider_fees": {
        "split_fare": 0.50
      },
      "partner_id": "8LvWuRAq2511gmr8EMkovekFNa2848lyMaQevIto-aXmnK9oKNRtfTxYLgPq9OSt8EzAu5pDB7XiaQIrcp-zXgOA5EyK4h00U6D1o7aZpXIQah--U77Eh7LEBiksj2rahB==",
      "currency_code": "USD"
    }
  ],
  "offset": 0
}


================================================
FILE: test/replies/drivers/partnerProfile.json
================================================
{
  "driver_id": "8LvWuRAq2511gmr8EMkovekFNa2848lyMaQevIto-aXmnK9oKNRtfTxYLgPq9OSt8EzAu5pDB7XiaQIrcp-zXgOA5EyK4h00U6D1o7aZpXIQah--U77Eh7LEBiksj2rahB==",
  "first_name": "Uber",
  "last_name": "Tester",
  "email": "uber.developer+tester@example.com",
  "phone_number": "+14155550000",
  "picture": "https://d1w2poirtb3as9.cloudfront.net/16ce502f4767f17b120e.png",
  "promo_code": "ubert4544ue",
  "rating": 5,
  "activation_status": "active"
}


================================================
FILE: test/replies/drivers/partnerTrips.json
================================================
{
  "count": 1200,
  "limit": 1,
  "trips": [
    {
      "fare": 6.2,
      "dropoff": {
        "timestamp": 1502844378
      },
      "vehicle_id": "0082b54a-6a5e-4f6b-b999-b0649f286381",
      "distance": 0.37,
      "start_city": {
        "latitude": 38.3498,
        "display_name": "Charleston, WV",
        "longitude": -81.6326
      },
      "status_changes": [
        {
          "status": "accepted",
          "timestamp": 1502843899
        },
        {
          "status": "driver_arrived",
          "timestamp": 1502843900
        },
        {
          "status": "trip_began",
          "timestamp": 1502843903
        },
        {
          "status": "completed",
          "timestamp": 1502844378
        }
      ],
      "surge_multiplier": 1,
      "pickup": {
        "timestamp": 1502843903
      },
      "driver_id": "8LvWuRAq2511gmr8EMkovekFNa2848lyMaQevIto-aXmnK9oKNRtfTxYLgPq9OSt8EzAu5pDB7XiaQIrcp-zXgOA5EyK4h00U6D1o7aZpXIQah--U77Eh7LEBiksj2rahB==",
      "status": "completed",
      "duration": 475,
      "trip_id": "b5613b6a-fe74-4704-a637-50f8d51a8bb1",
      "currency_code": "USD"
    }
  ],
  "offset": 0
}


================================================
FILE: test/replies/geocoder/locationA.json
================================================
{
    "results": [{
        "geometry": {
            "location": {
                "lat": 3.1357169,
                "lng": 101.6881501
            }
        }
    }]
}


================================================
FILE: test/replies/geocoder/locationB.json
================================================
{
    "results": [{
        "geometry": {
            "location": {
                "lat": 3.0831659,
                "lng": 101.6505078
            }
        }
    }]
}


================================================
FILE: test/replies/geocoder/locationC.json
================================================
{
    "results": [{
        "geometry": {
            "location": {
                "lat": 37.7598258,
                "lng": -122.4260558
            }
        }
    }]
}


================================================
FILE: test/replies/geocoder/locationEmpty.json
================================================
{
    "results": []
}


================================================
FILE: test/replies/riders/history.json
================================================
{
  "count": 15,
  "history": [
    {
      "status": "completed",
      "distance": 1.4780860317,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1475545183,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1475545808,
      "request_id": "fb0a7c1f-2cf7-4310-bd27-8ba7737362fe",
      "request_time": 1475545095
    },
    {
      "status": "completed",
      "distance": 1.2792152568,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1475513472,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1475513898,
      "request_id": "d72338b0-394d-4f0e-a73c-78d469fa0c6d",
      "request_time": 1475513393
    },
    {
      "status": "completed",
      "distance": 1.5084526246,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1475170251,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1475171154,
      "request_id": "2b61e340-27bd-4937-8304-122009e4a393",
      "request_time": 1475170088
    },
    {
      "status": "completed",
      "distance": 1.4705337758,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1475027766,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1475028387,
      "request_id": "58cb7b3c-fe22-47b4-94c0-2cf08b34f4be",
      "request_time": 1475027705
    },
    {
      "status": "completed",
      "distance": 0.6489455763,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1475002745,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1475003150,
      "request_id": "57be6f97-e10f-411e-a87e-670011c46b55",
      "request_time": 1475002656
    },
    {
      "status": "completed",
      "distance": 0.6632030652,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1475001862,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1475002218,
      "request_id": "0ca65d53-3351-4f3b-b07f-55e4fe4c1ad9",
      "request_time": 1475001534
    },
    {
      "status": "completed",
      "distance": 1.3935675129,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1474995527,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1474995943,
      "request_id": "c0453d97-4330-4ec2-88ab-38678101cc0b",
      "request_time": 1474995056
    },
    {
      "status": "completed",
      "distance": 1.5046201975,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1474909791,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1474910341,
      "request_id": "35822455-e4f5-4339-b763-6fc3ea16dc61",
      "request_time": 1474909743
    },
    {
      "status": "completed",
      "distance": 2.4445998557,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1474685017,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1474685568,
      "request_id": "81a0ffda-a879-4443-beb8-e253f4d19ecc",
      "request_time": 1474684872
    },
    {
      "status": "completed",
      "distance": 1.3603866105,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "start_time": 1474651767,
      "start_city": {
        "latitude": 37.7749,
        "display_name": "San Francisco",
        "longitude": -122.4194
      },
      "end_time": 1474652253,
      "request_id": "97736867-41ca-432a-b7e9-909e66d833ba",
      "request_time": 1474651636
    }
  ],
  "limit": 10,
  "offset": 0
}


================================================
FILE: test/replies/riders/paymentMethod.json
================================================
{
  "payment_methods": [
    {
      "payment_method_id": "5f384f7d-8323-4207-a297-51c571234a8c",
      "type": "baidu_wallet",
      "description": "***53"
    },
    {
      "payment_method_id": "f33847de-8113-4587-c307-51c2d13a823c",
      "type": "alipay",
      "description": "ga***@uber.com"
    },
    {
      "payment_method_id": "f43847de-8113-4587-c307-51c2d13a823c",
      "type": "visa",
      "description": "***23"
    },
    {
      "payment_method_id": "517a6c29-3a2b-45cb-94a3-35d679909a71",
      "type": "american_express",
      "description": "***05"
    },
    {
      "payment_method_id": "f53847de-8113-4587-c307-51c2d13a823c",
      "type": "business_account",
      "description": "Late Night Ride"
    }
  ],
  "last_used": "f53847de-8113-4587-c307-51c2d13a823c"
}


================================================
FILE: test/replies/riders/placeHome.json
================================================
{
   "address": "685 Market St, San Francisco, CA 94103, USA"
}


================================================
FILE: test/replies/riders/placeWork.json
================================================
{
   "address": "685 Market St, San Francisco, CA 94103, USA"
}


================================================
FILE: test/replies/riders/price.json
================================================
{
  "prices": [
    {
      "localized_display_name": "POOL",
      "distance": 6.17,
      "display_name": "POOL",
      "product_id": "26546650-e557-4a7b-86e7-6a3942445247",
      "high_estimate": 15,
      "low_estimate": 13,
      "duration": 1080,
      "estimate": "$13-14",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "uberX",
      "distance": 6.17,
      "display_name": "uberX",
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "high_estimate": 17,
      "low_estimate": 13,
      "duration": 1080,
      "estimate": "$13-17",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "uberXL",
      "distance": 6.17,
      "display_name": "uberXL",
      "product_id": "821415d8-3bd5-4e27-9604-194e4359a449",
      "high_estimate": 26,
      "low_estimate": 20,
      "duration": 1080,
      "estimate": "$20-26",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "SELECT",
      "distance": 6.17,
      "display_name": "SELECT",
      "product_id": "57c0ff4e-1493-4ef9-a4df-6b961525cf92",
      "high_estimate": 38,
      "low_estimate": 30,
      "duration": 1080,
      "estimate": "$30-38",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "BLACK",
      "distance": 6.17,
      "display_name": "BLACK",
      "product_id": "d4abaae7-f4d6-4152-91cc-77523e8165a4",
      "high_estimate": 43,
      "low_estimate": 43,
      "duration": 1080,
      "estimate": "$43.10",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "SUV",
      "distance": 6.17,
      "display_name": "SUV",
      "product_id": "8920cb5e-51a4-4fa4-acdf-dd86c5e18ae0",
      "high_estimate": 63,
      "low_estimate": 50,
      "duration": 1080,
      "estimate": "$50-63",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "ASSIST",
      "distance": 6.17,
      "display_name": "ASSIST",
      "product_id": "ff5ed8fe-6585-4803-be13-3ca541235de3",
      "high_estimate": 17,
      "low_estimate": 13,
      "duration": 1080,
      "estimate": "$13-17",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "WAV",
      "distance": 6.17,
      "display_name": "WAV",
      "product_id": "2832a1f5-cfc0-48bb-ab76-7ea7a62060e7",
      "high_estimate": 33,
      "low_estimate": 25,
      "duration": 1080,
      "estimate": "$25-33",
      "currency_code": "USD"
    },
    {
      "localized_display_name": "TAXI",
      "distance": 6.17,
      "display_name": "TAXI",
      "product_id": "3ab64887-4842-4c8e-9780-ccecd3a0391d",
      "high_estimate": null,
      "low_estimate": null,
      "duration": 1080,
      "estimate": "Metered",
      "currency_code": null
    }
  ]
}


================================================
FILE: test/replies/riders/product.json
================================================
{
  "products": [
    {
      "upfront_fare_enabled": true,
      "capacity": 2,
      "product_id": "26546650-e557-4a7b-86e7-6a3942445247",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png",
      "cash_enabled": false,
      "shared": true,
      "short_description": "POOL",
      "display_name": "POOL",
      "product_group": "rideshare",
      "description": "Share the ride, split the cost."
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 4,
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "uberX",
      "display_name": "uberX",
      "product_group": "uberx",
      "description": "THE LOW-COST UBER"
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 6,
      "product_id": "821415d8-3bd5-4e27-9604-194e4359a449",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberxl2.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "uberXL",
      "display_name": "uberXL",
      "product_group": "uberxl",
      "description": "LOW-COST RIDES FOR LARGE GROUPS"
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 4,
      "product_id": "57c0ff4e-1493-4ef9-a4df-6b961525cf92",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberselect.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "SELECT",
      "display_name": "SELECT",
      "product_group": "uberx",
      "description": "A STEP ABOVE THE EVERY DAY"
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 4,
      "product_id": "d4abaae7-f4d6-4152-91cc-77523e8165a4",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-black.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "BLACK",
      "display_name": "BLACK",
      "product_group": "uberblack",
      "description": "THE ORIGINAL UBER"
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 6,
      "product_id": "8920cb5e-51a4-4fa4-acdf-dd86c5e18ae0",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-suv.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "SUV",
      "display_name": "SUV",
      "product_group": "suv",
      "description": "ROOM FOR EVERYONE"
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 4,
      "product_id": "ff5ed8fe-6585-4803-be13-3ca541235de3",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "ASSIST",
      "display_name": "ASSIST",
      "product_group": "uberx",
      "description": "uberX with extra assistance"
    },
    {
      "upfront_fare_enabled": true,
      "capacity": 4,
      "product_id": "2832a1f5-cfc0-48bb-ab76-7ea7a62060e7",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-wheelchair.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "WAV",
      "display_name": "WAV",
      "product_group": "uberx",
      "description": "WHEELCHAIR ACCESSIBLE VEHICLES"
    },
    {
      "upfront_fare_enabled": false,
      "capacity": 4,
      "product_id": "3ab64887-4842-4c8e-9780-ccecd3a0391d",
      "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-taxi.png",
      "cash_enabled": false,
      "shared": false,
      "short_description": "TAXI",
      "display_name": "TAXI",
      "product_group": "taxi",
      "description": "TAXI WITHOUT THE HASSLE"
    }
  ]
}


================================================
FILE: test/replies/riders/productDetail.json
================================================
{
  "upfront_fare_enabled": false,
  "capacity": 4,
  "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
  "price_details": {
    "service_fees": [
      {
        "fee": 1.55,
        "name": "Booking fee"
      }
    ],
    "cost_per_minute": 0.22,
    "distance_unit": "mile",
    "minimum": 6.55,
    "cost_per_distance": 1.15,
    "base": 2,
    "cancellation_fee": 5,
    "currency_code": "USD"
  },
  "image": "http://d1a3f4spazzrp4.cloudfront.net/car-types/mono/mono-uberx.png",
  "cash_enabled": false,
  "shared": false,
  "short_description": "uberX",
  "display_name": "uberX",
  "product_group": "uberx",
  "description": "THE LOW-COST UBER"
}


================================================
FILE: test/replies/riders/profile.json
================================================
{
  "picture": "https://d1w2poirtb3as9.cloudfront.net/f3be498cb0bbf570aa3d.jpeg",
  "first_name": "Uber",
  "last_name": "Developer",
  "uuid": "f4a416e3-6016-4623-8ec9-d5ee105a6e27",
  "rider_id": "8OlTlUG1TyeAQf1JiBZZdkKxuSSOUwu2IkO0Hf9d2HV52Pm25A0NvsbmbnZr85tLVi-s8CckpBK8Eq0Nke4X-no3AcSHfeVh6J5O6LiQt5LsBZDSi4qyVUdSLeYDnTtirw==",
  "email": "uberdevelopers@gmail.com",
  "mobile_verified": true,
  "promo_code": "uberd340ue"
}


================================================
FILE: test/replies/riders/profilePromoError.json
================================================
{
   "meta": {},
   "errors":[
      {
         "status": 400,
         "code": "promotion_code_invalid",
         "title": "The promotion code is not valid."
      }
   ]
}


================================================
FILE: test/replies/riders/profilePromoSuccess.json
================================================
{
  "promotion_code": "FREE_RIDEZ",
  "description": "$20.00 off your next ride."
}


================================================
FILE: test/replies/riders/requestAccept.json
================================================
{
  "product_id": "17cb78a7-b672-4d34-a288-a6c6e44d5315",
  "request_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
  "status": "accepted",
  "surge_multiplier": 1.0,
  "shared": true,
  "driver": {
    "phone_number": "+14155550000",
    "sms_number": "+14155550000",
    "rating": 5,
    "picture_url": "https:\/\/d1w2poirtb3as9.cloudfront.net\/img.jpeg",
    "name": "Bob"
  },
  "vehicle": {
    "make": "Bugatti",
    "model": "Veyron",
    "license_plate": "I<3Uber",
    "picture_url": "https:\/\/d1w2poirtb3as9.cloudfront.net\/car.jpeg"
  },
  "location": {
    "latitude": 37.3382129093,
    "longitude": -121.8863287568,
    "bearing": 328
  },
  "pickup": {
    "alias": "work",
    "latitude": 37.3303463,
    "longitude": -121.8890484,
    "name": "1455 Market St.",
    "address": "1455 Market St, San Francisco, California 94103, US",
    "eta": 5
  },
  "destination": {
    "alias": "home",
    "latitude": 37.6213129,
    "longitude": -122.3789554,
    "name": "685 Market St.",
    "address": "685 Market St, San Francisco, CA 94103, USA",
    "eta": 19
  },
  "waypoints": [
    {
       "rider_id":null,
       "latitude":37.77508531,
       "type":"pickup",
       "longitude":-122.3976683872
    },
    {
       "rider_id":null,
       "latitude":37.773133,
       "type":"dropoff",
       "longitude":-122.415069
    },
    {
       "rider_id":"8KwsIO_YG6Y2jijSMf",
       "latitude":37.7752423,
       "type":"dropoff",
       "longitude":-122.4175658
    }
  ],
  "riders": [
    {
       "rider_id":"8KwsIO_YG6Y2jijSMf",
       "first_name":"Alec",
       "me": true
    },
    {
       "rider_id":null,
       "first_name":"Kevin",
       "me": false
    }
  ]
}


================================================
FILE: test/replies/riders/requestCreate.json
================================================
{
   "request_id": "852b8fdd-4369-4659-9628-e122662ad257",
   "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d",
   "status": "processing",
   "vehicle": null,
   "driver": null,
   "location": null,
   "eta": 5,
   "surge_multiplier": null
}


================================================
FILE: test/replies/riders/requestEstimate.json
================================================
{
  "fare": {
    "value": 5.73,
    "fare_id": "d30e732b8bba22c9cdc10513ee86380087cb4a6f89e37ad21ba2a39f3a1ba960",
    "expires_at": 1476953293,
    "display": "$5.73",
    "currency_code": "USD",
    "breakdown": [
     {
       "type": "promotion",
       "value": -2.00,
       "name": "Promotion"
     },
     {
       "type": "base_fare",
       "notice": "Fares are slightly higher due to increased demand",
       "value": 7.73,
       "name": "Base Fare"
     }
   ]
  },
  "trip": {
    "distance_unit": "mile",
    "duration_estimate": 540,
    "distance_estimate": 2.39
  },
  "pickup_estimate": 2
}


================================================
FILE: test/replies/riders/requestFareExpired.json
================================================
{
  "meta": {
    "fare_expired": {

    }
  },
  "errors":[
    {
      "status": 409,
      "code": "fare_expired",
      "title": "The fare has expired for the requested product."
    }
  ]
}

================================================
FILE: test/replies/riders/requestMap.json
================================================
{
    "request_id": "b5512127-a134-4bf4-b1ba-fe9f48f56d9d",
    "href": "https://trip.uber.com/abc123"
}


================================================
FILE: test/replies/riders/requestReceipt.json
================================================
{
    "request_id": "b5512127-a134-4bf4-b1ba-fe9f48f56d9d",
    "charges": [{
        "name": "Base Fare",
        "amount": "2.20",
        "type": "base_fare"
    }, {
        "name": "Distance",
        "amount": "2.75",
        "type": "distance"
    }, {
        "name": "Time",
        "amount": "3.57",
        "type": "time"
    }],
    "surge_charge": {
        "name": "Surge x1.5",
        "amount": "4.26",
        "type": "surge"
    },
    "charge_adjustments": [{
        "name": "Promotion",
        "amount": "-2.43",
        "type": "promotion"
    }, {
        "name": "Booking Fee",
        "amount": "1.00",
        "type": "booking_fee"
    }, {
        "name": "Rounding Down",
        "amount": "0.78",
        "type": "rounding_down"
    }],
    "normal_fare": "$8.52",
    "subtotal": "$12.78",
    "total_charged": "$5.92",
    "total_owed": null,
    "currency_code": "USD",
    "duration": "00:11:35",
    "distance": "1.49",
    "distance_label": "miles"
}


================================================
FILE: test/replies/riders/requestSurge.json
================================================
{
  "meta": {
    "surge_confirmation": {
      "href": "https:\/\/api.uber.com\/v1\/surge-confirmations\/e100a670",
      "surge_confirmation_id": "e100a670",
      "multiplier": 1.4,
      "expires_at": 1459191276
    }
  },
  "errors":[
    {
      "status": 409,
      "code": "surge",
      "title": "Surge pricing is currently in effect for this product."
    }
  ]
}

================================================
FILE: test/replies/riders/time.json
================================================
{
  "times": [
    {
      "localized_display_name": "POOL",
      "estimate": 60,
      "display_name": "POOL",
      "product_id": "26546650-e557-4a7b-86e7-6a3942445247"
    },
    {
      "localized_display_name": "uberX",
      "estimate": 60,
      "display_name": "uberX",
      "product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d"
    },
    {
      "localized_display_name": "uberXL",
      "estimate": 240,
      "display_name": "uberXL",
      "product_id": "821415d8-3bd5-4e27-9604-194e4359a449"
    },
    {
      "localized_display_name": "SELECT",
      "estimate": 240,
      "display_name": "SELECT",
      "product_id": "57c0ff4e-1493-4ef9-a4df-6b961525cf92"
    },
    {
      "localized_display_name": "BLACK",
      "estimate": 240,
      "display_name": "BLACK",
      "product_id": "d4abaae7-f4d6-4152-91cc-77523e8165a4"
    },
    {
      "localized_display_name": "SUV",
      "estimate": 240,
      "display_name": "SUV",
      "product_id": "8920cb5e-51a4-4fa4-acdf-dd86c5e18ae0"
    },
    {
      "localized_display_name": "ASSIST",
      "estimate": 300,
      "display_name": "ASSIST",
      "product_id": "ff5ed8fe-6585-4803-be13-3ca541235de3"
    },
    {
      "localized_display_name": "TAXI",
      "estimate": 480,
      "display_name": "TAXI",
      "product_id": "3ab64887-4842-4c8e-9780-ccecd3a0391d"
    }
  ]
}


================================================
FILE: test/riders/estimates.js
================================================
var common = require("../common"),
    should = common.should,
    uber = common.uber,
    reply = common.jsonReply,
    ac = common.authCode;

describe('Price', function() {
    it('should list all the price estimates by address', function(done) {
        uber.estimates.getPriceForRouteByAddress('A', 'B',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates by address with invalid seats count', function(done) {
        uber.estimates.getPriceForRouteByAddress('A', 'B', '',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates', function(done) {
        uber.estimates.getPriceForRoute(3.1357169, 101.6881501, 3.0831659, 101.6505078,
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates with invalid seats count', function(done) {
        uber.estimates.getPriceForRoute(3.1357169, 101.6881501, 3.0831659, 101.6505078, '',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates by address without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getPriceForRouteByAddress(
            'A',
            'B',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getPriceForRoute(3.1357169, 101.6881501, 3.0831659, 101.6505078,
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should return error if start address is invalid', function(done) {
        uber.estimates.getPriceForRouteByAddress(
            ' ',
            'B',
            function(err, res) {
                err.message.should.equal('No coordinates found for: " "');
                done();
            });
    });

    it('should return error if start address is invalid with seats', function(done) {
        uber.estimates.getPriceForRouteByAddress(
            ' ',
            'B',
            2,
            function(err, res) {
                err.message.should.equal('No coordinates found for: " "');
                done();
            });
    });

    it('should return error if start point lat and lon are invalid', function(done) {
        uber.estimates.getPriceForRoute(null, null, 3.1357169, 101.6881501, function(err, res) {
            err.message.should.equal('Invalid starting point latitude & longitude');
            done();
        });
    });

    it('should return error if end address is invalid', function(done) {
        uber.estimates.getPriceForRouteByAddress(
            'A',
            null,
            function(err, res) {
                err.message.should.equal('Geocoder.geocode requires a location.');
                done();
            });
    });

    it('should return error if end address is invalid with seats', function(done) {
        uber.estimates.getPriceForRouteByAddress(
            'A',
            null,
            2,
            function(err, res) {
                err.message.should.equal('Geocoder.geocode requires a location.');
                done();
            });
    });

    it('should return error if end point lat and lon are invalid', function(done) {
        uber.estimates.getPriceForRoute(3.1357169, 101.6881501, null, null, function(err, res) {
            err.message.should.equal('Invalid ending point latitude & longitude');
            done();
        });
    });

    it('should return error if both addresses are null', function(done) {
        uber.estimates.getPriceForRouteByAddress(
            null,
            null,
            function(err, res) {
                err.message.should.equal('Geocoder.geocode requires a location.');
                done();
            });
    });

    it('should return error if both addresses are invalid', function(done) {
        uber.estimates.getPriceForRouteByAddress(
            ' ',
            ' ',
            function(err, res) {
                err.message.should.equal('No coordinates found for: " "');
                done();
            });
    });

    it('should return error if there is no required params', function(done) {
        uber.estimates.getPriceForRoute(null, null, null, null, function(err, res) {
            err.message.should.equal('Invalid starting point latitude & longitude');
            done();
        });
    });
});

describe('Time', function() {
    it('should list all the price estimates for location', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.estimates.getETAForLocation(3.1357169, 101.6881501,
                    function(err, res) {
                        should.not.exist(err);
                        res.should.deep.equal(reply('riders/time'));
                        done();
                    });
            });
    });

    it('should list all the price estimates for address', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.estimates.getETAForAddress(
                    'A',
                    function(err, res) {
                        should.not.exist(err);
                        res.should.deep.equal(reply('riders/time'));
                        done();
                    });
            });
    });

    it('should list all the price estimates for location without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getETAForLocation(3.1357169, 101.6881501,
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for address without access token', function(done) {
        uber.estimates.getETAForAddress(
            'A',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for product and location', function(done) {
        uber.estimates.getETAForLocation(3.1357169, 101.6881501, '327f7914-cd12-4f77-9e0c-b27bac580d03',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for product and address', function(done) {
        uber.estimates.getETAForAddress(
            'A',
            '327f7914-cd12-4f77-9e0c-b27bac580d03',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for location with empty product', function(done) {
        uber.estimates.getETAForLocation(3.1357169, 101.6881501, '',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for address with empty product', function(done) {
        uber.estimates.getETAForAddress(
            'A',
            '',
            function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should return error if there is no required params', function(done) {
        uber.estimates.getETAForLocation(null, null, function(err, res) {
            err.message.should.equal('Invalid latitude & longitude');
            done();
        });
    });

    it('should return error if there is no valid address', function(done) {
        uber.estimates.getETAForAddress(' ', function(err, res) {
            err.message.should.equal('No coordinates found for: " "');
            done();
        });
    });

    it('should return error if there is no valid address but product_id', function(done) {
        uber.estimates.getETAForAddress(' ', '327f7914-cd12-4f77-9e0c-b27bac580d03', function(err, res) {
            err.message.should.equal('No coordinates found for: " "');
            done();
        });
    });

    it('should return error if there is no required params', function(done) {
        uber.estimates.getETAForAddress(null, function(err, res) {
            err.message.should.equal('Geocoder.geocode requires a location.');
            done();
        });
    });
});


================================================
FILE: test/riders/estimatesAsync.js
================================================
var common = require("../common"),
    should = common.should,
    uber = common.uber,
    reply = common.jsonReply,
    ac = common.authCode;

describe('Price', function() {
    it('should list all the price estimates by address', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync('A', 'B')
        .then(function(res) {
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates by address with invalid seats count', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync('A', 'B', '')
        .then(function(res) {
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates from server', function(done) {
        uber.estimates.getPriceForRouteAsync(3.1357169, 101.6881501, 3.0831659, 101.6505078)
            .then(function(res) {
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates from server with invalid seats count', function(done) {
        uber.estimates.getPriceForRouteAsync(3.1357169, 101.6881501, 3.0831659, 101.6505078, '')
            .then(function(res) {
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates by address without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getPriceForRouteByAddressAsync('A', 'B')
        .then(function(res) {
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should list all the price estimates from server without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getPriceForRouteAsync(3.1357169, 101.6881501, 3.0831659, 101.6505078)
            .then(function(res) {
                res.should.deep.equal(reply('riders/price'));
                done();
            });
    });

    it('should return error if start address is invalid', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync(' ', 'B')
        .error(function(err) {
                err.message.should.equal('No coordinates found for: " "');
                done();
            });
    });

    it('should return error if start address is invalid with seats', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync(' ', 'B', 2)
        .error(function(err) {
                err.message.should.equal('No coordinates found for: " "');
                done();
            });
    });

    it('should return error if start point lat and lon are invalid', function(done) {
        uber.estimates.getPriceForRouteAsync(null, null, 3.1357169, 101.6881501)
            .error(function(err) {
                err.message.should.equal('Invalid starting point latitude & longitude');
                done();
            });
    });

    it('should return error if end address is invalid', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync('A', null)
        .error(function(err) {
                err.message.should.equal('Geocoder.geocode requires a location.');
                done();
            });
    });

    it('should return error if end address is invalid with seats', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync('A', null, 2)
        .error(function(err) {
                err.message.should.equal('Geocoder.geocode requires a location.');
                done();
            });
    });

    it('should return error if end point lat and lon are invalid', function(done) {
        uber.estimates.getPriceForRouteAsync(3.1357169, 101.6881501, null, null)
            .error(function(err) {
                err.message.should.equal('Invalid ending point latitude & longitude');
                done();
            });
    });

    it('should return error if both addresses are null', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync(null, null)
        .error(function(err) {
                err.message.should.equal('Geocoder.geocode requires a location.');
                done();
            });
    });

    it('should return error if both addresses are invalid', function(done) {
        uber.estimates.getPriceForRouteByAddressAsync(' ', ' ')
        .error(function(err) {
                err.message.should.equal('No coordinates found for: " "');
                done();
            });
    });

    it('should return error if there is no required params', function(done) {
        uber.estimates.getPriceForRouteAsync(null, null, null, null)
            .error(function(err) {
                err.message.should.equal('Invalid starting point latitude & longitude');
                done();
            });
    });
});

describe('Time', function() {
    it('should list all the price estimates for location', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.estimates.getETAForLocationAsync(3.1357169, 101.6881501);
            })
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for address', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.estimates.getETAForAddressAsync('A');
            })
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for location without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getETAForLocationAsync(3.1357169, 101.6881501)
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for adddress without access token', function(done) {
        uber.clearTokens();
        uber.estimates.getETAForAddressAsync('A')
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for product and location', function(done) {
        uber.estimates.getETAForLocationAsync(3.1357169, 101.6881501, '327f7914-cd12-4f77-9e0c-b27bac580d03')
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for product and address', function(done) {
        uber.estimates.getETAForAddressAsync('A', '327f7914-cd12-4f77-9e0c-b27bac580d03')
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for location but empty product', function(done) {
        uber.estimates.getETAForLocationAsync(3.1357169, 101.6881501, '')
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should list all the price estimates for address but empty product', function(done) {
        uber.estimates.getETAForAddressAsync('A', '')
            .then(function(res) {
                res.should.deep.equal(reply('riders/time'));
                done();
            });
    });

    it('should return error if there is no required params', function(done) {
        uber.estimates.getETAForLocationAsync(null, null)
            .error(function(err) {
                err.message.should.equal('Invalid latitude & longitude');
            });
        done();
    });

    it('should return error if there is no valid address', function(done) {
        uber.estimates.getETAForAddressAsync(' ')
        .error(function(err) {
            err.message.should.equal('No coordinates found for: " "');
            done();
        });
    });

    it('should return error if there is no valid address but product_id', function(done) {
        uber.estimates.getETAForAddressAsync(' ', '327f7914-cd12-4f77-9e0c-b27bac580d03')
        .error(function(err) {
            err.message.should.equal('No coordinates found for: " "');
            done();
        });
    });

    it('should return error if there is no required params', function(done) {
        uber.estimates.getETAForAddressAsync(null)
        .error(function(err) {
            err.message.should.equal('Geocoder.geocode requires a location.');
            done();
        });
    });
});


================================================
FILE: test/riders/payment-methods.js
================================================
var common = require("../common"),
    should = common.should,
    uber = common.uber,
    reply = common.jsonReply,
    ac = common.authCode;

it('should list the payment methods after authentication', function(done) {
    uber.authorization({
            authorization_code: ac
        },
        function(err, accessToken, refreshToken) {
            should.not.exist(err);
            uber.payment.getMethods(function(err, res) {
                should.not.exist(err);
                res.should.deep.equal(reply('riders/paymentMethod'));
                done();
            });
        });
});

it('should return invalid access token error when no token found', function(done) {
    uber.clearTokens();
    uber.payment.getMethods(function(err, res) {
        err.message.should.equal('Invalid access token');
        done();
    });
});


================================================
FILE: test/riders/payment-methodsAsync.js
================================================
var common = require("../common"),
    nock = common.nock,
    should = common.should,
    uber = common.uber,
    reply = common.jsonReply,
    ac = common.authCode;

it('should list the payment methods after authentication', function(done) {
    uber.authorizationAsync({
            authorization_code: ac
        })
        .then(function(accessToken, refreshToken) {
            return uber.payment.getMethodsAsync();
        })
        .then(function(res) {
            res.should.deep.equal(reply('riders/paymentMethod'));
        })
        .error(function(err) {
            should.not.exist(err);
        });
    done();
});

it('should return invalid access token error when no token found', function(done) {
    uber.clearTokens();
    uber.payment.getMethodsAsync()
        .then(function(res) {
            should.not.exist(res);
        })
        .error(function(err) {
            err.message.should.equal('Invalid access token');
        });
    done();
});


================================================
FILE: test/riders/places.js
================================================
var common = require("../common"),
    should = common.should,
    uber = common.uber,
    reply = common.jsonReply,
    ac = common.authCode,
    acNPl = common.authCodeNoPlaces;

describe('Home', function() {
    it('should return error for missing access token', function(done) {
        uber.clearTokens();
        uber.places.updateHome('685 Market St, San Francisco, CA 94103, USA', function(err, res) {
            err.message.should.equal('Invalid access token');
            done();
        });
    });

    it('should list the home address after authentication', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.getHome(function(err, res) {
                    should.not.exist(err);
                    res.should.deep.equal(reply('riders/placeHome'));
                    done();
                });
            });
    });

    it('should return invalid access token error when no token found', function(done) {

        uber.clearTokens();
        uber.places.getHome(function(err, res) {
            err.message.should.equal('Invalid access token');
            done();
        });
    });

});

describe('Work', function() {
    it('should list the work address after authentication', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.getWork(function(err, res) {
                    should.not.exist(err);
                    res.should.deep.equal(reply('riders/placeWork'));
                    done();
                });
            });
    });

    it('should return invalid access token error when no token found', function(done) {
        uber.clearTokens();
        uber.places.getWork(function(err, res) {
            err.message.should.equal('Invalid access token');
            done();
        });
    });
});

describe('By Place ID', function() {
    it('should be able to update the home address', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.updateHome('685 Market St, San Francisco, CA 94103, USA', function(err, res) {
                    should.not.exist(err);
                    res.should.deep.equal(reply('riders/placeHome'));
                    done();
                });
            });
    });

    it('should return error for update of home address with missing scope', function(done) {
        uber.authorization({
                authorization_code: acNPl
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.updateHome('685 Market St, San Francisco, CA 94103, USA', function(err, res) {
                    err.message.should.equal('Required scope not found');
                    done();
                });
            });
    });

    it('should be able to update the work address', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.updateWork('1455 Market St, San Francisco, CA 94103, USA', function(err, res) {
                    should.not.exist(err);
                    res.should.deep.equal(reply('riders/placeWork'));
                    done();
                });
            });
    });

    it('should return error for invalid place_id for GET', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.getByID('shop', function(err, res) {
                    err.message.should.equal('place_id needs to be either "home" or "work"');
                    done();
                });
            });
    });

    it('should return error for missing place_id for GET', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.getByID(null, function(err, res) {
                    err.message.should.equal('Invalid place_id');
                    done();
                });
            });
    });

    it('should return error for invalid place_id for PUT', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.updateByID('shop', '685 Market St, San Francisco, CA 94103, USA', function(err, res) {
                    err.message.should.equal('place_id needs to be either "home" or "work"');
                    done();
                });
            });
    });

    it('should return error for missing place_id for PUT', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.updateByID(null, '685 Market St, San Francisco, CA 94103, USA', function(err, res) {
                    err.message.should.equal('Invalid place_id');
                    done();
                });
            });
    });

    it('should return error for missing new address for PUT', function(done) {
        uber.authorization({
                authorization_code: ac
            },
            function(err, accessToken, refreshToken) {
                should.not.exist(err);
                uber.places.updateHome(null, function(err, res) {
                    err.message.should.equal('Invalid address');
                    done();
                });
            });
    });
});


================================================
FILE: test/riders/placesAsync.js
================================================
var common = require("../common"),
    should = common.should,
    uber = common.uber,
    reply = common.jsonReply,
    ac = common.authCode,
    acNPl = common.authCodeNoPlaces;

describe('Home', function() {
    it('should return error for missing access token', function(done) {
        uber.clearTokens();
        uber.places.updateHomeAsync('685 Market St, San Francisco, CA 94103, USA').then(function(res) {
                should.not.exist(res);
            })
            .error(function(err) {
                err.message.should.equal('Invalid access token');
            });
        done();
    });

    it('should list the home address after authentication', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.places.getHomeAsync();
            })
            .then(function(res) {
                res.should.deep.equal(reply('riders/placeHome'));
            })
            .error(function(err) {
                should.not.exist(err);
            });
        done();
    });

    it('should return invalid access token error when no token found', function(done) {

        uber.clearTokens();
        uber.places.getHomeAsync().then(function(res) {
                should.not.exist(res);
            })
            .error(function(err) {
                err.message.should.equal('Invalid access token');
            });
        done();
    });
});

describe('Work', function() {
    it('should list the work address after authentication', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(access_token) {
                return uber.places.getWorkAsync();
            })
            .then(function(res) {
                res.should.deep.equal(reply('riders/placeWork'));
            })
            .error(function(err) {
                should.not.exist(err);
            });
        done();
    });

    it('should return invalid access token error when no token found', function(done) {
        uber.clearTokens();
        uber.places.getWorkAsync().then(function(res) {
                should.not.exist(res);
            })
            .error(function(err) {
                err.message.should.equal('Invalid access token');
            });
        done();
    });
});

describe('By Place ID', function() {
    it('should be able to update the home address', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(access_token) {
                return uber.places.updateHomeAsync('685 Market St, San Francisco, CA 94103, USA');
            })
            .then(function(res) {
                res.should.deep.equal(reply('riders/placeHome'));
            })
            .error(function(err) {
                should.not.exist(err);
            });
        done();
    });

    it('should return error for update of home address with missing scope', function(done) {
        uber.authorizationAsync({
                authorization_code: acNPl
            }).then(function(access_token) {
                return uber.places.updateHomeAsync('685 Market St, San Francisco, CA 94103, USA');
            })
            .error(function(err) {
                err.message.should.equal('Required scope not found');
            });
        done();
    });

    it('should be able to update the work address', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(access_token) {
                return uber.places.updateWorkAsync('1455 Market St, San Francisco, CA 94103, USA');
            })
            .then(function(res) {
                res.should.deep.equal(reply('riders/placeWork'));
            })
            .error(function(err) {
                should.not.exist(err);
            });
        done();
    });

    it('should return error for invalid place_id for GET', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(access_token) {
                return uber.places.getByIDAsync('shop');
            })
            .error(function(err) {
                err.message.should.equal('place_id needs to be either "home" or "work"');
            });
        done();
    });

    it('should return error for missing place_id for GET', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.places.getByIDAsync(null);
            })
            .error(function(err) {
                err.message.should.equal('Invalid place_id');
            });
        done();
    });

    it('should return error for invalid place_id for PUT', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.places.updateByIDAsync('shop', '685 Market St, San Francisco, CA 94103, USA');
            })
            .error(function(err) {
                err.message.should.equal('place_id needs to be either "home" or "work"');
            });
        done();
    });

    it('should return error for missing place_id for PUT', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.places.updateByIDAsync(null, '685 Market St, San Francisco, CA 94103, USA');
            })
            .error(function(err) {
                err.message.should.equal('Invalid place_id');
            });
        done();
    });

    it('should return error for missing new address for PUT', function(done) {
        uber.authorizationAsync({
                authorization_code: ac
            }).then(function(res) {
                return uber.places.updateHomeAsync(null);
            })
            .error(function(err) {
                err.message.should.equal('Invalid address');
            });
        done();
    });
});


================================================
FILE: test/riders/products.js
================================================
var common = require("../common"),
    should = common.should,
    uber = common.uber,
    uber_sandbox = common.uber_sandbox,
    reply = common.jsonReply,
    ac = common.authCode;

describe('List', function() {
    it('should list all the product types', function(done) {
        uber.clearTokens();
        uber.products.getAllForLocation(3.1357169, 101.6881501, function(err, res) {
            should.not.exist(err);
            res.should.deep.equal(reply('riders/product'));
            done();
        });
    });

    it('should list all the product types by address', funct
Download .txt
gitextract_dcrhj7s8/

├── .codeclimate.yml
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .travis.yml
├── LICENSE
├── README-Nodeback.md
├── README.md
├── examples/
│   ├── auth-get-products-async.js
│   └── auth-get-products.js
├── gulpfile.js
├── index.js
├── lib/
│   ├── Uber.js
│   └── resources/
│       ├── drivers/
│       │   ├── PartnerPayments.js
│       │   ├── PartnerProfile.js
│       │   └── PartnerTrips.js
│       └── riders/
│           ├── Estimates.js
│           ├── Payment.js
│           ├── Places.js
│           ├── Products.js
│           ├── Requests.js
│           └── User.js
├── package.json
└── test/
    ├── allTests.js
    ├── auth/
    │   ├── oauth.js
    │   └── oauthAsync.js
    ├── common.js
    ├── drivers/
    │   ├── payments.js
    │   ├── paymentsAsync.js
    │   ├── profile.js
    │   ├── profileAsync.js
    │   ├── trips.js
    │   └── tripsAsync.js
    ├── general.js
    ├── replies/
    │   ├── auth/
    │   │   ├── token.json
    │   │   ├── tokenExpired.json
    │   │   ├── tokenNoPlaces.json
    │   │   ├── tokenNoProfile.json
    │   │   ├── tokenNoRefresh.json
    │   │   ├── tokenNoRequest.json
    │   │   └── tokenRefreshed.json
    │   ├── drivers/
    │   │   ├── partnerPayments.json
    │   │   ├── partnerProfile.json
    │   │   └── partnerTrips.json
    │   ├── geocoder/
    │   │   ├── locationA.json
    │   │   ├── locationB.json
    │   │   ├── locationC.json
    │   │   └── locationEmpty.json
    │   └── riders/
    │       ├── history.json
    │       ├── paymentMethod.json
    │       ├── placeHome.json
    │       ├── placeWork.json
    │       ├── price.json
    │       ├── product.json
    │       ├── productDetail.json
    │       ├── profile.json
    │       ├── profilePromoError.json
    │       ├── profilePromoSuccess.json
    │       ├── requestAccept.json
    │       ├── requestCreate.json
    │       ├── requestEstimate.json
    │       ├── requestFareExpired.json
    │       ├── requestMap.json
    │       ├── requestReceipt.json
    │       ├── requestSurge.json
    │       └── time.json
    └── riders/
        ├── estimates.js
        ├── estimatesAsync.js
        ├── payment-methods.js
        ├── payment-methodsAsync.js
        ├── places.js
        ├── placesAsync.js
        ├── products.js
        ├── productsAsync.js
        ├── requests.js
        ├── requestsAsync.js
        ├── user.js
        └── userAsync.js
Download .txt
SYMBOL INDEX (12 symbols across 11 files)

FILE: lib/Uber.js
  function Uber (line 21) | function Uber(options) {

FILE: lib/resources/drivers/PartnerPayments.js
  function PartnerPayments (line 1) | function PartnerPayments(uber) {

FILE: lib/resources/drivers/PartnerProfile.js
  function PartnerProfile (line 1) | function PartnerProfile(uber) {

FILE: lib/resources/drivers/PartnerTrips.js
  function PartnerTrips (line 1) | function PartnerTrips(uber) {

FILE: lib/resources/riders/Estimates.js
  function Estimates (line 1) | function Estimates(uber) {

FILE: lib/resources/riders/Payment.js
  function Payment (line 1) | function Payment(uber) {

FILE: lib/resources/riders/Places.js
  function Places (line 1) | function Places(uber) {

FILE: lib/resources/riders/Products.js
  function Products (line 1) | function Products(uber) {

FILE: lib/resources/riders/Requests.js
  function Requests (line 1) | function Requests(uber) {
  function localCallback (line 14) | function localCallback(err, res) {

FILE: lib/resources/riders/User.js
  function User (line 1) | function User(uber) {

FILE: test/allTests.js
  function importTest (line 18) | function importTest(name, path) {
Condensed preview — 78 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (262K chars).
[
  {
    "path": ".codeclimate.yml",
    "chars": 321,
    "preview": "---\nengines:\n  duplication:\n    enabled: true\n    config:\n      languages:\n      - ruby\n      - javascript\n      - pytho"
  },
  {
    "path": ".eslintignore",
    "chars": 16,
    "preview": "**/*{.,-}min.js\n"
  },
  {
    "path": ".eslintrc",
    "chars": 3979,
    "preview": "env:\n  amd: true\n  browser: true\n  es6: true\n  jquery: true\n  node: true\n\n# http://eslint.org/docs/rules/\nrules:\n  # Pos"
  },
  {
    "path": ".gitignore",
    "chars": 729,
    "preview": "################################################\n## Dependencies\n################################################\nnode_m"
  },
  {
    "path": ".travis.yml",
    "chars": 250,
    "preview": "language: node_js\nnode_js:\n  - \"6.10\"\n  - \"6.9\"\n  - \"4.8\"\n  - \"4.4.1\"\n  - \"4.2\"\naddons:\n  code_climate:\n    repo_token: "
  },
  {
    "path": "LICENSE",
    "chars": 1100,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2016 Shern Shiou Tan, Alexander Graebe\n\nPermission is hereby granted, free of charg"
  },
  {
    "path": "README-Nodeback.md",
    "chars": 28091,
    "preview": "# Initialization\n\nIn order to use this module, you have to import it in your application first:\n\n```javasctipt\nvar Uber "
  },
  {
    "path": "README.md",
    "chars": 31047,
    "preview": "[![Join the chat at https://gitter.im/shernshiou/node-uber](https://badges.gitter.im/shernshiou/node-uber.svg)](https://"
  },
  {
    "path": "examples/auth-get-products-async.js",
    "chars": 1459,
    "preview": "var Uber = require('node-uber');\n\n// create new Uber instance\nvar uber = new Uber({\n    client_id: 'YOUR CLIENT ID',\n   "
  },
  {
    "path": "examples/auth-get-products.js",
    "chars": 1337,
    "preview": "var Uber = require('node-uber');\n\n// create new Uber instance\nvar uber = new Uber({\n    client_id: 'YOUR CLIENT ID',\n   "
  },
  {
    "path": "gulpfile.js",
    "chars": 1768,
    "preview": "var gulp = require('gulp'),\n    mocha = require('gulp-mocha'),\n    istanbul = require('gulp-istanbul'),\n    eslint = req"
  },
  {
    "path": "index.js",
    "chars": 40,
    "preview": "module.exports = require('./lib/Uber');\n"
  },
  {
    "path": "lib/Uber.js",
    "chars": 13187,
    "preview": "var request = require('request');\nvar qs = require('querystring');\nvar OAuth = require('oauth');\nvar util = require('uti"
  },
  {
    "path": "lib/resources/drivers/PartnerPayments.js",
    "chars": 741,
    "preview": "function PartnerPayments(uber) {\n  this._uber = uber;\n  this.path = 'partners/payments';\n  this.requiredScope = 'partner"
  },
  {
    "path": "lib/resources/drivers/PartnerProfile.js",
    "chars": 346,
    "preview": "function PartnerProfile(uber) {\n  this._uber = uber;\n  this.path = 'partners/me';\n  this.requiredScope = 'partner.accoun"
  },
  {
    "path": "lib/resources/drivers/PartnerTrips.js",
    "chars": 720,
    "preview": "function PartnerTrips(uber) {\n  this._uber = uber;\n  this.path = 'partners/trips';\n  this.requiredScope = 'partner.trips"
  },
  {
    "path": "lib/resources/riders/Estimates.js",
    "chars": 2997,
    "preview": "function Estimates(uber) {\n    this._uber = uber;\n    this.path = 'estimates';\n}\n\nmodule.exports = Estimates;\n\nEstimates"
  },
  {
    "path": "lib/resources/riders/Payment.js",
    "chars": 319,
    "preview": "function Payment(uber) {\n    this._uber = uber;\n    this.path = 'payment-methods';\n    this.requiredScope = 'request';\n}"
  },
  {
    "path": "lib/resources/riders/Places.js",
    "chars": 1564,
    "preview": "function Places(uber) {\n  this._uber = uber;\n  this.path = 'places';\n  this.requiredScope = 'places';\n}\n\nmodule.exports "
  },
  {
    "path": "lib/resources/riders/Products.js",
    "chars": 2707,
    "preview": "function Products(uber) {\n    this._uber = uber;\n    this.path = 'products';\n}\n\nmodule.exports = Products;\n\nProducts.pro"
  },
  {
    "path": "lib/resources/riders/Requests.js",
    "chars": 7843,
    "preview": "function Requests(uber) {\n    this._uber = uber;\n    this.path = 'requests';\n    this.requiredScope = ['request', 'all_t"
  },
  {
    "path": "lib/resources/riders/User.js",
    "chars": 932,
    "preview": "function User(uber) {\n  this._uber = uber;\n  this.path = ['me', 'history'];\n  this.requiredScope = ['profile', 'history'"
  },
  {
    "path": "package.json",
    "chars": 1163,
    "preview": "{\n  \"name\": \"node-uber\",\n  \"version\": \"2.0.0\",\n  \"description\": \"A Node.js wrapper for Uber API\",\n  \"main\": \"index.js\",\n"
  },
  {
    "path": "test/allTests.js",
    "chars": 9888,
    "preview": "var common = require(\"./common\"),\n    nock = common.nock,\n    jp = common.jsonReplyPath,\n    key = common.key,\n    jr = "
  },
  {
    "path": "test/auth/oauth.js",
    "chars": 5670,
    "preview": "var common = require('../common'),\n  should = common.should,\n  qs = common.qs,\n  uber = common.uber,\n  reply = common.js"
  },
  {
    "path": "test/auth/oauthAsync.js",
    "chars": 3809,
    "preview": "var common = require('../common'),\n  should = common.should,\n  qs = common.qs,\n  uber = common.uber,\n  reply = common.js"
  },
  {
    "path": "test/common.js",
    "chars": 2048,
    "preview": "var chai = require('chai'),\n    nock = require('nock'),\n    request = require('superagent'),\n    should = chai.should(),"
  },
  {
    "path": "test/drivers/payments.js",
    "chars": 1736,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  },
  {
    "path": "test/drivers/paymentsAsync.js",
    "chars": 1508,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  },
  {
    "path": "test/drivers/profile.js",
    "chars": 1158,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  },
  {
    "path": "test/drivers/profileAsync.js",
    "chars": 1044,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  },
  {
    "path": "test/drivers/trips.js",
    "chars": 1694,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  },
  {
    "path": "test/drivers/tripsAsync.js",
    "chars": 1466,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  },
  {
    "path": "test/general.js",
    "chars": 1133,
    "preview": "var common = require(\"./common\"),\n    key = common.key,\n    uber = common.uber;\n\nit('should load the key from a key.json"
  },
  {
    "path": "test/replies/auth/token.json",
    "chars": 297,
    "preview": "{\n    \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 2592000,\n    \"ref"
  },
  {
    "path": "test/replies/auth/tokenExpired.json",
    "chars": 218,
    "preview": "{\n  \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n  \"token_type\": \"Bearer\",\n  \"expires_in\": -100,\n  \"refresh_token\""
  },
  {
    "path": "test/replies/auth/tokenNoPlaces.json",
    "chars": 224,
    "preview": "{\n    \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 2592000,\n    \"ref"
  },
  {
    "path": "test/replies/auth/tokenNoProfile.json",
    "chars": 223,
    "preview": "{\n    \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 2592000,\n    \"ref"
  },
  {
    "path": "test/replies/auth/tokenNoRefresh.json",
    "chars": 218,
    "preview": "{\n  \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n  \"token_type\": \"Bearer\",\n  \"expires_in\": -100,\n  \"refresh_token\""
  },
  {
    "path": "test/replies/auth/tokenNoRequest.json",
    "chars": 223,
    "preview": "{\n    \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n    \"token_type\": \"Bearer\",\n    \"expires_in\": 2592000,\n    \"ref"
  },
  {
    "path": "test/replies/auth/tokenRefreshed.json",
    "chars": 221,
    "preview": "{\n  \"access_token\": \"EE1IDxytP04tJ767GbjH7ED9PpGmYvL\",\n  \"token_type\": \"Bearer\",\n  \"expires_in\": 2592000,\n  \"refresh_tok"
  },
  {
    "path": "test/replies/drivers/partnerPayments.json",
    "chars": 805,
    "preview": "{\n  \"count\": 1200,\n  \"limit\": 1,\n  \"payments\": [\n    {\n      \"payment_id\": \"5cb8304c-f3f0-4a46-b6e3-b55e020750d7\",\n     "
  },
  {
    "path": "test/replies/drivers/partnerProfile.json",
    "chars": 443,
    "preview": "{\n  \"driver_id\": \"8LvWuRAq2511gmr8EMkovekFNa2848lyMaQevIto-aXmnK9oKNRtfTxYLgPq9OSt8EzAu5pDB7XiaQIrcp-zXgOA5EyK4h00U6D1o7"
  },
  {
    "path": "test/replies/drivers/partnerTrips.json",
    "chars": 1146,
    "preview": "{\n  \"count\": 1200,\n  \"limit\": 1,\n  \"trips\": [\n    {\n      \"fare\": 6.2,\n      \"dropoff\": {\n        \"timestamp\": 150284437"
  },
  {
    "path": "test/replies/geocoder/locationA.json",
    "chars": 170,
    "preview": "{\n    \"results\": [{\n        \"geometry\": {\n            \"location\": {\n                \"lat\": 3.1357169,\n                \"l"
  },
  {
    "path": "test/replies/geocoder/locationB.json",
    "chars": 170,
    "preview": "{\n    \"results\": [{\n        \"geometry\": {\n            \"location\": {\n                \"lat\": 3.0831659,\n                \"l"
  },
  {
    "path": "test/replies/geocoder/locationC.json",
    "chars": 172,
    "preview": "{\n    \"results\": [{\n        \"geometry\": {\n            \"location\": {\n                \"lat\": 37.7598258,\n                \""
  },
  {
    "path": "test/replies/geocoder/locationEmpty.json",
    "chars": 22,
    "preview": "{\n    \"results\": []\n}\n"
  },
  {
    "path": "test/replies/riders/history.json",
    "chars": 4277,
    "preview": "{\n  \"count\": 15,\n  \"history\": [\n    {\n      \"status\": \"completed\",\n      \"distance\": 1.4780860317,\n      \"product_id\": \""
  },
  {
    "path": "test/replies/riders/paymentMethod.json",
    "chars": 793,
    "preview": "{\n  \"payment_methods\": [\n    {\n      \"payment_method_id\": \"5f384f7d-8323-4207-a297-51c571234a8c\",\n      \"type\": \"baidu_w"
  },
  {
    "path": "test/replies/riders/placeHome.json",
    "chars": 64,
    "preview": "{\n   \"address\": \"685 Market St, San Francisco, CA 94103, USA\"\n}\n"
  },
  {
    "path": "test/replies/riders/placeWork.json",
    "chars": 64,
    "preview": "{\n   \"address\": \"685 Market St, San Francisco, CA 94103, USA\"\n}\n"
  },
  {
    "path": "test/replies/riders/price.json",
    "chars": 2746,
    "preview": "{\n  \"prices\": [\n    {\n      \"localized_display_name\": \"POOL\",\n      \"distance\": 6.17,\n      \"display_name\": \"POOL\",\n    "
  },
  {
    "path": "test/replies/riders/product.json",
    "chars": 3761,
    "preview": "{\n  \"products\": [\n    {\n      \"upfront_fare_enabled\": true,\n      \"capacity\": 2,\n      \"product_id\": \"26546650-e557-4a7b"
  },
  {
    "path": "test/replies/riders/productDetail.json",
    "chars": 660,
    "preview": "{\n  \"upfront_fare_enabled\": false,\n  \"capacity\": 4,\n  \"product_id\": \"a1111c8c-c720-46c3-8534-2fcdd730040d\",\n  \"price_det"
  },
  {
    "path": "test/replies/riders/profile.json",
    "chars": 431,
    "preview": "{\n  \"picture\": \"https://d1w2poirtb3as9.cloudfront.net/f3be498cb0bbf570aa3d.jpeg\",\n  \"first_name\": \"Uber\",\n  \"last_name\":"
  },
  {
    "path": "test/replies/riders/profilePromoError.json",
    "chars": 174,
    "preview": "{\n   \"meta\": {},\n   \"errors\":[\n      {\n         \"status\": 400,\n         \"code\": \"promotion_code_invalid\",\n         \"titl"
  },
  {
    "path": "test/replies/riders/profilePromoSuccess.json",
    "chars": 84,
    "preview": "{\n  \"promotion_code\": \"FREE_RIDEZ\",\n  \"description\": \"$20.00 off your next ride.\"\n}\n"
  },
  {
    "path": "test/replies/riders/requestAccept.json",
    "chars": 1689,
    "preview": "{\n  \"product_id\": \"17cb78a7-b672-4d34-a288-a6c6e44d5315\",\n  \"request_id\": \"a1111c8c-c720-46c3-8534-2fcdd730040d\",\n  \"sta"
  },
  {
    "path": "test/replies/riders/requestCreate.json",
    "chars": 246,
    "preview": "{\n   \"request_id\": \"852b8fdd-4369-4659-9628-e122662ad257\",\n   \"product_id\": \"a1111c8c-c720-46c3-8534-2fcdd730040d\",\n   \""
  },
  {
    "path": "test/replies/riders/requestEstimate.json",
    "chars": 612,
    "preview": "{\n  \"fare\": {\n    \"value\": 5.73,\n    \"fare_id\": \"d30e732b8bba22c9cdc10513ee86380087cb4a6f89e37ad21ba2a39f3a1ba960\",\n    "
  },
  {
    "path": "test/replies/riders/requestFareExpired.json",
    "chars": 194,
    "preview": "{\n  \"meta\": {\n    \"fare_expired\": {\n\n    }\n  },\n  \"errors\":[\n    {\n      \"status\": 409,\n      \"code\": \"fare_expired\",\n  "
  },
  {
    "path": "test/replies/riders/requestMap.json",
    "chars": 105,
    "preview": "{\n    \"request_id\": \"b5512127-a134-4bf4-b1ba-fe9f48f56d9d\",\n    \"href\": \"https://trip.uber.com/abc123\"\n}\n"
  },
  {
    "path": "test/replies/riders/requestReceipt.json",
    "chars": 987,
    "preview": "{\n    \"request_id\": \"b5512127-a134-4bf4-b1ba-fe9f48f56d9d\",\n    \"charges\": [{\n        \"name\": \"Base Fare\",\n        \"amou"
  },
  {
    "path": "test/replies/riders/requestSurge.json",
    "chars": 373,
    "preview": "{\n  \"meta\": {\n    \"surge_confirmation\": {\n      \"href\": \"https:\\/\\/api.uber.com\\/v1\\/surge-confirmations\\/e100a670\",\n   "
  },
  {
    "path": "test/replies/riders/time.json",
    "chars": 1352,
    "preview": "{\n  \"times\": [\n    {\n      \"localized_display_name\": \"POOL\",\n      \"estimate\": 60,\n      \"display_name\": \"POOL\",\n      \""
  },
  {
    "path": "test/riders/estimates.js",
    "chars": 9596,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    reply = common.jsonReply,\n   "
  },
  {
    "path": "test/riders/estimatesAsync.js",
    "chars": 8879,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    reply = common.jsonReply,\n   "
  },
  {
    "path": "test/riders/payment-methods.js",
    "chars": 843,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    reply = common.jsonReply,\n   "
  },
  {
    "path": "test/riders/payment-methodsAsync.js",
    "chars": 976,
    "preview": "var common = require(\"../common\"),\n    nock = common.nock,\n    should = common.should,\n    uber = common.uber,\n    reply"
  },
  {
    "path": "test/riders/places.js",
    "chars": 6169,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    reply = common.jsonReply,\n   "
  },
  {
    "path": "test/riders/placesAsync.js",
    "chars": 6075,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    reply = common.jsonReply,\n   "
  },
  {
    "path": "test/riders/products.js",
    "chars": 4800,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    uber_sandbox = common.uber_sa"
  },
  {
    "path": "test/riders/productsAsync.js",
    "chars": 5007,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    uber_sandbox = common.uber_sa"
  },
  {
    "path": "test/riders/requests.js",
    "chars": 20568,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    uber_sandbox = common.uber_sa"
  },
  {
    "path": "test/riders/requestsAsync.js",
    "chars": 19995,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    uber_sandbox = common.uber_sa"
  },
  {
    "path": "test/riders/user.js",
    "chars": 4375,
    "preview": "var common = require(\"../common\"),\n    should = common.should,\n    uber = common.uber,\n    reply = common.jsonReply,\n   "
  },
  {
    "path": "test/riders/userAsync.js",
    "chars": 2990,
    "preview": "var common = require(\"../common\"),\n  should = common.should,\n  uber = common.uber,\n  reply = common.jsonReply,\n  ac = co"
  }
]

About this extraction

This page contains the full source code of the shernshiou/node-uber GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 78 files (241.5 KB), approximately 60.8k tokens, and a symbol index with 12 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!