Skip to content

Commit

Permalink
fix: UniqueConflict handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Clashsoft committed May 5, 2024
1 parent cdf6844 commit bde1c0e
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/util/unique-conflict.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,38 @@
import {applyDecorators, ArgumentsHost, Catch, ConflictException, UseFilters} from '@nestjs/common';
import {applyDecorators, ArgumentsHost, Catch, ExceptionFilter, HttpStatus, UseFilters} from '@nestjs/common';
import {ApiConflictResponse} from '@nestjs/swagger';
import {mongo} from 'mongoose';
import {BaseExceptionFilter} from '@nestjs/core';

// TODO move everything to @mean-stream/nestx

/**
* Converts a MongoServerError with code 11000 into a ConflictException with a configurable message.
*/
@Catch(mongo.MongoServerError)
class ConflictExceptionFilter extends BaseExceptionFilter {
class ConflictExceptionFilter implements ExceptionFilter {
constructor(
private description: Partial<Record<string, string>>,
) {
super();
}

catch(exception: mongo.MongoServerError, host: ArgumentsHost): any {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
if (exception.code !== 11000) {
return super.catch(exception, host);
response.status(500).json({
statusCode: 500,
message: exception.message,
});
return;
}

const keyPattern = exception.keyPattern; // e.g. { username: 1 }
const values = exception.keyValue; // e.g. { username: 'test' }
const indexKey = Object.keys(keyPattern).join('_');
const http = new ConflictException(this.description[indexKey] ?? `Unique constraint violation on '${indexKey}' with value ${JSON.stringify(values)}.`);
return super.catch(http, host);
const message = this.description[indexKey] ?? `Unique constraint violation on '${indexKey}' with value ${JSON.stringify(values)}.`;
response.status(HttpStatus.CONFLICT).json({
statusCode: HttpStatus.CONFLICT,
message,
});
}
}

Expand Down

0 comments on commit bde1c0e

Please sign in to comment.