Lautaro_dapinL
tRPC3y ago
1 reply
Lautaro_dapin

Discriminated output based on discrimiated input

I have this function which works correctly by itself, but when i put it on trpc, the output doesn't get inffered correctly based o the input

type GetFarmsInput = {
    growerId?: number;
    provider?: string;
    leafUserId?: string;
    page?: number;
    size?: number;
} & ({withFields: true} | {withFields?: false | undefined});

type GetFarmsOutput<T extends GetFarmsInput> = T extends {withFields: true}
    ? FarmSchema[]
    : (FarmSchema & {fields: FieldSchema[]})[];

export async function getFarms<T extends GetFarmsInput>(input: T): Promise<GetFarmsOutput<T>>;
export async function getFarms<T extends GetFarmsInput>(input: T) {
    const {withFields, ...options} = input;
    const searchParams = stringify(options);
    const response = await endpoint(`/services/fields/api/farms?${searchParams.toString()}`, 'GET');
    if (!response.ok) {
        throw Error(`Couldn't get the farms`, {cause: await response.json()});
    }
    const farms = await farmsSchema.parseAsync(await response.json());
    if (withFields) {
        return await Promise.all(
            farms.map(async (farm) => {
                const fieldsMap = mapToIds(
                    await getAllFields({farmId: farm.id, size: 100, leafUserId: options.leafUserId})
                );
                return {
                    ...farm,
                    fields: farm.fieldIds.map((id) => fieldsMap.get(id)),
                };
            })
        );
    }
    return farms;
}
Was this page helpful?