export const DirectoriesSchema = { name: 'Directories', primaryKey: 'id', properties: { id: 'int', name: 'string', parent: {type: 'int', optional: true}, order: 'int', needAuthorization: 'int', }, }; class DirectoryModel { constructor(realm) { this.schema = 'Directories'; this.realm = realm; } add(data) { this.realm.write(() => { this.realm.create(this.schema, data); }); } update(data) { this.realm.write(() => { this.realm.create(this.schema, data, 'modified'); }); } get(id) { let tmp = this.realm.objects(this.schema); if (tmp.length === 0) { return false; } else { tmp = tmp.filtered('id = ' + id)[0]; } return tmp; } getAll(role, authorizedFolders, format, lang) { if (authorizedFolders !== null && authorizedFolders !== undefined) { authorizedFolders = JSON.parse(authorizedFolders); } let tmp = this.realm.objects(this.schema); if (role === 'USER') { if (authorizedFolders.length > 0) { tmp = tmp.filtered( 'needAuthorization = 0 OR ' + authorizedFolders .map(folder => ' id = "' + folder.id + '"') .join(' OR '), ); } else { tmp = tmp.filtered('needAuthorization = 0'); } } if (format) { return this._recursiveDir(tmp, lang); } return tmp; } clear() { this.realm.write(() => { this.realm.delete(this.realm.objects(this.schema)); }); } _recursiveDir(list, lang, parent = null) { let root = list.filter(e => e.parent === parent); let tmp = []; for (let i = 0; i < root.length; i++) { let childs = this._recursiveDir(list, lang, root[i].id); let name = JSON.parse(root[i].name); tmp[i] = {}; tmp[i].id = root[i].id; tmp[i].name = this.getI18nName(lang, name); tmp[i].items = []; for (let j = 0; j < childs.length; j++) { childs[j].value = childs[j].id; tmp[i].items.push(childs[j]); } if (!tmp[i].items.length) { delete tmp[i].items; } } return tmp; } getI18nName(lang, name) { let tmp; switch (lang) { case 'fr': tmp = name.fr; break; case 'en': tmp = name.en; break; case 'de': tmp = name.de; break; case 'es': tmp = name.es; break; } if (tmp === undefined) { tmp = name.fr; } return tmp; } } export default DirectoryModel;