Using Json Type In Prisma

Thumbnail

Written by: developervsandhu

Technology and Gadgets

Using Json Type In Prisma

  • Setup your prisma and express server
  • Then create a Post model
	model  Post  {
		id String  @id  @default(auto())  @map("_id")  @db.ObjectId
		title String
		content Json
		createdAt DateTime  @default(now())
		updatedAt DateTime  @updatedAt
	}
  • Then we need to add zod validation for content type JSON in order to validate data
	import { z } from  "zod";
	export  const  ContentSchema = z.object({
		label: z.string({ message: "Label is required" }).min(5),
		options: z.array(
		z.object({
		id: z.number(),
		title: z.string({ message: "Title is required" }),
		url: z.string({ message: "Url is required" }),
		})
		),
	});  

	export  const  PostSchema = z.object({
		title: z.string({ message: "Title is required" }).min(5),
		content: ContentSchema,
	});
  • After that in a route we can validate and store the data in db
	app.post("/api/posts", async (req: Request, res: Response) => {
	
	try {
		const  payload = PostSchema.safeParse(req.body);
		if (!payload.success) {
		return  res.status(400).json({ errors: payload.error.flatten() });
		}
		const  result = await  prisma.post.create({
		data: {
		title: payload.data?.title,
		content: payload.data?.content,
		},
		});
		return  res.status(200).json({ data: result });
	} catch (error) {
		return  res.status(400).json({ error });
		}
	});
  • That's it you are good to go...

Login To Add Comment

No comments yet.