add smart random

This commit is contained in:
2023-07-14 14:54:47 +02:00
parent 68942e904f
commit b14fb39009
25 changed files with 509 additions and 104 deletions

View 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,
}
}

View 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,
})
}
}