-1

Does app.js get processed only once?. In that case, does it make sense to run setup queries in app.js so that I don't have to run it on every request?.

I have a table to countries and regions that I need in several requests.

I am looking at an implementation something like this https://stackoverflow.com/a/21133217/406659

Community
  • 1
  • 1
aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242

1 Answers1

1

No putting this in app.js does not make sense. I would create a models folder and encapsulate all of your database logic in a module within that folder. Then on startup of the app (ie on app.listen() callback) I would call a method from that module which does the setup for me. For example:

Some DB module in models

module.exports = {
   setup: () => {
    // Set up logic here - checking if tables exist etc
   }
}

Then in app.js or equal

require <SOME DB MODULE>

app.listen(<PORT>, () => {
   <SOME DB MODULE>.setup();
})

Note this is a generalised approach as I don't know the specifics of your setup - This approach just ensures encapsulated and reusable code. I've also used ES6 syntax where possible.

Hope this helps

Dylan

Dylan Scott
  • 468
  • 2
  • 8
  • my query was more to do with is it ok to do in app.js. All my model code is in models folder. – aWebDeveloper Feb 12 '17 at 15:11
  • Fair enough - generally speaking you could do your whole app in `app.js` but it's not a good idea. In answer to the original question calling a setup function in `app.js` is no problem and probably the best place to do it as long as its abstracted. As long as those tables are there before you need them then its fine :) – Dylan Scott Feb 12 '17 at 15:17
  • will these queries be called on each request or only once – aWebDeveloper Feb 12 '17 at 17:02
  • If you do it on `app.listen()` it will only be called once on app startup. Make sure you put in logic to check if tables exist and there is data in them so you don't double up – Dylan Scott Feb 12 '17 at 20:48