Facebook
From Jayeen, 2 Weeks ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 134
  1. const { operations } = require('../db');
  2. const searchCtrl = require('../controllers/searchCtrl');
  3.  
  4. /**
  5.  * This function is a middleware that handles HTTP requests and passes them to a given entity function
  6.  *
  7.  * @param {function} entity - The function that will handle the HTTP request
  8.  * @returns {function} - A function that takes in an express request and response object and processes the request using the `entity` function
  9.  */
  10. function reqCtrl(entity) {
  11.     return function (req, res) {
  12.         const httpRequest = {
  13.             token: req.token,
  14.             user: req.user,
  15.             // if the data submited with formData then the data will be in json format inside data field.
  16.             body: (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') ? ((req.body.data && req.body.data.startsWith('{') && req.body.data.endsWith('}')) ? JSON.parse(req.body?.data || '{}') : req.body) : {},
  17.             files: req.files,
  18.             query: req.query,
  19.             params: req.params,
  20.             ip: req.ip,
  21.             method: req.method,
  22.             path: req.path,
  23.             origin: req.headers['origin'],
  24.             headers: {
  25.                 'Content-Type': req.headers['Content-Type'],
  26.                 'Referer': req.headers['referer'],
  27.                 'User-Agent': req.headers['user-agent']
  28.             }
  29.         }
  30.         entity({ req: httpRequest, db: operations, searchCtrl })
  31.             .then((resp = {}) => {
  32.                 if (resp?.token || resp.token === null) {
  33.                     resp.token === null ?
  34.                         res.clearCookie('token') :
  35.                         res.cookie('token', resp.token, {
  36.                             httpOnly: true,
  37.                             sameSite: 'None',
  38.                             secure: true,
  39.                             expires: new Date(Date.now() + 172800000/*2 days*/),
  40.                         });
  41.                     delete resp.token;
  42.                 }
  43.                 res.status(isNaN(resp?.status) ? 200 : resp?.status).send(Object.freeze(resp))
  44.             })
  45.             .catch(err => res.status(400).send(Object.freeze({ error: err.message })));
  46.     }
  47. }
  48.  
  49. module.exports = reqCtrl;