-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
68 lines (62 loc) · 1.58 KB
/
mod.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
/**
* Request interface extension with additional `parsedBody` property (where parsed body gets stored)
*/
export interface ReqWithBody<T = Record<string, unknown>> extends Request {
parsedBody?: T
}
/**
* Universal body parser function
* @param fn request body formatter
*/
export const bodyParser =
<T>(fn: (body: string) => T) => async (req: ReqWithBody<T>) => {
const body = await req.text()
req.parsedBody = fn(body)
return req.parsedBody
}
type NextFunction = (err?: Error) => void
/**
* Parse a request with JSON body and `Content-Type`: `application/json` header.
* @param req Server request
* @param _
* @param next
*/
export const json = async <T = Record<string, unknown>>(
req: ReqWithBody<T>,
_?: unknown,
next?: NextFunction,
) => {
if (req.headers.get('content-type') === 'application/json') {
try {
await bodyParser((x) => JSON.parse(x.toString()))(req)
} catch (e) {
next?.(e)
} finally {
next?.()
}
} else next?.()
}
/**
* Parse a form with the body and `Content-Type`: `application/x-www-urlencoded` header.
* @param req Server request
* @param _
* @param next
*/
export const urlencoded = async (
req: ReqWithBody<Record<string, string>>,
_?: unknown,
next?: NextFunction,
) => {
if (req.headers.get('content-type') === 'application/x-www-form-urlencoded') {
try {
await bodyParser((x) => {
const u = new URLSearchParams(x.toString())
return Object.fromEntries(u.entries())
})(req)
} catch (e) {
next?.(e)
} finally {
next?.()
}
} else next?.()
}