云函数属于管理端,和小程序端云API 以同样的风格提供了数据库、存储和云函数的 API。
云函数在创建时会在云函数目录下默认新建一个 package.json。其中sdkVersion为云函数的SDK版本号,*代表最新版本。在云函数中调用数据库、云存储、外联等API时,需要依赖此云函数SDK版本号(老版本IDE会默认生成0.0.2-alpha.0版本,建议版本号始终保持最新)。
假设在数据库中已经有一个集合awards,使用以下方式在数据库中插入一条数据。
exports.main = async (context) => {
const cloud = context.cloud;
cloud.db.collection('users').insertOne({
name: 'tom',
age: 1
}).then(res => {
console.log(res)
})
return 'ok';
};
假设要使用云函数上传文件(云函数中只支持上传文件流)。
exports.uploadFile = async (context) => {
const cloud = context.cloud;
let result;
try{
result = await cloud.file.uploadFile({
fileContent:new Buffer("333434"),fileName:"test"
})
}catch(e){
console.log("e",e)
}
console.log("uploadFileResult",result);
return 'uploadFile';
};
假设要与外部服务器进行通信,使用SDK提供的外联API。注意:需要先申请白名单。
exports.main = async (context) => {
const result = await context.cloud.httpApi.invoke(
{
'domain':'http://11.19.128.205:10511',
'params': {
'sign':'addadad',
'test':1,
},
'method':'POST',
'headers': {
'Content-Type':'application/json;charset=UTF-8',
},
'body':{
'name':'cx',
'age':18,
}
});
return { success:true, msg: result }
};