forked from iotaledger/explorer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiHelper.ts
More file actions
256 lines (237 loc) · 8.47 KB
/
apiHelper.ts
File metadata and controls
256 lines (237 loc) · 8.47 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import { Converter, Ed25519 } from "@iota/iota.js";
import path from "path";
import { inspect } from "util";
import { IDataResponse } from "../models/api/IDataResponse";
import { IResponse } from "../models/api/IResponse";
import { ISignedResponse } from "../models/api/ISignedResponse";
import { IHttpRequest } from "../models/app/IHttpRequest";
import { IHttpResponse } from "../models/app/IHttpResponse";
import { IRoute } from "../models/app/IRoute";
import { IConfiguration } from "../models/configuration/IConfiguration";
/**
* Find a route to match
* @param findRoutes The routes to match against.
* @param url The url to find.
* @param method The method to find.
* @returns The matching route if there is one and any extracted params.
*/
export function findRoute(findRoutes: IRoute[], url: string, method: string): {
/**
* The matching route.
*/
route: IRoute;
/**
* Matching parameters for the route.
*/
params: { [id: string]: string };
} | undefined {
const urlParts = url.replace(/\/$/, "").split("/");
for (const route of findRoutes) {
if (route.method === method) {
const routeParts = route.path.split("/");
const params: { [id: string]: string } = {};
let i;
for (i = 0; i < urlParts.length && i < routeParts.length; i++) {
if (routeParts[i] === urlParts[i]) {
// This segment matches OK
} else if (routeParts[i].startsWith(":") &&
(i < urlParts.length || routeParts[i].endsWith("?"))
) {
// Its a param match in the url
// or an undefined parameter past the end of the match
if (i < urlParts.length) {
params[routeParts[i].slice(1).replace("?", "")] = urlParts[i];
}
} else {
break;
}
}
if (i === urlParts.length) {
return {
route,
params
};
}
}
}
}
/**
* Execute the route which matches the path.
* @param req The request.
* @param res The response.
* @param config The configuration.
* @param route The route.
* @param pathParams The params extracted from the url.
* @param verboseLogging Log full details of requests.
*/
export async function executeRoute(
req: IHttpRequest,
res: IHttpResponse,
config: IConfiguration,
route: IRoute,
pathParams: { [id: string]: string },
verboseLogging: boolean): Promise<void> {
let response: IResponse;
const start = Date.now();
let filteredParams;
let status = 400;
try {
let params;
let body;
if (route.dataBody) {
body = req.body;
params = { ...pathParams, ...req.query };
} else {
params = { ...pathParams, ...req.query, ...req.body };
}
filteredParams = logParams(params);
if (verboseLogging) {
console.log(`===> ${route.method.toUpperCase()} ${route.path}`);
console.log(inspect(filteredParams, false, undefined, false));
}
if (route.func) {
const modulePath = route.folder
? path.join(__dirname, "..", "routes", route.folder, route.func)
: path.join(__dirname, "..", "routes", route.func);
let mod;
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
mod = require(modulePath);
} catch (err) {
console.error(err);
}
if (mod) {
if (mod[route.func]) {
response = await mod[route.func](config, params, body, req.headers || {});
if (response && !response.error) {
status = 200;
}
} else {
response = {
error: `Route '${route.path}' module '${modulePath}' does not contain a method '${route.func}'`
};
}
} else {
response = { error: `Route '${route.path}' module '${modulePath}' failed to load` };
}
} else if (route.inline) {
response = await route.inline(config, params, body, req.headers || {});
if (response && !response.error) {
status = 200;
}
} else {
response = { error: `Route ${route.path} has no func or inline property set` };
}
} catch (err) {
status = err.httpCode || status;
response = { error: err.message };
}
if (verboseLogging || (response?.error)) {
console.log(`<=== duration: ${Date.now() - start}ms`);
console.log(inspect(response, false, undefined, false));
}
if (route.sign && config.privateKeyEd25519 && config.privateKeyEd25519.length === 128) {
(response as ISignedResponse).signature =
Converter.bytesToHex(Ed25519.sign(
Converter.hexToBytes(config.privateKeyEd25519),
Converter.utf8ToBytes(JSON.stringify(response))));
}
if (route.dataResponse) {
const dataResponse = response as IDataResponse;
res.status(status);
if (dataResponse.contentType) {
res.setHeader("Content-Type", dataResponse.contentType);
}
let filename = "";
if (dataResponse.filename) {
filename = `; filename="${dataResponse.filename}"`;
}
res.setHeader(
"Content-Disposition", `${dataResponse.inline ? "inline" : "attachment"}${filename}`);
if (dataResponse.data) {
res.setHeader(
"Content-Length", dataResponse.data.length);
res.send(dataResponse.data);
}
} else {
res.setHeader("Content-Type", "application/json");
res.status(status).send(JSON.stringify(response));
}
res.end();
}
/**
* Convert the params to logable
* @param obj The object to convert.
* @returns The converted object.
*/
function logParams(obj: { [id: string]: unknown }): { [id: string]: unknown } {
const newobj: { [id: string]: unknown } = {};
for (const key in obj) {
if (key.includes("pass")) {
newobj[key] = "*************";
} else if (key.includes("base64") || key.includes("binaryData")) {
newobj[key] = "<base64>";
} else if (obj[key] !== undefined && obj[key] !== null) {
const prop = obj[key];
if (prop.constructor.name === "Object") {
newobj[key] = logParams(prop as { [id: string]: unknown });
} else if (Array.isArray(prop)) {
newobj[key] = prop.map(item => logParams(item));
} else {
newobj[key] = prop;
}
} else {
newobj[key] = obj[key];
}
}
return newobj;
}
/**
* Handle cors.
* @param req Request The request.
* @param res Response The response.
* @param allowOrigins The allowed origins.
* @param allowMethods The allowed methods.
* @param allowHeaders The allowed headers.
*/
export function cors(
req: IHttpRequest,
res: IHttpResponse,
allowOrigins: string | string[] | undefined,
allowMethods: string | undefined,
allowHeaders: string | undefined): void {
if (!allowOrigins || allowOrigins === "*") {
res.setHeader("Access-Control-Allow-Origin", "*");
} else if (allowOrigins) {
const requestOrigin = req.headers.origin;
const origins = Array.isArray(allowOrigins) ? allowOrigins : allowOrigins.split(";");
let isAllowed;
for (const origin of origins) {
if (requestOrigin === origin || origin === "*") {
isAllowed = origin;
break;
}
}
if (isAllowed) {
res.setHeader("Access-Control-Allow-Origin", isAllowed);
}
}
if (req.method === "OPTIONS") {
res.setHeader(
"Access-Control-Allow-Methods",
allowMethods || "GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
allowHeaders || [
"X-Requested-With",
"Access-Control-Allow-Origin",
"X-HTTP-Method-Override",
"Content-Type",
"Authorization",
"Accept",
"Accept-Encoding"
].join(",")
);
}
}