1 | /**
|
2 | * Module dependencies
|
3 | */
|
4 |
|
5 | var request = require('request-promise')
|
6 |
|
7 | /**
|
8 | * Returns a promise for a protected API request.
|
9 | * Used by the Anvil Connect API client methods (in rest/*).
|
10 | * @method protectedAPIRequest
|
11 | * @private
|
12 | * @param [options={}] {Object} Options hashmap object
|
13 | * @param options.url {String} (Required) URL to send the request to. Can be
|
14 | * relative (if relative, gets prefixed with the `configuration.issuer`).
|
15 | * @param options.token {String} (Required) Access token. Gets sent as an
|
16 | * Authorization: Bearer <token> header.
|
17 | * @param [options.headers={}] {Object} Optional headers hashmap
|
18 | * @param [options.method='GET'] {String} HTTP request method (default: GET)
|
19 | * @param [options.json=true] {Object|Boolean} JSON payload (for create()
|
20 | * requests and so on).
|
21 | * @return {Promise<Request>}
|
22 | */
|
23 | function protectedAPIRequest (options) {
|
24 | var self = this
|
25 |
|
26 | return new Promise(function (resolve, reject) {
|
27 | options = options || {}
|
28 |
|
29 | // validate the options
|
30 | if (!options.url) { return reject(new Error('Missing request url')) }
|
31 | if (!options.token) { return reject(new Error('Missing access token')) }
|
32 |
|
33 | // initialize default values
|
34 | if (!options.url.match(/^http/)) {
|
35 | options.url = self.configuration.issuer + options.url
|
36 | }
|
37 |
|
38 | options.method = options.method || 'GET'
|
39 | options.headers = options.headers || {}
|
40 | options.headers['Authorization'] = 'Bearer ' + options.token
|
41 | options.json = options.json || true
|
42 | options.agentOptions = self.agentOptions
|
43 |
|
44 | // make the request
|
45 | request(options)
|
46 | .then(function (data) {
|
47 | resolve(data)
|
48 | })
|
49 | .catch(function (err) {
|
50 | reject(err)
|
51 | })
|
52 | })
|
53 | }
|
54 |
|
55 | /**
|
56 | * Export
|
57 | */
|
58 |
|
59 | module.exports = protectedAPIRequest
|