Fix fieldMetadata sync validation exceptions caught in exception handler (#10789)

## Context
Field metadata service was reusing validators from
validate-**OBJECT**-metadata-input which were throwing ObjectMetadata
exceptions not handled in fieldMetadataGraphqlApiExceptionHandler and
were going to Sentry.
To solve the issue since this validator is associated with both fields
and objects I'm moving the util to the root utils folder of metadata
module and throwing a common metadata user input exception
This commit is contained in:
Weiko
2025-03-11 18:41:29 +01:00
committed by GitHub
parent 9880114853
commit 4d0450069c
9 changed files with 94 additions and 49 deletions

View File

@ -0,0 +1,29 @@
import camelCase from 'lodash.camelcase';
import { slugify } from 'transliteration';
import { isDefined } from 'twenty-shared';
import { InvalidMetadataException } from 'src/engine/metadata-modules/utils/exceptions/invalid-metadata.exception';
export const computeMetadataNameFromLabel = (label: string): string => {
if (!isDefined(label)) {
throw new InvalidMetadataException('Label is required');
}
const prefixedLabel = /^\d/.test(label) ? `n${label}` : label;
if (prefixedLabel === '') {
return '';
}
const formattedString = slugify(prefixedLabel, {
trim: true,
separator: '_',
allowedChars: 'a-zA-Z0-9',
});
if (formattedString === '') {
throw new InvalidMetadataException(`Invalid label: "${label}"`);
}
return camelCase(formattedString);
};

View File

@ -0,0 +1,5 @@
export class InvalidMetadataException extends Error {
constructor(message: string) {
super(message);
}
}

View File

@ -0,0 +1,42 @@
import camelCase from 'lodash.camelcase';
import { slugify } from 'transliteration';
import { isDefined } from 'twenty-shared';
import { InvalidMetadataException } from 'src/engine/metadata-modules/utils/exceptions/invalid-metadata.exception';
export const validateNameAndLabelAreSyncOrThrow = (
label: string,
name: string,
) => {
const computedName = computeMetadataNameFromLabel(label);
if (name !== computedName) {
throw new InvalidMetadataException(
`Name is not synced with label. Expected name: "${computedName}", got ${name}`,
);
}
};
export const computeMetadataNameFromLabel = (label: string): string => {
if (!isDefined(label)) {
throw new InvalidMetadataException('Label is required');
}
const prefixedLabel = /^\d/.test(label) ? `n${label}` : label;
if (prefixedLabel === '') {
return '';
}
const formattedString = slugify(prefixedLabel, {
trim: true,
separator: '_',
allowedChars: 'a-zA-Z0-9',
});
if (formattedString === '') {
throw new InvalidMetadataException(`Invalid label: "${label}"`);
}
return camelCase(formattedString);
};