CoreID/app/models/Setting.model.js

57 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

const { Model } = require('flitter-orm')
class SettingModel extends Model {
static get services() {
return [...super.services, 'utility']
}
static get schema() {
return {
key: String,
value: String,
history: [String],
}
}
static async guarantee(key, value = '') {
if ( !(await this.findOne({ key })) ) {
const new_inst = new this({ key })
new_inst.set(value)
await new_inst.save()
}
}
static async get(key) {
const inst = await this.findOne({ key })
2020-05-20 14:56:03 +00:00
return inst?.get()
}
static async set(key, value) {
const inst = await this.findOne({ key })
inst.set(value)
await inst.save()
}
get() {
return JSON.parse(this.value)
}
set(value) {
if ( Array.isArray(this.history) )
this.history.push(this.value)
this.value = JSON.stringify(value)
}
async to_api() {
return {
id: this.key,
key: this.key,
value: this.get(),
history: this.history || [],
}
}
}
module.exports = exports = SettingModel