1 | 'use strict';
|
2 |
|
3 | const Hasha = require('hasha');
|
4 | const Assert = require('assert');
|
5 | const Crypto = require('crypto');
|
6 | const QueryString = require('querystring');
|
7 | const Bounce = require('bounce');
|
8 | const Wreck = require('wreck');
|
9 | const Boom = require('boom');
|
10 |
|
11 | module.exports = class CloudApi {
|
12 | constructor ({ token, url, keyId, key, log } = {}) {
|
13 | const env = process.env.NODE_ENV;
|
14 | Assert(token || env === 'development' || env === 'test', 'token is required for production');
|
15 |
|
16 | this._token = token;
|
17 | this._keyId = keyId;
|
18 | this._key = key;
|
19 | this._cache = {};
|
20 | this._wreck = Wreck.defaults({
|
21 | headers: this._authHeaders(),
|
22 | baseUrl: `${url}/my`,
|
23 | json: true
|
24 | });
|
25 | this._log = log.bind(this);
|
26 | this.fetch = this.fetch.bind(this);
|
27 | }
|
28 |
|
29 | _authHeaders () {
|
30 | const now = new Date().toUTCString();
|
31 | const signer = Crypto.createSign('sha256');
|
32 | signer.update(now);
|
33 | const signature = signer.sign(this._key, 'base64');
|
34 |
|
35 | const headers = {
|
36 | 'Content-Type': 'application/json',
|
37 | Date: now,
|
38 | Authorization: `Signature keyId="${
|
39 | this._keyId
|
40 | }",algorithm="rsa-sha256" ${signature}`
|
41 | };
|
42 |
|
43 | if (this._token) {
|
44 | headers['X-Auth-Token'] = this._token;
|
45 | }
|
46 |
|
47 | return headers;
|
48 | }
|
49 |
|
50 | _getCache (method = '', path, options) {
|
51 | if (method.toLowerCase() !== 'get') {
|
52 | return;
|
53 | }
|
54 |
|
55 | const ref = Hasha(JSON.stringify({ method, path, options }));
|
56 | const { val, when } = this._cache[ref] || {};
|
57 | const now = new Date().getTime();
|
58 |
|
59 | if (!when) {
|
60 | return;
|
61 | }
|
62 |
|
63 |
|
64 | if (now - when > 9000) {
|
65 | delete this._cache[ref];
|
66 | return val;
|
67 | }
|
68 |
|
69 | return val;
|
70 | }
|
71 |
|
72 | _setCache (method = '', path, options, payload) {
|
73 | if (method.toLowerCase() !== 'get') {
|
74 | return;
|
75 | }
|
76 |
|
77 | const ref = Hasha(JSON.stringify({ method, path, options }));
|
78 | this._cache[ref] = {
|
79 | when: new Date().getTime(),
|
80 | val: payload
|
81 | };
|
82 | }
|
83 |
|
84 | async _request (path = '/', options = {}) {
|
85 | const wreckOptions = {
|
86 | json: true,
|
87 | payload: options.payload,
|
88 | headers: options.headers
|
89 | };
|
90 |
|
91 | if (options.query) {
|
92 | path += `?${QueryString.stringify(options.query)}`;
|
93 | }
|
94 |
|
95 | const method = (options.method && options.method.toLowerCase()) || 'get';
|
96 |
|
97 | const cached = this._getCache(method, path, wreckOptions);
|
98 | if (cached) {
|
99 | return cached;
|
100 | }
|
101 |
|
102 | try {
|
103 | if (method.toLowerCase() === 'head') {
|
104 | const res = await this._wreck.request('head', path, wreckOptions);
|
105 | return { res, payload: {} };
|
106 | }
|
107 |
|
108 | const results = await this._wreck[method](path, wreckOptions);
|
109 | this._setCache(method, path, wreckOptions, results);
|
110 | return results;
|
111 | } catch (ex) {
|
112 | this._log(['error', path], (ex.data && ex.data.payload) || ex);
|
113 | Bounce.rethrow(ex, 'system');
|
114 |
|
115 | if (options.default !== undefined) {
|
116 | return { payload: options.default, res: {} };
|
117 | }
|
118 |
|
119 | if (ex.data && ex.data.payload && ex.data.payload.message) {
|
120 | throw new Boom(ex.data.payload.message, ex.output.payload);
|
121 | }
|
122 |
|
123 | throw ex;
|
124 | }
|
125 | }
|
126 |
|
127 | async fetch (path = '/', options = {}) {
|
128 | const { payload, res } = await this._request(path, options);
|
129 | return options.includeRes ? { payload, res } : payload;
|
130 | }
|
131 | };
|