Search code examples
mongodbexpresspostget

Re-use POST and GET methods in Express


I'm building a CMS where I have to do a lot of POST and GET requests to my MongoDB. The problem I am having now is that, the more I work on my CMS, the more POST and GET requests I have to do and eventually a lot of double code I'm having in my application. My question is, can I somehow re-use the POST and GET methods? I am using Express framework, MongoDB and Angular on the Front-End.

Here is an example how my application looks like:

Express:

router.post('/news_blocks', function(req, res, next){
  var randomNumber = Math.floor(1000 + Math.random() * 9000);
  var news_image = req.files.myImage;
  news_image.mv('/home//projects/website/public/uploads/' + 'image_' + randomNumber + '.jpg' , function(err) {
    if(err){
      console.log(err);
    }else{
      var data = new news_blocks(postOptions(req, randomNumber));
      saveToDB(data,res);
     }
  });
});

router.post('/research', function(req, res, next){
  var randomNumber = Math.floor(1000 + Math.random() * 9000);
  var research_image = req.files.myImage;
  research_image.mv('/home/projects/website/public/uploads/' + 'image_' + randomNumber + '.jpg' , function(err) {
    if(err){
      console.log(err);
    }else{
      var data = new research_blocks(postOptions(req, randomNumber));
      saveToDB(data,res);
     }
  });
});

postOptions = function(req, randomNumber){
  var options = {
    title: req.body.title,
    date: new Date,
    message: req.body.message,
    image: 'image_' + randomNumber
  };
  return options;
};

MongoDB model:

file1:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var research_block = new mongoose.Schema({
  title: String,
  date: String,
  message: String,
  image: String
}, {collection: 'research'});

module.exports = mongoose.model("research", research_block);

File 2:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var news_block = new mongoose.Schema({
  title: String,
  date: String,
  message: String,
  image: String
}, {collection: 'news'});

module.exports = mongoose.model("news", news_block);

As you can see, there is a lot of the same code in the POST methods. But I am not sure how I make this more DRY


Solution

  • Suggestion 1:
    Make a controller file for every table. And, write functions in it to do all kind of operations in it. And, while calling a service send type of operation along with it. On basis of type you can call any function you want.
    Suggestion 2:
    Try using GraphQL