This example shows how to use a Prisma Client extension to provide static and runtime types for a Json
field. It uses Zod to parse the field data and infer static TypeScript types.
This example includes a User
model with a JSON profile
field, which has a sparse structure which may vary between each users. The extension has two parts:
- A
result
extension that adds a computedprofileData
field. This field uses theProfile
Zod parser to parse the untypedprofile
field. TypeScript infers the static data type from the parser, so query results have both static and runtime type safety. - A
query
extension that parses theprofile
field of input data for theUser
model's write methods likecreate
andupdate
.
NOTE: Query extensions do not currently work for nested operations. In this example, validations are only run on the top level
data
object passed to methods such asprisma.user.create()
. Validations implemented this way do not automatically run for nested writes.
This extension is provided as an example only. It is not intended to be used in production environments.
Please read the documentation on query
extensions and result
extensions for more information.
Clone this repository:
git clone [email protected]:sbking/prisma-client-extensions.git
Create a .env
file and install dependencies:
cd json-field-types
cp .env.example .env
npm install
Run the following command to start a new Postgres database in a Docker container:
docker compose up -d
Run this command to apply migrations to the database:
npx prisma migrate deploy
Run the following command to add seed data to the database:
npx prisma db seed
To run the script.ts
file, run the following command:
npm run dev