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

Refactor field duplication exception handling #169

Merged
merged 2 commits into from
Dec 28, 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "monguito",
"version": "3.4.1",
"version": "4.0.0",
"description": "MongoDB Abstract Repository implementation for Node.js",
"author": {
"name": "Josu Martinez",
Expand Down
22 changes: 8 additions & 14 deletions src/mongoose.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,12 @@ export abstract class MongooseRepository<T extends Entity & UpdateQuery<T>>
`There is no document matching the given ID '${entity.id}'. New entities cannot not specify an ID`,
);
} catch (error) {
if (error.message.includes('validation failed')) {
if (
error.message.includes('validation failed') ||
error.message.includes('duplicate key error')
) {
throw new ValidationException(
`Some fields of the given entity do not specify valid values`,
'One or more fields of the given entity do not specify valid values',
error,
);
}
Expand Down Expand Up @@ -174,18 +177,9 @@ export abstract class MongooseRepository<T extends Entity & UpdateQuery<T>>
entity: S,
userId?: string,
): Promise<HydratedDocument<S>> {
try {
this.setDiscriminatorKeyOn(entity);
const document = this.createDocumentAndSetUserId(entity, userId);
return (await document.save()) as HydratedDocument<S>;
} catch (error) {
if (error.message.includes('duplicate key error')) {
throw new ValidationException(
`The given entity includes a field which value is expected to be unique`,
);
}
throw error;
}
this.setDiscriminatorKeyOn(entity);
const document = this.createDocumentAndSetUserId(entity, userId);
return (await document.save()) as HydratedDocument<S>;
}

private setDiscriminatorKeyOn<S extends T>(
Expand Down
Loading