CoreID/app/models/Setting.model.js
2020-05-20 09:56:03 -05:00

57 lines
1.2 KiB
JavaScript

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 })
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