Skip to content
This repository has been archived by the owner on Mar 14, 2024. It is now read-only.

Commit

Permalink
Unbond endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
kriogenia committed Jan 29, 2022
1 parent 8126468 commit d0da75f
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 11 deletions.
2 changes: 1 addition & 1 deletion __tests__/routes/auth/Refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe("Calling GET " + endpoint, () => {
const response = await getRequest(endpoint + "refreshToken", "authToken")
.send()
.expect(StatusCodes.UNAUTHORIZED);
expect(response.body.message).toBe(ERR_MSG.session_invalid);
expect(response.body.message).toBe(ERR_MSG.token_invalid);
});

});
2 changes: 1 addition & 1 deletion __tests__/routes/auth/SignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe("Calling GET " + endpoint, () => {
await request(app)
.get(`${endpoint}`)
.send()
.expect(StatusCodes.NOT_FOUND);
.expect(StatusCodes.BAD_REQUEST);
});

});
48 changes: 48 additions & 0 deletions __tests__/routes/user/bonds/RemoveBond.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Role, UserModel } from "@/models/User";
import * as db from "@test-util/MongoMemory";
import { openSession, deleteRequest } from "@test-util/SessionSetUp";
import { StatusCodes } from "http-status-codes";
import { SessionDto, UserDto } from "@/models/dto";

beforeAll(db.connect);
afterEach(db.clear);
afterAll(db.close);

const endpoint = "/user/bonds/";

describe("Calling DELETE " + endpoint, () => {

let session: SessionDto;
let user: UserDto;

beforeEach((done) => {
openSession((response) => {
session = response.session;
user = response.user;
if (session && user) {
done();
}
});
});

it("should remove the bond if it's correct", async () => {
const keeper = await UserModel.findById(user._id);
keeper.role = Role.Keeper;
await keeper.save();
const patient = await UserModel.create({
googleId: "patient",
role: Role.Patient
});
await patient.bondWith(keeper);

await deleteRequest(endpoint + patient._id, session.auth)
.send()
.expect(StatusCodes.NO_CONTENT);

const storedPatient = await UserModel.findById(patient._id);
expect(storedPatient.bonds.length).toBe(0);
const storedKeeper = await UserModel.findById(user._id);
expect(storedKeeper.cared).toBeUndefined();
});

});
6 changes: 3 additions & 3 deletions __tests__/services/UserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,14 @@ describe("The unbond function", () => {
expect(storedPatient.bonds[0]).not.toEqual(keeper._id);

const storedKeeper = await UserModel.findById(keeper._id);
expect(storedKeeper.cared).toBeNull();
expect(storedKeeper.cared).toBeUndefined();
});

it("should remove the bond when a Keeper removes a Patient", async () => {
await UserService.unbond(keeper._id, patient._id);

const storedKeeper = await UserModel.findById(keeper._id);
expect(storedKeeper.cared).toBeNull();
expect(storedKeeper.cared).toBeUndefined();
const storedPatient = await UserModel.findById(patient._id);
expect(storedPatient.bonds.length).toBe(1);
expect(storedPatient.bonds[0]).not.toEqual(keeper._id);
Expand All @@ -139,7 +139,7 @@ describe("The unbond function", () => {
expect(storedPatient.bonds.length).toBe(1);
expect(storedPatient.bonds[0]).not.toEqual(keeper._id);
const storedKeeper = await UserModel.findById(keeper._id);
expect(storedKeeper.cared).toBeNull();
expect(storedKeeper.cared).toBeUndefined();
});

});
Expand Down
6 changes: 3 additions & 3 deletions src/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export class UserSchema {
if (this.bonds.length >= parseInt(process.env.MAX_BONDS)) {
throw badRequestError(ERR_MSG.maximum_bonds_reached);
}
if (keeper.cared !== undefined) {
if (keeper.cared !== undefined && keeper.cared !== null) {
throw badRequestError(ERR_MSG.keeper_already_bonded);
}
this.bonds.push(keeper);
Expand All @@ -117,9 +117,9 @@ export class UserSchema {
}
if (this.role === Role.Patient) {
this.bonds.remove(bond);
bond.cared = null;
bond.cared = undefined;
} else {
this.cared = null;
this.cared = undefined;
bond.bonds.remove(this);
}
await Promise.all([this.save(), bond.save()]);
Expand Down
6 changes: 4 additions & 2 deletions src/routes/auth/SignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ export const signIn = async (
// Verify the Google token
return GoogleAuth.verify(req.params.token)
.then(UserService.getByGoogleId) // And get the user to return
.then((user) => res.status(StatusCodes.OK).json({
.then((user) => {
return res.status(StatusCodes.OK).json({
session: TokenService.sessionPackage(user.id),
user: user.dto()
}).send())
}).send();
})
.catch(next);
}
2 changes: 1 addition & 1 deletion src/routes/user/bond/BondsList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const list = async (
? UserService.getBonds(id)
: UserService.getBondsOfCared(id);
return list.then((users) => {
const bonds = users.filter(u => u._id != id).map(u => u.public);
const bonds = users.filter(u => u._id != id).map(u => u.dto());
return res.status(StatusCodes.OK).send({bonds: bonds});
}).catch(next);
}
38 changes: 38 additions & 0 deletions src/routes/user/bond/RemoveBond.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { NextFunction, Request, Response } from "express";
import { StatusCodes } from "http-status-codes";
import * as UserService from "@/services/UserService";
import { UserDto } from "@/models/dto";
import { IdParam } from "@/shared/values";
import * as NotificationService from "@/services/NotificationService";
import { Action } from "@/models/Notification";
import { Role } from "@/models/User";
import { GLOBAL } from "@/sockets/global";
import { io } from "@server";

/**
* Removes the bond of the user with the specified user
* @param req request with the bond id
* @param res carried response
* @param next invokation of the next middleware to use in case of error
* @returns the response with the success or error confirmation message
*/
export const removeBond = async (
req: Request<IdParam>,
res: Response,
next: NextFunction): Promise<void|Response<UserDto>> =>
{
let patientId: string;
return UserService.getRole(req.sessionId)
.then((role) => {
patientId = role === Role.Patient ? req.sessionId : req.params.id;
return UserService.unbond(req.sessionId, req.params.id);
})
.then(() => {
res.status(StatusCodes.NO_CONTENT).send();
return NotificationService.create(Action.BOND_DELETED, patientId);
})
.then((notification) => {
io.to(`${GLOBAL}:${patientId}`).emit(notification.event, notification.dto())
})
.catch(next);
}
4 changes: 4 additions & 0 deletions src/routes/user/bond/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ import { Router } from "express";
import { list } from "./BondsList";
import { establish } from "./EstablishBond";
import { generate } from "./GenerateBond";
import { removeBond } from "./RemoveBond";

const bondRouter = Router();

/* GET /user/bonds */
bondRouter.get("", list);

/* DELETE /user/bonds/:id */
bondRouter.delete("/:id", removeBond);

/* POST /user/bonds/establish */
bondRouter.post("/establish", establish);

Expand Down

0 comments on commit d0da75f

Please sign in to comment.