-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathapi.ts
More file actions
237 lines (205 loc) · 6.9 KB
/
api.ts
File metadata and controls
237 lines (205 loc) · 6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
'use strict';
import os = require('os');
import process = require('process');
import _ = require('lodash');
import { v4 as uuidv4 } from 'uuid';
import * as url from 'url';
import got, { Agents, OptionsOfJSONResponseBody } from 'got';
import qs from 'qs';
import { Environments, CLIENT_VERSION, API_VERSION } from '../constants';
import * as GoCardlessErrors from '../errors';
import {
ApiRequestSignatureHelper,
ApiRequestSigningOptions,
ApiRequestSigningOptionsInternal,
} from '../apiRequestSigning';
export interface APIOptions {
proxy?: Agents;
raiseOnIdempotencyConflict?: boolean;
apiRequestSigningOptions?: ApiRequestSigningOptions;
}
interface UrlParameter {
key?: string;
value?: string;
}
interface APIRequestParameters {
path: string;
method: string;
urlParameters?: UrlParameter[];
requestParameters?: object;
payloadKey?: string | null;
idempotencyKey?: string;
fetch?: (identity: string) => Promise<any> | null;
customHeaders?: object;
}
export class Api {
private _token: string;
private _environment: Environments;
private _baseUrl: string;
private _agent: Agents | undefined;
private raiseOnIdempotencyConflict: boolean;
private apiRequestSigningOptions: ApiRequestSigningOptionsInternal | null = null;
private processVersion: string;
private osRelease: string;
private osPlatform;
constructor(token: string, environment = Environments.Live, options: APIOptions) {
this._token = token;
this._environment = environment;
this._baseUrl = 'https://api.gocardless.com';
if (this._environment === Environments.Sandbox) {
this._baseUrl = 'https://api-sandbox.gocardless.com';
}
this._agent = undefined;
if (options.proxy) {
this._agent = options.proxy;
}
this.raiseOnIdempotencyConflict = options.raiseOnIdempotencyConflict || false;
this.apiRequestSigningOptions = options.apiRequestSigningOptions as ApiRequestSigningOptionsInternal;
this.processVersion = process.version;
this.osPlatform = os.platform();
this.osRelease = os.release();
}
async request({
path,
method,
urlParameters = [],
requestParameters = {},
payloadKey = '',
idempotencyKey = '',
customHeaders = {},
fetch,
}: APIRequestParameters) {
urlParameters.forEach((urlParameter) => {
path = path.replace(`:${urlParameter.key}`, urlParameter.value);
});
// `got` adds a slash to the end of `prefix_url` so we don't want one at the
// start of the path
if (path[0] === '/') {
path = path.slice(1);
}
let requestOptions = this.createRequestOptions(
method,
requestParameters,
payloadKey,
idempotencyKey,
customHeaders,
);
if (this.apiRequestSigningOptions) {
requestOptions = this.signApiRequest(`/${path}`, requestOptions);
}
try {
const response = await got(path, requestOptions);
return {
body: response.body,
__response__: {
headers: response.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
url: response.url,
},
};
} catch (e) {
if (e instanceof got.ParseError) {
throw new GoCardlessErrors.MalformedResponseError('Malformed JSON received from GoCardless API', e.response);
}
if (e instanceof got.HTTPError) {
const err = GoCardlessErrors.ApiError.buildFromResponse(e.response);
if (err instanceof GoCardlessErrors.IdempotentCreationConflictError && !this.raiseOnIdempotencyConflict) {
return fetch(err.conflictingResourceId);
}
throw err;
}
throw e;
}
}
private signApiRequest(path: string, requestOptions: OptionsOfJSONResponseBody): OptionsOfJSONResponseBody {
const body =
requestOptions.json !== null && requestOptions.json !== undefined
? JSON.stringify(requestOptions.json)
: undefined;
const contentDigest = body !== undefined ? ApiRequestSignatureHelper.getSha256Digest(body) : undefined;
const contentLength = body !== undefined ? Buffer.byteLength(body, 'utf8') : undefined;
const signer = new ApiRequestSignatureHelper({
apiRequestSigningOptions: this.apiRequestSigningOptions,
requestPath: path,
contentType: 'application/json',
host: this._baseUrl,
httpMethod: requestOptions.method.toUpperCase(),
contentDigest,
contentLength,
created: this.apiRequestSigningOptions.testMode ? 'created' : undefined,
nonce: this.apiRequestSigningOptions.testMode ? 'nonce' : undefined,
});
return {
...requestOptions,
headers: {
...requestOptions.headers,
'Gc-Signature': signer.getGcSignature(),
'Gc-Signature-Input': signer.getGcSignatureInput(),
'Content-Digest': contentDigest ? ApiRequestSignatureHelper.getSha256DigestHeader(contentDigest) : undefined,
},
};
}
private getHeaders(token, customHeaders = {}) {
const mandatoryHeaders = {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'GoCardless-Version': `${API_VERSION}`,
'GoCardless-Client-Version': `${CLIENT_VERSION}`,
'GoCardless-Client-Library': 'gocardless-nodejs',
'User-Agent': `gocardless-nodejs/${CLIENT_VERSION} node/${this.processVersion} ${this.osPlatform}/${this.osRelease}`,
};
return { ...customHeaders, ...mandatoryHeaders };
}
private createRequestOptions(
method = 'get',
requestParameters = {},
payloadKey = '',
idempotencyKey = '',
customHeaders = {},
) {
const headers = this.getHeaders(this._token, customHeaders);
const searchParams =
method === 'get' ? new url.URLSearchParams(this.formatQueryParameters(requestParameters)) : undefined;
// We want to always send POST requests with an idempotency key. If the user does not
// specify one, we'll generate one for them.
if (method.toLowerCase() === 'post') {
headers['Idempotency-Key'] = idempotencyKey ? idempotencyKey : this.generateIdempotencyKey();
}
const json = this.getRequestBody(method, requestParameters, payloadKey);
return {
agent: this._agent,
prefixUrl: this._baseUrl,
// tslint:disable-next-line:no-any
method: method as any,
responseType: 'json' as const,
headers,
searchParams,
json,
} as OptionsOfJSONResponseBody;
}
private getRequestBody(method: string, requestParameters, payloadKey) {
if ((method === 'post' || method === 'put') && requestParameters) {
if (payloadKey) {
return {
[payloadKey]: requestParameters,
};
} else {
return {
data: requestParameters,
};
}
}
return undefined;
}
private generateIdempotencyKey() {
return uuidv4();
}
private formatQueryParameters(parameters) {
return qs.stringify(parameters, {
encode: false,
indices: false,
arrayFormat: 'comma',
});
}
}