page.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * @class Page 页面模型
  3. */
  4. const BaseMod = require('./base')
  5. const {
  6. parseUrl
  7. } = require('../../shared')
  8. const {
  9. DateTime
  10. } = require('../lib')
  11. module.exports = class Page extends BaseMod {
  12. constructor() {
  13. super()
  14. this.tableName = 'pages'
  15. }
  16. /**
  17. * 获取页面信息
  18. * @param {String} appid
  19. * @param {String} url 页面地址
  20. */
  21. async getPage(appid, url) {
  22. const cacheKey = 'uni-stat-page-' + appid + '-' + url
  23. let pageData = await this.getCache(cacheKey)
  24. if (!pageData) {
  25. const pageInfo = await this.getCollection(this.tableName).where({
  26. appid: appid,
  27. path: url
  28. }).limit(1).get()
  29. pageData = []
  30. if (pageInfo.data.length > 0) {
  31. pageData = pageInfo.data[0]
  32. await this.setCache(cacheKey, pageData)
  33. }
  34. }
  35. return pageData
  36. }
  37. /**
  38. * 获取页面信息不存在则创建
  39. * @param {String} appid
  40. * @param {String} url 页面地址
  41. * @param {Object} title 页面标题
  42. */
  43. async getPageAndCreate(appid, url, title) {
  44. //获取url信息
  45. const urlInfo = parseUrl(url)
  46. if (!urlInfo) {
  47. return false
  48. }
  49. const baseurl = urlInfo.path
  50. const pageInfo = await this.getPage(appid, baseurl)
  51. //页面不存在则创建
  52. if (pageInfo.length === 0) {
  53. const thisTime = new DateTime().getTime()
  54. const insertParam = {
  55. appid: appid,
  56. path: baseurl,
  57. title: title,
  58. page_params: [],
  59. create_time: thisTime,
  60. update_time: thisTime
  61. }
  62. const res = await this.insert(this.tableName, insertParam)
  63. if (res && res.id) {
  64. return Object.assign(insertParam, {
  65. _id: res.id
  66. })
  67. }
  68. } else if (!pageInfo.title && title) {
  69. const cacheKey = 'uni-stat-page-' + appid + '-' + baseurl
  70. await this.clearCache(cacheKey)
  71. await this.update(this.tableName, {
  72. title: title
  73. }, {
  74. _id: pageInfo._id
  75. })
  76. }
  77. return pageInfo
  78. }
  79. }