// resource.js // Copyright (C) 2021 Digital Telepresence, LLC // License: Apache-2.0 'use strict'; const { SiteService } = require('../../lib/site-lib'); const mongoose = require('mongoose'); const ResourceView = mongoose.model('ResourceView'); class ResourceService extends SiteService { constructor (dtp) { super(dtp, module.exports); this.populateResourceView = [ { path: 'resource', }, ]; } /** * Records 24-hour unique view counts for a given resource happening on a * given ExpressJS Request. Views are uniqued by stripping time from the * current Date, and upserting a tracking object in MongoDB. * * @param {Request} req * @param {String} resourceType 'Post', 'Page', or 'Newsletter' * @param {mongoose.Types.ObjectId} resourceId The _id of the object for which * a view is being tracked. */ async recordView (req, resourceType, resourceId) { const CURRENT_DAY = new Date(); CURRENT_DAY.setHours(0, 0, 0, 0); let uniqueKey = req.ip.toString().trim().toLowerCase(); if (req.user) { uniqueKey += `:user:${req.user._id.toString()}`; } const response = await ResourceView.updateOne( { created: CURRENT_DAY, resourceType, resource: resourceId, uniqueKey, }, { $inc: { viewCount: 1 }, }, { upsert: true }, ); this.log.debug('resource view', { response }); if (response.upsertedCount > 0) { const Model = mongoose.model(resourceType); await Model.updateOne( { _id: resourceId }, { $inc: { 'stats.totalViewCount': 1 }, }, ); } } } module.exports = { slug: 'resource', name: 'resource', create: (dtp) => { return new ResourceService(dtp); }, };