-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
76 lines (59 loc) · 1.91 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
65
66
67
68
69
70
71
72
73
74
75
import minimatch from 'minimatch';
import path from 'path';
import { Application, NextFunction, Request, Response } from 'express';
import { IFixtureConfig, IRule } from './contracts';
const DEFAULT_METHOD = 'GET';
interface DevServer {
app: Application
}
export function MockDevServer(configPath: string = './mock-dev-server.config') {
const fixtureConfig: IFixtureConfig = require(configPath);
return function DevServerBefore(devServer: DevServer) {
devServer.app.all(fixtureConfig.entry || '*', function (req: Request, res: Response, next: NextFunction) {
const { method, originalUrl } = req;
const rule = getRule(req);
if (rule) {
setResponseHeaders(res, rule);
setResponseBody(res, rule);
} else {
console.warn(`No rule found for ${method} '${originalUrl}'`);
next();
}
});
};
function getRule(req: Request): IRule | null {
const { method, originalUrl } = req;
const rules = fixtureConfig.rules;
if (rules) {
for (let i = 0, y = rules.length; i < y; i++) {
const rule = rules[i];
if (isMatch(rule)) {
return rule;
}
}
}
function isMatch(rule: IRule) {
return (isMethodMatch(rule) && isTestMatch(rule));
}
function isMethodMatch(rule: IRule) {
const ruleMethod = rule.method || DEFAULT_METHOD;
return (ruleMethod === method);
}
function isTestMatch(rule: IRule) {
return minimatch(originalUrl, rule.test);
}
return null;
}
function setResponseBody(res: Response, rule: IRule): void {
const fixturePath = path.join(fixtureConfig.src || '', rule.filename);
res.json(require(fixturePath));
}
function setResponseHeaders(res: Response, rule: IRule): void {
if (rule.headers) {
Object.keys(rule.headers).forEach(header => {
// @ts-ignore
res.setHeader(header, rule.headers[header])
});
}
}
}