forked from unjs/h3
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
216 lines (189 loc) · 4.87 KB
/
app.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
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
import { withoutTrailingSlash } from "ufo";
import {
lazyEventHandler,
toEventHandler,
isEventHandler,
eventHandler,
H3Event,
} from "./event";
import { createError } from "./error";
import {
send,
sendStream,
isStream,
MIMES,
sendWebResponse,
isWebResponse,
} from "./utils";
import type { EventHandler, LazyEventHandler } from "./types";
export interface Layer {
route: string;
match?: Matcher;
handler: EventHandler;
}
export type Stack = Layer[];
export interface InputLayer {
route?: string;
match?: Matcher;
handler: EventHandler;
lazy?: boolean;
}
export type InputStack = InputLayer[];
export type Matcher = (url: string, event?: H3Event) => boolean;
export interface AppUse {
(
route: string | string[],
handler: EventHandler | EventHandler[],
options?: Partial<InputLayer>
): App;
(handler: EventHandler | EventHandler[], options?: Partial<InputLayer>): App;
(options: InputLayer): App;
}
export interface AppOptions {
debug?: boolean;
onError?: (error: Error, event: H3Event) => any;
}
export interface App {
stack: Stack;
handler: EventHandler;
options: AppOptions;
use: AppUse;
}
export function createApp(options: AppOptions = {}): App {
const stack: Stack = [];
const handler = createAppEventHandler(stack, options);
const app: App = {
// @ts-ignore
use: (arg1, arg2, arg3) => use(app as App, arg1, arg2, arg3),
handler,
stack,
options,
};
return app;
}
export function use(
app: App,
arg1: string | EventHandler | InputLayer | InputLayer[],
arg2?: Partial<InputLayer> | EventHandler | EventHandler[],
arg3?: Partial<InputLayer>
) {
if (Array.isArray(arg1)) {
for (const i of arg1) {
use(app, i, arg2, arg3);
}
} else if (Array.isArray(arg2)) {
for (const i of arg2) {
use(app, arg1, i, arg3);
}
} else if (typeof arg1 === "string") {
app.stack.push(
normalizeLayer({ ...arg3, route: arg1, handler: arg2 as EventHandler })
);
} else if (typeof arg1 === "function") {
app.stack.push(
normalizeLayer({ ...arg2, route: "/", handler: arg1 as EventHandler })
);
} else {
app.stack.push(normalizeLayer({ ...arg1 }));
}
return app;
}
export function createAppEventHandler(stack: Stack, options: AppOptions) {
const spacing = options.debug ? 2 : undefined;
return eventHandler(async (event) => {
const _reqPath = event.path;
let _layerPath: string;
for (const layer of stack) {
// 1. Remove prefix from path
if (layer.route.length > 1) {
if (!_reqPath.startsWith(layer.route)) {
continue;
}
_layerPath = _reqPath.slice(layer.route.length) || "/";
} else {
_layerPath = _reqPath;
}
// 2. Custom matcher
if (layer.match && !layer.match(_layerPath, event)) {
continue;
}
// 3. Update event path with layer path
event._path = _layerPath;
event.node.req.url = _layerPath; // Express compatibility
// 4. Handle request
const val = await layer.handler(event);
// Already handled
if (event.handled) {
return;
}
// Empty Content
if (val === null) {
event.node.res.statusCode = 204;
return send(event);
}
if (val) {
// Web Response
if (isWebResponse(val)) {
return sendWebResponse(event, val);
}
// Stream
if (isStream(val)) {
return sendStream(event, val);
}
// Buffer
if (val.buffer) {
return send(event, val);
}
// Blob
if (val.arrayBuffer && typeof val.arrayBuffer === "function") {
return send(
event,
Buffer.from(await (val as Blob).arrayBuffer()),
val.type
);
}
// Error
if (val instanceof Error) {
throw createError(val);
}
}
const valType = typeof val;
// HTML String
if (valType === "string") {
return send(event, val, MIMES.html);
}
// JSON Response
if (
valType === "object" ||
valType === "boolean" ||
valType === "number"
) {
return send(event, JSON.stringify(val, undefined, spacing), MIMES.json);
}
}
if (!event.handled) {
throw createError({
statusCode: 404,
statusMessage: `Cannot find any path matching ${event.path || "/"}.`,
});
}
});
}
function normalizeLayer(input: InputLayer) {
let handler = input.handler;
// @ts-ignore
if (handler.handler) {
// @ts-ignore
handler = handler.handler;
}
if (input.lazy) {
handler = lazyEventHandler(handler as LazyEventHandler);
} else if (!isEventHandler(handler)) {
handler = toEventHandler(handler, undefined, input.route);
}
return {
route: withoutTrailingSlash(input.route),
match: input.match,
handler,
} as Layer;
}