携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情
昨天我们通过微信的登录接口拿到了用户的openid,我们之前的数据没有这个用户唯一标识的字段,如果有多个用户的账单数据,我们是无法获取到哪些是当前用户的数据的,一旦我们加上这个字段,我们就可以通过这个唯一标识,将数据查询出来。我们手动修改数据库,给其中某条记录添加上这个字段:
现在我们的纸尿裤被我们加了个openid字段进去,这个openid就是我们之前获取到的那个,代表的是我自己的微信账号。
登录后,我们保存当前的openid,查询时带上这个参数:
onLoad() {
this.getTotalFee();
uni.login({
success: (res) => {
uniCloud.callFunction({
name: 'login',
data: {
code: res.code
},
success: (rsp) => {
+ uni.setStorageSync('openid', rsp.result.data.openid);
}
})
}
})
},
首先我们改云函数,加上openid查询条件:
'use strict';
const db = uniCloud.database()
const _ = db.command
exports.main = async (event, context) => {
const collection = db.collection('bill')
+ const res = await collection.where({'createTime': _.gt(event.beginTime), 'openid': event.openid}).get()
return res
};
修改首页以及历史记录的查询方法:
getTotalFee() {
let month = new Date().getMonth() + 1;
month = month < 10 ? '0' + month : month;
let year = new Date().getFullYear();
let dateStr = `${year}-${month}-01 00:00:00`;
uni.showLoading({
title: '处理中...'
})
uniCloud.callFunction({
name: 'get',
data: {
beginTime: new Date(dateStr).getTime(),
+ openid: uni.getStorageSync('openid')
}
}).then((res) => {
uni.hideLoading()
this.feeList = res.result.data;
this.total = this.feeList.reduce((p, c) => Number(c.price) + p, 0);
})
},
getListByDate(type) {
this.current = type;
uni.showLoading({
title: '处理中...'
})
let beginTime = null;
let now = new Date().getTime();
let day = 24 * 60 * 60 * 1000;
switch (type) {
case 'week':
beginTime = now - 7 * day;
break;
case 'month':
beginTime = now - 30 * day;
break;
case 'season':
beginTime = now - 90 * day;
break;
case 'halfyear':
beginTime = now - 180 * day;
break;
}
uniCloud.callFunction({
name: 'get',
data: {
beginTime,
+ openid: uni.getStorageSync('openid')
}
}).then((res) => {
uni.hideLoading()
this.list = res.result.data;
})
}
我们刚刚是给纸尿裤那条记录加了openid,所以正常情况是首页有纸尿裤,历史记录有纸尿裤,并且仅仅只有纸尿裤,其他的查不到了:
直接在数据库里加openid只是为了方便测试,真正openid是在添加记录的时候传的,我们再改下记一笔的逻辑:
async submit() {
uni.showLoading({
title: '处理中...'
});
const formRes = await this.$refs.form.validate();
const res = await uniCloud.callFunction({
name: 'add',
data: {
...formRes,
+ openid: uni.getStorageSync('openid'),
createTime: Date.now()
}
});
uni.showModal({
content: `成功添加一条数据,文档id为:${res.result.id}`,
showCancel: false
})
uni.hideLoading();
}
ok,至此,我们的数据记录就有了用户标识了,不同的用户查到的只能是自己的数据了,很nice,目前只是最最粗暴的用户系统,后面我们会优化它,今天就先到这啦,咱们明天再见~