denden
denden

Reputation: 1319

Adding custom middleware

I have a route with a req.param of :groupIndex in it. I would like to process this index as middleware in order to get a specific id.

Node and express are new to me, so I'm possibly missing something simple but reading docs and looking at other implementations hasn't seemed to work.

Any idea where I might be going wrong?

// routes.js
const express = require("express");  
const router = express.Router();
const customMiddleware = ('./customMiddleware.js');
const db = require('./mysqlCon.js');

router.get('/person/:groupIndex(\\d+)', customMiddleware(), function (req, res) {

let id = req.params.id;
let query = `
            SELECT 
                *
            FROM 
                data
            WHERE 
                id = ?
        `;
        let query_params = [id];
        db.query(
            query, 
            query_params, 
            function(error, result, fields) {
                if ( result.length == 1 ) {
                    res.status(200).json( result[0] );
                } else {
                    res.status(401).json({});
                }
            }
        );
});





// customMiddleware.js
const db = require('./mysqlCon.js');

module.exports = (req, res, next) => {

    let groupIndex =  parseInt(req.params.groupIndex);
    let query = `
            SELECT 
                id
            FROM 
                listofids
            LIMIT 1 
            OFFSET ?
    `;
    let query_params = [groupIndex];
    db.query(
        query, 
        query_params, 
        function(error, result, fields) {
            if ( result.length == 1 ) {
                req.params.id = result[0].id;
            } else {
                res.status(401).json({});
            }
        }
    );
    next();
}

Upvotes: 1

Views: 124

Answers (1)

Cisco
Cisco

Reputation: 22952

I would review the middleware guide, but generally all middleware functions have the following signature:

function myMiddleware(req, res, next)

Where req, res, next are passed in from Express itself. You do not invoke the function, you simply pass it in as an argument (higher-order functions) to your route definition:

router.get('/person/:groupIndex(\\d+)', myMiddleware, ...)

Upvotes: 2

Related Questions