/
index-server.ts
351 lines (317 loc) · 10.3 KB
/
index-server.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import {assert, Ctx, ResolverConfig} from "blitz"
import {NextApiRequest, NextApiResponse} from "next"
import {resolve} from "path"
import {deserialize, parse, serialize as superjsonSerialize} from "superjson"
import {RpcLogger} from "./rpc-logger"
import {LoaderOptions} from "./server/loader/utils/loader-utils"
import {RpcLoggerOptions} from "./server/plugin"
// TODO - optimize end user server bundles by not exporting all client stuff here
export * from "./index-browser"
export {RpcServerPlugin} from "./server/plugin"
export * from "./server/resolvers/resolver"
// Mechanism used by Vite/Next/Nuxt plugins for automatically loading query and mutation resolvers
function isObject(value: unknown): value is Record<string | symbol, unknown> {
return typeof value === "object" && value !== null
}
const defaultConfig: ResolverConfig = {
httpMethod: "POST",
}
function getGlobalObject<T extends Record<string, unknown>>(key: string, defaultValue: T): T {
assert(key.startsWith("__internal_blitz"), "unsupported key")
if (typeof global === "undefined") {
return defaultValue
}
assert(isObject(global), "not an object")
return ((global as Record<string, unknown>)[key] =
((global as Record<string, unknown>)[key] as T) || defaultValue)
}
type Resolver = (...args: unknown[]) => Promise<unknown>
type ResolverFiles = Record<
string,
{
absoluteResolverPath: string
resolver: () => Promise<{default?: Resolver; config?: ResolverConfig}>
}
>
export type ResolverPathOptions = "queries|mutations" | "root" | ((path: string) => string)
// We define `global.__internal_blitzRpcResolverFiles` to ensure we use the same global object.
// Needed for Next.js. I'm guessing that Next.js is including the `node_modules/` files in a seperate bundle than user files.
const g = getGlobalObject<{blitzRpcResolverFilesLoaded: ResolverFiles | null}>(
"__internal_blitzRpcResolverFiles",
{
blitzRpcResolverFilesLoaded: null,
},
)
export function loadBlitzRpcResolverFilesWithInternalMechanism() {
return g.blitzRpcResolverFilesLoaded
}
export function __internal_addBlitzRpcResolver(
routePath: string,
absoluteResolverPath: string,
resolver: () => Promise<{default?: Resolver; config?: ResolverConfig}>,
) {
g.blitzRpcResolverFilesLoaded = g.blitzRpcResolverFilesLoaded || {}
const existingResolver = g.blitzRpcResolverFilesLoaded[routePath]
if (existingResolver && existingResolver.absoluteResolverPath !== absoluteResolverPath) {
const logger = new RpcLogger(routePath)
const errorMessage = `\nThe following resolver files resolve to the same path: ${routePath}\n\n1. ${absoluteResolverPath}\n2. ${
existingResolver.absoluteResolverPath
}\n\nPossible Solutions:\n\n1. Remove or rename one of the resolver files. \n2. Set the following in your in next.config.js to load all resolvers using their absolute paths:
\n\n//next.config.js\nblitz:{\n resolverPath: "root",\n},\n
\n${
process.env.NODE_ENV === "production"
? `Resolver in ${absoluteResolverPath} is currently being shadowed by ${existingResolver.absoluteResolverPath}`
: ""
}
`
logger.error(errorMessage)
if (process.env.NODE_ENV !== "production") {
g.blitzRpcResolverFilesLoaded[routePath] = {
absoluteResolverPath,
resolver: async () => {
return {
...(await resolver()),
default: async () => {
const error = new Error(errorMessage)
error.name = "BlitzRPCResolverCollisionError"
error.stack = ""
throw error
},
}
},
}
}
} else {
g.blitzRpcResolverFilesLoaded[routePath] = {
absoluteResolverPath,
resolver,
}
}
return resolver
}
const dir = __dirname + (() => "")() // trick to avoid `@vercel/ncc` to glob import
const loaderClient = resolve(dir, "./loader-client.cjs")
const loaderServer = resolve(dir, "./loader-server.cjs")
const loaderServerResolvers = resolve(dir, "./loader-server-resolvers.cjs")
interface WebpackRule {
test: RegExp
use: Array<{
loader: string
options: LoaderOptions
}>
}
export interface InstallWebpackConfigOptions {
webpackConfig: {
resolve: {
alias: {
[key: string]: boolean | string
}
}
plugins: any[]
module: {
rules: WebpackRule[]
}
}
webpackRuleOptions: LoaderOptions
}
export function installWebpackConfig({
webpackConfig,
webpackRuleOptions,
}: InstallWebpackConfigOptions) {
webpackConfig.resolve.alias["npm-which"] = false
webpackConfig.resolve.alias["cross-spawn"] = false
webpackConfig.module.rules.push({
test: /[\\/]\[\[\.\.\.blitz]]?.+\.[jt]sx?$/,
use: [
{
loader: loaderServer,
options: webpackRuleOptions,
},
],
})
webpackConfig.module.rules.push({
test: /[\\/](queries|mutations)[\\/]/,
use: [
{
loader: loaderClient,
options: webpackRuleOptions,
},
{
loader: loaderServerResolvers,
options: webpackRuleOptions,
},
],
})
}
export function installTurboConfig() {
return {
resolveAlias: {
"cross-spawn": {browser: ".blitz/turbopack-empty.js"},
"npm-which": {browser: ".blitz/turbopack-empty.js"},
fs: {browser: ".blitz/turbopack-empty.js"},
child_process: {browser: ".blitz/turbopack-empty.js"},
},
rules: {
"**/*...blitz*.{jsx,tsx,js,ts}": {
default: {
loaders: [{loader: loaderServer, options: {}}],
as: "*.ts",
},
},
"**/{queries,mutations}/**": {
browser: {
loaders: [
{
loader: loaderClient,
options: {},
},
],
as: "*.ts",
},
default: {
loaders: [
{
loader: loaderServerResolvers,
options: {},
},
],
as: "*.ts",
},
},
},
}
}
// ----------
// END LOADER
// ----------
async function getResolverMap(): Promise<ResolverFiles | null | undefined> {
// Handles:
// - Next.js
// - Nuxt
// - Vite with `importBuild.js`
{
const resolverFilesLoaded = loadBlitzRpcResolverFilesWithInternalMechanism()
if (resolverFilesLoaded) {
return resolverFilesLoaded
}
}
// Handles:
// - Vite
// {
// const {resolverFilesLoaded, viteProvider} = await loadTelefuncFilesWithVite(runContext)
// if (resolverFilesLoaded) {
// assertUsage(
// Object.keys(resolverFilesLoaded).length > 0,
// getErrMsg(`Vite [\`${viteProvider}\`]`),
// )
// return resolverFilesLoaded
// }
// }
}
interface RpcConfig {
onError?: (error: Error, ctx: Ctx) => void
formatError?: (error: Error, ctx: Ctx) => Error
logging?: RpcLoggerOptions
}
export function rpcHandler(config: RpcConfig) {
return async function handleRpcRequest(req: NextApiRequest, res: NextApiResponse, ctx: Ctx) {
const resolverMap = await getResolverMap()
assert(resolverMap, "No query or mutation resolvers found")
assert(
Array.isArray(req.query.blitz),
"It seems your Blitz RPC endpoint file is not named [[...blitz]].(jt)s. Please ensure it is",
)
const relativeRoutePath = (req.query.blitz as string[])?.join("/")
const routePath = "/" + relativeRoutePath
const resolverName = routePath.replace(/(\/api\/rpc)?\//, "")
const rpcLogger = new RpcLogger(resolverName, config.logging)
const loadableResolver = resolverMap?.[routePath]?.resolver
if (!loadableResolver) {
throw new Error("No resolver for path: " + routePath)
}
const {default: resolver, config: resolverConfig} = await loadableResolver()
if (!resolver) {
throw new Error("No default export for resolver path: " + routePath)
}
const resolverConfigWithDefaults = {...defaultConfig, ...resolverConfig}
if (req.method === "HEAD") {
// We used to initiate database connection here
res.status(200).end()
return
} else if (
req.method === "POST" ||
(req.method === "GET" && resolverConfigWithDefaults.httpMethod === "GET")
) {
if (req.method === "POST" && typeof req.body.params === "undefined") {
const error = {message: "Request body is missing the `params` key"}
rpcLogger.error(error.message)
res.status(400).json({
result: null,
error,
})
return
}
try {
const data = deserialize({
json:
req.method === "POST"
? req.body.params
: req.query.params
? parse(`${req.query.params}`)
: undefined,
meta:
req.method === "POST"
? req.body.meta?.params
: req.query.meta
? parse(`${req.query.meta}`)
: undefined,
})
rpcLogger.timer.initResolver()
rpcLogger.preResolver(data)
const result = await resolver(data, (res as any).blitzCtx)
rpcLogger.timer.resolverDuration()
rpcLogger.postResolver(result)
rpcLogger.timer.initSerialization()
const serializedResult = superjsonSerialize(result)
rpcLogger.timer.initNextJsSerialization()
;(res as any).blitzResult = result
res.json({
result: serializedResult.json,
error: null,
meta: {
result: serializedResult.meta,
},
})
rpcLogger.timer.nextJsSerializationDuration()
rpcLogger.nextJsSerialization()
rpcLogger.timer.serializerDuration().totalDuration()
rpcLogger.postResponse()
return
} catch (error: any) {
if (error._clearStack) {
error.stack = ""
}
config.onError?.(error, ctx)
rpcLogger.error(error)
if (!error.statusCode) {
error.statusCode = 500
}
const formattedError = config.formatError?.(error, ctx) ?? error
const serializedError = superjsonSerialize(formattedError)
res.json({
result: null,
error: serializedError.json,
meta: {
error: serializedError.meta,
},
})
return
}
} else {
// Everything else is error
rpcLogger.warn(`${req.method} method not supported`)
res.status(404).end()
return
}
}
}