-
Notifications
You must be signed in to change notification settings - Fork 3
/
core.ts
170 lines (151 loc) · 4.82 KB
/
core.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
165
166
167
168
169
170
import { createServer, Server } from 'http';
import logger from '../utils/logger';
import axios from 'axios';
import { CommonUtils } from '../utils/common-utils';
import {
MiddlewareFn,
MockVariantOptions,
RouteData,
RouteVariants,
ServerOptions,
} from '../types';
import * as express from 'express';
import { Route } from '../models/route-model';
import { addAdminEndpoints, addAdminStaticSite } from './admin';
import { findRouteIndexById } from '../utils/routeMatchingUtils';
import * as fsDefault from 'fs';
import { SessionState } from '../models/sessionState';
import { DEFAULT_PORT, MEZZO_API_PATH } from '../utils/constants';
import * as bodyParser from 'body-parser';
export class Mezzo {
public userRoutes: Route[] = [];
public sessionState: SessionState;
private server: Server;
private app: express.Express;
private fs;
public util: CommonUtils;
public mockedDirectory;
public port;
private _resetRouteState = () => (this.userRoutes.length = 0);
private _addRouteToExpress = (myRoute: Route) => {
this.app[myRoute.method.toLowerCase()](myRoute.path, <MiddlewareFn>((
req,
res,
next
) => {
myRoute.processRequest(req, res, next);
}));
};
private _addRouteToState = (myRoute: Route) => {
this.userRoutes.push(myRoute);
};
private initializeMiddleware = () => {
this.app.use(bodyParser.json({ limit: '5mb' }));
};
public start = async (options?: ServerOptions): Promise<Server> => {
this.app = express();
this._resetRouteState();
this.initializeMiddleware();
addAdminEndpoints(this.app, this);
addAdminStaticSite(this.app, options);
this.fs = options?.fsOverride ?? fsDefault;
this.mockedDirectory = options.mockedDirectory;
this.util = new CommonUtils(this.userRoutes, this.fs, this.mockedDirectory);
this.sessionState = new SessionState();
this.port = options?.port ?? DEFAULT_PORT;
// if (options.fsOverride) {
// fs = options.fsOverride;
// }
return new Promise((resolve) => {
this.server = createServer(this.app).listen(this.port, () => {
logger.debug(
`***************Server running on port ${this.port} ***************`
);
resolve(this.server);
});
});
};
public stop = async (serverArg?: Server) => {
const serverToStop = serverArg ?? this.server;
return new Promise((resolve) => {
if (serverToStop) {
logger.debug(
'***************Stopping Mezzo mocking server ***************'
);
serverToStop.close(resolve);
this.app = undefined;
} else {
logger.warn(
'***************Unable to stop Mezzo mocking server ***************'
);
resolve(null);
}
});
};
/**
* Add route to mock server
* @param routeData
* @returns
*/
public route = (routeData: RouteData): Route => {
if (this.app == undefined) {
logger.error(
'You have not yet initialied the app, please start before adding routes'
);
throw new Error('App not yet initialized');
}
const myRoute = new Route(routeData, this.sessionState);
this._addRouteToExpress(myRoute);
this._addRouteToState(myRoute);
return myRoute;
};
// https://github.com/sgoff0/midway/blob/6614a6a91d3060951e99326c68333ebf78563e8c/src/utils/common-utils.ts#L318-L356
public setMockVariant = async (options: MockVariantOptions) => {
const url = `http://localhost:${
this.port
}${MEZZO_API_PATH}/route/${encodeURIComponent(options.routeId)}`;
await axios.post(url, {
variant: options.variantId,
});
};
public setMockVariantForSession = async (
sessionId: string,
payload: RouteVariants
) => {
const url = `http://localhost:${this.port}${MEZZO_API_PATH}/sessionVariantState/set/${sessionId}`;
await axios.post(url, payload);
};
public updateMockVariantForSession = async (
sessionId: string,
payload: RouteVariants
) => {
const url = `http://localhost:${this.port}${MEZZO_API_PATH}/sessionVariantState/update/${sessionId}`;
await axios.post(url, payload);
};
public serialiazeRoutes = () => {
return this.userRoutes.map((route) => {
// const variants = route.getVariants();
// console.log('KEYS: ', variants);
const variantRetVal = [];
route.getVariants().forEach((value, key) => {
console.log('Id: ' + key + ' label: ' + value.id);
variantRetVal.push({
id: key,
label: value.id,
});
// variantRetVal[key] = {
// label: value.id,
// };
});
return {
id: route.id,
method: route.method,
path: route.path,
// variants: Object.fromEntries(variants),
variants: variantRetVal,
activeVariant: route.getActiveVariant(),
};
});
};
}
export default new Mezzo();