-
-
Notifications
You must be signed in to change notification settings - Fork 815
Expand file tree
/
Copy pathapp.ts
More file actions
179 lines (158 loc) · 4.86 KB
/
app.ts
File metadata and controls
179 lines (158 loc) · 4.86 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
import {
App as H3App,
createApp,
createRouter,
eventHandler,
lazyEventHandler,
Router,
toNodeListener,
fetchWithEvent,
H3Error,
isEvent,
H3Event,
} from "h3";
import { createFetch, Headers } from "ofetch";
import destr from "destr";
import {
createCall,
createFetch as createLocalFetch,
} from "unenv/runtime/fetch/index";
import { createHooks, Hookable } from "hookable";
import type { NitroRuntimeHooks, CaptureError } from "./types";
import { useRuntimeConfig } from "./config";
import { cachedEventHandler } from "./cache";
import { normalizeFetchResponse } from "./utils";
import { createRouteRulesHandler, getRouteRulesForPath } from "./route-rules";
import type { $Fetch, NitroFetchRequest } from "nitropack";
import { plugins } from "#internal/nitro/virtual/plugins";
import errorHandler from "#internal/nitro/virtual/error-handler";
import { handlers } from "#internal/nitro/virtual/server-handlers";
export interface NitroApp {
h3App: H3App;
router: Router;
hooks: Hookable<NitroRuntimeHooks>;
localCall: ReturnType<typeof createCall>;
localFetch: ReturnType<typeof createLocalFetch>;
captureError: CaptureError;
}
function createNitroApp(): NitroApp {
const config = useRuntimeConfig();
const hooks = createHooks<NitroRuntimeHooks>();
const captureError: CaptureError = (error, context = {}) => {
const promise = hooks
.callHookParallel("error", error, context)
.catch((_err) => {
console.error("Error while capturing another error", _err);
});
if (context.event && isEvent(context.event)) {
const errors = context.event.context.nitro?.errors;
if (errors) {
errors.push({ error, context });
}
if (context.event.waitUntil) {
context.event.waitUntil(promise);
}
}
};
const h3App = createApp({
debug: destr(process.env.DEBUG),
onError: (error, event) => {
captureError(error, { event, tags: ["request"] });
return errorHandler(error as H3Error, event);
},
});
const router = createRouter({
preemptive: true,
});
h3App.use(createRouteRulesHandler());
// Create local fetch callers
const localCall = createCall(toNodeListener(h3App) as any);
const _localFetch = createLocalFetch(localCall, globalThis.fetch);
const localFetch = (...args: Parameters<typeof _localFetch>) => {
return _localFetch(...args).then((response) =>
normalizeFetchResponse(response)
);
};
const $fetch = createFetch({
fetch: localFetch,
Headers,
defaults: { baseURL: config.app.baseURL },
});
// @ts-ignore
globalThis.$fetch = $fetch;
// A generic event handler give nitro access to the requests
h3App.use(
eventHandler((event) => {
// Init nitro context
event.context.nitro = event.context.nitro || { errors: [] };
// Support platform context provided by local fetch
const envContext: { waitUntil?: H3Event["waitUntil"] } | undefined = (
event.node.req as unknown as { __unenv__: unknown }
)?.__unenv__;
if (envContext) {
Object.assign(event.context, envContext);
}
// Assign bound fetch to context
event.fetch = (req, init) =>
fetchWithEvent(event, req, init, { fetch: localFetch });
event.$fetch = ((req, init) =>
fetchWithEvent(event, req, init as RequestInit, {
fetch: $fetch,
})) as $Fetch;
// https://github.com/unjs/nitro/issues/1420
event.waitUntil = (promise) => {
if (!event.context.nitro._waitUntilPromises) {
event.context.nitro._waitUntilPromises = [];
}
event.context.nitro._waitUntilPromises.push(promise);
if (envContext?.waitUntil) {
envContext.waitUntil(promise);
}
};
event.captureError = (error, context) => {
captureError(error, { event, ...context });
};
})
);
for (const h of handlers) {
let handler = h.lazy ? lazyEventHandler(h.handler) : h.handler;
if (h.middleware || !h.route) {
const middlewareBase = (config.app.baseURL + (h.route || "/")).replace(
/\/+/g,
"/"
);
h3App.use(middlewareBase, handler);
} else {
const routeRules = getRouteRulesForPath(
h.route.replace(/:\w+|\*\*/g, "_")
);
if (routeRules.cache) {
handler = cachedEventHandler(handler, {
group: "nitro/routes",
...routeRules.cache,
});
}
router.use(h.route, handler, h.method);
}
}
h3App.use(config.app.baseURL as string, router.handler);
const app: NitroApp = {
hooks,
h3App,
router,
localCall,
localFetch,
captureError,
};
for (const plugin of plugins) {
try {
plugin(app);
} catch (err) {
captureError(err, { tags: ["plugin"] });
throw err;
}
}
return app;
}
export const nitroApp: NitroApp = createNitroApp();
export const useNitroApp = () => nitroApp;