微信小程序-云函数点赞业务实现
一、效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f91234315385e975d01a189314567d35.gif)
二、逻辑
1.用户信息存储到全局变量中
App({
onLaunch: function () {
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
wx.cloud.init({
env: 'test-3g0tlekwebabfec9',
traceUser: true,
})
}
this.globalData = {}
try {
var value = wx.getStorageSync('userInfo')
if (value) {
this.globalData.userInfo = JSON.parse(value);
}
} catch (e) {
console.log('app js:', '用户未登录')
}
}
})
2.login.js
var that;
const db = wx.cloud.database();
Page({
data: {
userInfo:null,
},
bindGetUserInfo: function (e) {
console.log('bindGetUserInfo:', e)
if (e.detail.userInfo) {
that.addUser(e.detail.userInfo);
} else {
wx.showToast({
icon: 'none',
title: '拒绝授权',
})
}
},
addUser(userInfo) {
wx.showLoading({
title: '正在登录...',
})
wx.cloud.callFunction({
name: 'login',
data: userInfo
}).then(res => {
console.log('callFunction success:', res)
if(res.result.code==200){
userInfo._openid=res.result.userInfo._openid;
}
if(res.result.code==201){
userInfo._openid=res.result._openid;
}
wx.setStorage({
data: JSON.stringify(userInfo),
key: 'userInfo',
success(res) {
getApp().globalData.userInfo = userInfo;
wx.hideLoading()
wx.showToast({
icon:'success',
title: '登录成功',
})
wx.navigateTo({
url: '../circle/list',
})
}
})
}).catch(error => {
wx.hideLoading()
})
},
onLoad: function (options) {
that = this;
console.log("login onload:", getApp().globalData.userInfo)
if (getApp().globalData.userInfo) {
wx.navigateTo({
url: '../circle/list',
})
that.setData({
userInfo: getApp().globalData.userInfo
})
}
},
})
3.login云函数
const cloud = require('wx-server-sdk')
cloud.init({
env: 'test-**********'
})
const db = cloud.database();
exports.main = (event, context) => {
console.log(event)
console.log(context)
const wxContext = cloud.getWXContext()
const {
nickName,
avatarUrl,
gender
} = event;
return db.collection('user').where({
_openid: wxContext.OPENID
}).get()
.then(res => {
if (res.data.length > 0) {
return {
code: 200,
errMsg: '用户已经存在',
userInfo: res.data[0]
}
} else {
return db.collection('user').add({
data: {
_openid: wxContext.OPENID,
nickName: nickName,
avatarUrl: avatarUrl,
gender: gender,
time: new Date()
}
}).then(res => {
return {
code: 201,
errMsg: '用户注册成功',
_openid: wxContext.OPENID
}
})
.catch(error=>{
return {
code: 301,
errMsg: '用户注册失败',
}
})
}
}).catch(error=>{
return {
code: 300,
errMsg:'用户查询失败',
}
})
}
4.具体页面点赞函数
clickLove(e) {
console.log("点赞函数",e);
var index = e.currentTarget.dataset.index;
var circleData = that.data.list[index];
var loveList = circleData.loveList;
var isHaveLove = false;
for (var i = 0; i < loveList.length; i++) {
if (that.data.userInfo._openid == loveList[i]._openid) {
isHaveLove = true;
loveList.splice(i, 1);
wx.cloud.callFunction({
name:'updateCircleLove',
data:{
type:0,
circleId:circleData._id
}
}).then(res=>{
console.log("取消赞成功",res);
}).catch(err=>{
console.error("取消赞失败",err);
})
circleData.isLove = false;
break;
}
}
if (!isHaveLove) {
loveList.push({
nickName: that.data.userInfo.nickName,
_openid: that.data.userInfo._openid
});
wx.cloud.callFunction({
name:'updateCircleLove',
data:{
type:1,
circleId:circleData._id,
nickName:that.data.userInfo.nickName
}
}).then(res=>{
console.log("点赞成功",res);
}).catch(err=>{
console.error("点赞失败",err);
})
circleData.isLove = true;
}
that.setData({
list: that.data.list,
showOperationPannelIndex: -1
})
},
5.js
var that;
var db = wx.cloud.database()
var _ = db.command
var _animation;
var _animationIndex = 0;
var _animationIntervalId = -1;
const _ANIMATION_TIME = 300;
Page({
data: {
userInfo: null,
list: [],
friendIds: [],
showOperationPannelIndex: -1,
currentCircleIndex: -1,
showCommentAdd: false,
commentContent: '',
heightBottom: '',
refresh: false,
loadMore: false,
haveMoreData: true,
loading: false,
page: 0,
pageCount: 10,
reply:'',
touchStartOperation:false,
touchStartOperationPannel:false,
moveHeight:'500',
},
onLoad: function (options) {
that = this;
that.setData({
userInfo: getApp().globalData.userInfo,
})
},
onReady: function () {
_animationIndex = 0;
_animationIntervalId = -1;
this.data.animation = '';
_animation = wx.createAnimation({
duration: _ANIMATION_TIME,
timingFunction: 'linear',
delay: 0,
transformOrigin: '50% 50% 0'
})
that.refresh();
},
onShow: function () {
},
rotateAni: function (n) {
_animation.rotate(120 * (n)).step()
this.setData({
animation: _animation.export()
})
},
clickBack(){
console.log('clickBack');
wx.navigateBack({
delta: 1,
})
},
startAnimationInterval: function () {
var that = this;
that.rotateAni(++_animationIndex);
_animationIntervalId = setInterval(function () {
that.rotateAni(++_animationIndex);
}, _ANIMATION_TIME);
},
stopAnimationInterval: function () {
if (_animationIntervalId > 0) {
clearInterval(_animationIntervalId);
_animationIntervalId = 0;
}
},
onHide: function () {
},
onUnload: function () {
},
onPullDownRefresh: function () {
console.log("onPullDownRefresh")
},
refresh() {
if (that.data.loading) {
return
}
that.setData({
refresh: true,
})
that.startAnimationInterval();
that.getList();
},
getList() {
if (that.data.loading) {
return
} else {
that.setData({
loading: true
})
}
var currentPage = that.data.page;
if (that.data.refresh) {
currentPage = 0;
}
db.collection('circle')
.orderBy('time', 'desc')
.skip(currentPage * that.data.pageCount)
.limit(that.data.pageCount)
.get()
.then(res => {
console.log('getList:', res)
if (that.data.refresh) {
that.setData({
list: []
})
}
if (res.data.length > 0) {
for (var i = 0; i < res.data.length; i++) {
res.data[i].isLove = false;
for (var j = 0; j < res.data[i].loveList.length; j++) {
if (that.data.userInfo._openid == res.data[i].loveList[j]._openid) {
res.data[i].isLove = true;
break;
}
}
res.data[i].time = that.js_date_time(res.data[i].time);
that.data.list.push(res.data[i])
}
that.setData({
list: that.data.list
})
if (res.data.length == that.data.pageCount) {
that.setData({
haveMoreData: true
})
} else {
that.setData({
haveMoreData: false
})
}
}
that.setData({
refresh: false,
loading: false,
loadMore: false,
page: currentPage + 1
})
that.stopAnimationInterval();
})
.catch(error => {
console.log('getList error:', error)
that.stopAnimationInterval();
that.setData({
refresh: false,
loading: false,
loadMore: false,
})
})
},
js_date_time(unixtime) {
var date = new Date(unixtime);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
},
onReachBottom: function () {
console.log("onReachBottom")
if (that.data.loading) {
return
} else {
that.setData({
loadMore: true
})
setTimeout(() => {
that.getList();
}, 300);
}
},
onShareAppMessage: function () {
},
onPageScroll(e) {
console.log("onPageScroll", e)
that.setData({
showOperationPannelIndex:-1
})
},
goPublish() {
wx.navigateTo({
url: 'publish',
})
},
showOperationPannel(e) {
console.log("showOperationPannel", e)
var index = e.currentTarget.dataset.index;
if (that.data.showOperationPannelIndex == index) {
that.setData({
showOperationPannelIndex: -1
})
} else {
that.setData({
showOperationPannelIndex: index
})
}
},
clickLove(e) {
console.log("点赞函数",e);
var index = e.currentTarget.dataset.index;
var circleData = that.data.list[index];
var loveList = circleData.loveList;
var isHaveLove = false;
for (var i = 0; i < loveList.length; i++) {
if (that.data.userInfo._openid == loveList[i]._openid) {
isHaveLove = true;
loveList.splice(i, 1);
wx.cloud.callFunction({
name:'updateCircleLove',
data:{
type:0,
circleId:circleData._id
}
}).then(res=>{
console.log("取消赞成功",res);
}).catch(err=>{
console.error("取消赞失败",err);
})
circleData.isLove = false;
break;
}
}
if (!isHaveLove) {
loveList.push({
nickName: that.data.userInfo.nickName,
_openid: that.data.userInfo._openid
});
wx.cloud.callFunction({
name:'updateCircleLove',
data:{
type:1,
circleId:circleData._id,
nickName:that.data.userInfo.nickName
}
}).then(res=>{
console.log("点赞成功",res);
}).catch(err=>{
console.error("点赞失败",err);
})
circleData.isLove = true;
}
that.setData({
list: that.data.list,
showOperationPannelIndex: -1
})
},
clickComment(e) {
that.setData({
currentCircleIndex: e.currentTarget.dataset.index,
showCommentAdd: true,
showOperationPannelIndex: -1,
})
},
bindInput(e) {
that.setData({
commentContent: e.detail.value
})
},
bindFocus(e) {
that.setData({
heightBottom: e.detail.height
})
},
clickSend(e) {
var circleData = that.data.list[that.data.currentCircleIndex];
var commentList = circleData.commentList;
var commentData = {};
commentData.nickName = that.data.userInfo.nickName + ":";
commentData.content = that.data.commentContent;
commentData._openid = that.data.userInfo._openid;
commentData.reply = that.data.reply;
if(that.data.reply.length>0){
commentData.nickName = that.data.userInfo.nickName;
}
commentList.push(commentData);
that.setData({
list: that.data.list,
showCommentAdd: false,
commentContent: '',
reply:''
})
db.collection('circle').doc(circleData._id).update({
data: {
commentList: _.push(commentData)
}
})
.then(res => {
console.log('comment add success:', res)
})
.catch(err => {
console.log('comment add fail:', err)
})
},
clickCommentItem(e){
var circleIndex = e.currentTarget.dataset.index;
var commentIndex = e.currentTarget.dataset.commentindex;
var circleData = that.data.list[circleIndex];
var commentList = circleData.commentList;
var commentData = commentList[commentIndex]
var nickName = commentData.nickName;
that.setData({
currentCircleIndex: e.currentTarget.dataset.index,
showCommentAdd: true,
showOperationPannelIndex: -1,
reply:nickName
})
},
bindTouchStart(e){
that.setData({
showCommentAdd: false,
})
if(that.data.touchStartOperation || that.data.touchStartOperationPannel){
} else {
that.setData({
showOperationPannelIndex: -1,
})
}
},
bindTouchStartOperation(e){
that.setData({
touchStartOperation:true
})
},
bindTouchStartOperationPannel(e){
that.setData({
touchStartOperationPannel:true
})
},
bindTouchEndOperation(e){
that.setData({
touchStartOperation:false
})
},
bindTouchEndOperationPannel(e){
that.setData({
touchStartOperationPannel:false
})
},
})
6.点赞云函数
const cloud = require('wx-server-sdk')
cloud.init({
env: 'test-**************'
})
const db = cloud.database()
const _ = db.command
exports.main = async (event, context) => {
const {
type,
circleId,
nickName,
} = event;
const wxContext = cloud.getWXContext()
if (type == 0) {
return db.collection('circle').doc(circleId).update({
data: {
loveList: _.pull({
_openid: wxContext.OPENID
})
}
})
.then(res => {
return {
code : 200,
errMsg:'取消赞成功'
}
})
.catch(err => {
return {
code : 300,
errMsg:'取消赞失败'
}
})
} else if (type == 1) {
return db.collection('circle').doc(circleId).update({
data: {
loveList: _.push({
_openid: wxContext.OPENID,
nickName:nickName
})
}
})
.then(res => {
return {
code : 200,
errMsg:'点赞成功'
}
})
.catch(err => {
return {
code : 300,
errMsg:'点赞失败'
}
})
}
}