express-json-object-middleware
v1.0.8
Published
Converts JSON into Objects before passing the object through the middleware chain. Useful when using mongoose which takes objects for filters, searches, updates, and more.
Downloads
2
Maintainers
Readme
JSON Express 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();
}