-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathroute.ts
184 lines (166 loc) · 5.06 KB
/
route.ts
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
import {
Context,
ServerlessCallback,
ServerlessFunctionSignature,
} from '@twilio-labs/serverless-runtime-types/types';
import {
NextFunction,
Request as ExpressRequest,
RequestHandler as ExpressRequestHandler,
Response as ExpressResponse,
} from 'express';
import twilio, { twiml } from 'twilio';
import { checkForValidAccountSid } from '../checks/check-account-sid';
import { StartCliConfig } from '../config/start';
import { wrapErrorInHtml } from '../utils/error-html';
import { getDebugFunction } from '../utils/logger';
import { cleanUpStackTrace } from '../utils/stack-trace/clean-up';
import { Response } from './internal/response';
import * as Runtime from './internal/runtime';
const { VoiceResponse, MessagingResponse, FaxResponse } = twiml;
const debug = getDebugFunction('twilio-run:route');
export function constructEvent<T extends {} = {}>(req: ExpressRequest): T {
return { ...req.query, ...req.body };
}
export function constructContext<T extends {} = {}>(
{ url, env }: StartCliConfig,
functionPath: string
): Context<{
ACCOUNT_SID?: string;
AUTH_TOKEN?: string;
DOMAIN_NAME: string;
PATH: string;
[key: string]: string | undefined | Function;
}> {
function getTwilioClient(): twilio.Twilio {
checkForValidAccountSid(env.ACCOUNT_SID, {
shouldPrintMessage: true,
shouldThrowError: true,
functionName: 'context.getTwilioClient()',
});
return twilio(env.ACCOUNT_SID, env.AUTH_TOKEN);
}
const DOMAIN_NAME = url.replace(/^https?:\/\//, '');
const PATH = functionPath;
return { PATH, DOMAIN_NAME, ...env, getTwilioClient };
}
export function constructGlobalScope(config: StartCliConfig): void {
const GlobalRuntime = Runtime.create(config);
(global as any)['Twilio'] = { ...twilio, Response };
(global as any)['Runtime'] = GlobalRuntime;
(global as any)['Functions'] = GlobalRuntime.getFunctions();
(global as any)['Response'] = Response;
if (
checkForValidAccountSid(config.env.ACCOUNT_SID) &&
config.env.AUTH_TOKEN
) {
(global as any)['twilioClient'] = twilio(
config.env.ACCOUNT_SID,
config.env.AUTH_TOKEN
);
}
}
function isError(obj: any): obj is Error {
return obj instanceof Error;
}
export function handleError(
err: Error | string | object,
req: ExpressRequest,
res: ExpressResponse,
functionFilePath?: string
) {
res.status(500);
if (isError(err)) {
const cleanedupError = cleanUpStackTrace(err);
if (req.useragent && (req.useragent.isDesktop || req.useragent.isMobile)) {
res.type('text/html');
res.send(wrapErrorInHtml(cleanedupError, functionFilePath));
} else {
res.send({
message: cleanedupError.message,
name: cleanedupError.name,
stack: cleanedupError.stack,
});
}
} else {
res.send(err);
}
}
export function isTwiml(obj: object): boolean {
const isVoiceTwiml = obj instanceof VoiceResponse;
const isMessagingTwiml = obj instanceof MessagingResponse;
const isFaxTwiml = obj instanceof FaxResponse;
return isVoiceTwiml || isMessagingTwiml || isFaxTwiml;
}
export function handleSuccess(
responseObject: string | number | boolean | object | undefined,
res: ExpressResponse
) {
res.status(200);
if (typeof responseObject === 'string') {
debug('Sending basic string response');
res.type('text/plain').send(responseObject);
return;
}
if (
responseObject &&
typeof responseObject === 'object' &&
isTwiml(responseObject)
) {
debug('Sending TwiML response as XML string');
res.type('text/xml').send(responseObject.toString());
return;
}
if (responseObject && responseObject instanceof Response) {
debug('Sending custom response');
responseObject.applyToExpressResponse(res);
return;
}
debug('Sending JSON response');
res.send(responseObject);
}
export function functionToRoute(
fn: ServerlessFunctionSignature,
config: StartCliConfig,
functionFilePath?: string
): ExpressRequestHandler {
return function twilioFunctionHandler(
req: ExpressRequest,
res: ExpressResponse,
next: NextFunction
) {
const event = constructEvent(req);
debug('Event for %s: %o', req.path, event);
const context = constructContext(config, req.path);
debug('Context for %s: %p', req.path, context);
let run_timings: {
start: [number, number];
end: [number, number];
} = {
start: [0, 0],
end: [0, 0],
};
const callback: ServerlessCallback = function callback(err, payload?) {
run_timings.end = process.hrtime();
debug('Function execution %s finished', req.path);
debug(
`(Estimated) Total Execution Time: ${(run_timings.end[0] * 1e9 +
run_timings.end[1] -
(run_timings.start[0] * 1e9 + run_timings.start[1])) /
1e6}ms`
);
if (err) {
handleError(err, req, res, functionFilePath);
return;
}
handleSuccess(payload, res);
};
debug('Calling function for %s', req.path);
try {
run_timings.start = process.hrtime();
fn(context, event, callback);
} catch (err) {
callback(err);
}
};
}