paradigm-core
Version:
Paradigm Core Modules
101 lines (76 loc) • 2.42 kB
JavaScript
const {
Dispatcher: {registerHook},
ApplicationsPlugin: {ApplicationModel},
} = require('structure-core')
const purgeUrlQueue = require('../queues/purge-url')
const moment = require('moment-timezone')
/**
* Hook for purging url after an update. Simply queues a purge job.
*
* @param {Object} req - express request object
* @param {Object} response - the response from the dispatcher, which cointains
* the data from the previous controller method.
* @returns {Object} response - the response to be returned to the user
*/
async function purgeUrlUpdate(req, response) {
const logger = req.logger || console
try {
const applicationId = req.headers.applicationid
const organizationId = req.headers.organizationid
const applicationModel = new ApplicationModel({
logger,
organizationId
})
logger.debug('Hook:documents--purge-url-update start')
const application = await applicationModel.getById(applicationId)
const id = req.params.id
const doc = response.pkg
// If document is published
if(['published'].indexOf(doc.status) > -1) {
purgeUrlQueue.add({
organizationId,
application,
status: 'published',
id,
protocol: application.protocol
})
// If document was previously published but is now draft
} else if((['published', 'scheduled'].indexOf(doc.previousStatus) > -1) && doc.status === 'draft') {
purgeUrlQueue.add({
organizationId,
application,
id,
})
// If document is scheduled
} else if(['scheduled'].indexOf(doc.status) > -1) {
const tz = doc.timezone || 'UTC'
const now = moment().tz(tz)
const publishedAt = moment(doc.publishedAt).tz(tz)
const delay = publishedAt.diff(now, 'milliseconds')
purgeUrlQueue.add({
organizationId,
application,
status: 'published', // this is the end result of the status
id,
protocol: application.protocol
}, {
delay
})
} else if (doc.status === 'draft') {
purgeUrlQueue.add({
organizationId,
application,
id,
cacheOnly: true
})
}
} catch(e) {
logger.debug('Hook:documents--purge-url-update failed', e)
}
return response
}
registerHook({
when: 'after',
serviceName: 'documents',
actionNames: ['updateById'],
}, purgeUrlUpdate)