import { ValueObject } from "@repo/rdx-ddd"; import { Result, RuleValidator, UndefinedOr } from "@repo/rdx-utils"; import Joi from "joi"; export interface IQuickSearchCriteria { searchTerms: string[]; isEmpty(): boolean; toStringArray(): string[]; toString(): string; toJSON(): string; toPrimitive(): string; } export class QuickSearchCriteria extends ValueObject> implements IQuickSearchCriteria { protected static validate(value: UndefinedOr) { const searchStringArray = value; const schema = Joi.array().items(Joi.string().trim().allow("")).default([]); const stringArrayOrError = RuleValidator.validate(schema, searchStringArray); if (stringArrayOrError.isFailure) { return stringArrayOrError; } return Result.ok(searchStringArray); } public static create(value: UndefinedOr) { const stringArrayOrError = QuickSearchCriteria.validate(value); if (stringArrayOrError.isFailure) { return Result.fail(stringArrayOrError.error); } const sanitizedTerms = QuickSearchCriteria.sanitize(stringArrayOrError.data); return Result.ok(new QuickSearchCriteria(sanitizedTerms)); } private static sanitize(terms: string[] | undefined): string[] { return terms ? terms.map((term) => term.trim()).filter((term) => term.length > 0) : []; } getValue() { return !this.isEmpty() ? this.props : undefined; } get value(): UndefinedOr { return this.getValue(); } get searchTerms(): string[] { return this.toStringArray(); } public isEmpty = (): boolean => { return this.props ? this.props.length === 0 : true; }; public toStringArray = (): string[] => { return this.props ? [...this.props] : []; }; public toString = (): string => { return this.toStringArray().toString(); }; public toJSON(): string { return JSON.stringify(this.toStringArray()); } public toPrimitive(): string { return this.toString(); } }