ldc-com-app/ComApp/src/Models/Common.js

65 lines
1.3 KiB
JavaScript
Raw Normal View History

import Database from '../Database';
const Realm = require('realm');
let realm = new Realm(Database);
class CommonModel {
constructor() {
this.schema = 'Common';
}
add(data) {
realm.write(() => {
if (data.id === undefined) {
let id: any = realm.objects(this.schema).max('id');
data.id = id === undefined ? 1 : id + 1;
}
try {
realm.create(this.schema, data, 'never');
} catch (e) {
console.log('db common add', e);
}
});
}
update(data) {
let tmp = this.get(data.key);
if (tmp === undefined) {
this.add(data);
} else {
if (data.id === undefined) {
data.id = tmp.id;
}
realm.write(() => {
realm.create(this.schema, data, 'modified');
});
}
}
get(key) {
let tmp = realm.objects(this.schema);
if (tmp.length === 0) {
return false;
} else {
tmp = tmp.filtered('key = "' + key + '"')[0];
}
return tmp;
}
getAll() {
let tmp = realm.objects(this.schema);
return tmp;
}
delete(key) {
const tmp = this.get(key);
if (typeof tmp === 'object') {
realm.write(() => {
realm.delete(tmp);
});
}
}
}
export default new CommonModel();