0%

记录-云开发遇到的问题和解决方案

云开发

技术产生背景

云计算

Saas: 常见软件
Pass: 钉钉,云服务器,阿里云,腾讯云。 amazon ec2, amzure
Lass: 算力,存储,网络,存储
Serverless(faas+baas): Serverless

一些概念

云数据库, 可以类比MongoDB,可以通过 http api 访问操作

环境

云函数

官方 quickStart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 官方 quickStart 例子
// /getOpenId/index
const cloud = require('wx-server-sdk');

cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
});



// 获取openId云函数入口函数
exports.main = async (event, context) => {
// 获取基础信息
const wxContext = cloud.getWXContext();

return {
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
};
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// /selectRecord/index.js
const cloud = require('wx-server-sdk');

cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();

// 查询数据库集合云函数入口函数
exports.main = async (event, context) => {
// 返回数据库查询结果
return await db.collection('sales').get();
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const getOpenId = require('./getOpenId/index');
const selectRecord = require('./selectRecord/index');

// 云函数入口函数
/*
通过传递过来的 type 切换
*/
exports.main = async (event, context) => {
switch (event.type) {
case 'getOpenId':
return await getOpenId.main(event, context);
case 'selectRecord':
return await selectRecord.main(event, context);
}
};

小程序请求

1
2
3
4
5
6
7
8
9
10
wx.cloud.callFunction({
name: 'quickStart', // 请求的一个云函数
data:{ type: 'getItemByItemName', title} // data 对应 event, type 是具体那个接口
}).then( resp =>{
console.log('返回结果', resp)

}).catch( error =>{
console.error('异常',error )

})

云数据库

云函数本地调试

云函数本地调试, 有些Bug,遇到问题重启即可。云函数本地调试

控制台数据库高级操作

云开发控制台-> 高级操作, 控制台数据库高级操作

日期字段的处理

日期 最好是转成事件戳进行存储, new Date().getTime(), 这样按照 orderBy(日期字段, desc | asc)

记录一下使用过的SQL语句

promise 风格

1
2
3
4
5
6
7
const db = wx.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // 填入当前用户 openid
}).count().then(res => {
console.log(res.total)
})
// then 返回查询后的字段

回调 风格

1
2
3
4
5
6
7
8
9
const db = wx.cloud.database()
db.collection('todos').where({
_openid: 'xxx' // 填入当前用户 openid
}).count({
success: function(res) {
console.log(res.total)
},
fail: console.error
})

db.collection().count()

count

db.collection('item').count().then( e=> e.total)

db.collection().get()

get

db.collection('item').limit(pageSize).skip(skipIndex).get().then( e => e.data)

db.command

const _ = db.command

_.eq, 是否相等
_.push数组push
_.pull数组匹配元素移除

db.collection().aggregate()

聚合 aggregate
match 根据条件过滤文档
sample 随机从文档中选取指定数量的记录
db.collection('item').aggregate().match({ publish:_.eq(1) }).sample({ size:1 }).end()
在集合中发起聚合操作,选取1条 publish字段等于1的记录返回

db.collection().update()

db.collection('user').where({}).update({ data: { })}})

HTTP API 请求

https://developers.weixin.qq.com/minigame/dev/wxcloud/reference-http-api/

  1. 获取 accesstoken
  2. 触发云函数消耗资源太多,建议后台访问云数据库时换成 http api 请求

例子

查询api为例

  1. sql拼接需要注意
  2. 返回结果是字符串,可以按照自己需要转成 对象