Fix unique error extraction in MySQL

Fixes #4995
This commit is contained in:
rijkvanzanten
2021-04-12 17:28:41 -04:00
parent 8643d0812c
commit 0f5a98f4f2
3 changed files with 28 additions and 6 deletions

View File

@@ -45,7 +45,20 @@ function uniqueViolation(error: MySQLError) {
if (!matches) return error;
const collection = matches[1].slice(1, -1).split('.')[0];
const field = matches[1].slice(1, -1).split('.')[1];
let field = null;
/**
* MySQL's error doesn't return the field name in the error. In case the field is created through
* Directus (/ Knex), the key name will be `<collection>_<field>_unique` in which case we can pull
* the field name from the key name
*/
const indexName = matches[1].slice(1, -1).split('.')[1];
if (indexName.startsWith(`${collection}_`) && indexName.endsWith('_unique')) {
field = indexName.slice(collection.length + 1, -7);
}
const invalid = matches[0].slice(1, -1);
return new RecordNotUniqueException(field, {

View File

@@ -2,12 +2,16 @@ import { BaseException } from '../base';
type Extensions = {
collection: string;
field: string;
field: string | null;
invalid?: string;
};
export class RecordNotUniqueException extends BaseException {
constructor(field: string, extensions?: Extensions) {
super(`Field "${field}" has to be unique.`, 400, 'RECORD_NOT_UNIQUE', extensions);
constructor(field: string | null, extensions?: Extensions) {
if (field) {
super(`Field "${field}" has to be unique.`, 400, 'RECORD_NOT_UNIQUE', extensions);
} else {
super(`Field has to be unique.`, 400, 'RECORD_NOT_UNIQUE', extensions);
}
}
}

View File

@@ -5,8 +5,13 @@
<p>{{ $t('unknown_validation_errors') }}</p>
<ul>
<li v-for="(validationError, index) of unknownValidationErrors" :key="index">
<strong>{{ validationError.field }}</strong>
: {{ $t(`validationError.${validationError.type}`, validationError) }}
<strong v-if="validationError.field">{{ validationError.field }}:</strong>
<template v-if="validationError.code === 'RECORD_NOT_UNIQUE'">
{{ $t('validationError.unique', validationError) }}
</template>
<template v-else>
{{ $t(`validationError.${validationError.code}`, validationError) }}
</template>
</li>
</ul>
</div>