-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
252 lines (217 loc) · 10.2 KB
/
index.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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/* eslint-disable @typescript-eslint/no-empty-function */
const Resp = require('./src/response');
const PathResolver = require('./src/pathResolver');
let isFunction = obj => { return !!(obj && obj.constructor && obj.call && obj.apply); };
// This class is a singleton because the standard usage dereferences the `handler` method which removes the binding to `this`
let apiFactory = null;
class ApiFactory {
constructor(options, overrideLogger = null) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
apiFactory = this;
this.Authorizer = null;
this.requestMiddleware = options && options.requestMiddleware || (r => r);
this.responseMiddleware = options && options.responseMiddleware || ((_, r) => r);
this.errorMiddleware = options && options.errorMiddleware || ((_, e) => e);
this.debug = options && !!options.debug;
this.handlers = {
onEvent() {},
onSchedule() {}
};
this.Routes = {};
this.ProxyRoutes = {};
this.paths = {};
this.pathResolver = options && options.pathResolver || new PathResolver();
this.logger = overrideLogger || (message => console.log(JSON.stringify(message, null, 2)));
}
setAuthorizer(authorizerFunc) {
if (!isFunction(authorizerFunc)) { throw new Error('Authorizer Function has not been defined as a function.'); }
this.Authorizer = authorizerFunc;
}
SetAuthorizer(authorizerFunc) {
this.setAuthorizer(authorizerFunc);
}
onEvent(onEventFunc) {
if (!isFunction(onEventFunc)) { throw new Error('onEvent has not been defined as a function.'); }
this.handlers.onEvent = onEventFunc;
}
onSchedule(onScheduleFunc) {
if (!isFunction(onScheduleFunc)) { throw new Error('onSchedule has not been defined as a function.'); }
this.handlers.onSchedule = onScheduleFunc;
}
head(route, p0, p1) { this.method('HEAD', route, p0, p1); }
get(route, p0, p1) { this.method('GET', route, p0, p1); }
post(route, p0, p1) { this.method('POST', route, p0, p1); }
put(route, p0, p1) { this.method('PUT', route, p0, p1); }
patch(route, p0, p1) { this.method('PATCH', route, p0, p1); }
query(route, p0, p1) { this.method('QUERY', route, p0, p1); }
delete(route, p0, p1) { this.method('DELETE', route, p0, p1); }
options(route, p0, p1) { this.method('OPTIONS', route, p0, p1); }
any(route, p0, p1) { this.method('ANY', route, p0, p1); }
method(verb, route, p0, p1) {
let params = [p0, p1].filter(p => p);
let handler = null;
let options = {};
if (params.length > 0) { handler = params[params.length - 1]; }
if (params.length > 1) { options = params[params.length - 2]; }
if (params.length > 2) { throw new Error(`Method not defined with ${params.length} parameters. Closest match is function(route, options, handler).`); }
if (!isFunction(handler)) { throw new Error('Handler is not defined as a function.'); }
let path = route.toString();
if (path[0] !== '/') { path = `/${route}`; }
let api = {
ResourcePath: path,
Method: verb,
Handler: handler,
Options: options || {}
};
if (!apiFactory.Routes[path]) {
apiFactory.Routes[path] = {};
apiFactory.ProxyRoutes[path] = {};
}
apiFactory.Routes[path][verb] = api;
apiFactory.ProxyRoutes = apiFactory.pathResolver.storePath(apiFactory.ProxyRoutes, verb, path, api);
if (!apiFactory.paths[path]) {
apiFactory.paths[path] = {};
}
if (verb !== 'ANY') {
apiFactory.paths[path][verb] = {};
}
}
getPathMap() {
return apiFactory.paths;
}
resolveRoute(method, path) {
const routeData = apiFactory.pathResolver.resolvePath(apiFactory.ProxyRoutes, method, path);
return routeData && routeData.constructedRoute;
}
convertEvent(event) {
event.openApiOptions = event.openApiOptions || {};
event.queryStringParameters = event.queryStringParameters || {};
event.stageVariables = event.stageVariables || {};
event.pathParameters = event.pathParameters || {};
if (!event.requestContext) {
event.requestContext = {};
}
event.requestContext.authorizer = event.requestContext.authorizer || {};
const method = event.httpMethod || event.requestContext.http && event.requestContext.http.method;
let definedRoute = null;
const proxyPath = '/{proxy+}';
event.path = event.path || event.requestContext.http && event.requestContext.http.path || event.requestContext.path;
// Remove stage from Path
event.path = event.path.startsWith(`/${event.requestContext.stage}`) ? event.path.substring(event.requestContext.stage.length + 1) : event.path;
// The replace handles cases where the route key is prepended with a method from API Gateway
const routeKey = event.routeKey && event.routeKey.replace(/^[A-Z]+\s/, '') || event.resource;
const map = apiFactory.pathResolver.resolvePath(apiFactory.ProxyRoutes, method, event.path);
const definedMethods = map && map.methods;
if (map) {
// if it is a proxy path then then look up the proxied value.
definedRoute = map.value;
delete event.pathParameters.proxy;
event.pathParameters = Object.assign({}, map.tokens, event.pathParameters);
}
if (!definedRoute && routeKey.lastIndexOf(proxyPath) === -1 && routeKey !== '$default') {
// default to defined path when proxy is not specified.
if (apiFactory.Routes[routeKey] && apiFactory.Routes[routeKey][method]) {
definedRoute = apiFactory.Routes[routeKey][method];
} else if (apiFactory.Routes[routeKey] && apiFactory.Routes[routeKey].ANY) {
definedRoute = apiFactory.Routes[routeKey].ANY;
}
}
// either it is proxied and not defined or not defined, either way go to the first proxy route available in the hierarchy.
if (!definedRoute) {
const fallbackRoutes = routeKey.split('/').map((_, index) => routeKey.split('/').slice(0, index + 1).join('/') + proxyPath).reverse();
definedRoute = fallbackRoutes.map(fallbackAttemptRoute => apiFactory.Routes[fallbackAttemptRoute]
&& (apiFactory.Routes[fallbackAttemptRoute][method] || apiFactory.Routes[fallbackAttemptRoute].ANY)).find(r => r);
}
if (definedRoute) {
event.route = definedRoute.ResourcePath;
event.openApiOptions.definedMethods = definedMethods;
return { event, definedRoute };
}
event.route = null;
event.openApiOptions.definedMethods = definedMethods;
return { event, definedRoute };
}
/* This is the entry point from AWS Lambda. */
async handler(originalEvent, context) {
if (apiFactory.debug) {
apiFactory.logger({ level: 'DEBUG', title: 'Original Event, before transformation', originalEvent });
}
if ((originalEvent.path || originalEvent.rawPath) && !originalEvent.type) {
let { event, definedRoute } = apiFactory.convertEvent(originalEvent);
if (!definedRoute) {
return new Resp({
title: 'No handler defined for method and resource.',
details: { event, context }
}, 500);
}
let lambda = definedRoute.Handler;
event.openApiOptions = Object.assign({}, event.openApiOptions, definedRoute.Options || {});
if (event.isBase64Encoded) {
event.body = Buffer.from(event.body || '', 'base64').toString('utf8');
event.isBase64Encoded = false;
}
if (!definedRoute.Options.rawBody) {
// Convert a string body into a javascript object, if it is valid json and raw body is not set.
try {
event.body = JSON.parse(event.body);
} catch (e) { /* */ }
}
try {
let request = await apiFactory.requestMiddleware(event, context);
let response = await lambda(request, context);
let result = await apiFactory.responseMiddleware(request, response);
if (!result) { return new Resp(null, 204); }
if (!(result instanceof Resp)) { return new Resp(result, result && result.statusCode ? null : 200); }
return result;
} catch (e) {
try {
let error = await apiFactory.errorMiddleware(event, e);
if (error instanceof Resp) { return error; }
if (error instanceof Error) {
apiFactory.logger({ level: 'ERROR', title: 'Exception thrown by invocation of the runtime lambda function, check the implementation.', api: definedRoute, error: e });
return new Resp({ title: 'Unexpected error', errorId: event.requestContext.requestId }, 500);
}
return new Resp(error, error && error.statusCode ? null : 500);
} catch (middleE) {
apiFactory.logger({ level: 'ERROR', title: 'Exception thrown by invocation of the error middleware, check the implementation.', api: definedRoute, error: e, middleware: middleE });
return new Resp({ title: 'Unexpected error', errorId: event.requestContext.requestId }, 500);
}
}
}
//If this is the authorizer lambda, then call the authorizer
if (originalEvent.type === 'REQUEST' && (originalEvent.methodArn || originalEvent.routeArn)) {
if (!apiFactory.Authorizer) {
apiFactory.logger({ title: 'No authorizer function defined' });
throw new Error('Authorizer Undefined');
}
const { event } = apiFactory.convertEvent(originalEvent);
try {
let policy = await apiFactory.Authorizer(event, context);
if (!policy.principalId) {
apiFactory.logger({ title: 'OpenAPI-Factory: PolicyResult Failure, missing required parameter in policy: principalId', level: 'WARN', details: policy });
}
if (apiFactory.debug) {
apiFactory.logger({ title: 'OpenAPI-Factory: PolicyResult Success', level: 'INFO', details: policy });
}
return policy;
} catch (error) {
if (apiFactory.debug) {
apiFactory.logger({ title: 'OpenAPI-Factory: PolicyResult Failure', level: 'WARN', error });
}
throw error;
}
}
// this is a scheduled trigger
if (originalEvent.source === 'aws.events') {
// eslint-disable-next-line no-return-await
return await apiFactory.handlers.onSchedule(originalEvent, context);
}
// Otherwise execute the onEvent handler
// eslint-disable-next-line no-return-await
return await apiFactory.handlers.onEvent(originalEvent, context);
}
}
ApiFactory.getInstance = function getInstance() {
return apiFactory;
};
module.exports = ApiFactory;