Skip to content

Commit

Permalink
Merge pull request #290 from GolosChain/285_leaders_fix
Browse files Browse the repository at this point in the history
#285 Leader model fixes.
  • Loading branch information
Format-X22 authored Jun 13, 2019
2 parents f03bb64 + 42b617f commit 13c7ab5
Showing 1 changed file with 29 additions and 40 deletions.
69 changes: 29 additions & 40 deletions src/controllers/prism/Leader.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,39 @@ class Leader extends Abstract {
}

async register({ witness: userId, url }, { communityId }) {
const action = { $set: { communityId, userId, active: true } };
const action = { communityId, userId, active: true };

if (typeof url === 'string') {
action.url = url;
}

await this._updateLeaderWithUpsert(communityId, userId, action);
let previousModel = await LeaderModel.findOneAndUpdate(
{ communityId, userId },
{ $set: action }
);

if (previousModel) {
await this.registerForkChanges({
type: 'update',
Model: LeaderModel,
documentId: previousModel._id,
data: action,
});
} else {
previousModel = await LeaderModel.create({ communityId, userId, ...action });

await this.registerForkChanges({
type: 'create',
Model: LeaderModel,
documentId: previousModel._id,
});
}

await this._updateProfile(userId);
}

async unregister({ witness: userId }, { communityId }) {
const previousModel = await LeaderModel.findOneAndDelete({
userId,
communityId,
});
const previousModel = await LeaderModel.findOneAndDelete({ userId, communityId });

if (!previousModel) {
return;
Expand Down Expand Up @@ -114,29 +132,10 @@ class Leader extends Abstract {
});
}

async _updateLeaderWithUpsert(communityId, userId, action) {
let previousModel = await LeaderModel.findOneAndUpdate({ communityId, userId }, action);

if (!previousModel) {
previousModel = await LeaderModel.create({ communityId, userId, ...action });
}

await this.registerForkChanges({
type: 'update',
Model: LeaderModel,
documentId: previousModel._id,
data: action,
});
}

async _setActiveState(userId, communityId, active) {
const previousModel = await LeaderModel.findOneAndUpdate(
{ communityId, userId },
{
$set: {
active,
},
}
{ $set: { active } }
);

if (previousModel) {
Expand All @@ -159,22 +158,12 @@ class Leader extends Abstract {

async _updateProfile(userId) {
const communities = await LeaderModel.find(
{
userId,
active: true,
},
{
communityId: true,
},
{
lean: true,
}
{ userId, active: true },
{ communityId: true },
{ lean: true }
);

const previousModel = await ProfileModel.findOneAndUpdate(
{
userId,
},
{ userId },
{
$set: {
leaderIn: communities.map(community => community.communityId),
Expand Down

0 comments on commit 13c7ab5

Please sign in to comment.