UNPKG

aliyun-function-compat

Version:

aliyun function computing compat

57 lines (52 loc) 1.73 kB
'use strict' function isHttpFunction(req, res) { return typeof res.send === 'function' } module.exports = function (handler) { async function normal(events, context, callback) { if (events instanceof Buffer) { events = JSON.parse(events.toString()) } try { let result = await handler(events, context) callback(null, result) } catch (err) { callback(err) } } async function http(req, res, context) { req.body = await receiveData(req) try { let result = await handler(req, context) const isObj = typeof result === 'object' res.setHeader('content-type', isObj ? 'application/json' : 'text/plain') res.send(isObj ? JSON.stringify(result) : result) } catch (err) { res.setStatusCode(500) res.setHeader('content-type', 'application/json') res.send(JSON.stringify({ errcode: err.code || -1, message: typeof err === 'string' ? err : err.message })) } } return function (...args) { isHttpFunction(...args) ? http(...args) : normal(...args) } } function receiveData(req) { return new Promise(res => { const method = req.method if (method !== 'POST' && method !== 'PUT') { return res(null) } const arr = [] req.on('data', buf => arr.push(buf)) req.on('end', () => { let json = /json/i.test(req.headers['content-type']) let buf = Buffer.concat(arr) res(json ? JSON.parse(buf.toString('utf8')) : buf) }) req.on('error', res) }) }