Skip to content

Instantly share code, notes, and snippets.

@huytd
Created January 23, 2020 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huytd/cb407d9bbba9b2edbab2052dd281e698 to your computer and use it in GitHub Desktop.
Save huytd/cb407d9bbba9b2edbab2052dd281e698 to your computer and use it in GitHub Desktop.
A very inefficient file-based database. For prototyping only.
fs = require "fs"
###
A very inefficient file-based database. For prototyping only.
Usage:
db = new DB()
# Insert new row
db.insert { ... }
# Delete any row matched condition
db.delete (row) -> condition
# Find some row
db.find (row) -> condition
# Update rows that matched the condition
db.update (row) -> condition, (row) -> updatedRow
###
DB = () ->
@data = null;
# Read and update the internal data model
@readData = () ->
data = fs.readFileSync "./data.db", "utf-8"
try
@data = JSON.parse data
catch e
console.log "DB ERROR:", e
# Write current data to file
@writeData = () ->
content = JSON.stringify @data
fs.writeFileSync "./data.db", content
# Get
@find = (fn) -> @data.filter fn
# Delete
@delete = (fn) ->
@data = @data.filter not fn
@writeData()
# Insert
@insert = (row) ->
@data = @data.concat row
@writeData()
# Update
@update = (fn, update) ->
@data = @data.map (row) -> if fn row then update row else row
@writeData()
# Main DB implementation
@readData()
return this
module.exports = DB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment