Git Product home page Git Product logo

cache-base's Introduction

cache-base NPM version NPM monthly downloads NPM total downloads Linux Build Status

Basic object cache with get, set, del, and has methods for node.js/javascript projects.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

(TOC generated by verb using markdown-toc)

Install

Install with npm:

$ npm install --save cache-base

Quickstart

const CacheBase = require('cache-base');
const app = new CacheBase();

app.set('a.b', 'c');

console.log(app.cache.a);    //=> { b: 'c' }
console.log(app.cache.a.b);  //=> 'c'

console.log(app.get('a'));   //=> { b: 'c' }
console.log(app.get('a.b')); //=> 'c'

More usage examples below.

API

Params

  • prop {String|Object}: (optional) Property name to use for the cache, or the object to initialize with.
  • cache {Object}: (optional) An object to initialize with.

Example

const app = new CacheBase();

Assign value to key. Also emits set with the key and value.

Params

  • key {String|Array}: The name of the property to set. Dot-notation may be used to set nested properties.
  • value {any}
  • returns {Object}: Returns the instance for chaining.

Events

  • emits: set with key and value as arguments.

Example

app.on('set', function(key, val) {
  // do something when `set` is emitted
});

app.set('admin', true);

// also takes an object or an array of objects
app.set({ name: 'Brian' });
app.set([{ foo: 'bar' }, { baz: 'quux' }]);
console.log(app);
//=> { name: 'Brian', foo: 'bar', baz: 'quux' }

Return the value of key.

Params

  • key {String|Array}: The name of the property to get. Dot-notation may be used to set nested properties.
  • returns {any}: Returns the value of key

Events

  • emits: get with key and value as arguments.

Example

app.set('a.b.c', 'd');
app.get('a.b');
//=> { c: 'd' }

Create a property on the cache with the given value only if it doesn't already exist.

Params

  • key {String}: Property name or object path notation.
  • val {any}
  • returns {Object}: Returns the instance for chaining.

Example

console.log(app.cache); //=> {}
app.set('one', { foo: 'bar' });
app.prime('one', { a: 'b' });
app.prime('two', { c: 'd' });
console.log(app.cache.one); //=> { foo: 'bar' }
console.log(app.cache.two); //=> { c: 'd' }

Set a default value to be used when .get() is called and the value is not defined on the cache. Returns a value from the defaults when only a key is passed.

Params

  • key {String|Array}: The name of the property to set. Dot-notation may be used to set nested properties.
  • value {any}: (optional) The value to set on the defaults object.
  • returns {Object}: Returns the instance for chaining.

Example

app.set('foo', 'xxx');
app.default('foo', 'one');
app.default('bar', 'two');
app.default('baz', 'three');
app.set('baz', 'zzz');

console.log(app.get('foo'));
//=> 'xxx'

console.log(app.get('bar'));
//=> 'two'

console.log(app.get('baz'));
//=> 'zzz'

console.log(app);
// CacheBase {
//   cache: { foo: 'xxx', bar: 'two', baz: 'zzz' },
//   defaults: { foo: 'one', bar: 'two', baz: 'three' } }

Set an array of unique values on cache key.

Params

  • key {String|Array}: The name of the property to union. Dot-notation may be used to set nested properties.
  • value {any}
  • returns {Object}: Returns the instance for chaining.

Example

app.union('a.b.c', 'foo');
app.union('a.b.c', 'bar');
app.union('a.b.c', ['bar', 'baz']);
console.log(app.get('a'));
//=> { b: { c: ['foo', 'bar', 'baz'] } }

Return true if the value of property key is not undefined.

Params

  • key {String|Array}: The name of the property to check. Dot-notation may be used to set nested properties.
  • returns {Boolean}

Example

app.set('foo', true);
app.set('baz', null);
app.set('bar', undefined);

app.has('foo'); //=> true
app.has('bar'); //=> true
app.has('baz'); //=> false

Returns true if the specified property is an own (not inherited) property. Similar to .has(), but returns true if the key exists, even if the value is undefined.

Params

  • key {String}
  • returns {Boolean}: Returns true if object key exists. Dot-notation may be used to set nested properties.

Example

app.set('a.b.c', 'd');
app.set('x', false);
app.set('y', null);
app.set('z', undefined);

app.hasOwn('a');      //=> true
app.hasOwn('b');      //=> true
app.hasOwn('c');      //=> true
app.hasOwn('a.b.c');  //=> true
app.hasOwn('x');      //=> true
app.hasOwn('y');      //=> true
app.hasOwn('z');      //=> true
app.hasOwn('lslsls'); //=> false

Delete one or more properties from the instance.

Params

  • key {String|Array}: The name of the property to delete. Dot-notation may be used to set nested properties.
  • returns {Object}: Returns the instance for chaining.

Events

  • emits: del with the key as the only argument.

Example

// setup a listener to update a property with a default
// value when it's deleted by the user
app.on('del', key => app.set(key, app.default(key)));

app.del(); // delete all properties on the cache
// or
app.del('foo');
// or an array of keys
app.del(['foo', 'bar']);

Reset the entire cache to an empty object. Note that this does not also clear the defaults object, since you can manually do cache.defaults = {} if you want to reset that object as well.

Example

// clear "defaults" whenever the cache is cleared
app.on('clear', key => (app.defaults = {}));
app.clear();

Visit (or map visit) the specified method (key) over the properties in the given object or array.

Params

  • key {String|Array}: The name of the method to visit.
  • val {Object|Array}: The object or array to iterate over.
  • returns {Object}: Returns the instance for chaining.

Gets an array of names of all enumerable properties on the cache.

Example

const app = new CacheBase();
app.set('user', true);
app.set('admin', false);

console.log(app.keys);
//=> ['user', 'admin']

Gets the length of keys.

Example

const app = new CacheBase();
app.set('user', true);
app.set('admin', false);

console.log(app.size);
//=> 2

Usage examples

Create an instance of cache-base

const app = new CacheBase();

app.set('a', 'b');
app.set('c.d', 'e');

console.log(app.get('a'));
//=> 'b'
console.log(app.get('c'));
//=> { d: 'e' }
console.log(app);
//=> CacheBase { a: 'b' }

Initialize with an object

const app = new CacheBase({ a: 'b', c: { d: 'e' } });

console.log(app.get('a'));
//=> 'b'
console.log(app.get('c'));
//=> { d: 'e' }
console.log(app.get('c.d'));
//=> 'e'
console.log(app);
//=> CacheBase { cache: { a: 'b' } }

Inherit

class MyApp extends CacheBase {}

const app = new MyApp();
app.set('a', 'b');
app.set('c', 'd');

console.log(app.get('a'));
//=> 'b'

console.log(app);
//=> MyApp { cache: { a: 'b', c: 'd' } }

Custom namespace

Pass a string as the first value to the contructor to define a custom property name to use for the cache. By default values are stored on the cache property.

const CacheBase = require('cache-base');
const app = new CacheBase('data', { a: 'b' });
app.set('c.d', 'e');

// get values
console.log(app.get('a'));
//=> 'b'
console.log(app.get('c'));
//=> { d: 'e' }
console.log(app.data);
//=> { a: 'b', c: { d: 'e' } }
console.log(app);
//=> CacheBase { data: { a: 'b', c: { d: 'e' } } }

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

  • base-methods: base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… more | homepage
  • get-value: Use property paths like 'a.b.c' to get a nested value from an object. Even works… more | homepage
  • has-value: Returns true if a value exists, false if empty. Works with deeply nested values using… more | homepage
  • option-cache: Simple API for managing options in JavaScript applications. | homepage
  • set-value: Create nested values and any intermediaries using dot notation ('a.b.c') paths. | homepage
  • unset-value: Delete nested properties from an object using dot notation. | homepage

Contributors

Commits Contributor
67 jonschlinkert
2 wtgtybhertgeghgtwtg

Author

Jon Schlinkert

License

Copyright © 2018, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.6.0, on March 23, 2018.

cache-base's People

Contributors

jonschlinkert avatar wtgtybhertgeghgtwtg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cache-base's Issues

TODO: config-cache

potentially use this as a base for config-cache. the only thing I'm having a hard time deciding on is whether or not to allow getting/setting of property paths, e.g.

get('data.foo.bar');
//=> '{foo: {bar: {...}}}'

This can be expensive, but I think if we prevent lookups when the key doesn't have a . it should speed things up. Also, I'm not currently doing any setting of object paths (set('a.b.c', {foo: 'bar'})), but it can be (re)implemented if it's necessary to use this for config-cache.

cc @doowb

fix documentation or make it real

It shows that default writing is to app.cache but it writes to app.
So, PR for fix or PR for module.exports = namespace('cache')?

Support for TTL

Hi,

Can't find support for TTL. Would be very usefull.

Thanks

remove support for setting on the root of the cache

I've never been a fan of settings values on the root, as it creates potential for conflicts, makes it harder to get the actually user-defined values, et cetera.

I think we should just set values on .cache by default, or a property specified by the user.

The consequence of this change is that you won't be able to directly get or set values from the root of the instance of cacheBase, you'd have to get and set on cacheBase.cache or whatever property was defined.

@doowb any thoughts? can you think of other side effects of removing support for getting/setting on the root of the object? will it materially change how we do things in other libs?

add `.default()` method

I think it would be nice to support adding default values that would work like this:

const CacheBase = require('cache-base');
const app = new CacheBase();

app.set('foo', 'xxx');
app.default('foo', 'one');
app.default('bar', 'two');
app.default('baz', 'three');
app.set('baz', 'zzz');

console.log(app.get('foo'));
//=> 'xxx'

console.log(app.get('bar'));
//=> 'two'

console.log(app.get('baz'));
//=> 'zzz'

console.log(app);
// Cache {
//   cache: { foo: 'xxx', bar: 'two', baz: 'zzz' },
//   defaults: { foo: 'one', bar: 'two', baz: 'three' } }

@doowb any thoughts?

Another issue, #5 describes a similar but different approach

more real `.has` method?

Before was using has-value(s), now is just typeof val !== undefined

also add hasOwn and union methods?

denial of service and may lead to remote code execution vulnerability

According to https://app-eu.whitesourcesoftware.com/Wss/WSS.html#!securityVulnerability;id=CVE-2020-28275 there is a

Prototype pollution vulnerability in 'cache-base' versions 0.7.0 through 4.0.0 allows attacker to cause a denial of service and may lead to remote code execution.

in

this.emit('set', key, ...rest);

There seems to be a CVE already assigned: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-28275

Any chance to get this fixed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.