UNPKG

@kohanajs/mod-live-home

Version:

The Live Homepage allow admin to refresh visitor's home page.

69 lines (53 loc) 2.34 kB
const { ControllerMixin } = require('@kohanajs/core-mvc'); const {KohanaJS, ControllerMixinView} = require("kohanajs"); const {readFile} = require('fs/promises'); const path = require('path'); class ControllerMixinLiveHome extends ControllerMixin { static PING_DATA = "PING_DATA"; static async setup(state) { //read properties from controller const client = state.get(ControllerMixin.CLIENT); const {request, language} = client; //only redirect action listed in config file const action = state.get(ControllerMixin.FULL_ACTION_NAME).replace("action_", ""); if(!(action === "index" || KohanaJS.config.livehome.homepages.has(action)))return; //only redirect GET if(request.raw && request.raw.method && request.raw.method !== 'GET')return; //url query have no redirect param, do nothing; if (request.query && request.query[KohanaJS.config.livehome.url_param_no_redirect] !== undefined) return; //read ping file try { const ping = await readFile(path.normalize(KohanaJS.config.livehome.ping_file), 'utf-8'); state.set(this.PING_DATA, JSON.parse(ping || "{}")) } catch (e) { console.log(e); return; } const {payload} = state.get(this.PING_DATA); //check controller action match ping file payload.home if (state.get(ControllerMixin.FULL_ACTION_NAME) === `action_${payload.home}`) return; const homepage = KohanaJS.config.livehome.homepages.has(payload.home) ? payload.home : (KohanaJS.config.livehome.default_home || 'register'); //keep query string but forward to another page; await client.redirect(language ? `/${language}/${homepage}`: `/${homepage}`, true); } static async after(state){ if(!state.get(ControllerMixinView.LAYOUT))return; const ping = state.get(this.PING_DATA); if(!ping)return; const layoutData = state.get(ControllerMixinView.LAYOUT).data; if(!Array.isArray(layoutData.scripts)){ layoutData.scripts = []; } layoutData.scripts.push('ping-update.js'); Object.assign( layoutData, { now: Date.now(), home: ping.payload?.home, state: ping.payload?.state, last_update: ping.meta?.last_update, } ) } } module.exports = ControllerMixinLiveHome;