node系列之購物車的業務邏輯
在第二個章節中講解了用戶的登陸註冊,在第三個章節中講解了產品的相關接口設計,本章節中講解的購物車的相關邏輯
1、加入購物車業務邏輯
1.1 創建購物車模塊 myapp/routes/cart.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.send('購物車')
});
module.exports = router;
1.2 app.js中註冊路由
var cartRouter = require('./routes/cart');
app.use('/cart', cartRouter);
1.3 設計購物車的數據庫集合
// sql/collection/carts.js
const mongoose = require('../db.js'); // 引入數據庫連接模塊
const Schema = mongoose.Schema; // 拿到當前數據庫相應的集合對象
const cartSchema = new Schema({
cartid: {type: String },
userid: { type: String },
proid: { type: String },
num: { type: Number }
})
module.exports = mongoose.model('Cart', cartSchema);
1.4 加入購物車業務邏輯
如果用戶之前添加過當前商品需要更新數量
加入購物車需要參數用戶id、產品id以及商品數量
// 加入購物車 購物車數據id 產品id 用戶id 產品的數量num
router.get('/add', (req, res, next) => {
// 1、獲取數據
let { userid, proid, num } = req.query;
num = num * 1 || 1 // 設定默認數量
// 2、加入購物車
// 如果當前用戶的購物車中有這個產品,數量加1,否則加入
sql.find(Cart, { userid, proid }, { _id: 0 }).then(data => {
if (data.length === 0) {
// 2.1沒有改數據 --- 插入數據庫操作
sql.insert(Cart, {
cartid: 'cart_' + uuid.v1(),
userid,
proid,
num
}).then(() => {
res.send({
code: '200',
message: '加入購物車成功'
})
})
} else {
// 2.2更新數據庫中購物車產品的數量
sql.update(Cart, { userid, proid }, { $inc: { num: 1 } }).then(() => {
res.send({
code: '200',
message: '加入購物車成功'
})
})
}
})
})
2、查看購物車業務邏輯
依據用戶id獲取所有該用戶的購物車數據,然後依據產品id依次查詢產品集合,獲取購物車需要的數據,最後返回
router.get('/', function(req, res, next) {
// 1、獲取用戶id
let { userid } = req.query;
let cartarr = []
// 2、依據用戶id查詢購物車的數據
sql.find(Cart, { userid }, { _id: 0 }).then(data => {
// 如果沒有數據,告訴用戶沒有數據
if (data.length === 0) {
// 2.1 沒有數據
res.send(utils.cartnull)
} else {
cartarr = data
let promise1 = data.map(item => {
return sql.find(Pro, { proid: item.proid}, { _id: 0})
})
return Promise.all(promise1)
}
}).then(list => {
console.log('list', list)
console.log('cartarr', cartarr)
let arr = []
list.map((item, index) => {
arr.push({
proid: item[0].proid,
proname: item[0].proname,
proimg: item[0].proimg,
price: item[0].price,
cartid: cartarr[index].cartid,
userid: cartarr[index].userid,
num: cartarr[index].num
})
})
res.send({
code: '200',
data: arr
})
})
});
3、刪除購物車數據
刪除哪個用戶添加的哪個商品
// 刪除購物車
router.get('/delete', (req, res, next) => {
// 1、獲取刪除的條件
let { userid, proid } = req.query
// 2、刪除
sql.delete(Cart, { userid, proid }).then(() => {
res.send(utils.deletesuccess)
})
})
4、更新購物車數據
根據購物車的id 修改商品的數量
// 更新購物車
router.get('/update', (req, res, next) => {
// 1、獲取更新的數據
let { cartid, num } = req.query
// 2、更新數據
sql.update(Cart, { cartid }, { $set: { num: num } }).then(() => {
res.send(utils.updatesuccess)
})
})
5、預告
下次分享node系列之訂單接口的實現