Prisma middleware for validating data before creating or updating records.
Performing custom validation of data before creating or updating records using Prisma is generally left up to the application. This middleware provides a global way to validate data using a custom validation function and supports using third party validation libraries such as Zod or Superstruct.
Data is validated before any create or update, including when using nested relations. It does this by using the prisma-nested-middleware library to handle nested relations.
This module is distributed via npm and should be installed as one of your project's dependencies:
npm install --save prisma-validation-middleware
@prisma/client
is a peer dependency of this library, so you will need to
install it if you haven't already:
npm install --save @prisma/client
To add validation to your Prisma client create the middleware using the createValidationMiddleware
function and $use
it with your client.
The createValidationMiddleware
function takes a config object where you can define the validation function you want to
use for your models. The validation function has the data being used to create or update the record as its only
argument. You can use this data to perform any validation you want and throw an error if the data is invalid.
import { PrismaClient } from "@prisma/client";
import { createValidationMiddleware } from "prisma-validation-middleware";
const client = new PrismaClient();
client.$use(
createValidationMiddleware({
Comment: (data) => {
if (data.content?.length > 1000) {
throw new Error("content must be less than 1000 characters");
}
},
})
);
You can pass a validation function for each model you want to validate. If you don't pass a validation function for a model then no validation will be performed for it.
To use this middleware with Zod you can use a custom validation function that uses Zod schemas to validate the data.
Below is an example function that takes a Zod Schema and returns a validation function, the zod-validation-error
library is used to convert the Zod error into more readable error:
const { z } = require("zod");
const { fromZodError } = require("zod-validation-error");
function validate(schema) {
return (data) => {
try {
schema.parse(data);
} catch (err) {
throw fromZodError(err, {
prefix: "",
prefixSeparator: "",
});
}
};
}
If you are using Typescript the function would look like this:
import { z } from "zod";
import { fromZodError } from "zod-validation-error";
function validate(schema: z.ZodType<any>) {
return (data: any) => {
try {
schema.parse(data);
} catch (err) {
throw fromZodError(err as z.ZodError, {
prefix: "",
prefixSeparator: "",
});
}
};
}
You can then use the validate
function to validate each model using Zod:
import { z } from "zod";
client.$use(
createValidationMiddleware({
Comment: validate(
z.object({
// validate content is between 10 and 128 characters
content: z.string().min(10).max(128),
})
),
})
);
To use this middleware with Superstruct you can use a custom validation function that uses Superstruct structs it to validate the data.
Below is an example function that takes a Superstruct Struct
and returns a validation function that uses it to
validate the data:
const { assert, mask } = require("superstruct");
function validate(struct) {
return (data) => assert(mask(data, struct), struct);
}
If you are using Typescript the function would look like this:
import { assert, mask, Struct } from "superstruct";
function validate<T extends Struct<any, any>>(struct: T) {
return (data: any) => assert<T, any>(mask(data, struct), struct);
}
You can then use the validate
function to validate each model using Superstruct:
import { object, string, size } from "superstruct";
client.$use(
createValidationMiddleware({
Comment: validate(
object({
// validate content is between 10 and 128 characters
content: size(string(), 10, 128),
})
),
})
);
Data is validated for create
, update
, upsert
, createMany
, updateMany
and connectOrCreate
operations. This
includes when models are created or updated through nested relations. For example all the Comment data below would be
validated:
await client.post.update({
where: { id: 1 },
data: {
comments: {
update: {
where: {
id: 2,
},
data: {
content: "My Comment Content",
},
},
},
},
});
The error thrown by the middleware is the error thrown by the validation function prefixed with information about the model and action that failed.
Apache 2.0