-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
64 lines (55 loc) · 2.29 KB
/
index.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
import { NextFunction, Request, Response } from 'express';
import hijackResponse from 'hijackresponse';
import stringReplaceStream from './stringReplaceStream';
export type Options = Record<'contentTypeFilterRegexp', RegExp>;
export type ReplaceFunction = (req: Request, res: Response) => string;
const defaultOptions: Options = {
contentTypeFilterRegexp: /^text\/|^application\/json$|^application\/xml$/,
};
export const stringReplace = (
replacements: Record<string, string | ReplaceFunction>,
options: Partial<Options> = {}
) => {
const opts = { ...defaultOptions, ...options };
// Split string and function replacements so we don't have to process them on every request
const stringReplacements: Record<string, string> = {};
const functionReplacements: Record<string, ReplaceFunction> = {};
Object.keys(replacements).forEach(function(key, _index) {
const replacement = replacements[key];
if (typeof replacement === 'function') {
functionReplacements[key] = replacement;
} else {
stringReplacements[key] = replacement;
}
});
const hasFunctionReplacements = Object.keys(functionReplacements).length > 0;
return (req: Request, originalResponse: Response, next: NextFunction) => {
hijackResponse(originalResponse, function(err, res) {
const contentType = res.get('content-type') || '';
if (opts.contentTypeFilterRegexp.test(contentType)) {
if (err) {
res.unhijack(); // Make the original res object work again
return next(err);
}
res.removeHeader('content-length');
let scopedReplacements: Record<string, string>;
if (hasFunctionReplacements) {
// If we have dynamic replacements, calculate for this request
scopedReplacements = { ...stringReplacements };
Object.keys(functionReplacements).forEach(function(key, _index) {
scopedReplacements[key] = functionReplacements[key](req, res);
});
} else {
// No dynamic replacements, safe to share the global
scopedReplacements = stringReplacements;
}
res.pipe(stringReplaceStream(scopedReplacements)).pipe(res);
} else {
return res.unhijack();
}
});
next();
};
};
module.exports = stringReplace;
module.exports.stringReplace = stringReplace;