Last active
February 23, 2018 06:00
-
-
Save alexkrolick/443968c5923d1b6bea6520625ed00497 to your computer and use it in GitHub Desktop.
Knex.js Mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash' | |
// In-memory Knex mock 🤯 | |
function DB () { | |
const db = function (table) { | |
if (!table) return db | |
db._table = table | |
if (!db._db[table]) { | |
db._db[table] = { | |
_latestId: 0, | |
_items: {}, | |
} | |
} | |
db._result = db._db[table] | |
return db | |
} | |
db._db = {} | |
db._table = null | |
db._result = [] | |
this._select = i => i | |
db.transaction = cb => cb(db) | |
db.insert = item => { | |
const table = db._db[db._table] | |
table._latestId++ | |
item.id = table._latestId | |
table._items[item.id] = item | |
db._result = [item] | |
return db | |
} | |
db.select = columns => { | |
const all = _.includes(columns, '*') | |
this._select = all ? (i => i) : (i => _.pick(i, columns)) | |
return db | |
} | |
db.where = (column, value) => { | |
const table = db._db[db._table] | |
db._result = _.filter(table._items, { [column]: value }).map(this._select) | |
this._select = i => i | |
return db | |
} | |
db.then = cb => { | |
return cb(_.cloneDeep(db._result)) | |
} | |
return db | |
} | |
const mock = new DB() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment