import { OrderByCondition } from 'typeorm'; import { OrderByDirection } from '@/types'; import { enumFromStringValue } from '@/utils'; import { PagesOrderBy, PagesOrderByField } from './types'; type Keys = string; const FieldEnumToFieldNameMapper = new Map([ [PagesOrderByField.FEATURED, 'featured'], ]); /** * @returns {string} key for orderBy that contains a prefix if one is provided */ const optionallyPrefixedKey = (key: string, prefix?: string): string => `${prefix ? `${prefix}.` : ''}${key}`; /** * Given input for reports query, generate typeorm order field that can be * used to control sort direction * @default { featured: 'DESC' } */ export const convertOrderByGraphQLToTypeormOrder = ( orderBy?: PagesOrderBy, prefix?: string ): OrderByCondition => { const defaultOrderBy: OrderByCondition = { [optionallyPrefixedKey('featured', prefix)]: 'DESC', }; if (!orderBy) { return defaultOrderBy; } const fieldAsEnum = enumFromStringValue(PagesOrderByField, orderBy.field); if (!fieldAsEnum) { return defaultOrderBy; } const field = FieldEnumToFieldNameMapper.get(fieldAsEnum); if (!field) { return defaultOrderBy; } const direction = orderBy.direction === OrderByDirection.ASC ? 'ASC' : 'DESC'; return { [optionallyPrefixedKey(field, prefix)]: { order: direction, nulls: 'NULLS LAST', }, }; };