2019-05-13 08:56:06 +00:00
|
|
|
import fs from 'fs'
|
|
|
|
import path from 'path'
|
|
|
|
import http from 'http'
|
2019-05-26 10:30:45 +00:00
|
|
|
import serveHandler from 'serve-handler'
|
2019-05-13 08:13:19 +00:00
|
|
|
|
2019-05-14 01:36:25 +00:00
|
|
|
import serve404 from './libs/serve-404'
|
2019-06-01 06:37:20 +00:00
|
|
|
import serveDocs from './endpoints/docs'
|
2019-05-13 08:13:19 +00:00
|
|
|
|
2019-05-14 02:44:05 +00:00
|
|
|
const sendError = (req, res, error) => {
|
|
|
|
res.statusCode = 500
|
|
|
|
res.end(error.message)
|
|
|
|
}
|
|
|
|
|
2019-05-13 12:00:56 +00:00
|
|
|
const badgeHandlers = fs.readdirSync(path.join(__dirname, 'endpoints'))
|
2019-05-13 08:39:17 +00:00
|
|
|
.filter(name => !name.startsWith('_'))
|
2019-05-13 12:00:56 +00:00
|
|
|
.map(name => name.replace(/\.ts$/, ''))
|
2019-05-13 08:13:19 +00:00
|
|
|
|
2019-05-26 10:30:45 +00:00
|
|
|
const isStatic = (url) => {
|
|
|
|
if (url === '/') return true
|
|
|
|
if (url.startsWith('/static/')) return true
|
|
|
|
if (url.startsWith('/_next/')) return true
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-05-14 02:44:05 +00:00
|
|
|
const server = http.createServer(async (req, res) => {
|
2019-05-26 10:30:45 +00:00
|
|
|
// handle statics
|
|
|
|
if (isStatic(req.url)) {
|
2019-06-03 13:37:41 +00:00
|
|
|
return serveHandler(req, res, { public: path.join(__dirname, 'dist') })
|
2019-05-26 10:30:45 +00:00
|
|
|
}
|
|
|
|
|
2019-06-01 06:37:20 +00:00
|
|
|
// handle `/docs/:name`
|
|
|
|
if (req.url!.startsWith('/docs/')) {
|
|
|
|
return serveDocs(req, res)
|
|
|
|
}
|
|
|
|
|
2019-05-26 10:30:45 +00:00
|
|
|
// handle endpoints
|
2019-06-01 04:16:52 +00:00
|
|
|
const handlerName = badgeHandlers.find(h => req.url!.startsWith(`/${h}/`))
|
2019-05-13 08:13:19 +00:00
|
|
|
|
2019-05-14 02:44:05 +00:00
|
|
|
try {
|
|
|
|
if (handlerName) {
|
|
|
|
const handlerPath = path.join(__dirname, 'endpoints', handlerName)
|
|
|
|
const { default: handler } = await import(handlerPath)
|
|
|
|
return handler(req, res)
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error)
|
|
|
|
return sendError(req, res, error)
|
2019-05-13 08:13:19 +00:00
|
|
|
}
|
2019-05-14 02:44:05 +00:00
|
|
|
|
|
|
|
return serve404(req, res)
|
2019-05-13 08:13:19 +00:00
|
|
|
})
|
2019-05-13 08:39:17 +00:00
|
|
|
|
2019-05-25 09:26:44 +00:00
|
|
|
// Auto run
|
2019-05-14 02:24:21 +00:00
|
|
|
if (require.main === module) {
|
2019-05-14 02:44:05 +00:00
|
|
|
server.listen(3000)
|
2019-05-13 08:39:17 +00:00
|
|
|
}
|
|
|
|
|
2019-06-01 06:37:20 +00:00
|
|
|
process.on('unhandledRejection', e => {
|
|
|
|
console.error(500, e)
|
|
|
|
})
|
|
|
|
|
2019-05-14 02:44:05 +00:00
|
|
|
export default server
|