UserModel.observe('before save', function (context, next) {
let data = context.instance ? context.instance : context.data;
const hasBase64InAvatar = (data.avatar || '').indexOf('base64,') > -1;
let [fileType, base64] = [];
if (hasBase64InAvatar) {
[fileType, base64] = data.avatar.split('base64,');
data.base64 = base64;
[, fileType] = fileType.split('/');
}
let fileName = data.username || (context.currentInstance ? context.currentInstance.username : new Date());
if (fileType) {
fileType = fileType.replace(';', '');
fileName += fileType ? '.' + fileType : '';
}
// We need to add roles to user if uploading data has roles
let allPromises = [];
if (_.isObjectLike(data.roles)) {
const roles = _.isArray(data.roles) ? data.roles : [data.roles];
allPromises.push(UserModel._addRoles({roles, userId}));
delete data.roles;
}
if ((data.base64 || '').length > 100) {
allPromises.push(
new Promise((resolve, reject) => {
UserModel
._saveImage(data.base64, fileName)
.then((result) => {
data.avatar = result;
resolve(true);
})
.catch((err) => {
reject(err);
});
})
);
delete data.base64;
}
Promise.all([...allPromises]).then((values) => {
console.log('resolve all ', values);
next();
});
});