ok changing everything again, decided to simplify the Friendship.entity, so i made a class that returns the stuff we need from a Friendship

This commit is contained in:
Me
2022-12-25 05:53:29 +01:00
parent 2b5f8a9667
commit b7b9b3d645
10 changed files with 251 additions and 137 deletions

View File

@@ -5,9 +5,9 @@ export class CreateFriendshipDto {
@IsPositive() @IsPositive()
// @Max(1000) ? // @Max(1000) ?
readonly receiverId: number; readonly receiverId: number;
@IsNotEmpty() // @IsNotEmpty()
@IsString() // @IsString()
readonly receiverUsername: string; // readonly receiverUsername: string;
@IsEnum(FriendshipStatus) @IsEnum(FriendshipStatus)
readonly status: FriendshipStatus; readonly status: FriendshipStatus;
} }

View File

@@ -27,15 +27,15 @@ export class Friendship {
// ok so the username is still here because i think it might be useful for the frontend to have access to it, but really all i need is the ID's // ok so the username is still here because i think it might be useful for the frontend to have access to it, but really all i need is the ID's
// since i have the ID's do i even need the User ? // since i have the ID's do i even need the User ?
@Column() // @Column()
senderUsername : string; // senderUsername : string;
@Column() // @Column()
senderId : number; // senderId : number;
@Column() // @Column()
receiverUsername : string; // receiverUsername : string;
@Column() // @Column()
receiverId : number; // receiverId : number;
@Column({ type: 'enum', enum: FriendshipStatus, default: FriendshipStatus.REQUESTED}) @Column({ type: 'enum', enum: FriendshipStatus, default: FriendshipStatus.REQUESTED})
status: FriendshipStatus; status: FriendshipStatus;

View File

@@ -21,8 +21,8 @@ export class FriendshipController {
// @Query('username') username: string, // @Query('username') username: string,
// new and improved finder of people // new and improved finder of people
// GET http://transcendance:8080/api/v2/network/:friendUsername // GET http://transcendance:8080/api/v2/network/myfriends
@Get('findfriends') @Get('myfriends')
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
findOne(@Query('username') otherUsername: string, @Query('id') id: number, @Req() req) { findOne(@Query('username') otherUsername: string, @Query('id') id: number, @Req() req) {
@@ -52,8 +52,8 @@ export class FriendshipController {
// POST http://transcendance:8080/api/v2/network/myfriends // POST http://transcendance:8080/api/v2/network/relations
@Post('myfriends') @Post('relations')
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@@ -64,8 +64,8 @@ export class FriendshipController {
return new HttpException('You can\'t request a frienship to yourself', HttpStatus.BAD_REQUEST); return new HttpException('You can\'t request a frienship to yourself', HttpStatus.BAD_REQUEST);
} }
// PATCH http://transcendance:8080/api/v2/network/myfriends/relationshipId/accept // PATCH http://transcendance:8080/api/v2/network/relations/:relationshipId/accept
@Patch('myfriends/:relationshipId/accept') @Patch('relations/:relationshipId/accept')
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
updateAccept(@Param('relationshipId') relationshipId: number, @Req() req) { updateAccept(@Param('relationshipId') relationshipId: number, @Req() req) {
@@ -73,7 +73,8 @@ export class FriendshipController {
return this.friendshipService.acceptFriendship(relationshipId, user); return this.friendshipService.acceptFriendship(relationshipId, user);
} }
@Patch('myfriends/:relationshipId/decline') // PATCH http://transcendance:8080/api/v2/network/relations/:relationshipId/decline
@Patch('relations/:relationshipId/decline')
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
updateDecline(@Param('relationshipId') relationshipId: number, @Req() req) { updateDecline(@Param('relationshipId') relationshipId: number, @Req() req) {
@@ -81,7 +82,8 @@ export class FriendshipController {
return this.friendshipService.declineFriendship(relationshipId, user); return this.friendshipService.declineFriendship(relationshipId, user);
} }
@Patch('myfriends/:relationshipId/block') // PATCH http://transcendance:8080/api/v2/network/relations/:relationshipId/block
@Patch('relations/:relationshipId/block')
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
updateBlock(@Param('relationshipId') relationshipId: number, @Req() req) { updateBlock(@Param('relationshipId') relationshipId: number, @Req() req) {
@@ -89,8 +91,8 @@ export class FriendshipController {
return this.friendshipService.blockFriendship(relationshipId, user); return this.friendshipService.blockFriendship(relationshipId, user);
} }
// DELETE http://transcendance:8080/api/v2/network/myfriends/relationshipId // DELETE http://transcendance:8080/api/v2/network/relations/:relationshipId
@Delete('myfriends/:relationshipId') @Delete('relations/:relationshipId')
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
remove(@Param('relationshipId') relationshipId: number, @Req() req) { remove(@Param('relationshipId') relationshipId: number, @Req() req) {

View File

@@ -4,6 +4,7 @@ import { User } from 'src/users/entities/user.entity';
import { Repository, Brackets } from 'typeorm'; import { Repository, Brackets } from 'typeorm';
import { CreateFriendshipDto } from './dto/create-friendship.dto'; import { CreateFriendshipDto } from './dto/create-friendship.dto';
import { Friendship, FriendshipStatus } from './entities/friendship.entity'; import { Friendship, FriendshipStatus } from './entities/friendship.entity';
import { SendableFriendship } from './sendableFriendship';
@Injectable() @Injectable()
export class FriendshipService { export class FriendshipService {
@@ -16,21 +17,36 @@ export class FriendshipService {
) { } ) { }
// createSendableFriendship(friendship: Friendship): SendableFriendship {
// let ret = new SendableFriendship;
// ret.id = friendship.id;
// ret.date = friendship.date
// ret.senderUsername = friendship.sender.username;
// ret.senderId = friendship.sender.id;
// ret.receiverUsername = friendship.receiver.username;
// ret.receiverId = friendship.receiver.id;
// ret.status = friendship.status;
// return ret;
// };
async findOneRelationshipById(friendId : number, userId : number) { async findOneRelationshipById(friendId : number, userId : number) {
const friendship = await this.friendshipRepository const friendship = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
.leftJoinAndSelect('friendship.receiver', 'receiver')
.where( .where(
new Brackets((qb) => { new Brackets((qb) => {
qb.where( qb.where(
new Brackets((subAQb) => { new Brackets((subAQb) => {
subAQb.where('friendship.senderId = :userId', { userId : userId}) subAQb.where('sender.id = :userId', { userId : userId})
.andWhere('friendship.receiverId = :friendId', {friendId : friendId}) .andWhere('receiver.id = :friendId', {friendId : friendId})
}) })
) )
.orWhere( .orWhere(
new Brackets((subBQb) => { new Brackets((subBQb) => {
subBQb.where('friendship.senderId = :friendId', {friendId : friendId}) subBQb.where('sender.id = :friendId', {friendId : friendId})
.andWhere('friendship.receiverId = :userId', {userId : userId}) .andWhere('receiver.id = :userId', {userId : userId})
}) })
) )
}), }),
@@ -44,7 +60,9 @@ export class FriendshipService {
if (!friendship) { if (!friendship) {
throw new HttpException(`There is no such friendship`, HttpStatus.NOT_FOUND); throw new HttpException(`There is no such friendship`, HttpStatus.NOT_FOUND);
} }
return friendship; // return friendship;
// return this.createSendableFriendship(friendship);
return new SendableFriendship(friendship);
} }
// basically useless now // basically useless now
@@ -79,46 +97,63 @@ export class FriendshipService {
if (!friendship) { if (!friendship) {
throw new HttpException(`There is no such friendship`, HttpStatus.NOT_FOUND); throw new HttpException(`There is no such friendship`, HttpStatus.NOT_FOUND);
} }
return friendship; // return friendship;
return new SendableFriendship(friendship);
} }
// lets see what happens here, doing directly receiver.id not LeftJoinAndSelect ...
async findAllFriends(userId: number) { async findAllFriends(userId: number) {
const friendship = await this.friendshipRepository const friendship = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
.leftJoinAndSelect('friendship.receiver', 'receiver')
.where('friendship.status = :status', { status: FriendshipStatus.ACCEPTED }) .where('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.andWhere('friendship.receiverId = :addressee', { addressee: userId }) .andWhere('receiver.id = :addressee', { addressee: userId })
.orWhere('friendship.senderId = :requester', { requester: userId }) .orWhere('sender.id = :requester', { requester: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.ACCEPTED }) .andWhere('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.getMany(); .getMany();
// for (const friend of friendship) // for (const friend of friendship)
// console.log("FRIENDSHIP : " + friend.status); // console.log("FRIENDSHIP : " + friend.status);
return friendship; // return friendship;
return new SendableFriendship(friendship);
} }
async findOneBlocked(friendshipId: number, userId: number) { async findOneBlocked(friendshipId: number, userId: number) {
const friendship = await this.friendshipRepository.findOneBy({ id: friendshipId, senderId: userId, status: FriendshipStatus.BLOCKED }); // const friendship = await this.friendshipRepository.findOneBy({ id: friendshipId, sender.id: userId, status: FriendshipStatus.BLOCKED });
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
.where('friendship.id = :id', { id: friendshipId })
.andWhere('sender.id = :requester', { requester: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED })
.getOne();
if (!friendship) if (!friendship)
throw new HttpException(`The requested blocked not found.`, HttpStatus.NOT_FOUND); throw new HttpException(`The requested blocked not found.`, HttpStatus.NOT_FOUND);
return friendship; // return friendship;
return new SendableFriendship(friendship);
} }
async findOneBlockedByUsername(blockedUsername : string, userId : number) { async findOneBlockedByUsername(blockedUsername : string, userId : number) {
const friendship = await this.friendshipRepository const friendship = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.where('friendship.senderId = :senderId', {senderId : userId}) .leftJoinAndSelect('friendship.sender', 'sender')
.andWhere('friendship.receiverUsername = :friendUsername', {friendUsername : blockedUsername}) .leftJoinAndSelect('friendship.receiver', 'receiver')
.where('sender.id = :senderId', {senderId : userId})
.andWhere('receiver.username = :friendUsername', {friendUsername : blockedUsername})
.andWhere('friendship.status = :status ', {status : FriendshipStatus.BLOCKED}) .andWhere('friendship.status = :status ', {status : FriendshipStatus.BLOCKED})
.getOne() .getOne()
if (!friendship) { if (!friendship) {
throw new HttpException(`The requested blocked not found.`, HttpStatus.NOT_FOUND); throw new HttpException(`The requested blocked not found.`, HttpStatus.NOT_FOUND);
} }
return friendship; // return friendship;
return new SendableFriendship(friendship);
} }
async findAllBlockedFriends(userId: number) { async findAllBlockedFriends(userId: number) {
const friendships : Friendship[] = await this.friendshipRepository const friendships : Friendship[] = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.where('friendship.senderId = :requestee', { requestee: userId }) .leftJoinAndSelect('friendship.sender', 'sender')
.where('sender.id = :requestee', { requestee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED }) .andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED })
.getMany(); .getMany();
// let partialFriendship : Partial<Friendship>[] = []; // let partialFriendship : Partial<Friendship>[] = [];
@@ -130,13 +165,20 @@ export class FriendshipService {
console.log('friendship.service findAllBlockedFriends, partial friendship:') console.log('friendship.service findAllBlockedFriends, partial friendship:')
// console.log({...partialFriendship}) // console.log({...partialFriendship})
// return partialFriendship; // return partialFriendship;
return friendships; // return friendships;
let sendFrienships: SendableFriendship[] = []
for (const friendship of friendships) {
sendFrienships.push(new SendableFriendship(friendship));
}
// return new SendableFriendship(friendship);
return sendFrienships;
} }
async findAllPendantRequestsForFriendship(userId: number) { async findAllPendantRequestsForFriendship(userId: number) {
const friendships = await this.friendshipRepository const friendships = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.where('friendship.senderId = :requestee', { requestee: userId }) .leftJoinAndSelect('friendship.sender', 'sender')
.where('sender.id = :requestee', { requestee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED }) .andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany(); .getMany();
// let partialFriendship : Partial<Friendship>[] = []; // let partialFriendship : Partial<Friendship>[] = [];
@@ -148,13 +190,19 @@ export class FriendshipService {
// return partialFriendship; // return partialFriendship;
console.log('friendships services pendant friendships:') console.log('friendships services pendant friendships:')
console.log({...friendships}) console.log({...friendships})
return friendships; // return friendships;
let sendFrienships: SendableFriendship[] = []
for (const friendship of friendships) {
sendFrienships.push(new SendableFriendship(friendship));
}
return sendFrienships;
} }
async findAllReceivedRequestsForFriendship(userId: number) { async findAllReceivedRequestsForFriendship(userId: number) {
const friendships = await this.friendshipRepository const friendships = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.where('friendship.receiverId = :addressee', { addressee: userId }) .leftJoinAndSelect('friendship.receiver', 'receiver')
.where('receiver.id = :addressee', { addressee: userId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED }) .andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany(); .getMany();
// let partialFriendship : Partial<Friendship>[] = []; // let partialFriendship : Partial<Friendship>[] = [];
@@ -164,10 +212,17 @@ export class FriendshipService {
// return partialFriendship; // return partialFriendship;
console.log('friendship service received requests') console.log('friendship service received requests')
console.log({...friendships}) console.log({...friendships})
return friendships; // return friendships;
let sendFrienships: SendableFriendship[] = []
for (const friendship of friendships) {
sendFrienships.push(new SendableFriendship(friendship));
}
return sendFrienships;
} }
async create(createFriendshipDto: CreateFriendshipDto, creator : User) : Promise <Partial<Friendship>> { // this is no longer the right return
// async create(createFriendshipDto: CreateFriendshipDto, creator : User) : Promise <Partial<Friendship>> {
async create(createFriendshipDto: CreateFriendshipDto, creator : User) {
console.log("DTO : \n") console.log("DTO : \n")
console.log({...createFriendshipDto}) console.log({...createFriendshipDto})
const receiver = await this.userRepository.findOneBy({id: createFriendshipDto.receiverId}); const receiver = await this.userRepository.findOneBy({id: createFriendshipDto.receiverId});
@@ -193,25 +248,28 @@ export class FriendshipService {
} }
const newFriendship = new Friendship(); const newFriendship = new Friendship();
newFriendship.sender = creator; newFriendship.sender = creator;
newFriendship.senderUsername = creator.username; // newFriendship.senderUsername = creator.username;
newFriendship.senderId = creator.id; // newFriendship.senderId = creator.id;
newFriendship.receiver = receiver; newFriendship.receiver = receiver;
newFriendship.receiverUsername = receiver.username; // newFriendship.receiverUsername = receiver.username;
newFriendship.receiverId = receiver.id; // newFriendship.receiverId = receiver.id;
newFriendship.status = createFriendshipDto.status; newFriendship.status = createFriendshipDto.status;
const savedFriendship = this.friendshipRepository.save(newFriendship); const savedFriendship = await this.friendshipRepository.save(newFriendship);
const partialFriendship : Partial<Friendship> = { // const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id, // id : (await savedFriendship).id,
date : (await savedFriendship).date, // date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername, // receiverUsername: (await savedFriendship).receiverUsername,
receiverId: (await savedFriendship).receiverId, // receiverId: (await savedFriendship).receiverId,
status : (await savedFriendship).status // status : (await savedFriendship).status
} // }
console.log('friendship.service create friendship, partial friendship') // console.log('friendship.service create friendship, partial friendship')
console.log({...partialFriendship}) // console.log({...partialFriendship})
console.log('friendship.service create friendship, NEW friendship') console.log('friendship.service create friendship, NEW friendship')
console.log({...newFriendship}) console.log({...newFriendship})
return partialFriendship; console.log('friendship.service create friendship, SAVED friendship')
console.log({...savedFriendship})
// return partialFriendship;
return new SendableFriendship(savedFriendship);
} }
async acceptFriendship(relationshipId: number, user: User) { async acceptFriendship(relationshipId: number, user: User) {
@@ -224,18 +282,19 @@ export class FriendshipService {
throw new HttpException(`You can't accept your own request.`, HttpStatus.NOT_FOUND); throw new HttpException(`You can't accept your own request.`, HttpStatus.NOT_FOUND);
} }
relation.status = FriendshipStatus.ACCEPTED; relation.status = FriendshipStatus.ACCEPTED;
const savedFriendship = this.friendshipRepository.save(relation); const savedFriendship = await this.friendshipRepository.save(relation);
const partialFriendship : Partial<Friendship> = { // const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id, // id : (await savedFriendship).id,
date : (await savedFriendship).date, // date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername, // receiverUsername: (await savedFriendship).receiverUsername,
receiverId: (await savedFriendship).receiverId, // receiverId: (await savedFriendship).receiverId,
status : (await savedFriendship).status // status : (await savedFriendship).status
} // }
console.log('.service accept friendship END') // console.log('.service accept friendship END')
console.log({...partialFriendship}) // console.log({...partialFriendship})
return partialFriendship; // return partialFriendship;
return new SendableFriendship(savedFriendship);
} }
async declineFriendship(relationshipId: number, user: User) { async declineFriendship(relationshipId: number, user: User) {
@@ -246,16 +305,17 @@ export class FriendshipService {
throw new HttpException(`You can't decline your own request.`, HttpStatus.NOT_FOUND); throw new HttpException(`You can't decline your own request.`, HttpStatus.NOT_FOUND);
} }
relation.status = FriendshipStatus.DECLINED; relation.status = FriendshipStatus.DECLINED;
const savedFriendship = this.friendshipRepository.save(relation); const savedFriendship = await this.friendshipRepository.save(relation);
const partialFriendship : Partial<Friendship> = { // const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id, // id : (await savedFriendship).id,
date : (await savedFriendship).date, // date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername, // receiverUsername: (await savedFriendship).receiverUsername,
status : (await savedFriendship).status // status : (await savedFriendship).status
} // }
console.log('decline friend request') // console.log('decline friend request')
console.log({...partialFriendship}) // console.log({...partialFriendship})
return partialFriendship // return partialFriendship
return new SendableFriendship(savedFriendship);
} }
async blockFriendship(relationshipId: number, user: User) { async blockFriendship(relationshipId: number, user: User) {
@@ -283,15 +343,16 @@ export class FriendshipService {
return await this.create(newFriendshipDto, user); return await this.create(newFriendshipDto, user);
} else { } else {
relation.status = FriendshipStatus.BLOCKED; relation.status = FriendshipStatus.BLOCKED;
const savedFriendship = this.friendshipRepository.save(relation); const savedFriendship = await this.friendshipRepository.save(relation);
const partialFriendship : Partial<Friendship> = { // const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id, // id : (await savedFriendship).id,
date : (await savedFriendship).date, // date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername, // receiverUsername: (await savedFriendship).receiverUsername,
receiverId: (await savedFriendship).receiverId, // receiverId: (await savedFriendship).receiverId,
status : (await savedFriendship).status // status : (await savedFriendship).status
} // }
return partialFriendship // return partialFriendship
return new SendableFriendship(savedFriendship);
} }
} }
@@ -323,18 +384,20 @@ export class FriendshipService {
const friendship = await this.friendshipRepository const friendship = await this.friendshipRepository
.createQueryBuilder('friendship') .createQueryBuilder('friendship')
.leftJoinAndSelect('friendship.sender', 'sender')
.leftJoinAndSelect('friendship.receiver', 'receiver')
.where( .where(
new Brackets((qb) => { new Brackets((qb) => {
qb.where( qb.where(
new Brackets((subAQb) => { new Brackets((subAQb) => {
subAQb.where('friendship.senderId = :senderId', { senderId: userConnectedId}) subAQb.where('sender.id = :senderId', { senderId: userConnectedId})
.andWhere('friendship.receiverId = :receiverId', { receiverId: userToFindId}) .andWhere('receiver.id = :receiverId', { receiverId: userToFindId})
}) })
) )
.orWhere( .orWhere(
new Brackets((subBQb) => { new Brackets((subBQb) => {
subBQb.where('friendship.senderId = :senderId', {senderId : userToFindId}) subBQb.where('sender.id = :senderId', {senderId : userToFindId})
.andWhere('friendship.receiverId = :receiverId', {receiverUsername : userConnectedId}) .andWhere('receiver.id = :receiverId', {receiverUsername : userConnectedId})
}) })
) )
}), }),

View File

@@ -0,0 +1,28 @@
import { Friendship, FriendshipStatus } from "./entities/friendship.entity";
// Ok i don't really know what i'm doing but i want a thing that is typeset that i can use to send info back to the Front when they create a friendship or ask for a friendship
// Ok it doesn't seem like i really need an interface, that just enfoces the types
// export interface SendableFriendship {
export class SendableFriendship {
id: number;
date: Date;
senderUsername: string;
senderId: number;
receiverUsername: string;
receiverId: number;
status: FriendshipStatus;
// if my constructor is here won't it get sent all over the place too?
constructor(friendship: Friendship) {
this.id = friendship.id;
this.date = friendship.date
this.senderUsername = friendship.sender.username;
this.senderId = friendship.sender.id;
this.receiverUsername = friendship.receiver.username;
this.receiverId = friendship.receiver.id;
this.status = friendship.status;
};
}

View File

@@ -19,6 +19,7 @@ export class UsersController {
constructor(private readonly usersService: UsersService) {} constructor(private readonly usersService: UsersService) {}
// par exemple dans postamn ou insomnia http://localhost:3000/users?limit=10&offset=20 // par exemple dans postamn ou insomnia http://localhost:3000/users?limit=10&offset=20
// GET http://transcendance:8080/user/all
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Get('all') @Get('all')
@@ -61,8 +62,16 @@ export class UsersController {
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Get() @Get()
findMe(@Req() req) { findOne(@Query('id') toFindId: number, @Req() req) {
return this.usersService.findOne(req.user.id); console.log('users service findOne toFindId:')
console.log(toFindId)
console.log('users service findOne my Id:')
console.log(req.user.id)
if (toFindId === undefined)
return this.usersService.findOne(req.user.id);
else
return this.usersService.findOne(toFindId);
// i would rather just use numbers but i'm guessing Cherif uses this all over
} }
// also seems useless... // also seems useless...
@@ -75,6 +84,7 @@ export class UsersController {
// } // }
// PATCH http://transcendance:8080/user
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Patch() @Patch()
@@ -93,6 +103,7 @@ export class UsersController {
response.status(200).send("OK") response.status(200).send("OK")
} }
// DELETE http://transcendance:8080/user
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Delete() @Delete()
@@ -100,6 +111,7 @@ export class UsersController {
return this.usersService.remove(req.user.id); return this.usersService.remove(req.user.id);
} }
// POST http://transcendance:8080/user/avatar
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Post('avatar') @Post('avatar')
@@ -109,6 +121,7 @@ export class UsersController {
this.usersService.updateAvatar(user.id, file.filename); this.usersService.updateAvatar(user.id, file.filename);
} }
// GET http://transcendance:8080/user/avatar
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard) @UseGuards(TwoFactorGuard)
@Get('avatar') @Get('avatar')

View File

@@ -32,11 +32,11 @@ export class UsersService {
return user; return user;
} }
async findOne(id: string) { async findOne(id: number) {
console.log(`FIND ONE USER SERVICE Find user ${id}`); console.log(`FIND ONE USER SERVICE Find user ${id}`);
const user = await this.userRepository.createQueryBuilder('user') const user = await this.userRepository.createQueryBuilder('user')
.leftJoinAndSelect('user.stats', 'stats') .leftJoinAndSelect('user.stats', 'stats')
.where('user.id = :id', { id: +id }) .where('user.id = :id', { id: id })
.getOne(); .getOne();
if (!user) if (!user)
throw new NotFoundException(`The requested user not found.`); throw new NotFoundException(`The requested user not found.`);
@@ -53,6 +53,7 @@ export class UsersService {
return partialUser; return partialUser;
} }
// Ok this gets called in the Authenitcation Service, but like i was still able to make a username === someone else's
async isUsernameExists(usernameToSearch: string): Promise<boolean> { async isUsernameExists(usernameToSearch: string): Promise<boolean> {
const user = await this.userRepository.findOneBy({username : usernameToSearch}); const user = await this.userRepository.findOneBy({username : usernameToSearch});
if (!user) if (!user)

View File

@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import GenerateUserDisplay from '../../pieces/GenerateUserDisplay.svelte'; import GenerateUserDisplay from '../../pieces/GenerateUserDisplay.svelte';
let user; let user;
@@ -20,7 +20,7 @@
<div class="outer"> <div class="outer">
<!-- OHHHH i could use #await instead of if and have an nice loading page! --> <!-- OHHHH i could use #await instead of if and have an nice loading page! -->
{#if user !== undefined} {#if user !== undefined}
<GenerateUserDisplay {user} primary={true}/> <GenerateUserDisplay user={user} primary={true}/>
{:else} {:else}
<!-- might be unnecessary since you can't access the page without fetching the user --> <!-- might be unnecessary since you can't access the page without fetching the user -->
<h2>Sorry</h2> <h2>Sorry</h2>

View File

@@ -14,7 +14,7 @@
let myFriends; let myFriends;
let requestsMade, requestsRecieved; let requestsMade, requestsRecieved;
let blockedUsers; let blockedUsers;
let usernameBeingViewed; let userIdBeingViewed;
let friendshipStatusFull; // id, date, senderUsername, reveiverUsername, status let friendshipStatusFull; // id, date, senderUsername, reveiverUsername, status
/**** Layout variables ****/ /**** Layout variables ****/
@@ -60,7 +60,7 @@
}; };
const fetchMyFriends = async() => { const fetchMyFriends = async() => {
myFriends = await fetch('http://transcendance:8080/api/v2/network/myfriends') myFriends = await fetch('http://transcendance:8080/api/v2/network/relations')
.then( x => x.json() ); .then( x => x.json() );
console.log('got my friends ') console.log('got my friends ')
console.log({...myFriends}) console.log({...myFriends})
@@ -90,35 +90,36 @@
/**** END OF MAIN FETCH ****/ /**** END OF MAIN FETCH ****/
// returns everything but BLOCKED // returns everything but BLOCKED
const fetchFriendshipFull = async(aUsername) => { const fetchFriendshipFull = async(aUserId) => {
console.log('fetch friendship from a username') console.log('fetch friendship from a username')
console.log(aUsername) console.log(aUserId)
friendshipStatusFull = await fetch(`http://transcendance:8080/api/v2/network/myfriends/${aUsername}`) friendshipStatusFull = await fetch(`http://transcendance:8080/api/v2/network/relations/${aUserId}`)
.then( x => x.json()); .then( x => x.json());
console.log({...friendshipStatusFull}) console.log({...friendshipStatusFull})
}; };
const sendFriendRequest = async(aUsername) => { const sendFriendRequest = async(aUser) => {
const resp = await fetch("http://transcendance:8080/api/v2/network/myfriends", { const resp = await fetch("http://transcendance:8080/api/v2/network/relations", {
method : "POST", method : "POST",
headers: { 'Content-Type': 'application/json'}, headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ body: JSON.stringify({
"receiverUsername": aUsername, "receiverUsername": aUser.username,
"receiverId": aUser.id,
"status": "R" "status": "R"
}) })
}) })
.then( x => x.json()) .then( x => x.json())
fetchFriendshipFull(aUsername); fetchFriendshipFull(aUser.id);
}; };
const viewAUser = async(aUsername) => { const viewAUser = async(aUserId) => {
console.log('Profile Friend updating userBeingViewed') console.log('Profile Friend updating userBeingViewed')
usernameBeingViewed = aUsername; userIdBeingViewed = aUserId;
// friendshipStatusFull = undefined; // friendshipStatusFull = undefined;
// id, date, senderUsername, reveiverUsername, status // id, date, senderUsername, reveiverUsername, status
await fetchFriendshipFull(aUsername); await fetchFriendshipFull(aUserId);
console.log('Friendship Status Full') console.log('Friendship Status Full')
console.log({...friendshipStatusFull}) console.log({...friendshipStatusFull})
@@ -128,13 +129,13 @@
const acceptFriendRequest = async(relationshipId) => { const acceptFriendRequest = async(relationshipId) => {
console.log('accept friend request') console.log('accept friend request')
// PATCH http://transcendance:8080/api/v2/network/myfriends/:relationshipId/accept // PATCH http://transcendance:8080/api/v2/network/myfriends/:relationshipId/accept
const resp = await fetch(`http://transcendance:8080/api/v2/network/myfriends/${relationshipId}/accept`, { const resp = await fetch(`http://transcendance:8080/api/v2/network/relations/${relationshipId}/accept`, {
method: "PATCH"}) method: "PATCH"})
.then( x => x.json()); .then( x => x.json());
// maybe not the most robust things, not super reusable cuz it depends on outside vars but works for now... // maybe not the most robust things, not super reusable cuz it depends on outside vars but works for now...
console.log('accepted friend request, now response') console.log('accepted friend request, now response')
console.log({...resp}) console.log({...resp})
await fetchFriendshipFull(usernameBeingViewed); await fetchFriendshipFull(userIdBeingViewed);
// will this make it reload? C'est un peu bourain... do i even need it? // will this make it reload? C'est un peu bourain... do i even need it?
activeTabItem = activeTabItem; activeTabItem = activeTabItem;
@@ -143,24 +144,24 @@
const declineFriendRequest = async(relationshipId) => { const declineFriendRequest = async(relationshipId) => {
console.log('decline friend request') console.log('decline friend request')
// PATCH http://transcendance:8080/api/v2/network/myfriends/:relationshipId/decline // PATCH http://transcendance:8080/api/v2/network/myfriends/:relationshipId/decline
const resp = await fetch(`http://transcendance:8080/api/v2/network/myfriends/${relationshipId}/decline`, { const resp = await fetch(`http://transcendance:8080/api/v2/network/relations/${relationshipId}/decline`, {
method: "PATCH"}) method: "PATCH"})
.then( x => x.json()); .then( x => x.json());
// maybe not the most robust things, not super reusable cuz it depends on outside vars but works for now... // maybe not the most robust things, not super reusable cuz it depends on outside vars but works for now...
console.log('declined friend request, now response') console.log('declined friend request, now response')
console.log({...resp}) console.log({...resp})
await fetchFriendshipFull(usernameBeingViewed); await fetchFriendshipFull(userIdBeingViewed);
}; };
const unfriend = async(relationshipId) => { const unfriend = async(relationshipId) => {
console.log('Unfriend') console.log('Unfriend')
const resp = await fetch(`http://transcendance:8080/api/v2/network/myfriends/${relationshipId}`, { const resp = await fetch(`http://transcendance:8080/api/v2/network/relations/${relationshipId}`, {
method: "DELETE"}) method: "DELETE"})
.then( x => x.json()); .then( x => x.json());
// friendshipStatusFull = undefined; // friendshipStatusFull = undefined;
// OR // OR
await fetchFriendshipFull(usernameBeingViewed); await fetchFriendshipFull(userIdBeingViewed);
if (Object.keys(friendshipStatusFull).length === 0) if (Object.keys(friendshipStatusFull).length === 0)
friendshipStatusFull = undefined; friendshipStatusFull = undefined;
@@ -168,22 +169,23 @@
activeTabItem = activeTabItem; activeTabItem = activeTabItem;
}; };
const blockANonFriendUser = async(aUsername) => { const blockANonFriendUser = async(aUser) => {
console.log('Block a non friend user, their username') console.log('Block a non friend user, their username')
console.log(aUsername) console.log({...aUser})
const blockResp = await fetch("http://transcendance:8080/api/v2/network/myfriends", { const blockResp = await fetch("http://transcendance:8080/api/v2/network/relations", {
method : "POST", method : "POST",
headers: { 'Content-Type': 'application/json'}, headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ body: JSON.stringify({
"receiverUsername": aUsername, "receiverUsername": aUser.username,
"receiverId": aUser.id,
"status": "B" "status": "B"
}) })
}) })
.then( x => x.json()) .then( x => x.json())
await fetchBlockedUsers(); await fetchBlockedUsers();
await fetchAllUsers(); await fetchAllUsers();
usernameBeingViewed = undefined; userIdBeingViewed = undefined;
friendshipStatusFull = undefined; friendshipStatusFull = undefined;
// will this make it reload? // will this make it reload?
@@ -193,13 +195,13 @@
const blockAFriend = async(relationshipId) => { const blockAFriend = async(relationshipId) => {
console.log('blocking a friend, the relationshipID') console.log('blocking a friend, the relationshipID')
console.log(relationshipId) console.log(relationshipId)
const resp = await fetch(`http://transcendance:8080/api/v2/network/myfriends/${relationshipId}/block`, {method: "PATCH"}) const resp = await fetch(`http://transcendance:8080/api/v2/network/relations/${relationshipId}/block`, {method: "PATCH"})
.then( x => x.json() ); .then( x => x.json() );
console.log('blocked a user response') console.log('blocked a user response')
console.log({...resp}) console.log({...resp})
await fetchBlockedUsers(); await fetchBlockedUsers();
await fetchAllUsers(); await fetchAllUsers();
usernameBeingViewed = undefined; userIdBeingViewed = undefined;
friendshipStatusFull = undefined; friendshipStatusFull = undefined;
// will this make it reload? // will this make it reload?
@@ -250,9 +252,9 @@
{/if} {/if}
<!-- does this work? --> <!-- does this work? -->
<!-- {#each allUsers as aUser (aUser.username)} --> <!-- {#each allUsers as aUser (aUser.username)} -->
<!-- {#each allUsers as aUser (aUser.id)} --> <!-- {#each allUsers as aUser} -->
{#each allUsers as aUser} {#each allUsers as aUser (aUser.id)}
<div class="sidebar-item" on:click={() => viewAUser(aUser.username)}>{aUser.username}</div> <div class="sidebar-item" on:click={() => viewAUser(aUser.id)}>{aUser.username}</div>
<!-- i could make an indicator component? like green for connected or something? <!-- i could make an indicator component? like green for connected or something?
i could use words but color them? i could use words but color them?
i could make it so if they're in a game --> i could make it so if they're in a game -->
@@ -266,7 +268,7 @@
{/if} {/if}
<!-- {#each myFriends as aUser (aUser.id)} --> <!-- {#each myFriends as aUser (aUser.id)} -->
{#each myFriends as aUser} {#each myFriends as aUser}
<div class="sidebar-item" on:click={() => viewAUser(aUser.username)}>{aUser.username}</div> <div class="sidebar-item" on:click={() => viewAUser(aUser.id)}>{aUser.username}</div>
<div class="status sidebar-item">{aUser.status}</div> <div class="status sidebar-item">{aUser.status}</div>
<br> <br>
{/each} {/each}
@@ -298,8 +300,9 @@
<div class="main-display"> <div class="main-display">
{#if usernameBeingViewed !== undefined} {#if userIdBeingViewed !== undefined}
<DisplayAUser aUsername={usernameBeingViewed}/> <!-- <DisplayAUser aUsername={usernameBeingViewed}/> -->
<DisplayAUser aUserId={userIdBeingViewed}/>
<div class="buttons-area"> <div class="buttons-area">
{#if friendshipStatusFull && friendshipStatusFull.id} {#if friendshipStatusFull && friendshipStatusFull.id}
@@ -330,8 +333,8 @@
{/if} {/if}
{/if} {/if}
{:else} {:else}
<Button type="secondary" on:click={() => sendFriendRequest(usernameBeingViewed)}>Add Friend</Button> <Button type="secondary" on:click={() => sendFriendRequest(userIdBeingViewed)}>Add Friend</Button>
<Button on:click={() => blockANonFriendUser(usernameBeingViewed)}>Block User</Button> <Button on:click={() => blockANonFriendUser(userIdBeingViewed)}>Block User</Button>
{/if} {/if}
</div> </div>
{:else} {:else}

View File

@@ -3,13 +3,15 @@
import { onMount, afterUpdate } from 'svelte'; import { onMount, afterUpdate } from 'svelte';
import GenerateUserDisplay from './GenerateUserDisplay.svelte'; import GenerateUserDisplay from './GenerateUserDisplay.svelte';
export let aUsername; // export let aUsername;
export let aUserId;
let user; let user;
onMount( async() => { onMount( async() => {
console.log('Display aUser username: '+ aUsername) // console.log('Display aUser username: '+ aUsername)
// http://transcendance:8080/api/v2/user?username=NomDuUserATrouver // http://transcendance:8080/api/v2/user?username=NomDuUserATrouver
user = await fetch(`http://transcendance:8080/api/v2/user?username=${aUsername}`) // user = await fetch(`http://transcendance:8080/api/v2/user?username=${aUsername}`)
user = await fetch(`http://transcendance:8080/api/v2/user?id=${aUserId}`)
.then( (x) => x.json() ); .then( (x) => x.json() );
// console.log('Display a user: ') // console.log('Display a user: ')
@@ -27,13 +29,15 @@
export const updateUser = async() => { export const updateUser = async() => {
console.log('Display Update aUser username: '+ aUsername) // console.log('Display Update aUser username: '+ aUsername)
// http://transcendance:8080/api/v2/user?username=NomDuUserATrouver // http://transcendance:8080/api/v2/user?username=NomDuUserATrouver
user = await fetch(`http://transcendance:8080/api/v2/user?username=${aUsername}`) // user = await fetch(`http://transcendance:8080/api/v2/user?username=${aUsername}`)
user = await fetch(`http://transcendance:8080/api/v2/user?id=${aUserId}`)
.then( (x) => x.json() ); .then( (x) => x.json() );
}; };
$: aUsername, updateUser(); // $: aUsername, updateUser();
$: aUserId, updateUser();
</script> </script>
@@ -45,7 +49,7 @@
<!-- <GenerateUserDisplay user={user} primary={true}/> --> <!-- <GenerateUserDisplay user={user} primary={true}/> -->
{:else} {:else}
<h2>Sorry</h2> <h2>Sorry</h2>
<div>Failed to load user {aUsername}</div> <div>Failed to load user {aUserId}</div>
{/if} {/if}