Namespaces

What namespace is used for?

Namespace is used to avoid overwriting items when you are storing them using the same key.

If this isn't clear yet, have a look at this example:

import { createCache } from 'stash-it';
import createMemoryAdapter from 'stash-it-adapter-memory';

const adapterA = createMemoryAdapter({ namespace: 'A' });
const cacheA = createCache(adapterA);

cacheA.setItem('key', 'value_1');
cacheA.setItem('key', 'value_2');

const item = cacheA.getItem('key');

item.value; // value_2

Why did it happen?

Each adapter uses the same storage for every cache instance in which it's being used. Under the hood namespace is combined with key and they both construct 'the key' that is finally used to store items. For memory adapter it's just joining key and namespace with a dot. So taking above example, item is stored in memory under A.key key. Thus, setting it once again for the same key will overwrite it.

How to avoid that?

Use different namespace in different parts of your application to not worry about overwriting somebody else's stuff. Here's how you do it:

import { createCache } from 'stash-it';
import createMemoryAdapter from 'stash-it-adapter-memory';

const adapterA = createMemoryAdapter({ namespace: 'A' });
const cacheA = createCache(adapterA);

const adapterB = createMemoryAdapter({ namespace: 'B' });
const cacheB = createCache(adapterB);

cacheA.setItem('key', 'value_1');
cacheB.setItem('key', 'value_2');

cacheA.getItem('key').value; // value_1
cacheB.getItem('key').value; // value_2

How about having different cache instances but same namespaces for same adapter?

Well, it will behave exactly like in first example:

import { createCache } from 'stash-it';
import createMemoryAdapter from 'stash-it-adapter-memory';

const adapter1 = createMemoryAdapter({ namespace: 'A' });
const adapter2 = createMemoryAdapter({ namespace: 'A' });

const cache1 = createCache(adapter1);
const cache2 = createCache(adapter2);

cache2.hasItem('key'); // false

cache1.setItem('key', 'value');

cache2.hasItem('key'); // true
cache2.getItem('key').value; // value
cache2.setItem('key', 'other value');

cache1.getItem('key').value; // other value

// Removing an item will affect both caches as well
cache1.removeItem('key'); // true

cache1.hasItem('key'); // false
cache2.hasItem('key'); // false

Can I use any namespace? E.g. '123$%^ === X'?

It depends on the adapter you're using. Each adapter will use namespace in combination with key to store some value under that constructed key. And if that key must be a string (because that adapter can only hold strings as keys), then it must be a string.

Detailed information about namespaces can be found in each adapter.


results matching ""

    No results matching ""