D
D
ds32019-08-19 07:13:46
Node.js
ds3, 2019-08-19 07:13:46

How to update the cache when editing data?

For caching, I use this cache-all library . And I encountered such a problem that when editing data, the old data that is stored in the cache does not update the changes until the cache storage time expires. How to cache when data changes?
I set up caching loading in index.js:

const cache = require('cache-all')

cache.init({
  expireIn: 86400
})

routing:
const express = require("express");
const router = express.Router();
const controller = require("../controllers/users");
const cache = require('cache-all')

router.get("/get_all", cache.middleware(86400), controller.getAll);
router.patch("/patch/:USER_ID", controller.update);

module.exports = router;

Now, what needs to be done so that the cache is updated every time the data changes? Here is my not working version:
const cache = require('cache-all')
module.exports.update = async function (req, res) {
    try {
        let users = await User.findOne({ USER_ID: req.params.USER_ID });
        await users.set({
            LOGIN: req.body.LOGIN
        })
        users.save().then(function () {
            return cache.set('patch:' + req.params.USER_ID, users);
        }).then(() => {
            return res.status(200).json(users);
        })
    } catch (e) {
        errorHandler(res, e);
    }
};

Or can you recommend a better and easier to use caching library?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Inviz Custos, 2019-08-19
@ds3

You don't look at the source code at all?
1) Full reset - https://github.com/bahung1221/cache-all/blob/maste...
2) Reset by key - https://github.com/bahung1221/cache-all/blob/maste..
3) Key generation - https : //github.com/bahung1221/cache-all/blob/maste...
PS
What kind of horror is this?

let users = await User.findOne({ USER_ID: req.params.USER_ID });
        await users.set({
            LOGIN: req.body.LOGIN
        })
        users.save().then(function () {
            return cache.set('patch:' + req.params.USER_ID, users);
        }).then(() => {
            return res.status(200).json(users);
        })

It seems that you took the code with an example of using async / await somewhere and added your own chain of promises to it.
Well, in pursuit - you have a bug in this code. Take a closer look.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question