Skip to content

Instantly share code, notes, and snippets.

@truemedian
Created September 11, 2021 18:12
Show Gist options
  • Save truemedian/dc80d58a17ef3116233153e8e85ebf14 to your computer and use it in GitHub Desktop.
Save truemedian/dc80d58a17ef3116233153e8e85ebf14 to your computer and use it in GitHub Desktop.
local fs = require 'fs'
local json = require 'json'
local Database = {}
Database.__index = Database
function Database.load(path)
local self = setmetatable({}, Database)
self.path = path
self.dirty = false
if fs.existsSync(path) then
local data = assert(fs.readFileSync(path))
if data == '' then
self.data = {}
else
self.data = json.parse(data)
assert(type(self.data) == 'table', 'invalid data schema')
end
else
self.data = {}
end
end
function Database:save()
if not self.dirty then
return
end
local tmpname = self.path .. '.tmp'
local data = json.stringify(self.data)
assert(fs.writeFileSync(tmpname, data))
assert(fs.renameSync(tmpname, self.path))
end
function Database:get(key)
return self.data[key]
end
function Database:set(key, value)
self.data[key] = value
self.dirty = true
end
--[[ Example:
local db = Database.load('/path/to/db.json')
db:set('foo', 'bar')
db:get('foo') --> 'bar'
db:save()
--- db.json
{"foo":"bar"}
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment