import { ClassConstructor, plainToInstance } from 'class-transformer';
import { validateOrReject } from 'class-validator';
import { makeApiErrorFromValidation } from '../error/api-error-helpers';

export async function apiParseJsonWhere<T extends object>(
  where_json: string | undefined,
  cl: ClassConstructor<T>,
): Promise<T> {
  const where: T = new cl();
  if (where_json) {
    const parsed_where = JSON.parse(where_json);
    const parsed_instance = plainToInstance(cl, parsed_where);
    try {
      await validateOrReject(parsed_instance);
    } catch (errors: any) {
      throw makeApiErrorFromValidation(errors);
    }
    Object.assign(where, parsed_instance);
  }
  return where;
}
