1.0.3 • Published 3 months ago
tcb-function-router v1.0.3
刚学 js、ts,根据个人使用习惯改写了 simple-cloudbase-router
https://www.npmjs.com/package/simple-cloudbase-router
https://github.com/sonofmagic/simple-cloudbase-router
// 云函数的 index.js
const app = require("./src/index");
const router = app.compose([
// 全局中间件处理
async (ctx, next) => {
ctx.body = "Hello router!";
await next();
},
// 路由处理
app.route("/user", async (ctx, next) => {
let { id } = ctx.params;
ctx.body = {
id,
msg: "Hello router!",
};
await next();
}),
]);
// 云函数入口
exports.main = async (event, context) => {
return await app.run(event, context, router);
};
// 客户端调用
// utils/tcb.js
import tcb from "@cloudbase/js-sdk";
export const app = tcb.init({ env: "env-id" });
export const apiFunc = async (url: string, params?: any) => {
try {
let res = await app.callFunction({
name: "function-name",
data: {
$url: url,
params: params,
},
});
// api接口调用成功:status=200;
if (res.result.status == 200) {
return res.result.data;
}
} catch (e) {
return e;
}
};
// api/user.js
import { apiFunc } from "@/utils/tcb";
export const getUserInfo = async () => {
return await apiFunc("/user", { id: "id001" });
};