Klein: Combining knex with Immutable.js
I'm a big fan of knex as a database wrapper and am a heavy user of Immutable.js on the client side for data handling in React/Redux.
Previously, I had used Bookshelf as an ORM because it provided a simple interface to manage basic CRUD actions on models and their relationships. While I do like Bookshelf, there were a few things that didn't sit right with me. I like immutable data structures and Bookshelf doesn't use them. I also think the relationship management is more complicated than it needed to be for what I was using. With those two things in mind (plus a bunch of smaller gripes) I set out to make a simple ORM that would combine knex with Immutable.js for immutable data.
Introducing Klein, a small ORM that used immutable data for models.
Defining a model is as simple as telling Klein the name of the table:
const Klein = require('klein/auto');
const Things = Klein.model('things');
Then you can query it using methods similar to straight knex:
Things.all().then(things => {
// things is an Immutable.List()
console.log(things);
});
Things.where({ some_field: 'some value' }).first().then(thing => {
// thing is an Immutable.Map()
console.log(thing);
});
As each model 'instance' is simply an instance of Immutable, all ORM methods are performed from the model's class:
let cat = Immutable.Map({
name: 'Cat',
says: 'Meow'
});
Things.save(cat).then(cat => {
// cat is an instance of Immutable.Map() and now has id, created_at, and updated_at fields
cat = cat.set('says', 'MEOW!!');
return Things.save(cat);
}).then(cat => {
// cat is an instance of Immutable.Map() and now says 'MEOW!!'
console.log(cat);
});
For more (up to date) information read the Klein docs.
If I just made your day a little better then thank me with a coffee: