Arky
PPrisma
•Created by Arky on 10/18/2024 in #help-and-questions
Validate Model
Finally created a function that answers this question in case anyone needs it
Example usage:
export type GetModel<T extends Prisma.ModelName> = Exclude<
Awaited<ReturnType<PrismaClient[Uncapitalize<T>]["findUnique"]>>,
null
>;
export const validateModel = <T extends Prisma.ModelName>(
model: T,
data: GetModel<Prisma.ModelName>
): data is GetModel<T> => {
const prismaModelEnum = Prisma[`${model}ScalarFieldEnum`];
return Object.keys(prismaModelEnum)
.map((v) => v in data)
.every((v) => v);
};
export type GetModel<T extends Prisma.ModelName> = Exclude<
Awaited<ReturnType<PrismaClient[Uncapitalize<T>]["findUnique"]>>,
null
>;
export const validateModel = <T extends Prisma.ModelName>(
model: T,
data: GetModel<Prisma.ModelName>
): data is GetModel<T> => {
const prismaModelEnum = Prisma[`${model}ScalarFieldEnum`];
return Object.keys(prismaModelEnum)
.map((v) => v in data)
.every((v) => v);
};
import { Prisma, Model1, Model2, Model3 } from "@prisma/client";
import { prisma } from "@/libraries/prisma";
type Multiple = Model1 | Model2 | Model3;
const search = async (query: string): Promise<Multiple[]> => {
const model1 = await prisma.model1.findMany({ where: { name: { contains: query } } });
const model2 = await prisma.model2.findMany({ where: { name: { contains: query } } });
const model3 = await prisma.model3.findMany({ where: { name: { contains: query } } });
return [...model1, ...model2, ...model3];
}
const displayData = (model: Multiple) => {
// How can i use the validator there (or something else) to validate the type of my model?
if (validateModel("Model1", model)) return "model1";
if (validateModel("Model2", model)) return "model2";
if (validateModel("Model3", model)) return "model3";
}
const response = await search("hello world");
const data = displayData(response);
// do something with data
import { Prisma, Model1, Model2, Model3 } from "@prisma/client";
import { prisma } from "@/libraries/prisma";
type Multiple = Model1 | Model2 | Model3;
const search = async (query: string): Promise<Multiple[]> => {
const model1 = await prisma.model1.findMany({ where: { name: { contains: query } } });
const model2 = await prisma.model2.findMany({ where: { name: { contains: query } } });
const model3 = await prisma.model3.findMany({ where: { name: { contains: query } } });
return [...model1, ...model2, ...model3];
}
const displayData = (model: Multiple) => {
// How can i use the validator there (or something else) to validate the type of my model?
if (validateModel("Model1", model)) return "model1";
if (validateModel("Model2", model)) return "model2";
if (validateModel("Model3", model)) return "model3";
}
const response = await search("hello world");
const data = displayData(response);
// do something with data
4 replies