@cloudbase/page-module
单页模板 SDK,该 SDK 同时支持 云函数端
和 微信小程序端
使用,内部自动识别运行环境,场景模块接口保持一致。
Note: 云函数端使用,依赖的
wx-server-sdk
需自行安装。
Install
npm install @cloudbase/page-module
yarn add @cloudbase/page-module
Usage
初始化 PageModule
实例:
import { PageModule } from '@cloudbase/page-module'
const pageModule = new PageModule('tcb:SignUp')
调用接口
pageModule.callMethod('check_sign_able', {
a: 1,
b: 2
})
操作数据库
pageModule.database().collection('your_datasource_name').add({
name: 'test'
})
API
Class: PageModule
-
init(moduleName: string, options: IPageModuleOptions = {}): PageModule
- 初始化PageModule
实例-
moduleName: string
- 单页模板模块名称 -
options
- 可选参数-
cloudbaseInstanceInitOptions
- 初始化 CloudBase 实例的参数,请参考 sdk init 方法 参数
-
-
-
callMethod(methodName: string, data: object)
- 调用接口-
methodName: string
- 数据源方法名称 -
data: object
- 数据源参数,如:{a:1, b:2}
-
-
database(): Database
- 获取数据库实例,实例说明见:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/Cloud.database.html
cloudbase
- 默认已使用当前云函数所在环境初始化的 wx-server-sdk
实例
import { cloudbase } from '@cloudbase/page-module'
Note: 非云函数环境下,无当前环境,将使用默认环境,如不满足需求,请使用
wx-server-sdk
自行初始化实例
callSelfDefinedMethod(event, context)
- 调用自定义方法
-
event
- 云函数调用时传入的参数-
methodName
- 方法名 -
params
- 方法参数
-
-
context
- 云函数调用时传入的参数
以下为使用示例(TS版本)
目录结构:
$ tree -L 2
.
├── README.md
├── api
│ └── doSomething.ts # 自定义方法
├── index.ts # 云函数入口函数
├── node_modules
└── package.json
云函数入口函数:index.ts
,该文件内通过 callSelfDefinedMethod
实现对自定义方法的调用
const { callSelfDefinedMethod } = require('@cloudbase/page-module')
exports.main = async function (event, context) {
return callSelfDefinedMethod(event, context)
}
如有如下自定义 doSomething
方法:apis/doSomething.ts
const { cloudbase } = require('@cloudbase/page-module')
module.exports = async function doSomething(event, context) {
console.log(event, context, 'doSomething')
const result = await cloudbase.callFunction({
name: 'doSomething',
})
console.log(result, 'cloudbase.callFunction')
}
如下为对入口函数进行调用的参数示例:
main({
methodName: 'doSomething', params: {a: 1, b: 2, c: 3}
}, {
hello: 'world'
})