-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
extend.ts
101 lines (97 loc) · 2.69 KB
/
extend.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
import { App } from './app.ts'
import { getRequestHeader } from './extensions/req/headers.ts'
import {
checkIfXMLHttpRequest,
getAccepts,
getAcceptsEncodings,
getAcceptsLanguages,
getFreshOrStale,
getHostname,
getIP,
getIPs,
getProtocol,
getSubdomains,
reqIs,
} from './extensions/req/mod.ts'
import {
append,
attachment,
clearCookie,
cookie,
end,
formatResponse,
getResponseHeader,
json,
redirect,
send,
sendFile,
sendStatus,
setContentType,
setHeader,
setLinksHeader,
setLocationHeader,
setVaryHeader,
status,
} from './extensions/res/mod.ts'
import type { THRequest } from './request.ts'
import { THResponse } from './response.ts'
import type { NextFunction } from './types.ts'
import { CookieMap } from './deps.ts'
import { renderTemplate } from './utils/template.ts'
/**
* Extends Request and Response objects with custom properties and methods
*/
export const extendMiddleware = <EngineOptions>(app: App<EngineOptions>) =>
async function extend(
req: THRequest,
res: THResponse<EngineOptions>,
next: NextFunction,
): Promise<void> {
if (app.settings?.bindAppToReqRes) {
req.app = app
res.app = app
}
// Request
req.accepts = getAccepts(req)
req.path = req._urlObject.pathname
// req.acceptsCharsets = getAcceptsCharsets(req)
req.acceptsEncodings = getAcceptsEncodings(req)
req.acceptsLanguages = getAcceptsLanguages(req)
req.is = reqIs(req)
req.xhr = checkIfXMLHttpRequest(req)
req.protocol = getProtocol(req)
req.hostname = getHostname(req)
req.secure = req.protocol === 'https'
Object.defineProperty(req, 'fresh', {
get: getFreshOrStale.bind(null, req, res),
})
req.stale = !req.fresh
req.ip = getIP(req)
req.ips = getIPs(req)
req.subdomains = getSubdomains(req, app.settings.subdomainOffset)
req.get = getRequestHeader(req)
req.query = req._urlObject.searchParams
req.cookies = new CookieMap(req.headers)
// Response
res.end = end(res)
res.send = send(req, res)
res.sendFile = sendFile(req, res)
res.json = json(res)
res.sendStatus = sendStatus(res)
res.attachment = attachment(res)
res.format = formatResponse(req, res, next)
res.status = status(res)
res.links = setLinksHeader(res)
res.vary = setVaryHeader(res)
res.redirect = redirect(req, res, next)
res.append = append(res)
res.render = renderTemplate<EngineOptions>(res, app)
res.cookie = cookie(res)
res.clearCookie = clearCookie(res)
res.location = setLocationHeader(req, res)
res.get = getResponseHeader(res)
res.header = setHeader(res)
res.set = setHeader(res)
res.type = setContentType(res)
await next()
}