sc-helloworld/api/server.mjs

51 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-09-04 11:03:59 +00:00
import { readFileSync } from 'fs'
import { Util } from 'service-core'
2020-09-04 11:03:59 +00:00
export function run(http, orgPort, ctx) {
let localUtil = new Util(import.meta.url)
let packagePath = localUtil.getPathFromRoot('../package.json')
let packageInfo = JSON.parse(readFileSync(packagePath))
2020-09-04 11:03:59 +00:00
const server = http.createServer(function (req, res) {
2022-03-29 10:07:06 +00:00
const d1 = new Date().getTime()
let finishedRequest = false
var done = function () {
if (finishedRequest) return
finishedRequest = true
2022-03-29 10:07:06 +00:00
var requestTime = new Date().getTime() - d1
let level = 'info'
if (res.statusCode >= 400) {
level = 'warn'
}
if (res.statusCode >= 500) {
level = 'error'
}
let status = ''
if (res.statusCode >= 400) {
status = res.statusCode + ' '
}
ctx.log[level]({
duration: requestTime,
status: res.statusCode,
}, `<-- ${status}${req.method} ${req.url}`)
}
res.addListener('finish', done);
res.addListener('close', done);
2020-09-04 11:03:59 +00:00
res.writeHead(200);
2020-09-09 13:54:26 +00:00
res.write(JSON.stringify(packageInfo, null, ' '))
2020-09-04 11:03:59 +00:00
res.end()
})
2020-09-09 14:32:23 +00:00
let port = orgPort || 4000
2020-09-04 11:03:59 +00:00
return server.listenAsync(port)
.then(function() {
ctx.log.event.info(`Server is listening on ${port} serving package ${packagePath}`)
ctx.log.info(`Server is listening on ${port} serving package ${packagePath}`)
2020-09-04 11:03:59 +00:00
})
}