简体   繁体   English

将参数传递给expressjs中的中间件函数

[英]Pass parameter to middleware function in expressjs

I am trying to add cache functionality to the nodejs. 我正在尝试向nodejs添加缓存功能。

I want to have code like this, 我想要这样的代码,

app.get('/basement/:id', cache, (req,res) =>  {
   client.set('basement' + req.params.id,'hello:'+req.params.id)
   res.send('success from source');
});


function cache(req,res,next) {
    console.log('Inside mycache:' + req.params.id);
    client.get('basement' + req.params.id, function (error, result) {
        if (error) {
            console.log(error);
            throw error;
        } else {
            if(result !== null && result !== '') {
                console.log('IN  Cache, fetching from cache and returning it');
                console.log('Result:' + result);
                res.send('success from cache');

            } else {
                console.log('Not in Cache, so trying to fetch from source ');;
                next();
            }
        }
    });
}

I want to apply a middleware function named cache to the request received by the /basement/:id route. 我想将一个名为cache的中间件函数应用于/ basement /:id路由接收的请求。

The cache function will receive the key as its parameter. 缓存功能将接收密钥作为其参数。 Inside the cache I want to check for existence of cache and if so return it from there, otherwise I want to call the actual route handler. 在缓存中我想检查是否存在缓存,如果是,则从那里返回它,否则我想调用实际的路由处理程序。 The key is based on one or more request parameters. 密钥基于一个或多个请求参数。

In this way, i will end up writing a separate cache function for every handler in my app. 通过这种方式,我将最终为我的应用程序中的每个处理程序编写一个单独的缓存函数。

The logic inside my cache function is generic expect for the key, which is based on the actual request object and may differ from method to method. 我的缓存函数中的逻辑是密钥的通用期望,它基于实际的请求对象,并且可能因方法而异。

So, I want to have a generic cache function which can take the key as a parameter, so that I can have code like this, 所以,我想要一个通用的缓存函数,它可以将键作为参数,这样我就可以拥有这样的代码,

app.get('/basement/:id', cache, (req,res) =>  {
    client.set('basement' + req.params.id,'hello:'+req.params.id)
    res.send('sucess from source');
});

I mean i will pass the cache key to the cache function. 我的意思是我将缓存密钥传递给缓存功能。 So, the cache function can be generic. 因此,缓存功能可以是通用的。

But, if I change my cache function like below as so as to receive the cache key , it does not work. 但是,如果我像下面那样更改我的缓存功能以便接收缓存密钥 ,则它不起作用。

function cache(cachekey,req,res,next) {

}

Seems like I cannot have another parameter in my cache function to receive the passed parameter. 好像我的缓存函数中没有其他参数来接收传递的参数。

I would like to pass the cache key as a parameter to the function. 我想将缓存键作为参数传递给函数。

If someone has faced a similar issue, can you please help me on this. 如果有人遇到类似的问题,请你帮我解决一下。

But, if I change my cache function like below as so as to receive the cache key, it does not work. 但是,如果我像下面那样更改我的缓存功能以便接收缓存密钥,则它不起作用。

You can't because it's not a valid express middleware (It's actually an error middleware), express will pass: req , res , next in that order. 你不能,因为它不是一个有效的快速中间件(它实际上是一个错误的中间件),express将按顺序传递: reqresnext and err , req , res , next for error middlewares. errreqresnext for error middlewares。

Your cache function will need to return a middleware instead, so you can pass a key to it. 您的缓存function需要返回中间件,因此您可以将密钥传递给它。

I wanted to create a generic cache function which can take any cache key. 我想创建一个通用缓存函数,它可以使用任何缓存键。 In this case it was id, but other cases may have different keys 在这种情况下,它是id,但其他情况可能有不同的键

function cache(key, prefix = '') {

    // Or arrange the parameters as you wish to suits your needs
    // The important thing here is to return an express middleware
    const cacheKey = prefix + req.params[key];
    return (req, res, next) => {

        console.log('Inside mycache:' + cacheKey);
        client.get(cacheKey , function(error, result) {
            if (error) {
                console.log(error);
                return next(error); // Must be an error object
            }

            if (result !== null && result !== '') {
                console.log('IN  Cache, fetching from cache and returning it');
                console.log('Result:' + result);
                return res.send('success from cache');

            }

            console.log('Not in Cache, so trying to fetch from source ');;
            next();

        });

    }
}

And now you can use it like this: 现在你可以像这样使用它:

app.get('/basement/:id', cache('id', 'basement'), (req, res) => { /* ... */ });
app.get('/other/:foo', cache('foo', 'other'), (req, res) => { /* ... */ });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM