WorkshopTasker/server/utils/prismaToWeb.ts

45 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

import { Prisma } from "@prisma/client";
type func = (...args: any[]) => any | Function;
export type replaceJsonUnparsableToString<T> =
T extends Array<infer E> ? Array<replaceJsonUnparsableToString<E>>
: {
[K in keyof T]:
T[K] extends null ? null
: T[K] extends func ? never
: T[K] extends Prisma.Decimal ? `${number}`
: T[K] extends Array<infer E> ? Array<replaceJsonUnparsableToString<E>>
: T[K] extends object ? replaceJsonUnparsableToString<T[K]>
: T[K] extends bigint ? `${bigint}`
: T[K]
};
type exactToInterface = (...args: any[]) => any extends Function ? true : false;
function arrayPrismaToWeb<T>(array: Array<T>) {
return array.reduce(
(pV, cV) => {
pV.push(prismaToWeb(cV));
return pV;
},
[] as Array<replaceJsonUnparsableToString<T>>,
);
}
export function prismaToWeb<T>(ivalue: T): replaceJsonUnparsableToString<T> {
const rvalue: any = ivalue instanceof Array ? [] : {};
for (const i in ivalue) {
const current = ivalue[i];
if (current === null) rvalue[i] = null;
else if (typeof current === 'function') continue;
else if (current instanceof Prisma.Decimal) rvalue[i] = current.toString();
else if (current instanceof Array) rvalue[i] = arrayPrismaToWeb(current);
else if (typeof current === 'object') rvalue[i] = prismaToWeb(current);
else if (typeof current === 'bigint') rvalue[i] = current.toString();
else rvalue[i] = current;
}
return rvalue;
}