express-json-object-middleware

1.0.8 • Public • Published

JSON Express Middleware

Features

  • Allows to convert axios params back into Objects
  • Easy to use
  • Helps with mongoose requests such as find, update, delete etc. which require objects

How to use with Express



npm i --save express-json-object-middleware

Project Router

const Express = require("express");
const Router = Express.Router();
const JSONMiddleware= require("express-json-object-middleware");
 
const ProjectsController = require("../controllers/projects-controller");
 
Router.get("/", JSONMiddleware.parse, ProjectsController.editByQuery);
 
Router.delete("/", JSONMiddleware.parse, ProjectsController.removeByQuery);
 
module.exports = Router;

Routes

const Express = require("express");
const Router = Express.Router();
 
const ProjectRouter = require("./project");
 
Router.use("/projects", ProjectRouter);
Express().use("/", Router);
 

 
const axios = require("axios").default;
 
 
try {
 const results = await axios.get("/projects", {filter: {_id: 1}});
 console.log(results);
} catch(err) {
  console.log(err)
}

JSON Middleware

 
parse(req, res, next){
  // req.query = {filter: '{_id: 1}'}
  // console.log(typeof(req.query.filter))
  // prints String
 
    parse(req, res, next) {
      if ((req.query === undefined) || (req.query.params === undefined)) {
        return next()
      };
      const JSONQuery = {};
      const query = typeof(req.query.params) === "string"
        ? JSON.parse(req.query.params)
        : req.query.params;
      Object.keys(query).map(key => {
        JSONQuery[key] = query[key];
      })
      req.query = JSONQuery;
      return next();
    }
  }
  // console.log(JSONObject)
  // prints {filter: {_id: 1}}
  // console.log(typeof(JSONObject.filter))
  // prints Object
  // Edits the query after converting it to a Object
 
  req.query = JSONQuery;
  return next();
}

Package Sidebar

Install

npm i express-json-object-middleware

Weekly Downloads

1

Version

1.0.8

License

ISC

Unpacked Size

3.28 kB

Total Files

3

Last publish

Collaborators

  • kfluckiger