Using Memoizee with node.js

2.2k views Asked by At

I want to use Memoizee on my node.js backend, to speed up the requests.

But for some reason, I can't get it to work like I want to. I have a route, that waits for the callback of another method, but no matter how long I save the result in cache, it runs the whole method every time.

What am I doing wrong?

Here is an example of my implementation.

var memoize = require('memoizee');

module.exports = function (app) {

app.route('/someurl/:user_id')
    .get(function (req, res) {

        var user_id = req.params.user_id;

        memoized(user_id, function (result) {      
            res.send(result)
        })
    });
};

var doWork = memoize(function(user_id, done) {
    //Handling a lot of data - takes about 10-15 seconds
    done(index);
});

var memoized = memoize(doWork, {maxAge: 300000});
1

There are 1 answers

0
Mariusz Nowak On

There are two issues:

  1. As there are two function parameters, memoization memoizes against those two.
    It's likely that done callback on every call is different, hence you see function re-run every time.
    How to fix it? Firstly you can limit memoization scope to just first parameter by passing { length: 1 } in options. Secondly I have a notion it's an async function that you try to memoize, for that it would be better to rely on either async or promise configuration options in memoizee (see it's documentation)

  2. As @Bergi pointed you try to memoize already memoized function. Second memoization (one with maxAge) has no effect, as memoization internally detects what you're trying to do, and ignores second call. There should be just one memoizee wrap (options can be combined, there's no problem with that).