-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathnespresso.ts
83 lines (80 loc) · 2.85 KB
/
nespresso.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
import { Request as ExpressRequest, Response as ExpressResponse, request, response } from "express";
import { NextRequest, NextResponse } from "next/server";
type ExpressMiddleware = (expressReq: ExpressRequest, expressRes: ExpressResponse, next: () => void) => void
interface ExpressMiddlewareCtx {
expressReq: ExpressRequest,
expressRes: ExpressResponse,
sendCall?: any,
endCall?: any
redirectCall?: any
}
function runMiddleware(mds: Array<ExpressMiddleware>, i: number, ctx: ExpressMiddlewareCtx) {
console.log("running middleware", { i, ctx })
ctx.expressRes = {
...ctx.expressRes,
send(...args) {
console.log("sending", args)
if (ctx.sendCall) {
throw new Error("already sent")
}
ctx.sendCall = args
},
end(...args) {
console.log("ending", args)
if (ctx.sendCall) {
throw new Error("already ended")
}
ctx.endCall = args
},
redirect(...args) {
console.log("redirect")
ctx.redirectCall = args
}
}
function next() {
if (i === mds.length - 1) {
throw new Error("no next middleware")
}
// we only have a handful middleware so recursivity is ok
// using a stack would be cleaner, see Connect
runMiddleware(mds, i + 1, ctx)
}
const middleware = mds[i]
middleware(ctx.expressReq, ctx.expressRes, next)
return ctx
}
/**
* Turn a chain of middlewares into a Next Route Handler
*/
export function nespresso(...middlewares: Array<ExpressMiddleware>) {
return function (req: NextRequest): NextResponse {
// inspired from Express codebase
// TODO: how to properly initialize an Express request?
// Without that, we have to mimick all features of Express by hand
// let expressReq = Object.create(request, {}) as Request
// let expressRes = Object.create(response, {}) as Response
let expressReq = {
...req,
}
let expressRes = {
status(s: number) {
this.statusCode = s
return this
}
}
const ctx: ExpressMiddlewareCtx = { expressReq, expressRes }
runMiddleware(middlewares, 0, ctx)
console.log({ ctx })
if (ctx.sendCall) {
// we assume JSON for now
// @ts-ignore
return NextResponse.json(ctx.sendCall[0], { status: ctx.expressRes.statusCode || 200 })
} else if (ctx.endCall) {
// @ts-ignore
return NextResponse.json({ status: ctx.expressRes.statusCode || 200 })
} else if (ctx.redirectCall) {
return NextResponse.redirect(ctx.redirectCall[0])
}
return NextResponse.json({ error: "no response from middleware" }, { status: 500 })
}
}