npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

prisma-validation-middleware

v1.1.0

Published

Prisma middleware for validating data before creating or updating records

Downloads

43

Readme

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.

Build Status version MIT License semantic-release PRs Welcome

Table of Contents

Installation

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

Usage

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.

Usage with Zod

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),
      })
    ),
  })
);

Usage with Superstruct

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),
      })
    ),
  })
);

Behavior

Validated Operations

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",
        },
      },
    },
  },
});

Error Messages

The error thrown by the middleware is the error thrown by the validation function prefixed with information about the model and action that failed.

LICENSE

Apache 2.0