sc-helloworld/api/server.mjs
Jonatan Nilsson 4560d20b04
All checks were successful
continuous-integration/appveyor/branch AppVeyor build succeeded
server: Log incoming requests on finish
2022-03-29 10:03:35 +00:00

49 lines
No EOL
1.3 KiB
JavaScript

import { readFileSync } from 'fs'
import { Util } from 'service-core'
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))
const server = http.createServer(function (req, res) {
let finishedRequest = false
var done = function () {
if (finishedRequest) return
finishedRequest = true
let level = 'debug'
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);
res.writeHead(200);
res.write(JSON.stringify(packageInfo, null, ' '))
res.end()
})
let port = orgPort || 4000
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}`)
})
}