Nodejs12
http触发器,提供API服务
函数计算服务角色允许通过VPC访问表格存储
保存下面文件为serverless.js
// serverless.js
const util = require('util')
const TableStore = require('tablestore')
const getJsonBody = util.promisify(require('body/json'))
let client
exports.initializer = (context, callback) => {
client = new TableStore.Client({
accessKeyId: context.credentials.accessKeyId,
accessKeySecret: context.credentials.accessKeySecret,
securityToken: context.credentials.securityToken,
endpoint: '[TableStore Endpoint]',
instancename: '[TableStore Instance Name]'
})
callback(null, '')
}
// handlers = { GET: [func1, func2], POST: [func] }
// handler function:
// - @return false - next
// - @return { status, data } - abort
exports.handler = (handlers) => {
return async (req, resp) => {
const m = req.method
resp.setHeader('content-type', 'text/plain;charset=utf-8')
if (!handlers[m]) {
resp.setStatusCode(404)
resp.send('Method not allowed')
return
}
try {
if (m === 'POST' || m === 'PUT') req.body = await getJsonBody(req)
} catch {
resp.setStatusCode(400)
resp.send('需要JSON格式的请求体')
return
}
try {
let res = false
for (const f of handlers[m]) {
res = await <