-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathhttp.ts
More file actions
120 lines (107 loc) · 3.19 KB
/
http.ts
File metadata and controls
120 lines (107 loc) · 3.19 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
import type { BaseServer } from '@logux/server'
import { COMMON_ERRORS, type Endpoint } from '@slowreader/api'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { config } from './config.ts'
function badRequest(res: ServerResponse, msg: string): true {
res.writeHead(400, { 'Content-Type': 'text/plain' })
res.end(msg)
return true
}
function collectBody(req: IncomingMessage): Promise<string> {
return new Promise(resolve => {
let data = ''
req.on('data', chunk => {
data += String(chunk)
})
req.on('end', () => {
resolve(data)
})
})
}
export class ErrorResponse {
message: string
constructor(message: string) {
this.message = message
}
}
function allowCors(res: ServerResponse, origin: string): void {
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, POST, GET, PUT, DELETE'
)
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Subprotocol')
}
const LOCALHOST = /:\/\/localhost:/
const PRODUCTION = /(:\/\/|\.)slowreader\.app$/
export function jsonApi<Response, Request extends object>(
server: BaseServer,
endpoint: Endpoint<Response, Request>,
listener: (
params: Request,
res: ServerResponse,
req: IncomingMessage
) =>
| ErrorResponse
| false
| Promise<ErrorResponse>
| Promise<false>
| Promise<Response>
| Response
): void {
server.http(async (req, res) => {
if (req.headers.origin) {
if (
(config.env === 'development' && LOCALHOST.test(req.headers.origin)) ||
PRODUCTION.test(req.headers.origin)
) {
allowCors(res, req.headers.origin)
}
}
if (req.headers['x-subprotocol'] && server.options.minSubprotocol) {
let clientSubprotocol = Number(req.headers['x-subprotocol'])
if (
isNaN(clientSubprotocol) ||
clientSubprotocol < server.options.minSubprotocol
) {
return badRequest(res, COMMON_ERRORS.OUTDATED_CLIENT)
}
}
if (req.method === 'OPTIONS') {
res.writeHead(200)
res.end()
return true
}
if (req.method === endpoint.method) {
let url = new URL(req.url!, 'http://localhost')
let urlParams = endpoint.parseUrl(url.pathname)
if (urlParams) {
if (req.headers['content-type'] !== 'application/json') {
return badRequest(res, 'Wrong content type')
}
let data = await collectBody(req)
let body: unknown
try {
body = JSON.parse(data)
} catch {
return badRequest(res, 'Invalid JSON')
}
let validated = endpoint.checkBody(body, urlParams)
if (!validated) {
return badRequest(res, 'Invalid body')
}
let answer = await listener(validated, res, req)
if (answer === false) {
return badRequest(res, 'Invalid request')
} else if (answer instanceof ErrorResponse) {
return badRequest(res, answer.message)
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(answer))
return true
}
}
return false
})
}