55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import { ApiException } from './exceptions/api.exception';
|
|
import { HttpStatus } from '@nestjs/common';
|
|
|
|
export const uuidPattern =
|
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
|
|
export function invalidRequest(message: string): never {
|
|
throw new ApiException(HttpStatus.BAD_REQUEST, 'invalid_request', message);
|
|
}
|
|
|
|
export function objectBody(
|
|
value: unknown,
|
|
keys: string[],
|
|
): Record<string, unknown> {
|
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
return invalidRequest('Ожидается JSON-объект');
|
|
}
|
|
const body = value as Record<string, unknown>;
|
|
if (Object.keys(body).some((key) => !keys.includes(key))) {
|
|
return invalidRequest('Неизвестное поле запроса');
|
|
}
|
|
return body;
|
|
}
|
|
|
|
export function requiredText(
|
|
value: unknown,
|
|
field: string,
|
|
max: number,
|
|
): string {
|
|
if (typeof value !== 'string' || value.trim().length === 0) {
|
|
return invalidRequest(`Некорректное поле ${field}`);
|
|
}
|
|
let codePoints = 0;
|
|
for (const _character of value) codePoints++;
|
|
if (codePoints > max) return invalidRequest(`Некорректное поле ${field}`);
|
|
return value;
|
|
}
|
|
|
|
export function uuid(value: unknown, field: string): string {
|
|
if (typeof value !== 'string' || !uuidPattern.test(value)) {
|
|
return invalidRequest(`Некорректное поле ${field}`);
|
|
}
|
|
return value.toLowerCase();
|
|
}
|
|
|
|
export function pageLimit(value: unknown): number {
|
|
if (value === undefined) return 50;
|
|
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
|
|
return invalidRequest('Некорректный limit');
|
|
}
|
|
const limit = Number(value);
|
|
if (limit > 100) return invalidRequest('Некорректный limit');
|
|
return limit;
|
|
}
|