yarkovaleksei / vue2-storage

Wrapper over browser storage for JavaScript or Vue.js app
http://yarkovaleksei.github.io/vue2-storage/
MIT License
112 stars 11 forks source link

stringify replacer function option #43

Closed halaprop closed 3 years ago

halaprop commented 4 years ago

Thanks for this library. Would be great to have an optional replacer function in the options that gets passed to JSON.stringify. This would allow callers to add objects with cyclic references.

yarkovaleksei commented 4 years ago

@halaprop, maybe something similar to middlewares?

halaprop commented 4 years ago

That might be the most general form. Simpler (and enough for me) would be to let the caller specify the second parameter to the library's JSON.stringify() call.

// client code
const blacklist = [ 'foo', 'bar' ]
const options = {
  prefix: 'app_',
  // etc
  replacer: (key, value) => blacklist.includes(key) ? undefined : value
}

Then in vue2-storage...

    toJSON(data, options = {}) {
        const ttl = ('ttl' in options) ? options.ttl : this.options.ttl;
        return JSON.stringify({
            value: data,
            ttl: ttl > 0 ? ttl + Date.now() : 0,
        },
        options.replacer  // JSON stringify filters values through this
        );
    }
yarkovaleksei commented 4 years ago

Yes, I meant it. This is a great idea!