38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
function camelToSnake(key: string): string {
|
|
return key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
|
}
|
|
|
|
function snakeToCamel(key: string): string {
|
|
return key.replace(/_([a-z0-9])/g, (_, letter) => letter.toUpperCase());
|
|
}
|
|
|
|
export function toSnakeCase<T extends Record<string, unknown>>(obj: T): Record<string, unknown> {
|
|
const result: Record<string, unknown> = {};
|
|
for (const [key, value] of Object.entries(obj)) {
|
|
result[camelToSnake(key)] = value;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function toCamelCase<T extends Record<string, unknown>>(obj: T): Record<string, unknown> {
|
|
const result: Record<string, unknown> = {};
|
|
for (const [key, value] of Object.entries(obj)) {
|
|
result[snakeToCamel(key)] = value;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// Keeps only the allowed keys from an object — used to drop unexpected/protected
|
|
// fields from request bodies before they reach the database.
|
|
export function pick(
|
|
obj: Record<string, unknown>,
|
|
allowed: readonly string[]
|
|
): Record<string, unknown> {
|
|
const allowedSet = new Set(allowed);
|
|
const result: Record<string, unknown> = {};
|
|
for (const [key, value] of Object.entries(obj)) {
|
|
if (allowedSet.has(key)) result[key] = value;
|
|
}
|
|
return result;
|
|
}
|