event.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @class StatEvent 事件统计模型
  3. */
  4. const BaseMod = require('./base')
  5. const {
  6. DateTime
  7. } = require('../lib')
  8. module.exports = class StatEvent extends BaseMod {
  9. constructor() {
  10. super()
  11. this.tableName = 'events'
  12. this.defaultEvent = this.getConfig('event') || {
  13. login: '登录',
  14. register: '注册',
  15. click: '点击',
  16. share: '分享',
  17. pay_success: '支付成功',
  18. pay_fail: '支付失败'
  19. }
  20. }
  21. /**
  22. * 获取事件信息
  23. * @param {String} appid: DCloud appid
  24. * @param {String} eventKey 事件键值
  25. */
  26. async getEvent(appid, eventKey) {
  27. const cacheKey = 'uni-stat-event-' + appid + '-' + eventKey
  28. let eventData = await this.getCache(cacheKey)
  29. if (!eventData) {
  30. const eventInfo = await this.getCollection(this.tableName).where({
  31. appid: appid,
  32. event_key: eventKey
  33. }).get()
  34. eventData = []
  35. if (eventInfo.data.length > 0) {
  36. eventData = eventInfo.data[0]
  37. await this.setCache(cacheKey, eventData)
  38. }
  39. }
  40. return eventData
  41. }
  42. /**
  43. * 获取事件信息不存在则创建
  44. * @param {String} appid: DCloud appid
  45. * @param {String} eventKey 事件键值
  46. */
  47. async getEventAndCreate(appid, eventKey) {
  48. const eventInfo = await this.getEvent(appid, eventKey)
  49. if (eventInfo.length === 0) {
  50. const thisTime = new DateTime().getTime()
  51. const insertParam = {
  52. appid: appid,
  53. event_key: eventKey,
  54. event_name: this.defaultEvent[eventKey] ? this.defaultEvent[eventKey] : '',
  55. create_time: thisTime,
  56. update_time: thisTime
  57. }
  58. const res = await this.insert(this.tableName, insertParam)
  59. if (res && res.id) {
  60. return Object.assign(insertParam, {
  61. _id: res.id
  62. })
  63. }
  64. }
  65. return eventInfo
  66. }
  67. }