-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.ts
164 lines (142 loc) · 5.52 KB
/
app.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
#!/usr/bin/env node
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import express from 'express';
import fs from 'fs';
type Handler = (event: APIGatewayProxyEvent) => Promise<APIGatewayProxyResult>;
interface Route {
path: string,
endpoint: string
}
interface Config {
port: number,
routes: Route[],
env: {[key: string]: string} | undefined
}
const app = express();
const configPath = './lamba.json' || process.argv[2];
const config = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Config;
if (!config.port) {
config.port = 6987;
}
for (let key in config.env) {
process.env[key] = config.env[key];
}
const fullUrl = (req: express.Request) => {
return `${req.protocol}://${req.get('host')}${req.originalUrl}`;
};
const printError = (req: express.Request, statusCode: number, error: any) => {
console.log(`%c${statusCode}: %cResponse for ${req.method} request at %c${fullUrl(req)}`,
'color: #fc5b21; font-weight: bold',
'color: #fc5b21',
'color: #fc5b21; font-weight: bold; text-decoration: underline'
);
console.log(`%c${error}\n`, 'color: #ff8772');
};
let modifiedDates: { [path: string]: number } = {};
const hasFileChanged = async (path: string): Promise<boolean> => {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stats) => {
if (err) {
reject(err);
}
if (!modifiedDates[path] || modifiedDates[path] !== stats.mtimeMs) {
modifiedDates[path] = stats.mtimeMs;
resolve(true);
} else {
resolve(false);
}
});
});
};
app.use(express.text({ type: '*/*', limit: '50mb' }))
config.routes.forEach(route => {
app.all(route.endpoint, async (req, res) => {
for (let entry in require.cache) {
if (await hasFileChanged(entry)) {
delete require.cache[entry];
}
}
console.log(`%cRouted %c${fullUrl(req)}%c -> %c${route.endpoint}%c -> %c${route.path}`,
'color: gold',
'color: gold; font-weight: bold; text-decoration: underline',
'color: gold',
'color: gold; font-weight: bold; text-decoration: underline',
'color: gold',
'color: gold; font-weight: bold; text-decoration: underline');
const handler: Handler = (await import(process.cwd() + route.path)).lambdaHandler;
let event: APIGatewayProxyEvent = {
body: typeof(req.body) === 'string' ? req.body : null,
headers: {},
multiValueHeaders: {},
httpMethod: req.method,
isBase64Encoded: false,
path: req.baseUrl,
pathParameters: req.params,
queryStringParameters: req.query as {[key: string]: string},
multiValueQueryStringParameters: null,
stageVariables: null,
requestContext: {
accountId: '',
apiId: '',
authorizer: undefined,
protocol: '',
httpMethod: req.method,
identity: {
accessKey: null,
accountId: null,
apiKey: null,
apiKeyId: null,
caller: null,
clientCert: null,
cognitoAuthenticationProvider: null,
cognitoAuthenticationType: null,
cognitoIdentityId: null,
cognitoIdentityPoolId: null,
principalOrgId: null,
sourceIp: '',
user: null,
userAgent: null,
userArn: null
},
path: req.path,
stage: '',
requestId: '',
requestTimeEpoch: 0,
resourceId: '',
resourcePath: ''
},
resource: ''
};
for (let header in req.headers) {
event.headers[header] = req.headers[header]?.toString();
}
handler(event)
.then(result => {
if (result.statusCode < 400) {
console.log(`%c${result.statusCode}: %cResponse for ${req.method} request at %c${fullUrl(req)}\n`,
'color: mediumspringgreen; font-weight: bold',
'color: mediumspringgreen',
'color: mediumspringgreen; font-weight: bold; text-decoration: underline'
);
} else {
printError(req, result.statusCode, result.body);
}
for (let header in result.headers) {
res.header(header, result.headers[header].toString());
}
res.status(result.statusCode).send(result.body);
}).catch(error => {
printError(req, 500, JSON.stringify(error));
res.status(500).send(JSON.stringify(error));
});
});
});
app.listen(config.port, () => {
console.log(`%cLamba server initializing on port ${config.port}...`, 'color: gold; font-weight: bold;');
console.log(`%c${config.routes.length} routes found in ${configPath}`, `color: gold`);
console.log(' ');
config.routes.forEach(route => {
console.log(`%cLamba listening on endpoint: %chttp://localhost:${config.port}${route.endpoint}`, 'color: gold', 'color: gold; font-weight: bold; text-decoration: underline');
});
console.log(' ');
});