示例02 云函数编写与触发 对应教程:第 2 章 · 云函数:Serverless 后端逻辑核心 基础云函数(事件驱动) 客户端调用: HTTP 触发云函数 定时触发云函数 定时触发器配置(cloudbaserc.json): 云函数中调用其他云资源
对应教程:第 2 章 · 云函数:Serverless 后端逻辑核心
// functions/hello/index.js exports.main = async (event, context) => { const { name = 'World' } = event return { message: `Hello, ${name}!`, timestamp: Date.now() } }
客户端调用:
const res = await app.callFunction({ name: 'hello', data: { name: 'CloudBase' } }) console.log(res.result) // { message: 'Hello, CloudBase!', timestamp: ... }
// functions/api/index.js exports.main = async (event, context) => { const { httpMethod, path } = event if (httpMethod === 'GET' && path === '/api/status') { return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'ok', version: '1.0.0' }) } } return { statusCode: 404, body: 'Not Found' } }
// functions/cleanup/index.js const cloud = require('@cloudbase/node-sdk') const app = cloud.init({ env: cloud.SYMBOL_CURRENT_ENV }) const db = app.database() exports.main = async (event, context) => { // 清理 7 天前的过期数据 const sevenDaysAgo = Date.now() - 7 * 24 * 3600 * 1000 const { deleted } = await db.collection('logs') .where({ createdAt: db.command.lt(sevenDaysAgo) }) .remove() return { deletedCount: deleted } }
定时触发器配置(cloudbaserc.json):
{ "triggers": [{ "name": "dailyCleanup", "type": "timer", "config": "0 0 2 * * * *" }] }
// functions/order/index.js const cloud = require('@cloudbase/node-sdk') const app = cloud.init({ env: cloud.SYMBOL_CURRENT_ENV }) const db = app.database() const storage = app.storage() exports.main = async (event, context) => { const { orderId } = event // 1. 查数据库获取订单 const { data: order } = await db.collection('orders').doc(orderId).get() // 2. 从云存储下载附件 const fileRes = await storage.downloadFile({ fileID: order.attachmentFileID }) // 3. 更新订单状态 await db.collection('orders').doc(orderId).update({ status: 'processing', updatedAt: db.serverDate() }) return { success: true, order } }