UNPKG

@universis/evaluations

Version:

Universis evaluations library

132 lines (121 loc) 3.95 kB
import express from 'express'; import {EvaluationKeyHandler} from "./handlers/evaluation-key-handler"; import { getEntitySetFunction} from "@themost/express"; import i18n from "i18n"; import {postEntitySetFunction} from "@themost/express"; const el = require('./locales/el.json'); /** * * @param {ExpressDataApplication} app * @returns {*} */ export function evaluationRouter(app) { const router = express.Router(); // add translations if (app && app.parentApplication) { const translateService = app.parentApplication.getService(function TranslateService() { }); if (translateService) { translateService.setTranslation('el', el); } } router.use((req, res, next) => { // create router context const newContext = app.createContext(); /** * try to find if request has already a data context * @type {ExpressDataContext|*} */ const interactiveContext = req.context; // finalize already assigned context if (interactiveContext) { if (typeof interactiveContext.finalize === 'function') { // finalize interactive context return interactiveContext.finalize(() => { // and assign new context Object.defineProperty(req, 'context', { enumerable: false, configurable: true, get: () => { return newContext } }); // exit handler return next(); }); } } // otherwise assign context Object.defineProperty(req, 'context', { enumerable: false, configurable: true, get: () => { return newContext } }); // and exit handler return next(); }); router.use((req, res, next) => { // set context locale from request req.context.locale = req.locale; // set translation req.context.translate = function() { return i18n.__.apply(req.context, Array.from(arguments)); }; return next(); }); // use this handler to finalize router context // important note: context finalization is very important in order // to close and finalize database connections, cache connections etc. router.use((req, res, next) => { req.on('end', () => { //on end if (req.context) { //finalize data context return req.context.finalize( () => { // }); } }); return next(); }); router.use(async (req, res, next) => { try { await new EvaluationKeyHandler().beginRequestAsync(req, res); return next(); } catch (err) { return next(err); } }); router.get('/', (req, res, next) => { // set entity set parameters Object.assign(req.params, { entitySetFunction : 'Current' }); return next(); }, getEntitySetFunction({ entitySet: 'EvaluationEvents' })); router.get('/Form', (req, res, next) => { // set entity set parameters Object.assign(req.params, { entitySetFunction : 'Current', entityFunction : 'Form' }); return next(); }, getEntitySetFunction({ entitySet: 'EvaluationEvents' })); router.post('/Evaluate', (req, res, next) => { // set entity set parameters Object.assign(req.params, { entitySetFunction : 'Current', entityAction : 'Evaluate' }); return next(); }, postEntitySetFunction({ entitySet: 'EvaluationEvents' })); return router; }