Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
♻️ Check for primary email on deleting emails
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Nov 15, 2020
1 parent d03d7cd commit d0a4ace
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/errors/errors.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const ORDER_BY_FORMAT = '400012: Invalid ordering format';
export const WHERE_PIPE_FORMAT = '400013: Invalid query format';
export const OPTIONAL_INT_PIPE_NUMBER = '400014: $key should be a number';
export const CURSOR_PIPE_FORMAT = '400015: Invalid cursor format';
export const EMAIL_DELETE_PRIMARY = '400016: Cannot delete primary email';

export const EMAIL_USER_CONFLICT =
'409001: User with this email already exists';
Expand Down
21 changes: 20 additions & 1 deletion src/modules/emails/emails.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
BadRequestException,
Injectable,
NotFoundException,
UnauthorizedException,
Expand All @@ -11,13 +12,15 @@ import {
emailsWhereUniqueInput,
} from '@prisma/client';
import {
EMAIL_DELETE_PRIMARY,
EMAIL_NOT_FOUND,
UNAUTHORIZED_RESOURCE,
USER_NOT_FOUND,
} from '../../errors/errors.constants';
import { safeEmail } from '../../helpers/safe-email';
import { Expose } from '../../providers/prisma/prisma.interface';
import { AuthService } from '../auth/auth.service';
import { PrismaService } from '../../providers/prisma/prisma.service';
import { AuthService } from '../auth/auth.service';
import { UsersService } from '../users/users.service';

@Injectable()
Expand Down Expand Up @@ -78,6 +81,22 @@ export class EmailsService {
if (!testEmail) throw new NotFoundException(EMAIL_NOT_FOUND);
if (testEmail.userId !== userId)
throw new UnauthorizedException(UNAUTHORIZED_RESOURCE);
const user = await this.prisma.users.findOne({
where: { id: userId },
include: { prefersEmail: true },
});
if (!user) throw new NotFoundException(USER_NOT_FOUND);
if (user.prefersEmail.id === id) {
const otherEmails = (
await this.prisma.emails.findMany({ where: { user: { id: userId } } })
).filter((i) => i.id !== id);
if (!otherEmails.length)
throw new BadRequestException(EMAIL_DELETE_PRIMARY);
await this.prisma.users.update({
where: { id: userId },
data: { prefersEmail: { connect: { id: otherEmails[0].id } } },
});
}
const email = await this.prisma.emails.delete({
where: { id },
});
Expand Down

0 comments on commit d0a4ace

Please sign in to comment.