Skip to content

Commit 50f351d

Browse files
committed
💥 refactor profile error messages
1 parent 97332cb commit 50f351d

File tree

3 files changed

+47
-45
lines changed

3 files changed

+47
-45
lines changed

src/constants/decode.ts

+25-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { PrismaService } from 'prisma/prisma.service';
2-
import { BadRequestException } from '@nestjs/common';
32
import * as jwt from 'jsonwebtoken';
43
import { SECRET_KEY } from './env';
4+
import { HttpException, HttpStatus } from '@nestjs/common';
55

66
/**
77
* It takes a token and a prisma service as arguments, decodes the token, finds the user in the
@@ -14,10 +14,29 @@ export const decode = async (token: string, prisma: PrismaService) => {
1414
const decoded = jwt.verify(token, SECRET_KEY) as jwt.JwtPayload;
1515
const userId = decoded?.user;
1616
if (!userId) throw new Error('Invalid authorization token');
17-
const user = await prisma.user.findUnique({
18-
where: { id: userId },
19-
});
20-
if (!user) throw new BadRequestException('Invalid authorization token');
21-
if (!user.isVerified) throw new BadRequestException('User not verified');
17+
const user = await prisma.user.findUnique({ where: { id: userId } });
18+
if (!user)
19+
throw new HttpException(
20+
'Invalid authorization token',
21+
HttpStatus.BAD_REQUEST,
22+
);
23+
if (!user.isVerified)
24+
throw new HttpException('User not verified', HttpStatus.BAD_REQUEST);
2225
return user;
2326
};
27+
28+
/**
29+
* It gets the token from the request header, and if it's not found, it throws an error.
30+
* @param {any} context - any - this is the context object that is passed to the resolver function.
31+
* @returns The token is being returned.
32+
*/
33+
export const getToken = (context: any) => {
34+
const authorization = context?.req?.headers?.authorization;
35+
const token = authorization?.split(' ')[1];
36+
if (token === undefined)
37+
throw new HttpException(
38+
'Invalid request, token not found',
39+
HttpStatus.BAD_REQUEST,
40+
);
41+
return token;
42+
};

src/profile/profile.resolver.ts

+10-34
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,15 @@ import {
1010
UserIdInput,
1111
} from 'src/graphql.types';
1212
import { ProfileService } from './profile.service';
13+
import { getToken } from 'src/constants/decode';
1314

1415
@Resolver()
1516
export class ProfileResolver {
1617
constructor(private readonly profileService: ProfileService) {}
1718

1819
@Mutation('authorizeGithub')
1920
async authorizeGithub(@Context() context) {
20-
const authorization = context.req.headers.authorization;
21-
const token = authorization?.split(' ')[1];
22-
if (token === undefined)
23-
throw new Error('Invalid request, token not found');
21+
const token = getToken(context);
2422
return this.profileService.authorizeGithub(token);
2523
}
2624

@@ -29,19 +27,13 @@ export class ProfileResolver {
2927
@Args('input') input: AddUsernameInput,
3028
@Context() context,
3129
) {
32-
const authorization = context.req.headers.authorization;
33-
const token = authorization?.split(' ')[1];
34-
if (token === undefined)
35-
throw new Error('Invalid request, token not found');
30+
const token = getToken(context);
3631
return this.profileService.addUsername(input, token);
3732
}
3833

3934
@Query('getUser')
4035
async getUser(@Context() context): Promise<RestrictedUserSelf> {
41-
const authorization = context.req.headers.authorization;
42-
const token = authorization?.split(' ')[1];
43-
if (token === undefined)
44-
throw new Error('Invalid request, token not found');
36+
const token = getToken(context);
4537
return await this.profileService.getUser(token);
4638
}
4739

@@ -50,9 +42,7 @@ export class ProfileResolver {
5042
@Args('input') input: UserIdInput,
5143
@Context() context,
5244
): Promise<RestrictedUserOther> {
53-
const token = context?.req?.headers?.authorization?.split(' ')[1];
54-
if (token === undefined)
55-
throw new Error('Invalid request, token not found');
45+
const token = getToken(context);
5646
return await this.profileService.getUserById(input.userId, token);
5747
}
5848

@@ -61,10 +51,7 @@ export class ProfileResolver {
6151
@Args('input') input: SearchInput,
6252
@Context() context,
6353
): Promise<RestrictedUserOther[]> {
64-
const authorization = context.req.headers.authorization;
65-
const token = authorization?.split(' ')[1];
66-
if (token === undefined)
67-
throw new Error('Invalid request, token not found');
54+
const token = getToken(context);
6855
return await this.profileService.search(
6956
input.query,
7057
input?.page || 1,
@@ -77,10 +64,7 @@ export class ProfileResolver {
7764
@Args('input') input: ToggleFollowInput,
7865
@Context() context,
7966
): Promise<string> {
80-
const authorization = context.req.headers.authorization;
81-
const token = authorization?.split(' ')[1];
82-
if (token === undefined)
83-
throw new Error('Invalid request, token not found');
67+
const token = getToken(context);
8468
return await this.profileService.toggleFollow(input, token);
8569
}
8670

@@ -89,10 +73,7 @@ export class ProfileResolver {
8973
@Args('input') input: PaginatedUserInput,
9074
@Context() context,
9175
): Promise<RestrictedUserOther[]> {
92-
const authorization = context.req.headers.authorization;
93-
const token = authorization?.split(' ')[1];
94-
if (token === undefined)
95-
throw new Error('Invalid request, token not found');
76+
const token = getToken(context);
9677
return await this.profileService.getFollowers(
9778
input?.page || 1,
9879
input.userId,
@@ -105,10 +86,7 @@ export class ProfileResolver {
10586
@Args('input') input: PaginatedUserInput,
10687
@Context() context,
10788
): Promise<RestrictedUserOther[]> {
108-
const authorization = context.req.headers.authorization;
109-
const token = authorization?.split(' ')[1];
110-
if (token === undefined)
111-
throw new Error('Invalid request, token not found');
89+
const token = getToken(context);
11290
return await this.profileService.getFollowing(
11391
input?.page || 1,
11492
input.userId,
@@ -121,9 +99,7 @@ export class ProfileResolver {
12199
@Args('input') input: DescriptionInput,
122100
@Context() context,
123101
): Promise<string> {
124-
const token = context?.req?.headers?.authorization?.split(' ')[1];
125-
if (token === undefined)
126-
throw new Error('Invalid request, token not found');
102+
const token = getToken(context);
127103
return await this.profileService.addDescription(input.description, token);
128104
}
129105
}

src/profile/profile.service.ts

+12-5
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
} from 'src/graphql.types';
1717
import { NotificationService } from 'src/notification/notification.service';
1818
import { followingNotification } from 'src/constants/notifications';
19+
import { HttpException, HttpStatus } from '@nestjs/common';
1920

2021
@Injectable()
2122
export class ProfileService {
@@ -34,7 +35,7 @@ export class ProfileService {
3435
const user = await decode(token, this.prisma);
3536
const userId = user.id;
3637
if (!user) {
37-
throw new BadRequestException('User not found');
38+
throw new HttpException('User not found', HttpStatus.BAD_REQUEST);
3839
}
3940
const state = this.createState(userId);
4041
await this.clearGithubAuthTokens(userId);
@@ -62,7 +63,10 @@ export class ProfileService {
6263
const userId = user.id;
6364
const { username, platform } = data;
6465
if (!username || !platform) {
65-
throw new BadRequestException('Username and platform are required');
66+
throw new HttpException(
67+
'Username and platform are required',
68+
HttpStatus.BAD_REQUEST,
69+
);
6670
}
6771
if (platform === Website.CODEFORCES) {
6872
await this.prisma.user.update({
@@ -75,7 +79,7 @@ export class ProfileService {
7579
data: { leetcodeUsername: username },
7680
});
7781
} else {
78-
throw new BadRequestException('Invalid platform');
82+
throw new HttpException('Invalid platform', HttpStatus.BAD_REQUEST);
7983
}
8084
return 'Username added successfully';
8185
}
@@ -142,7 +146,10 @@ export class ProfileService {
142146
const userId = user.id;
143147
const friendId = data.userId;
144148
if (friendId === userId) {
145-
throw new BadRequestException('You cannot follow or unfollow yourself');
149+
throw new HttpException(
150+
'You cannot follow or unfollow yourself',
151+
HttpStatus.BAD_REQUEST,
152+
);
146153
}
147154
if (data.action === 'ADD') {
148155
await this.addFollowing(userId, friendId);
@@ -156,7 +163,7 @@ export class ProfileService {
156163
await this.removeFollowing(userId, friendId);
157164
await this.removeFollowedBy(userId, friendId);
158165
} else {
159-
throw new BadRequestException('Invalid action');
166+
throw new HttpException('Invalid action', HttpStatus.BAD_REQUEST);
160167
}
161168
return 'Follow toggled successfully';
162169
}

0 commit comments

Comments
 (0)