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

99 lines
2.7 KiB
JavaScript
Raw Normal View History

2021-06-01 20:18:13 +00:00
module.exports = function(Self) {
Self.remoteMethodCtx('setPosition', {
description: 'sets the position of a given module',
accessType: 'WRITE',
returns: {
type: 'object',
root: true
},
accepts: [
{
arg: 'moduleName',
type: 'string',
required: true,
description: 'The module name'
},
{
2021-06-02 08:31:26 +00:00
arg: 'direction',
2021-06-01 20:18:13 +00:00
type: 'string',
required: true,
2021-06-02 08:31:26 +00:00
description: 'Whether to move left or right the module position'
2021-06-01 20:18:13 +00:00
}
],
http: {
path: `/setPosition`,
verb: 'post'
}
});
2021-06-02 08:31:26 +00:00
Self.setPosition = async(ctx, moduleName, direction, options) => {
2021-06-01 20:18:13 +00:00
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
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
},
order: 'position DESC'
};
const [movingModule] = await models.StarredModule.find(filter, myOptions);
let operator;
let order;
2021-06-02 08:31:26 +00:00
switch (direction) {
case 'left':
2021-06-01 20:18:13 +00:00
operator = {lt: movingModule.position};
order = 'position DESC';
break;
2021-06-02 08:31:26 +00:00
case 'right':
2021-06-01 20:18:13 +00:00
operator = {gt: movingModule.position};
order = 'position ASC';
break;
default:
return;
}
const pushedModule = await models.StarredModule.findOne({
where: {
position: operator,
workerFk: userId
},
order: order
}, myOptions);
if (!pushedModule) return;
const movingPosition = pushedModule.position;
const pushingPosition = movingModule.position;
await movingModule.updateAttribute('position', movingPosition, myOptions);
await pushedModule.updateAttribute('position', pushingPosition, myOptions);
if (tx) await tx.commit();
return {
movingModule: movingModule,
pushedModule: pushedModule
};
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};