naivemodel
v0.5.3
Published
When you want some minimal, anarchic, 'demoable' persistence.
Downloads
6
Readme
Naive Model
When you want some minimal, anarchic, "demoable" persistence.
Usage
Here's a small but complete example:
import { Model } from 'naivemodel';
let model = new Model('./database.json');
// this will create the file with the given content, if none exists.
model.initialize({
counter: 99,
beverage: 'Beer'
});
// if you just need the contents, use `Model.read`
model
.read()
.then(db => {
console.log(`${db.counter} bottles of ${db.beverage} on the wall, ${db.counter} of ${db.beverage}`);
});
// if you need to change the contents, pass an updater to `Model.update`
model
.update(db => ({...db, counter: db.counter - 1}))
.then(db => {
console.log(`take one down and pass it around, ${db.counter} bottles of ${db.beverage} on the wall.`);
});
// if your update has some kind of result (e.g. a new id of an inserted item), use `Model.updateWithResult`
model
.updateWithResult(db => ({
state: {...db, counter: db.counter + 1},
result: db.counter + 1
}))
.then(r => {
console.log(`Go to the store, buy one more, ${r.result} bottles of ${db.beverage} on the wall.`);
})
// if you need to completely overwrite the data, use `Model.write`
model
.write({message: "We are pivoting!"})
.then(db => {
console.log(db.message);
});
Preventively Answered Questions
Does it cache?
Nope. The OS should do some caching, and this project will probably do no better if it tries, and if performance is an issue, a real database may be the preferrable solution.
Does it lock?
Yes. Especially keep an eye on update
or updateWithResult
, because the file
is locked while your update function resolves.