NutellaAddict
NutellaAddict

Reputation: 574

Is this an incorrect usage of routes for express?

Disclaimer: kinda new at express/node, working on a photo hosting/gallery app as practice.

My understanding is that routers are used as endpoints from the server to the client/database.

In this case I have a function called storeImages which stores image locations to the DB but gets called from within the Node js app and not directly from a client side request.

Should I move storeImages as a helper function outside the router folder instead?

I am a little confused because even though this isn't being called directly from a client post/get request, I feel the images.js route is intrinsically tied to the Image.js model... and database manipulation should not exist outside of it. Am I wrong in thinking this way?

If it is in fact best to keep it in the router folder, what is the proper way to export said function along with the router? the current method below is not working, I also tried:

module.exports = {router: router, storeImages: storeImages, }

But that did not work either.

var express = require('express');
var router = express.Router();
var Image = require('../models/image');

router.get('/getImageLocations', function(req,res){
    //Do Stuff
});


exports.storeImages = function(memoryId, location, comment){
    var newImage = new Image({
        ...
    });
    Image.storeImageURL(newImage, function(err, user){
        ...
    })
};

module.exports = router;

Upvotes: 0

Views: 52

Answers (1)

nikjohn
nikjohn

Reputation: 21910

Routers are functions that deal with http requests. Now, there's no hard and fast rule about what needs to go into the router file and what doesn't, but from what I understand in your code, storeImages is a function that accepts from params and stores persists into the database. Here are a couple of thumb rules:

  • If the function is tied to a route, i.e. it is used only when one particular route is invoked, it makes sense to keep it within that router
  • If the function is used in multiple routes, it should be stored as a shared utility function outside the route file
  • If it is a model related function, you can store it within your model files, depending on how you're handling your model layer

Upvotes: 2

Related Questions