salix/back/methods/starred-module/toggleStarredModule.js

79 lines
2.3 KiB
JavaScript
Raw Normal View History

module.exports = function(Self) {
Self.remoteMethodCtx('toggleStarredModule', {
description: 'creates or deletes a starred module for the current user',
2021-03-02 09:33:35 +00:00
accessType: 'WRITE',
returns: {
type: 'object',
root: true
},
accepts: {
arg: 'moduleName',
type: 'string',
required: true,
description: 'The module name'
},
http: {
path: `/toggleStarredModule`,
verb: 'post'
}
});
2021-06-01 20:18:13 +00:00
Self.toggleStarredModule = async(ctx, moduleName, options) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
2021-06-01 20:18:13 +00:00
let tx;
const myOptions = {};
2021-06-01 20:18:13 +00:00
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const filter = {
where: {
workerFk: userId,
moduleFk: moduleName
}
};
const [starredModule] = await models.StarredModule.find(filter, myOptions);
delete filter.moduleName;
const allStarredModules = await models.StarredModule.getStarredModules(ctx, myOptions);
let addedModule;
if (starredModule)
await starredModule.destroy(myOptions);
else {
let highestPosition;
if (allStarredModules.length) {
allStarredModules.sort((a, b) => {
return a.position - b.position;
});
highestPosition = allStarredModules[allStarredModules.length - 1].position + 1;
} else
highestPosition = 1;
addedModule = await models.StarredModule.create({
workerFk: userId,
moduleFk: moduleName,
position: highestPosition
}, myOptions);
}
2021-06-01 20:18:13 +00:00
if (tx) await tx.commit();
2021-06-01 20:18:13 +00:00
return addedModule;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};