Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add catch prisma error decorator #61

Merged
merged 1 commit into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 6 additions & 13 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,12 @@ export class AuthController {
})
@Post('signUp')
async signup(@Body() body: CreateUserDto): Promise<SignupResponse> {
try {
const user = await this.authService.signUp(body);
const loginedUser = await this.authService.accessToken(user);
return {
user,
accessToken: loginedUser,
};
} catch (e) {
if (e.code === 'P2002') {
throw new BadRequestException('Username already exists');
}
throw new Error('Something went wrong');
}
const user = await this.authService.signUp(body);
const loginedUser = await this.authService.accessToken(user);
return {
user,
accessToken: loginedUser,
};
}

@UseGuards(LocalAuthGuard)
Expand Down
23 changes: 23 additions & 0 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,27 @@ describe('Given a auth service', function () {
});
expect(user).toBeDefined();
});

it('Should be able to signUp', async () => {
const authService = new AuthService(
new JwtService(),
userService,
mockRedis as any,
prisma,
);
const user = await authService.signUp({
email: '',
name: '',
password: 'password',
username: 'abc',
});

const user2 = await authService.signUp({
email: '[email protected]',
name: 'a',
password: 'password',
username: 'abc',
});
expect(user).toBeDefined();
});
});
8 changes: 8 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from './dto/mfa.authenticate.dto';
import { server } from 'webauthn';
import { Environments } from '../common/environment';
import { catchPrismaErrorDecorator } from '../decorators/catchPrismaDecorator';

@Injectable()
export class AuthService {
Expand All @@ -32,6 +33,7 @@ export class AuthService {
// eslint-disable-next-line prettier/prettier
}

@catchPrismaErrorDecorator()
async validateUser(username: string, password: string) {
const user = await this.userService.findOneBy(username);
const isMatched = await this.userService.comparePassword(
Expand Down Expand Up @@ -60,10 +62,12 @@ export class AuthService {
});
}

@catchPrismaErrorDecorator()
async signUp(user: CreateUserDto) {
return this.userService.create(user);
}

@catchPrismaErrorDecorator()
async getMfaRegistrationCredentials(
userId: string,
): Promise<GetMfaAuthenticationResponse> {
Expand Down Expand Up @@ -94,6 +98,7 @@ export class AuthService {
* @param data
* @returns credential id
*/
@catchPrismaErrorDecorator()
async createMfaAuthentication(
userId: string,
data: CreateMfaAuthenticationDto,
Expand Down Expand Up @@ -126,6 +131,7 @@ export class AuthService {
* @param userId
* @param data
*/
@catchPrismaErrorDecorator()
async getMfaAuthenticate(
userId: string,
): Promise<GetMfaAuthenticateResponse> {
Expand All @@ -146,6 +152,7 @@ export class AuthService {
};
}

@catchPrismaErrorDecorator()
async verifyMfaAuthenticate(
userId: string,
data: CreateMfaAuthenticateDto,
Expand Down Expand Up @@ -174,6 +181,7 @@ export class AuthService {
return registration;
}

@catchPrismaErrorDecorator()
getRedisKey(
userId: string,
type: 'registration' | 'authentication' | 'authenticated',
Expand Down
37 changes: 37 additions & 0 deletions src/decorators/catchPrismaDecorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';

export function mapPrismaErrorToHttpException(error: any) {
if (error.code === 'P2002') {
return new BadRequestException('Duplicate entry found');
} else if (error.code === 'P2003') {
return new BadRequestException('Key constraint failed');
} else if (error.code === 'P2025') {
return new NotFoundException('The record was not found');
} else if (error.code === 'P2014') {
return new BadRequestException(
'The record violates the schema on relationship',
);
}
if (error.name === 'PrismaClientValidationError') {
return new BadRequestException('Some of the data is invalid');
}
return error;
}

export function catchPrismaErrorDecorator() {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
try {
return await originalMethod.apply(this, args);
} catch (error: any) {
throw mapPrismaErrorToHttpException(error);
}
};
return descriptor;
};
}