somewhere
Version:
Small in-memory database for Node.js that persists on disk
87 lines (70 loc) • 2.46 kB
text/coffeescript
'use strict'
fs = require 'fs'
class Somewhere
constructor: (databasePath) ->
= databasePath
= {}
do if
connect: ->
if fs.existsSync
= JSON.parse fs.readFileSync , 'utf-8'
clear: ->
fs.unlinkSync if
= {}
write: ->
fs.writeFileSync , JSON.stringify if
save: (collection, data) ->
_checkCollection , collection
data.id = do _uuid
[collection].push data
do
_extend {}, data
findOne: (collection, attrs) ->
_checkCollection , collection
return {} if !attrs
_filterOne [collection], _matches attrs
find: (collection, attrs) ->
_checkCollection , collection
return [collection] if !attrs
_filter [collection], _matches attrs
update: (collection, id, attrs) ->
_checkCollection , collection
data = item for item in [collection] when item.id is id
data[key] = val for key, val of attrs if data
do
_extend {}, data
remove: (collection, id) ->
_checkCollection , collection
index = [collection].indexOf(item) for item in [collection] when item.id is id
return false if not index and index isnt 0
[collection].splice index, 1 if index > -1
do
true
# -- Private methods -----------------------------------------------------------
_uuid = ->
date = new Date().getTime()
uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = (date + Math.random() * 16) % 16 | 0
date = Math.floor date/16
v = if c is 'x' then r else r & 7 | 8
v.toString 16
_checkCollection = (database, collection) ->
return if database[collection]
database[collection] = []
_filter = (obj, predicate) ->
result = []
result.push _extend({}, item) for item in obj when predicate item
result
_filterOne = (obj, predicate) ->
result = {}
return _extend result, item for item in obj when predicate item
result
_matches = (attrs) ->
(obj) ->
return false for key, val of attrs when attrs[key] isnt obj[key]
true
_extend = (obj, args...) ->
args.forEach (source) ->
obj[method] = source[method] for method of source when hasOwnProperty.call source, method
obj
module.exports = Somewhere