danforth
v0.1.0
Published
A tiny embedded document database for small Node services. No dependencies.
Maintainers
Readme
danforth
A tiny embedded document database for small Node services. No dependencies, one file, about 300 lines.
const danforth = require("danforth");
const db = danforth.open("./data/app.db");
const parts = db.collection("parts");
parts.insert({ name: "Carburetor", asking: 60, status: "listed" });
parts.update(1, { status: "sold", soldFor: 55 });
parts.find((p) => p.status === "listed");Everything lives in memory, so reads are instant. Every change is appended to a text file before it takes effect, so nothing is lost when the process stops.
Install
npm install danforthAPI
danforth.open([file])
Opens a database. With a filename, that file is read if it exists and every later change is written to it. With no filename, everything stays in memory and nothing is saved — handy for tests.
Throws if another process already has this database open.
db.collection(name)
Returns the collection, creating it if this is the first time it has been asked for. There is no setup step and no schema. Note that a typo gives you a new empty collection rather than an error.
db.close()
Closes the file and releases the lock. Nothing is buffered, so closing is only about tidying up, not about saving.
db.compact()
Rewrites the file as a clean snapshot of the current data. Happens automatically when it's worth doing; this is only for forcing it.
collection.insert(doc)
Stores a copy of doc and returns it with id, createdAt and updatedAt
filled in. Ids are whole numbers starting at 1, and are never reused.
const part = parts.insert({ name: "Rear rack", asking: 40 });
part.id; // 1collection.get(id)
Returns a copy of the record, or null if there isn't one. Accepts 7 or
"7", since ids arriving from a form or a URL are text.
collection.update(id, patch)
Merges patch into the record and returns the new version, or null if there
is no such record. Only the fields in patch change. id and createdAt are
protected; updatedAt is refreshed.
parts.update(1, { status: "sold", soldFor: 55 });collection.remove(id)
Deletes the record. Returns true if there was one, false otherwise.
collection.find(fn) / collection.findOne(fn)
Plain JavaScript instead of a query language. find returns an array,
findOne returns the first match or null.
parts.find((p) => p.status === "listed" && p.asking > 50);
parts.findOne((p) => p.name === "Carburetor");Every record is checked one at a time, which is fine at this size.
collection.all() / collection.count()
Every record as an array, and how many there are.
collection.isValidId(input)
Whether input could be an id at all — useful for telling "that's not an id"
apart from "no such record" in a form handler.
Licence
MIT
