Skip to content

Instantly share code, notes, and snippets.

@icebob
Created December 14, 2018 11:22
Show Gist options
  • Save icebob/40a612ec3c453347aef7a808b82ab747 to your computer and use it in GitHub Desktop.
Save icebob/40a612ec3c453347aef7a808b82ab747 to your computer and use it in GitHub Desktop.
Memoize mixin for Moleculer services

Memoize mixin for Moleculer services

Add caching for Moleculer service methods too. This mixin creates a memoize method which caches responses in service methods.

Usage

const Memoize = require("../mixins/memoize.mixin");

module.exports = {
    name: "acl",

    mixins: [
        Memoize()
    ],

    methods: {
        async getPermissions(roleNames) {
            return await this.memoize("permissions", roleNames, async () => {
                // Do something. The response will be cached based on `roleNames` value.

                return res;
            });
        },        
    }
}
"use strict";
module.exports = function(opts = {}) {
return {
methods: {
async memoize(name, params, fn) {
if (!this.broker.cacher) return fn();
const key = this.broker.cacher.defaultKeygen(`${this.name}:memoize-${name}`, params, {});
let res = await this.broker.cacher.get(key);
if (res)
return res;
res = await fn();
this.broker.cacher.set(key, res, opts.ttl);
return res;
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment