Last active
April 9, 2019 16:54
-
-
Save ianfabs/81d165283fa0b8e45d8f8f51ee42e76e to your computer and use it in GitHub Desktop.
A really really REAAAALLLY tiny DB I made for testing things, works great with graphql apis :-)
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
// Do not use this class yet, please just use the Collection class | |
class DB { | |
constructor(collections) { | |
if ( | |
collections !== null && | |
collections !== undefined && | |
collections !== [] | |
) { | |
//this._db = collections.map((s, i) => ({ ...s, id: i })); | |
if (collections instanceof Object) { | |
this._db = collections; | |
console.log(collections); | |
Object.values(this._db).forEach(el => { | |
if (!(el instanceof Collection)) { | |
throw new Error( | |
"TinyDB: You supplied a value that is not an instanceof a collection" | |
); | |
} | |
}); | |
} else { | |
throw new Error("eh"); | |
} | |
} else { | |
this._db = {}; | |
} | |
} | |
} | |
class Collection { | |
constructor(set) { | |
if (set !== null && set !== undefined && set !== []) { | |
this._c = set.map((s, i) => ({ ...s, id: i })); | |
} else { | |
this._c = []; | |
} | |
} | |
get items() { | |
return this._c.map((s, i) => ({ ...s, id: i })); | |
} | |
findByKey(key, value) { | |
return this._c.filter(el => el[key] === value); | |
} | |
findByKeyLike(key, value) { | |
return this._c.filter(el => el[key].match(value)); | |
} | |
findById(id) { | |
return this._c[id]; | |
} | |
findByIdAndUpdate(id, item) { | |
this._c[id] = { ...this._c[id], ...item }; | |
return this._c[id]; | |
} | |
findByIdAndRemove(id) { | |
if (this._c.length > -1) { | |
this._c.splice(id, 1); | |
return true; | |
} else return false; | |
} | |
findAndRemoveDuplicatesByKey(key) { | |
const values = this._c.map(e => e[key]); | |
this._c = this._c.filter((el, i) => values.indexOf(el[key]) === i); | |
return this._c; | |
} | |
insert(item) { | |
const _new = { ...item, id: this._c.length }; | |
this._c.push(_new); | |
return _new; | |
} | |
} | |
export default Collection; | |
export { DB, Collection }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment