filesync는 fileasync도 아마 사용 가능한걸로 알고 있다.
정말 간단하게 구현해본 select, insert, update, delete
select와 insert에서 cond나 keys에다가 빼낼 필드 이름을 적어주면 그 필드들만 가져온다.
delete가 drop인건 delete가 예약어이기 때문....
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | var low = require( 'lowdb' ); const FileSync = require( 'lowdb/adapters/FileSync' ) const adapter = new FileSync(__dirname+ '/../db/db.json' ) const db = low(adapter) /** * key * id pw name birthday sex email hp favorites */ const defaultDataSet = { id: '' , pw: '' , name: '' , birthday: '' , sex: '' , email: '' , hp: '' , favorites: [] } db.defaults({ users: [{id: 'test' , pw: '123' , name: 'ktw' }] }).write(); /** * select * from users where id = key * ex) * console.log(db.select('kwon3286')); * => { id: 'kwon3286', pw: 'asdf', name: 'asdf' } * * @params { id, ['id', 'pw', ...] } * @returns { object{id:'', pw:'', name:'', ...} } */ const select = function (key, cond = []){ const allInfo = db.get( 'users' ) .find({id: key}) .value(); if (cond.length === 0){ return allInfo; } if (allInfo === undefined) return {}; let result = {}; for (let i=0;i<cond.length;i++){ result[cond[i]] = allInfo[cond[i]]; } return result; } /** * insert */ const insert = function (value, keys = []){ let info = {}; info = JSON.parse(JSON.stringify(defaultDataSet)); if (keys.length === 0){ db.get( 'users' ) .push(value) .write() } else { for (let key of keys){ info[key] = value[key]; } db.get( 'users' ) .push(info) .write() } } /** * update */ const update = function (id, key, value){ let data = {}; data[key] = value; db.get( 'users' ) .find({id: id}) .assign(data) .write() } /** * drop */ const drop = function (id){ db.get( 'users' ) .remove({ id: id }) .write() } module.exports = { select, insert, update, drop, } |