How to use a const with middleware and Routes?

Asked

Viewed 61 times

0

I have the following const in my file Routes.js:

const database = [];

For learning purposes I’m using it as if it were my own "database", where according to the type of request I handle this variable... This variable is in the file mentioned above and I am using inside the routes after the use of certain middleware.

Using good practices I would like to know how I can use this variable among my middleware and my routes, what I tried to do was create a global middleware where I would do the following:

res.locals.database = [];
next();

But this code "erases" the variable when the answer is given with the res.

1 answer

1


I see no need in using middlewares, you can declare a module as your database and access this module when necessary, do not need to attach it in your res.

For example:

// database.js

const database = {
    users: [],
    messages: []
}

module.exports = database

As in Nodejs the data persists in memory (volatile), you can attach and remove items from this "database" in different requests.

Now just import this module and use it in your handlers. Example:

// app.js

const express = require('express')
const bodyParser = require('body-parser')
const database = require('./database')

const server = express()
server.use(bodyParser.json())

server.post('/messages', (req, res) => {
    database.messages.push(req.body)
    res.send()
})

server.get('/messages', (req, res) => {
    res.json(database.messages)
})

server.listen(3000, () => {
    console.log('Servidor iniciado na porta 3000')
})

En route POST /messages you can send a payload to be attached in the array of messages, while en route GET /messages, you recover all messages. These data will persist because the database used for all requests is always the same.

  • 1

    It is also possible to shorten the database.js for module.exports = { /* ... */ }, since the variable is only exported, it does not need it, just export the literal object directly, but the variable can be useful to make it clear that that object is the database

  • Thank you both, I enjoyed both replies.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.