2022-11-04 14:59:41 +01:00
|
|
|
import http from 'http'
|
|
|
|
|
import { v4 } from 'uuid'
|
|
|
|
|
import { Logger, LogLevel } from '../common/logger'
|
2022-11-21 19:07:43 +01:00
|
|
|
import { work as schedule } from '../common/scheduler'
|
2022-11-27 15:59:20 +01:00
|
|
|
import { parseJson } from './utils'
|
2022-11-04 14:59:41 +01:00
|
|
|
|
|
|
|
|
// Handles POST requests to /reservations
|
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
|
|
|
const { url, method } = req
|
|
|
|
|
|
2022-11-27 15:59:20 +01:00
|
|
|
Logger.instantiate('request', v4(), LogLevel.DEBUG)
|
2022-11-04 14:59:41 +01:00
|
|
|
Logger.debug('Incoming request')
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
!url ||
|
|
|
|
|
!method ||
|
|
|
|
|
!/^\/reservations$/.test(url) ||
|
|
|
|
|
method.toLowerCase() !== 'post'
|
|
|
|
|
) {
|
2022-11-21 18:53:42 +01:00
|
|
|
Logger.info('Not found')
|
|
|
|
|
res.writeHead(404, 'Not found')
|
2022-11-04 14:59:41 +01:00
|
|
|
res.end()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-27 15:59:20 +01:00
|
|
|
let jsonBody: Record<string, unknown>
|
|
|
|
|
const contentType = req.headers['content-type'] || 'application/json'
|
|
|
|
|
if (contentType !== 'application/json') {
|
|
|
|
|
Logger.error('Invalid content type', { contentType })
|
|
|
|
|
res.writeHead(406, 'Unsupported content type')
|
|
|
|
|
res.end()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-04 14:59:41 +01:00
|
|
|
try {
|
|
|
|
|
const length = Number.parseInt(req.headers['content-length'] || '0')
|
|
|
|
|
const encoding = req.readableEncoding || 'utf8'
|
2022-11-27 15:59:20 +01:00
|
|
|
jsonBody = await parseJson(length, encoding, req)
|
2022-11-04 14:59:41 +01:00
|
|
|
} catch (error: any) {
|
2022-11-27 15:59:20 +01:00
|
|
|
Logger.error('Failed to parse body', { error: error.message })
|
|
|
|
|
res.writeHead(400, 'Bad request')
|
|
|
|
|
res.end()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await schedule(jsonBody)
|
|
|
|
|
} catch (error: any) {
|
|
|
|
|
Logger.error('Failed to schedule request', { error })
|
2022-11-04 14:59:41 +01:00
|
|
|
res.writeHead(400, 'Bad request')
|
|
|
|
|
res.end()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res.end()
|
|
|
|
|
})
|
|
|
|
|
|
2022-11-27 15:59:20 +01:00
|
|
|
export default server
|