@insertish/mutable
v1.1.0
Published
Mutable object utilities.
Downloads
3
Readme
Why?
The use-case of this library is for when you need to monitor mutations for a set of objects.
- When taking an object from the map, you will get a reference as JS passes objects by reference.
- This means everywhere you use the object will have the latest version of the object.
- Then to monitor mutations, we use a Proxy on the object internally which feeds into an EventEmitter on the map.
You may be wondering if something like Redux would do the job, probably, but it gets a bit messy when you also want to persist all the data, i.e. you're serializing and writing huge amounts of data for every small little change.
The solution is to wrap every object internally and catch any mutations on the objects.
- For any mutation, events are emitted which can be used to re-render React elements which use that relevant data.
- And for any mutation, we can also update IndexedDB with the new partial data, instead of re-saving everything.
Example Usage
import { MutableMap } from '@insertish/mutable';
type User = {
_id: string
username: string
online: boolean
flag: number
}
class Users extends MutableMap<User> {
updateUsername(id: string, username: string) {
// we would call an API here to verify we can do this
// and then use Reflect to set the correct field
this.map[id].username = username;
}
}
let map = new Users();
map.on('create', item => console.log('Created user', item));
map.on('delete', id => console.log('Deleted user with id', id));
map.on('mutation', (user: User, property: string) => console.log('User', user._id, 'has had property', property, 'changed!'));
map.create({ _id: '123', username: 'aaa', online: true, flag: 0 });
let user = map.get('123');
map.updateUsername('123', 'bbb');
map.updateUsername('123', 'bbb'); // Internally, we use lodash.isEqual to prevent multiple events firing.
console.log(JSON.stringify(user)); // Since it's a normal object, we can just serialize it if we want.
map.set({ _id: '456', username: 'bbb', online: false, flag: 0 });
map.set({ _id: '456', username: 'bbb', online: false, flag: 8 });
map.patch('456', { online: true });
map.patch('123', { flag: 1 });
map.delete('456');
Usage with IndexedDB
To use with IDB, simply pass a ZangoDB collection in. (reliance on this library isn't necessary, but I am already using it elsewhere in the project this is going to be used in, feel free to PR to use just IDB)
import { Db } from '@insertish/zangodb';
let db = new Db('state', 1, [ 'users' ]);
let map = new MutableMap<T>(db.collection('users'));
// After constructing, always reload state first.
map.restore(); // -> Promise<void>
// All changes are automatically saved to IDB.