Skip to content

Commit

Permalink
change-vote
Browse files Browse the repository at this point in the history
  • Loading branch information
benawad committed Aug 15, 2020
1 parent 2812265 commit 49dbaec
Showing 1 changed file with 43 additions and 15 deletions.
58 changes: 43 additions & 15 deletions server/src/resolvers/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { MyContext } from "../types";
import { isAuth } from "../middleware/isAuth";
import { getConnection } from "typeorm";
import { Updoot } from "../entities/Updoot";
import { tmpdir } from "os";

@InputType()
class PostInput {
Expand Down Expand Up @@ -52,25 +53,52 @@ export class PostResolver {
const isUpdoot = value !== -1;
const realValue = isUpdoot ? 1 : -1;
const { userId } = req.session;
// await Updoot.insert({
// userId,
// postId,
// value: realValue,
// });
await getConnection().query(
`
START TRANSACTION;

const updoot = await Updoot.findOne({ where: { postId, userId } });

// the user has voted on the post before
// and they are changing their vote
if (updoot && updoot.value !== realValue) {
await getConnection().transaction(async (tm) => {
await tm.query(
`
update updoot
set value = $1
where "postId" = $2 and "userId" = $3
`,
[realValue, postId, userId]
);

await tm.query(
`
update post
set points = points + $1
where id = $2
`,
[2 * realValue, postId]
);
});
} else if (!updoot) {
// has never voted before
await getConnection().transaction(async (tm) => {
await tm.query(
`
insert into updoot ("userId", "postId", value)
values (${userId},${postId},${realValue});
values ($1, $2, $3)
`,
[userId, postId, realValue]
);

await tm.query(
`
update post
set points = points + ${realValue}
where id = ${postId};
COMMIT;
`
);
set points = points + $1
where id = $2
`,
[realValue, postId]
);
});
}
return true;
}

Expand Down

0 comments on commit 49dbaec

Please sign in to comment.