page.js 1.8 KB
Newer Older
study夏羽's avatar
study夏羽 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/**
 * @class Page 页面模型
 */
const BaseMod = require('./base')
const {
	parseUrl
} = require('../../shared')
const {
	DateTime
} = require('../lib')
module.exports = class Page extends BaseMod {
	constructor() {
		super()
		this.tableName = 'pages'
	}

	/**
	 * 获取页面信息
	 * @param {String} appid
	 * @param {String} url 页面地址
	 */
	async getPage(appid, url) {
		const cacheKey = 'uni-stat-page-' + appid + '-' + url
		let pageData = await this.getCache(cacheKey)
		if (!pageData) {
			const pageInfo = await this.getCollection(this.tableName).where({
				appid: appid,
				path: url
			}).limit(1).get()
			pageData = []
			if (pageInfo.data.length > 0) {
				pageData = pageInfo.data[0]
				await this.setCache(cacheKey, pageData)
			}
		}
		return pageData
	}

	/**
	 * 获取页面信息不存在则创建
	 * @param {String} appid
	 * @param {String} url 页面地址
	 * @param {Object} title 页面标题
	 */
	async getPageAndCreate(appid, url, title) {
		//获取url信息
		const urlInfo = parseUrl(url)
		if (!urlInfo) {
			return false
		}
		const baseurl = urlInfo.path
		const pageInfo = await this.getPage(appid, baseurl)
		//页面不存在则创建
		if (pageInfo.length === 0) {
			const thisTime = new DateTime().getTime()
			const insertParam = {
				appid: appid,
				path: baseurl,
				title: title,
				page_params: [],
				create_time: thisTime,
				update_time: thisTime
			}
			const res = await this.insert(this.tableName, insertParam)

			if (res && res.id) {
				return Object.assign(insertParam, {
					_id: res.id
				})
			}
		} else if (!pageInfo.title && title) {
			const cacheKey = 'uni-stat-page-' + appid + '-' + baseurl
			await this.clearCache(cacheKey)
			await this.update(this.tableName, {
				title: title
			}, {
				_id: pageInfo._id
			})
		}

		return pageInfo
	}
}