mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-17 12:33:22 +00:00
add smart random
This commit is contained in:
30
src/infrastructure/common/helpers/get-order-by-object.ts
Normal file
30
src/infrastructure/common/helpers/get-order-by-object.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
type OrderByDirection = 'asc' | 'desc'
|
||||
|
||||
export function createPrismaOrderBy(input: string | null) {
|
||||
if (!input || input === 'null') {
|
||||
return undefined
|
||||
}
|
||||
const [key, direction] = input.split('-')
|
||||
|
||||
if (!key || !direction) {
|
||||
throw new Error("Invalid format. Expected format is 'key-direction'")
|
||||
}
|
||||
|
||||
if (direction !== 'asc' && direction !== 'desc') {
|
||||
throw new Error("Invalid direction. Expected 'asc' or 'desc'")
|
||||
}
|
||||
|
||||
if (key.includes('.')) {
|
||||
const [relation, field] = key.split('.')
|
||||
|
||||
return {
|
||||
[relation]: {
|
||||
[field]: direction,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
[key]: direction as OrderByDirection,
|
||||
}
|
||||
}
|
||||
45
src/infrastructure/decorators/is-order-by-constraint.ts
Normal file
45
src/infrastructure/decorators/is-order-by-constraint.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
registerDecorator,
|
||||
ValidationArguments,
|
||||
ValidationOptions,
|
||||
ValidatorConstraint,
|
||||
ValidatorConstraintInterface,
|
||||
} from 'class-validator'
|
||||
|
||||
@ValidatorConstraint({ async: false })
|
||||
export class IsOrderByConstraint implements ValidatorConstraintInterface {
|
||||
validate(orderBy: string | null, args: ValidationArguments) {
|
||||
console.log(orderBy)
|
||||
if (!orderBy || orderBy === 'null' || orderBy === '') {
|
||||
return true
|
||||
}
|
||||
const [key, direction] = orderBy.split('-')
|
||||
|
||||
if (!key || !direction) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (direction !== 'asc' && direction !== 'desc') {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
defaultMessage(args: ValidationArguments) {
|
||||
return 'Invalid format. Expected format is "key-direction". Direction must be "asc" or "desc".'
|
||||
}
|
||||
}
|
||||
|
||||
export function IsOrderBy(validationOptions?: ValidationOptions) {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
return function (object: { constructor: Function }, propertyName: string) {
|
||||
registerDecorator({
|
||||
target: object.constructor,
|
||||
propertyName: propertyName,
|
||||
options: validationOptions,
|
||||
constraints: [],
|
||||
validator: IsOrderByConstraint,
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user