Files
directus/api/src/utils/validate-keys.ts
ian 8f52fdf1f9 Validate type of items' primary keys (#13276)
* Validate type of items' primary keys

* Update tests

* Update validations

* Remove DB specific check for statusCode in existing e2e test

* Extract as util function

* Add unit test

* Refactor to generic validateKeys
2022-05-24 11:11:28 -04:00

28 lines
807 B
TypeScript

import { SchemaOverview } from '@directus/shared/types';
import { ForbiddenException } from '../exceptions';
import { PrimaryKey } from '../types';
import validateUUID from 'uuid-validate';
/**
* Validate keys based on its type
*/
export function validateKeys(
schema: SchemaOverview,
collection: string,
keyField: string,
keys: PrimaryKey | PrimaryKey[]
) {
if (Array.isArray(keys)) {
for (const key of keys) {
validateKeys(schema, collection, keyField, key);
}
} else {
const primaryKeyFieldType = schema.collections[collection].fields[keyField].type;
if (primaryKeyFieldType === 'uuid' && !validateUUID(String(keys))) {
throw new ForbiddenException();
} else if (primaryKeyFieldType === 'integer' && !Number.isInteger(Number(keys))) {
throw new ForbiddenException();
}
}
}