forked from twilio/twilio-cli-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopen-api-client.js
195 lines (152 loc) · 5.16 KB
/
open-api-client.js
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
const url = require('url');
const { logger } = require('./messaging/logging');
const { doesObjectHaveProperty } = require('./javascript-utilities');
const JsonSchemaConverter = require('./api-schema/json-converter');
class OpenApiClient {
constructor({ httpClient, apiBrowser, converter }) {
this.httpClient = httpClient;
this.apiBrowser = apiBrowser;
this.converter = converter || new JsonSchemaConverter();
}
async request(opts) {
opts = { ...opts };
const domain = this.apiBrowser.domains[opts.domain];
if (!domain) {
throw new Error(`Domain name not found: ${opts.domain}`);
}
const path = domain.paths[opts.path];
if (!path) {
throw new Error(`Path not found: ${opts.domain}.${opts.path}`);
}
const operation = path.operations[opts.method];
if (!operation) {
throw new Error(`Operation not found: ${opts.domain}.${opts.path}.${opts.method}`);
}
const isPost = opts.method.toLowerCase() === 'post';
const params = this.getParams(opts, operation);
if (!opts.uri) {
opts.uri = this.getUri(opts);
}
// If the URI is relative, determine the host and prepend it.
if (opts.uri.startsWith('/')) {
if (!opts.host) {
opts.host = path.server;
}
opts.uri = opts.host + opts.uri;
}
const uri = new url.URL(opts.uri);
uri.hostname = this.getHost(uri.hostname, opts);
opts.uri = uri.href;
opts.params = isPost ? null : params;
opts.data = isPost ? params : null;
const response = await this.httpClient.request(opts);
return this.parseResponse(domain, operation, response, opts);
}
getParams(opts, operation) {
const params = {};
(operation.parameters || []).forEach((parameter) => {
/*
* Build the actual request params from the spec's query parameters. This
* effectively drops all params that are not in the spec.
*/
if (parameter.in === 'query' && doesObjectHaveProperty(opts.data, parameter.name)) {
let value = opts.data[parameter.name];
if (parameter.schema.type === 'boolean') {
value = value.toString();
}
params[parameter.name] = value;
}
});
return params;
}
getUri(opts) {
/*
* Evaluate the request path by replacing path parameters with their value
* from the request data.
*/
return opts.path.replace(/{(.+?)}/g, (fullMatch, pathNode) => {
let value = '';
if (doesObjectHaveProperty(opts.pathParams, pathNode)) {
value = opts.pathParams[pathNode];
value = encodeURIComponent(value);
}
logger.debug(`pathNode=${pathNode}, value=${value}`);
return value;
});
}
getHost(host, opts) {
if (opts.region || opts.edge) {
const domain = host.split('.').slice(-2).join('.');
const prefix = host.split(`.${domain}`)[0];
// eslint-disable-next-line prefer-const
let [product, edge, region] = prefix.split('.');
if (edge && !region) {
region = edge;
edge = undefined;
}
edge = opts.edge || edge;
region = opts.region || region || (opts.edge && 'us1');
return [product, edge, region, domain].filter((part) => part).join('.');
}
return host;
}
parseResponse(domain, operation, response, requestOpts) {
if (response.body) {
const responseSchema = this.getResponseSchema(domain, operation, response.statusCode, requestOpts.headers.Accept);
// If we were able to find the schema for the response body, convert it.
if (responseSchema) {
response.body = this.convertBody(response.body, responseSchema);
}
}
return response;
}
getResponseSchema(domain, operation, statusCode, contentType) {
let response = operation.responses[statusCode];
if (!response) {
const statusCodeRange = `${statusCode.toString()[0]}XX`;
response = operation.responses[statusCodeRange];
if (!response) {
logger.debug(`Response schema not found for status code ${statusCode} (${statusCodeRange})`);
return undefined;
}
}
const { schema } = response.content[contentType];
return this.evaluateRefs(schema, domain);
}
convertBody(responseBody, schema) {
return this.converter.convertSchema(schema, responseBody);
}
evaluateRefs(schema, domain) {
if (!schema || typeof schema !== 'object') {
return schema;
}
if (doesObjectHaveProperty(schema, '$ref')) {
schema = this.getRef(schema.$ref, domain);
}
Object.entries(schema).forEach(([key, value]) => {
schema[key] = this.evaluateRefs(value, domain);
});
return schema;
}
getRef(ref, domain) {
// https://swagger.io/docs/specification/using-ref/
const [remote, local] = ref.split('#');
if (remote) {
logger.debug(`Remote refs are not yet supported. Assuming local ref: ${remote}`);
}
let node = domain;
local
.split('/')
.filter((n) => n)
.forEach((nodeName) => {
if (doesObjectHaveProperty(node, nodeName)) {
node = node[nodeName];
}
});
if (!node) {
logger.debug(`Ref not found: ${ref}`);
}
return node;
}
}
module.exports = OpenApiClient;