-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
430 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.