export const SettingsSchema = { name: 'Settings', primaryKey: 'id', properties: { /** @type {number} */ id: 'int', key: 'string', value: 'string', }, }; /** * @typedef {Unmanaged & import('realm').Object} Setting */ class SettingModel { /** * SettingModel * @param {Realm} realm */ constructor(realm) { /** @type string */ this.schema = 'Settings'; /** @type {Realm} */ this.realm = realm; } /** * @param {Setting} data */ add(data) { this.realm.write(() => { if (data.id === undefined) { const id = this.realm.objects(this.schema).max('id'); data.id = id === undefined ? 1 : id + 1; } try { this.realm.create(this.schema, data, 'never'); } catch (e) { console.log('db setting add', e); } }); } /** * @param {Setting} data */ upsert(data) { const tmp = this.get(data.key); if (tmp === null) { this.add(data); } else { if (data.id === undefined) { data.id = tmp.id; } this.realm.write(() => { this.realm.create(this.schema, data, 'modified'); }); } } /** * @param {Setting} data */ update(data) { this.realm.write(() => { this.realm.create(this.schema, data, 'modified'); }); } /** * get setting with key * @param {string} key * @returns {Setting?} */ get(key) { /** @type {import('realm').Results} */ const tmp = this.realm.objects(this.schema); if (tmp.length === 0) { return null; } return tmp.filtered('key = "' + key + '"')[0] ?? null; } /** * delete setting with id * @param {number} id id */ delete(id) { const tmp = this.get(id); if (typeof tmp === 'object') { this.realm.write(() => { this.realm.delete(tmp); }); } } } export default SettingModel;