trade.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class TradeService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'trade');
  10. this.redis = this.app.redis;
  11. this.redisKey = this.app.config.redisKey;
  12. this.redisTimeout = this.app.config.redisTimeout;
  13. this.shopModel = this.ctx.model.Shop.Shop;
  14. this.goodsModel = this.ctx.model.Shop.Goods;
  15. this.goodsSpecModel = this.ctx.model.Shop.GoodsSpec;
  16. }
  17. /**
  18. * 检测是否可以购买该物品
  19. * @param {Object} param 查询条件
  20. * @param param.shop 商店id
  21. * @param param.goods 商品id
  22. * @param param.goodsSpec 商品规格id
  23. * @param param.num 购买数量
  24. * @param makeCache 生成缓存
  25. */
  26. async checkCanBuy({ shop, goods, goodsSpec, num }, makeCache = true) {
  27. assert(shop, '缺少店铺信息');
  28. assert(goods, '缺少商品信息');
  29. assert(goodsSpec, '缺少商品规格信息');
  30. assert(num, '缺少购买数量');
  31. const result = { result: true };
  32. // 1.检查商店是否正常运行
  33. const shopData = await this.shopModel.findById(shop);
  34. if (!shopData) {
  35. result.msg = '未找到店铺';
  36. result.result = false;
  37. return result;
  38. }
  39. if (shopData.status !== '1') {
  40. result.msg = '店铺不处于营业状态';
  41. result.result = false;
  42. return result;
  43. }
  44. // 2.检查商品是否可以购买
  45. const goodsData = await this.goodsModel.findById(goods);
  46. if (!goodsData) {
  47. result.msg = '未找到商品';
  48. result.result = false;
  49. return result;
  50. }
  51. if (goodsData.status === '0') {
  52. result.msg = '该商品已下架';
  53. result.result = false;
  54. return result;
  55. }
  56. // 3.检验该规格是否可以购买
  57. const goodsSpecData = await this.goodsSpecModel.findById(goodsSpec);
  58. if (!goodsSpecData) {
  59. result.msg = '未找到商品的指定规格';
  60. result.result = false;
  61. return result;
  62. }
  63. if (goodsSpecData.status !== '0') {
  64. result.msg = '该规格的商品已下架';
  65. result.result = false;
  66. return result;
  67. }
  68. if (goodsSpecData.num < num) {
  69. result.msg = '库存量不足';
  70. result.result = false;
  71. return result;
  72. }
  73. if (makeCache) {
  74. const str = this.createNonceStr();
  75. const key = `${this.redisKey.orderKeyPrefix}${str}`;
  76. const value = JSON.stringify({ shop, goods, goodsSpec, num });
  77. await this.redis.set(key, value, 'EX', this.redisTimeout);
  78. result.key = str;
  79. }
  80. return result;
  81. }
  82. // 随机字符串产生函数
  83. createNonceStr() {
  84. return Math.random().toString(36).substr(2, 15);
  85. }
  86. }
  87. module.exports = TradeService;