Skip to content

Commit

Permalink
Models: add simple model class
Browse files Browse the repository at this point in the history
  • Loading branch information
jsmrcaga committed Mar 26, 2022
1 parent 5012ef3 commit 2d9cf68
Show file tree
Hide file tree
Showing 7 changed files with 430 additions and 3 deletions.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Router = require('./lib/router');
const App = require('./lib/app');
const Model = require('./lib/model');

module.exports = { Router, App };
module.exports = { Router, App, Model };
50 changes: 50 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class Model {
static KV_BINDING = null;
static PREFIX = '';

static get_id(id) {
const separator = this.PREFIX ? '-' : '';
return `${this.PREFIX}${separator}${id}`;
}

static id(instance) {
return instance.id;
}

static get(id) {
return this.KV_BINDING.get(this.get_id(id)).then(data => {
if(data === null) {
return null;
}

const model_data = JSON.parse(data);
return this.fromJSON(model_data);
});
}

static bind_kv(binding) {
this.KV_BINDING = binding;
}

static fromJSON(data) {
return new this(data);
}

toJSON() {
return {...this};
}

save() {
const id = this.constructor.id(this);
if(!id) {
throw new Error('Cannot save model with no id');
}

return this.constructor.KV_BINDING.put(
this.constructor.get_id(id),
JSON.stringify(this)
).then(() => this);
}
}

module.exports = Model;
208 changes: 207 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"license": "MIT",
"devDependencies": {
"chai": "^4.3.6",
"mocha": "^9.2.1"
"mocha": "^9.2.1",
"sinon": "^13.0.1"
},
"publishConfig": {
"access": "public"
Expand Down
Loading

0 comments on commit 2d9cf68

Please sign in to comment.