2019-04-26 21:15:25 +00:00
|
|
|
import { InteractionManager } from 'react-native';
|
2019-10-07 20:56:30 +00:00
|
|
|
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
|
2019-04-26 21:15:25 +00:00
|
|
|
|
2019-10-07 20:56:30 +00:00
|
|
|
import database from '../database';
|
2019-04-26 21:15:25 +00:00
|
|
|
import log from '../../utils/log';
|
2019-10-07 20:56:30 +00:00
|
|
|
import protectedFunction from './helpers/protectedFunction';
|
2019-04-26 21:15:25 +00:00
|
|
|
|
2019-06-17 13:57:07 +00:00
|
|
|
export default function() {
|
2019-10-07 20:56:30 +00:00
|
|
|
const db = database.active;
|
2019-06-17 13:57:07 +00:00
|
|
|
return new Promise(async(resolve) => {
|
|
|
|
try {
|
|
|
|
// RC 0.70.0
|
|
|
|
const result = await this.sdk.get('roles.list');
|
2019-04-26 21:15:25 +00:00
|
|
|
|
2019-06-17 13:57:07 +00:00
|
|
|
if (!result.success) {
|
|
|
|
return resolve();
|
|
|
|
}
|
2019-04-26 21:15:25 +00:00
|
|
|
|
2019-06-17 13:57:07 +00:00
|
|
|
const { roles } = result;
|
2019-04-26 21:15:25 +00:00
|
|
|
|
2019-06-17 13:57:07 +00:00
|
|
|
if (roles && roles.length) {
|
2019-10-07 20:56:30 +00:00
|
|
|
InteractionManager.runAfterInteractions(async() => {
|
|
|
|
await db.action(async() => {
|
|
|
|
const rolesCollections = db.collections.get('roles');
|
|
|
|
const allRolesRecords = await rolesCollections.query().fetch();
|
|
|
|
|
|
|
|
// filter roles
|
|
|
|
let rolesToCreate = roles.filter(i1 => !allRolesRecords.find(i2 => i1._id === i2.id));
|
|
|
|
let rolesToUpdate = allRolesRecords.filter(i1 => roles.find(i2 => i1.id === i2._id));
|
|
|
|
|
|
|
|
// Create
|
|
|
|
rolesToCreate = rolesToCreate.map(role => rolesCollections.prepareCreate(protectedFunction((r) => {
|
|
|
|
r._raw = sanitizedRaw({ id: role._id }, rolesCollections.schema);
|
|
|
|
Object.assign(r, role);
|
|
|
|
})));
|
|
|
|
|
|
|
|
// Update
|
|
|
|
rolesToUpdate = rolesToUpdate.map((role) => {
|
|
|
|
const newRole = roles.find(r => r._id === role.id);
|
|
|
|
return role.prepareUpdate(protectedFunction((r) => {
|
|
|
|
Object.assign(r, newRole);
|
|
|
|
}));
|
|
|
|
});
|
|
|
|
|
|
|
|
const allRecords = [
|
|
|
|
...rolesToCreate,
|
|
|
|
...rolesToUpdate
|
|
|
|
];
|
|
|
|
|
2019-06-17 13:57:07 +00:00
|
|
|
try {
|
2019-10-07 20:56:30 +00:00
|
|
|
await db.batch(...allRecords);
|
2019-06-17 13:57:07 +00:00
|
|
|
} catch (e) {
|
2019-09-03 19:27:57 +00:00
|
|
|
log(e);
|
2019-06-17 13:57:07 +00:00
|
|
|
}
|
2019-10-07 20:56:30 +00:00
|
|
|
return allRecords.length;
|
|
|
|
});
|
2019-06-17 13:57:07 +00:00
|
|
|
return resolve();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} catch (e) {
|
2019-09-03 19:27:57 +00:00
|
|
|
log(e);
|
2019-06-17 13:57:07 +00:00
|
|
|
return resolve();
|
2019-04-26 21:15:25 +00:00
|
|
|
}
|
2019-06-17 13:57:07 +00:00
|
|
|
});
|
2019-04-26 21:15:25 +00:00
|
|
|
}
|