fcapi
Version:
cloud function computing api generator
29 lines (27 loc) • 974 B
JavaScript
module.exports = function (handler) {
return async (req, res, context) => {
try {
if (req.method !== 'POST') throw 'Invalid method'
if (!/json/i.test(req.headers['content-type'])) throw 'Invalid content'
res.setHeader('content-type', 'application/json')
const str = await read(req)
const result = await handler(JSON.parse(str), context)
res.send(JSON.stringify(
typeof result === 'object' ? result : { data: result }
))
} catch (err) {
res.setStatusCode(500)
res.send(JSON.stringify({
message: err instanceof Error ? err.message : err
}))
}
}
}
function read(req) {
return new Promise((resolve, reject) => {
req.on('error', reject)
let arr = []
req.on('data', r => arr.push(r))
req.on('end', () => resolve(Buffer.concat(arr).toString('utf8')))
})
}