Moleculer - cacher example
let { ServiceBroker } = require("moleculer");
let MemoryCacher = require("moleculer").Cachers.Memory;
let broker = new ServiceBroker({
logger: console,
cacher: new MemoryCacher()
});
broker.createService({
name: "users",
// cache: true, // If you enable here, all actions will be cached!
actions: {
list: {
cache: true, // Cache this action
handler(ctx) {
this.logger.info("Handler called!");
return [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
]
}
}
}
});
Promise.resolve()
.then(() => {
// Will be called the handler, because the cache is empty
return broker.call("users.list").then(res => console.log("Users count: " + res.length));
})
.then(() => {
// Return from cache, handler won't be called
return broker.call("users.list").then(res => console.log("Users count from cache: " + res.length));
})
.then(() => {
console.log(">> Clean the cache <<");
// Clean the cache & call again the action
broker.cacher.clean();
return broker.call("users.list").then(res => console.log("Users count after cache clear: " + res.length));
});
no comments