-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhyperexpress-middlewrap.js
336 lines (308 loc) · 11.3 KB
/
hyperexpress-middlewrap.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { Readable } from 'stream';
import path from 'path';
import fs from 'fs';
import mime from 'mime-types';
/**
* @typedef {Object} WrapperOptions
* @property {Console} [logger] - Custom logger (default: console)
* @property {function} [errorHandler] - Custom error handler function
*/
/**
* Creates a readable stream from the request body
* @param {Object} request - HyperExpress request object
* @returns {Promise<Readable>}
*/
const createBodyStream = async (request) => {
const readable = new Readable();
readable._read = () => {};
try {
const body = await request.text();
readable.push(Buffer.from(body));
readable.push(null);
} catch (err) {
readable.destroy(err);
}
return readable;
};
/**
* Wraps an Express middleware for use with HyperExpress
* @param {function} expressMiddleware - Express middleware to wrap
* @param {WrapperOptions} [options] - Options for the wrapper
* @returns {function} - HyperExpress compatible middleware
*/
const wrapExpressMiddleware = (expressMiddleware, options = {}) => {
const {
logger = console,
errorHandler = (err, req, res) => {
res.status(500).json({ error: err.message });
}
} = options;
return (request, response, next) => {
let nextCalled = false;
let responseSent = false;
const callNext = (error) => {
if (!nextCalled) {
nextCalled = true;
next(error);
}
};
const req = {
...request,
app: { locals: {} },
baseUrl: request.base,
body: undefined,
cookies: {},
fresh: false,
hostname: request.hostname,
ip: request.ip,
ips: [request.ip],
method: request.method,
originalUrl: request.url,
params: request.path_parameters,
path: request.path,
protocol: request.protocol,
query: request.query_parameters,
route: {},
secure: request.secure,
signedCookies: {},
stale: true,
subdomains: [],
xhr: false,
accepts: () => {},
acceptsCharsets: () => {},
acceptsEncodings: () => {},
acceptsLanguages: () => {},
get: (header) => request.headers[header.toLowerCase()],
is: () => {},
range: () => {},
};
const res = {
...response,
app: { locals: {} },
headersSent: false,
locals: {},
append: (field, value) => {
if (!responseSent) {
const prev = response.getHeader(field);
const val = Array.isArray(prev) ? prev.concat(value)
: Array.isArray(value) ? [prev].concat(value)
: [prev, value];
response.header(field, val);
}
return res;
},
attachment: (filename) => {
if (!responseSent) {
response.header('Content-Disposition', filename ? `attachment; filename="${filename}"` : 'attachment');
}
return res;
},
cookie: (name, value, options) => {
if (!responseSent) {
let cookie = `${name}=${value}`;
if (options) {
if (options.maxAge) cookie += `; Max-Age=${options.maxAge}`;
if (options.domain) cookie += `; Domain=${options.domain}`;
if (options.path) cookie += `; Path=${options.path}`;
if (options.secure) cookie += '; Secure';
if (options.httpOnly) cookie += '; HttpOnly';
if (options.sameSite) cookie += `; SameSite=${options.sameSite}`;
}
response.header('Set-Cookie', cookie);
}
return res;
},
clearCookie: (name, options) => {
if (!responseSent) {
const opts = { ...options, expires: new Date(1), path: '/' };
return res.cookie(name, '', opts);
}
return res;
},
end: (data) => {
if (!responseSent) {
responseSent = true;
response.send(data);
callNext();
}
},
get: (field) => response.getHeader(field),
json: (body) => {
if (!responseSent) {
responseSent = true;
response.json(body);
callNext();
}
},
location: (url) => {
if (!responseSent) {
response.header('Location', url);
}
return res;
},
redirect: (status, url) => {
if (!responseSent) {
responseSent = true;
if (typeof status === 'string') {
url = status;
status = 302;
}
response.status(status).header('Location', url).send();
callNext();
}
},
send: (body) => {
if (!responseSent) {
responseSent = true;
response.send(body);
callNext();
}
},
sendStatus: (code) => {
if (!responseSent) {
responseSent = true;
response.status(code).send(String(code));
callNext();
}
},
set: (field, value) => {
if (!responseSent) {
response.header(field, value);
}
return res;
},
setHeader: (field, value) => {
if (!responseSent) {
response.header(field, value);
}
return res;
},
status: (code) => {
if (!responseSent) {
response.status(code);
}
return res;
},
type: (type) => {
if (!responseSent) {
response.type(type);
}
return res;
},
vary: (field) => {
if (!responseSent) {
response.header('Vary', field);
}
return res;
},
getHeader: (field) => response.getHeader(field),
removeHeader: (field) => {
if (!responseSent) {
response.removeHeader(field);
}
return res;
},
download: (filePath, filename, options, callback) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof filename === 'function') {
callback = filename;
filename = path.basename(filePath);
}
fs.stat(filePath, (err, stats) => {
if (err) {
if (callback) {
callback(err);
} else {
errorHandler(err, req, res);
}
return;
}
const mimeType = mime.lookup(filePath) || 'application/octet-stream';
response.header('Content-Type', mimeType);
response.header('Content-Disposition', `attachment; filename="${filename}"`);
response.header('Content-Length', stats.size);
const fileStream = fs.createReadStream(filePath);
response.stream(fileStream);
if (callback) {
callback(null);
}
});
},
sendFile: (filePath, options, callback) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
fs.stat(filePath, (err, stats) => {
if (err) {
if (callback) {
callback(err);
} else {
errorHandler(err, req, res);
}
return;
}
const mimeType = mime.lookup(filePath) || 'application/octet-stream';
response.header('Content-Type', mimeType);
response.header('Content-Length', stats.size);
const fileStream = fs.createReadStream(filePath);
response.stream(fileStream);
if (callback) {
callback(null);
}
});
},
jsonp: (obj) => {
const callbackName = req.query.callback || 'callback';
const jsonString = JSON.stringify(obj);
const body = `${callbackName}(${jsonString});`;
response.type('application/javascript').send(body);
}
};
// If HyperExpress has a render method, use it
if (typeof response.render === 'function') {
res.render = response.render.bind(response);
}
const expressNext = (error) => {
if (error) {
logger.error('Express middleware error:', error);
errorHandler(error, req, res);
callNext(error);
} else if (!responseSent) {
callNext();
}
};
createBodyStream(request).then(bodyStream => {
req.read = bodyStream.read.bind(bodyStream);
req.pipe = bodyStream.pipe.bind(bodyStream);
req.unpipe = bodyStream.unpipe.bind(bodyStream);
req.on = bodyStream.on.bind(bodyStream);
req.once = bodyStream.once.bind(bodyStream);
req.removeListener = bodyStream.removeListener.bind(bodyStream);
logger.debug(`Executing middleware for ${req.method} ${req.path}`);
try {
const result = expressMiddleware(req, res, expressNext);
if (result && typeof result.then === 'function') {
result.catch(expressNext);
}
} catch (err) {
expressNext(err);
}
}).catch(err => {
logger.error('Error creating body stream:', err);
callNext(err);
});
};
};
/**
* Wraps multiple Express middlewares for use with HyperExpress
* @param {...function} middlewares - Express middlewares to wrap
* @returns {function[]} - Array of HyperExpress compatible middlewares
*/
const wrapExpressMiddlewares = (...middlewares) => {
return middlewares.map(wrapExpressMiddleware);
};
export { wrapExpressMiddleware, wrapExpressMiddlewares };