-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathapp.ts
More file actions
208 lines (177 loc) · 5.69 KB
/
app.ts
File metadata and controls
208 lines (177 loc) · 5.69 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
import fs, { rm } from "node:fs/promises";
import nodePath from "node:path";
import { dereference } from "@apidevtools/json-schema-ref-parser";
import { createHttpTerminator, type HttpTerminator } from "http-terminator";
import { startRepl as startReplServer } from "./repl/repl.js";
import type { Config } from "./server/config.js";
import { ContextRegistry } from "./server/context-registry.js";
import { createKoaApp } from "./server/create-koa-app.js";
import {
Dispatcher,
DispatcherRequest,
type OpenApiDocument,
} from "./server/dispatcher.js";
import { koaMiddleware } from "./server/koa-middleware.js";
import { ModuleLoader } from "./server/module-loader.js";
import { Registry } from "./server/registry.js";
import { Transpiler } from "./server/transpiler.js";
import { CodeGenerator } from "./typescript-generator/code-generator.js";
type MswHandlerMap = {
[key: string]: (request: MockRequest) => Promise<unknown>;
};
const allowedMethods = [
"all",
"head",
"get",
"post",
"put",
"delete",
"patch",
"options",
] as const;
export type MockRequest = DispatcherRequest & { rawPath: string };
export async function loadOpenApiDocument(source: string) {
try {
return (await dereference(source)) as OpenApiDocument;
} catch {
return undefined;
}
}
const mswHandlers: MswHandlerMap = {};
export async function handleMswRequest(request: MockRequest) {
const { method, rawPath } = request;
const handler = mswHandlers[`${method}:${rawPath}`];
if (handler) {
return handler(request);
}
console.warn(`No handler found for ${method} ${rawPath}`);
return { error: `No handler found for ${method} ${rawPath}`, status: 404 };
}
export async function createMswHandlers(
config: Config,
ModuleLoaderClass = ModuleLoader,
) {
// TODO: For some reason the Vitest Custom Commands needed by Vitest Browser mode fail on fs.readFile when they are called from the nested loadOpenApiDocument function.
// If we "pre-read" the file here it works. This is a workaround to avoid the issue.
await fs.readFile(config.openApiPath);
const openApiDocument = await loadOpenApiDocument(config.openApiPath);
if (openApiDocument === undefined) {
throw new Error(
`Could not load OpenAPI document from ${config.openApiPath}`,
);
}
const modulesPath = config.basePath;
const compiledPathsDirectory = nodePath
.join(modulesPath, ".cache")
.replaceAll("\\", "/");
const registry = new Registry();
const contextRegistry = new ContextRegistry();
const dispatcher = new Dispatcher(
registry,
contextRegistry,
openApiDocument,
config,
);
const moduleLoader = new ModuleLoaderClass(
compiledPathsDirectory,
registry,
contextRegistry,
openApiDocument,
);
await moduleLoader.load();
const routes = registry.routes;
const handlers = routes.flatMap((route) => {
const { methods, path } = route;
return Object.keys(methods)
.filter((method) =>
allowedMethods.includes(
method.toLowerCase() as (typeof allowedMethods)[number],
),
)
.map((method) => {
const lowerMethod = method.toLowerCase();
const apiPath = `${openApiDocument.basePath ?? ""}${path.replaceAll("{", ":").replaceAll("}", "")}`;
const handler = async (request: MockRequest) => {
return await dispatcher.request(request);
};
mswHandlers[`${method}:${apiPath}`] = handler;
return { method: lowerMethod, path: apiPath };
});
});
return handlers;
}
export async function counterfact(config: Config) {
const modulesPath = config.basePath;
const compiledPathsDirectory = nodePath
.join(modulesPath, ".cache")
.replaceAll("\\", "/");
await rm(compiledPathsDirectory, { force: true, recursive: true });
const registry = new Registry();
const contextRegistry = new ContextRegistry();
const codeGenerator = new CodeGenerator(
config.openApiPath,
config.basePath,
config.generate,
);
const openApiDocument = await loadOpenApiDocument(config.openApiPath);
const dispatcher = new Dispatcher(
registry,
contextRegistry,
openApiDocument,
config,
);
const transpiler = new Transpiler(
nodePath.join(modulesPath, "routes").replaceAll("\\", "/"),
compiledPathsDirectory,
"commonjs",
);
const moduleLoader = new ModuleLoader(
compiledPathsDirectory,
registry,
contextRegistry,
openApiDocument,
);
const middleware = koaMiddleware(dispatcher, config);
const koaApp = createKoaApp(registry, middleware, config, contextRegistry);
async function start(options: Config) {
const { generate, startServer, watch, buildCache } = options;
if (generate.routes || generate.types) {
await codeGenerator.generate();
}
if (watch.routes || watch.types) {
await codeGenerator.watch();
}
let httpTerminator: HttpTerminator | undefined;
if (startServer) {
await transpiler.watch();
await moduleLoader.load();
await moduleLoader.watch();
const server = koaApp.listen({
port: config.port,
});
httpTerminator = createHttpTerminator({
server,
});
} else if (buildCache) {
// If we are not starting the server, we still want to transpile and load modules
await transpiler.watch();
await transpiler.stopWatching();
}
return {
async stop() {
await codeGenerator.stopWatching();
await transpiler.stopWatching();
await moduleLoader.stopWatching();
await httpTerminator?.terminate();
},
};
}
return {
contextRegistry,
koaApp,
koaMiddleware: middleware,
registry,
start,
startRepl: () => startReplServer(contextRegistry, registry, config),
};
}