Skip to content

Commit

Permalink
fix: Prevent users from using non-unique usernames
Browse files Browse the repository at this point in the history
  • Loading branch information
flacial committed Dec 26, 2022
1 parent e25de42 commit 83c1a02
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
21 changes: 21 additions & 0 deletions graphql/resolvers/userDataCrud.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ describe('User Data CRUD resolvers', () => {
}

prismaMock.user.update.mockResolvedValueOnce(userMock)
prismaMock.user.findFirst.mockResolvedValueOnce(null)

expect(
updateUserNames(
Expand All @@ -27,4 +28,24 @@ describe('User Data CRUD resolvers', () => {
)
).resolves.toStrictEqual(userMock)
})

it('Should not update the user username and name if username already used', async () => {
expect.assertions(1)

const userMock = {
username: mockUsername,
name: mockName
}

prismaMock.user.update.mockResolvedValueOnce(userMock)
prismaMock.user.findFirst.mockResolvedValueOnce(userMock)

expect(
updateUserNames(
null,
{ username: mockUsername, mockName },
{ req: { user: { id: 1 } } }
)
).rejects.toEqual(Error('Username is already used'))
})
})
10 changes: 10 additions & 0 deletions graphql/resolvers/userDataCrud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ export const updateUserNames = withUserContainer<
>(async (_, args, { req }) => {
const { username, name } = args

const usernameAlreadyUsed = await prisma.user.findFirst({
where: {
username
}
})

if (usernameAlreadyUsed) {
throw new Error('Username is already used')
}

const user = await prisma.user.update({
where: {
id: req.user!.id
Expand Down

0 comments on commit 83c1a02

Please sign in to comment.