2021-03-01 11:15:13 +00:00
|
|
|
module.exports = function(Self) {
|
|
|
|
Self.remoteMethodCtx('toggleStarredModule', {
|
2021-03-01 21:21:04 +00:00
|
|
|
description: 'creates or deletes a starred module for the current user',
|
2021-03-02 09:33:35 +00:00
|
|
|
accessType: 'WRITE',
|
2021-03-01 11:15:13 +00:00
|
|
|
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;
|
2021-03-01 11:15:13 +00:00
|
|
|
const userId = ctx.req.accessToken.userId;
|
2021-06-01 20:18:13 +00:00
|
|
|
|
|
|
|
let tx;
|
|
|
|
let myOptions = {};
|
|
|
|
|
|
|
|
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-03-01 11:15:13 +00:00
|
|
|
}
|
|
|
|
|
2021-06-01 20:18:13 +00:00
|
|
|
if (tx) await tx.commit();
|
2021-03-01 11:15:13 +00:00
|
|
|
|
2021-06-01 20:18:13 +00:00
|
|
|
return addedModule;
|
|
|
|
} catch (e) {
|
|
|
|
if (tx) await tx.rollback();
|
|
|
|
throw e;
|
2021-03-01 11:15:13 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|