-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
195 lines (185 loc) · 4.04 KB
/
index.mjs
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
import fs from 'node:fs/promises'
import path from 'node:path'
import http from 'node:http'
const MAX_REQUEST_BODY_SIZE = 1024 * 1024
const contentTypesByExtension = {
html: 'text/html',
ico: 'image/x-icon',
js: 'text/javascript',
json: 'application/json',
}
const dataDirectory = 'data'
const srcDirectory = 'src'
const port = parseInt(process.env.PORT ?? '8000', 10)
/**
* @param {import('http').IncomingMessage} req
* @param {import('http').ServerResponse} res
*/
async function GET(req, res) {
switch (req.url) {
case '/':
sendFile(res, path.join(srcDirectory, 'index.html'))
break
case '/favicon.ico':
sendFile(res, 'favicon.ico')
break
default:
const dataPrefix = '/data/'
const srcPrefix = '/src/'
if (req.url.startsWith(srcPrefix)) {
sendFile(
res,
path.join(
srcDirectory,
...req.url.substring(srcPrefix.length).split('/')
)
)
} else if (req.url.startsWith(dataPrefix)) {
const fileName = req.url.substring(dataPrefix.length)
const fileDir = segmentedDir(fileName)
sendFile(
res,
path.join(dataDirectory, fileDir, fileName)
)
} else {
res.writeHead(404)
res.end('Not found')
}
}
}
/**
* Get segmented file path
* @param {string} file
* @returns {string}
*/
function segmentedDir(file) {
const a = file.substring(0, 5)
const b = file.substring(5, 10)
return path.join(a, b)
}
/**
* @param {import('http').IncomingMessage} req
* @param {import('http').ServerResponse} res
*/
async function POST(req, res) {
switch (req.url) {
case '/data':
try {
const data = await getBody(req)
const now = Date.now()
const id = (
Math.random().toString(32) + '0000'
).substring(2, 6)
const file = `${now}-${id}.json`
const fileDir = path.join(
dataDirectory,
segmentedDir(file)
)
await fs.mkdir(fileDir, { recursive: true })
await fs.writeFile(path.join(fileDir, file), data, {
encoding: 'utf-8',
})
const responseBody = JSON.stringify({ url: file })
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(responseBody),
})
res.end(responseBody)
} catch (e) {
if (e.clientError) {
res.writeHead(400)
res.end(e.message)
} else {
console.error(e)
res.writeHead(500)
res.end('Server error')
}
}
break
default:
res.writeHead(404)
res.end('Not found')
}
}
/**
* Get request body
* @param {import('http').IncomingMessage} req
* @returns {Promise<string>}
*/
async function getBody(req) {
return new Promise((resolve, reject) => {
let body = ''
let ok = true
req.on('data', (chunk) => {
if (ok) {
if (
body.length + chunk.length >
MAX_REQUEST_BODY_SIZE
) {
ok = false
const requestBodyError = new Error(
`Request body too large (limit is ${MAX_REQUEST_BODY_SIZE})`
)
requestBodyError.clientError = true
reject(requestBodyError)
}
body += chunk
}
})
req.on('end', () => {
if (ok) {
resolve(body)
}
})
})
}
/**
* @param {import('http').ServerResponse} res
* @param {string} file
*/
async function sendFile(res, file) {
try {
const extension = file.substring(
file.lastIndexOf('.') + 1
)
const content = await fs.readFile(
file,
extension === 'ico'
? {}
: {
encoding: 'utf-8',
}
)
res.writeHead(200, {
'Content-Type':
contentTypesByExtension[extension] ?? 'text/plain',
})
res.end(content)
} catch (e) {
res.writeHead(404)
res.end('Not found')
}
}
/**
* @param {import('http').IncomingMessage} req
* @param {import('http').ServerResponse} res
*/
async function listener(req, res) {
const handler = { GET, POST }[req.method]
if (handler) {
handler(req, res)
} else {
res.writeHead(404)
res.end('Not found')
}
}
async function main() {
console.log('Starting...')
await fs.mkdir(dataDirectory, { recursive: true })
http
.createServer(listener)
.listen(port, () =>
console.log(`Listening on http://localhost:${port}`)
)
}
main().catch((e) => console.error(e))