R
R
Roman2021-04-07 10:43:44
Express.js
Roman, 2021-04-07 10:43:44

How to arrange modules - routes in expressjs?

1) There is an index.js and db.js file with the database connection logic

const app = require('express')()
async function main() {
  const db = await require('./db')
  app.use('/api', require('./api')(db))
}
main()


2) There is a route file /api/index.js

const app = require('express')()

module.exports = function (db) {
  const a = 1
  const b = 2

  function f() {}
  function b() {}

  app.get('/', () => {})
  app.post('/', () => {})

  return app
}


Exporting the function to pass db

a) Where is it more correct to place variables with module imports (in the exported function or before exporting)
b) Where to create variables used in different routes (in the exported function or before exporting)
c) Where to create functions. One function is used in one route (in the route itself, in the exported function, or before module.exports - in the global scope), there are those that are used in several.

If you declare a variable such as let userId in the global scope and change it in the middleware, what is the probability that it will turn out like this:

the 1st user accesses - ID is written in the middleware - the 2nd user accesses - the ID is recorded - the 1st user enters the route where this ID is required, will it be the 2nd user? Or everything is so single-threaded and fast that the 2nd user will not have time to overwrite the userId before the 1st gets into the route.


thanks for answers

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question