0
votes

So guys, what I want to accomplish and not manage to get is to write a function that performs a query against database as a middleware, using req and res objects, and also can be used in a socket connection, to pass parameters to it and not use the req and res objects. Also I want it to return the result of the query. I tried using a middleware wrapper

function myFunc(param1, param2){
   return (req, res) => {
      here query
}}

works when hitting the endpoint with or without args i send, but dosnt work when i call the function from somewhere else

1
When you call myFunc you get returned a new function, are you invoking that function? Something like: myFunc('value1','value2')() - Bergur
oh, you are right. this was missing. but now, if i call it like this, req and res are missing so it throws an error - user_id
i want to use either query.params or the args i give when calling the function - user_id

1 Answers

0
votes

When you call myFunc you get returned a new function. You need to invoke that funcion, something like

myFunc('value1', 'value2')()

This will cause an error since you have no request or response object. These are express objects.

A better way to re-use the database code would be to put it in a function and inject that function to the middlewere.

E.g.

function getArticleById(id) {
 return db.query('select * from articles where id = $1', [id])
}

Then create a middlewhere that takes this function in as dependency

function makeMiddlewere (getArticleById) {
  return (req, res) => {
    return articleById(req.query.id).then(articles => {
      res.json(articles)
    })
  }
}

Then in your code you can do

Normal way

getArticleById(5).then(articles => {
  console.log(articles)
})

Create the middlwere an

const express = require('express')
const getArticleById = require('./articlebyid')
const makeMiddlewere = require('./makemiddlewere')

const middlwere = makeMiddlwere(getArticleById)
   
const app = express.app
app.get('/article', middlewere)