forked from twikoojs/twikoo-zeabur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
38 lines (34 loc) · 1.1 KB
/
server.js
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
#!/usr/bin/env node
const http = require('http')
const twikoo = process.env.MONGODB_URI ? require('./mongo') : require('./index')
const server = http.createServer()
server.on('request', async function (request, response) {
try {
const buffers = []
for await (const chunk of request) {
buffers.push(chunk)
}
request.body = JSON.parse(Buffer.concat(buffers).toString())
} catch (e) {
console.error(e.message)
request.body = {}
}
response.status = function (code) {
this.statusCode = code
return this
}
response.json = function (json) {
if (!response.writableEnded) {
this.writeHead(200, { 'Content-Type': 'application/json' })
this.end(JSON.stringify(json))
}
return this
}
return await twikoo(request, response)
})
const port = parseInt(process.env.TWIKOO_PORT) || 8080
const host = process.env.TWIKOO_LOCALHOST_ONLY === 'true' ? 'localhost' : '::'
server.listen(port, host, function () {
console.log(`Twikoo is using ${process.env.MONGODB_URI ? 'mongo' : 'loki'} database`)
console.log(`Twikoo function started on host ${host} port ${port}`)
})