{"id":26600669,"url":"https://github.com/multipliedtwice/prisma-generator-express","last_synced_at":"2026-05-11T06:17:07.360Z","repository":{"id":239289656,"uuid":"799114569","full_name":"multipliedtwice/prisma-generator-express","owner":"multipliedtwice","description":"This tool automatically generates Express CRUD API that uses Prisma to handle database operations and validates responses with Zod schemas to ensure the integrity of input and output.","archived":false,"fork":false,"pushed_at":"2026-04-17T12:09:34.000Z","size":330907,"stargazers_count":29,"open_issues_count":7,"forks_count":6,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-04-17T14:17:20.653Z","etag":null,"topics":["api","api-rest","crud","express","generator","prisma"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/prisma-generator-express","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/multipliedtwice.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-05-11T08:13:23.000Z","updated_at":"2026-04-17T12:09:36.000Z","dependencies_parsed_at":"2025-04-09T16:39:45.366Z","dependency_job_id":null,"html_url":"https://github.com/multipliedtwice/prisma-generator-express","commit_stats":null,"previous_names":["multipliedtwice/prisma-generator-express"],"tags_count":52,"template":false,"template_full_name":null,"purl":"pkg:github/multipliedtwice/prisma-generator-express","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multipliedtwice%2Fprisma-generator-express","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multipliedtwice%2Fprisma-generator-express/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multipliedtwice%2Fprisma-generator-express/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multipliedtwice%2Fprisma-generator-express/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/multipliedtwice","download_url":"https://codeload.github.com/multipliedtwice/prisma-generator-express/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/multipliedtwice%2Fprisma-generator-express/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32005833,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T20:23:30.271Z","status":"online","status_checked_at":"2026-04-19T02:00:07.110Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-rest","crud","express","generator","prisma"],"created_at":"2025-03-23T18:33:07.812Z","updated_at":"2026-04-19T12:02:34.645Z","avatar_url":"https://github.com/multipliedtwice.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Prisma Generator Express\n\n[![npm version](https://badge.fury.io/js/prisma-generator-express.svg)](https://badge.fury.io/js/prisma-generator-express)\n[![npm](https://img.shields.io/npm/dt/prisma-generator-express.svg)](https://www.npmjs.com/package/prisma-generator-express)\n[![HitCount](https://hits.dwyl.com/multipliedtwice/prisma-generator-express.svg?style=flat)](http://hits.dwyl.com/multipliedtwice/prisma-generator-express)\n[![Coverage Status](https://codecov.io/github/multipliedtwice/prisma-generator-express/graph/badge.svg?token=TTJ30HVKB8)](https://codecov.io/github/multipliedtwice/prisma-generator-express)\n[![npm](https://img.shields.io/npm/l/prisma-generator-express.svg)](LICENSE)\n\nThis tool helps you quickly create API endpoints in your Express app using your Prisma models.\n\nExposes Prisma API to clients - all operations with database is available, including all relationships at any depth.\n\nWhen you run `npx prisma generate`, it will:\n\n- Generate service (CRUD) functions that you can import into your Express routes.\n- Create a router generator function that lets you select which routes to enable in your express app and which middlewares to apply.\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Basic Usage](#basic-usage)\n- [Router Generator Usage](#router-generator-usage)\n- [Request Object Properties](#request-object-properties)\n- [Router Schema](#router-schema)\n\n# Installation\n\nUsing npm:\n\n```bash\n npm install prisma-generator-express\n```\n\nUsing yarn:\n\n```bash\n yarn add prisma-generator-express\n```\n\n# Basic usage\n\n- Include this generator in your schema.prisma file:\n\n```prisma\ngenerator express {\n  provider = \"prisma-generator-express\"\n}\n```\n\n- Generate your middleware functions by running:\n\n```bash\n  npx prisma generate\n```\n\n- Attach Prisma instance\n\n```ts\nimport { PrismaClient } from '@prisma/client'\nimport express from 'express'\n\nconst prisma = new PrismaClient()\nconst app = express()\n\napp.use(express.json()) // for parsing application/json\n\n// Attach Prisma to every request\napp.use((req, res, next) =\u003e {\n  req.prisma = prisma\n  next()\n})\n```\n\n- Here’s how you can use a generated function in your Express app:\n\n```ts\nimport { UserFindUnique } from './generated/api/UserFindUnique' // Adjust the path as necessary\nimport { FindUniqueUserSchema } from './prisma-zod-generator/schemas/FindUniqueUser.schema' // Adjust the path as necessary\nimport { FindUniqueUserSchemaOutput } from './prisma-zod-generator/schemas/FindUniqueUserOutput.schema' // Adjust the path as necessary\n\n// move this to /helpers\nexport function validateQuery(schema: ZodSchema) {\n  return async (req: Request, res: Response, next: NextFunction) =\u003e {\n    try {\n      req.query = schema.parse(req.query)\n      next()\n    } catch (error) {\n      res.status(400).json({\n        error: 'Input Validation failed',\n        details: error.errors,\n      })\n    }\n  }\n}\n\napp.get(\n  '/user/:id',\n  validateQuery(FindUniqueUserSchema),\n  async (req, res, next) =\u003e {\n    // Attach generated Zod schema for output validation\n    req.outputValidation = FindUniqueUserOutput\n\n    // Use the generated middleware to handle the request\n    await UserFindUnique(req, res, next)\n  },\n)\n```\n\nThe `UserFindUnique` function will fetch the user details from the database, validate the output with Zod, and handle the API response.\n\n# Router generator usage\n\nThe library will create functions to generate routers per each model in schema. Each route can accept middleware that will be injected right before generated handler is invoked. You can use it to modify/remove/validate request payload. The output validation can be also attached to `req` object on this step.\n\n```ts\nimport express, { json } from 'express'\nimport type { Response, Request, NextFunction, RequestHandler } from 'express'\n\nimport { PrismaClient } from '../prisma/generated/client'\nimport { UserAccountRouter } from '../prisma/generated/express/UserAccount'\nimport { RouteConfig } from '~prisma/generated/express/routeConfig'\nimport { UserAccountFindFirstSchema } from '../prisma/generated/prisma-zod-generator/schemas'\n\nconst app = express()\n\nconst prisma = new PrismaClient()\n\n/**\n * Middleware to attach Prisma client instance to the request object.\n * This ensures that Prisma client is available in all subsequent middleware and route handlers.\n */\nconst addPrisma: RequestHandler = (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) =\u003e {\n  req.prisma = prisma\n  next()\n}\n\n/**\n * Run context-related operations or modify `req` properties to control the behavior of the route\n */\nconst beforeFindFirst: RequestHandler = (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) =\u003e {\n  req.passToNext = true\n  next()\n}\n\n/**\n * if `req.passToNext` is true, then the result of generated middleware\n * will be available in req.locals?.data for modifications\n */\nconst afterFindFirst: RequestHandler = (\n  req: Request,\n  res: Response,\n  next: NextFunction,\n) =\u003e {\n  console.log('req.locals?.data :\u003e\u003e ', req.locals?.data)\n  next()\n}\n\n/**\n * For generated route the middleware order will be as follows:\n * 1. Query parser (kicks in for GET requests)\n * 2. Custom middlewares: config.{method}.before[]\n * 3. Input validator middleware (Optional): config.{method}.input. For GET request validates `req.query`, for others - `req.body`\n * 4. Generated middleware\n * 5. Output validator middleware: config.{method}.input\n * 6. Custom middlewares: config.{method}.after[] (not available if req.passToNext is falsy)\n */\nconst userAccounRouterConfig: RouteConfig\u003cRequestHandler\u003e = {\n  FindFirst: {\n    before: [beforeFindFirst],\n    after: [afterFindFirst],\n    input: {\n      schema: UserAccountFindFirstSchema, // make sure you set `isGenerateSelect = true` in prisma-zod-generator\n      allow: [\n        'select.id',\n        'select.full_name',\n        'select.emailAddress',\n        'select.orders[].ProductName',\n        'select.orders[].quantity',\n        'where.id',\n        'where.createdAt',\n      ],\n    },\n  },\n  addModelPrefix: true,\n  enableAll: true,\n  customUrlPrefix: '/v1',\n}\n\napp.use(addPrisma)\napp.use(UserAccountRouter(userAccounRouterConfig))\n\napp.listen(3000, () =\u003e {\n  console.log('Server is running on http://localhost:3000')\n})\n```\n\n## Request Object Properties\n\nThe following properties can be attached to the `req` object to control the behavior of generated middleware:\n\n| Property               | Type         | Description                                                                                                                     |\n| ---------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------- |\n| `prisma`               | PrismaClient | An instance of PrismaClient that allows the middleware to interact with your database.                                          |\n| `passToNext`           | boolean      | Optional, if `true` - the result of a Prisma request will be passed to the next middleware as `if (req.locals) req.locals.data` |\n| `outputValidation`     | ZodTypeAny   | (Optional) A Zod schema used to validate the data returned from the Prisma query before sending it to the client.               |\n\n## Router Schema\n\n| Function     | Method   | URL          |\n| ------------ | -------- | ------------ |\n| `findUnique` | `GET`    | `/:id`       |\n| `findFirst`  | `GET`    | `/first`     |\n| `findMany`   | `GET`    | `/`          |\n| `aggregate`  | `GET`    | `/aggregate` |\n| `count`      | `GET`    | `/count`     |\n| `groupBy`    | `GET`    | `/groupby`   |\n| `create`     | `POST`   | `/`          |\n| `createMany` | `POST`   | `/many`      |\n| `update`     | `PUT`    | `/`          |\n| `updateMany` | `PUT`    | `/many`      |\n| `upsert`     | `PATCH`  | `/`          |\n| `delete`     | `DELETE` | `/`          |\n| `deleteMany` | `DELETE` | `/many`      |\n\n## Skip generation\n\n```prisma\n/// generator off\nmodel UserAccount {\n  ID           Int         @id @default(autoincrement())\n  full_name    String\n  emailAddress String      @unique\n  createdAt    DateTime    @default(now())\n  orders       orderItem[]\n}\n```\n\n## Helper functions\n\n### createValidatorMiddleware(validatorOptions: ValidatorOptions)\n\nSimple wrapper that internally uses `allow` or `forbid` logic for filtering incoming queries and data payloads. Helps to make sure that schemas from `prisma-zod-generator` is not too permissive.\n\n```ts\ninterface ValidatorOptions {\n  schema: ZodSchema\u003cany\u003e\n  allowedPaths?: string[] // Fobids all except allowed. For example [`where.user.id`, `select.id`], all other provided inputs will throw an error\n  forbiddenPaths?: string[] // Similar, but allows all, except forbidden\n  target?: 'body' | 'query'\n}\n```\n\n### encodeQueryParams(params: Params)\n\nIt can be used on the frontend to encode Prisma-compatible queries. Alternatively `qs` can be used, but it probably won't work with `OR: [{ blah: false }, { blah: null }]` or some other edge cases.\n\n```ts\ntype RecursiveUrlParams = {\n  [key: string]: RecursiveUrlParams | string | boolean | unknown\n}\ntype Params = Record\u003cstring, RecursiveUrlParams | string\u003e\n```\n\n### parseQueryParams(params: QueryParams)\n\n```ts\ntype QueryParams = string | ParsedQs | string[] | ParsedQs[] | undefined\n```\n\nRecursively converts strings \"true\", \"false\", \"null\", and \"number\" into correct formats.\n\n### allow\u003cT extends z.ZodTypeAny\u003e( schema: T, allowedPaths: string[] ): ZodEffects\u003cT, any, any\u003e\n\nAccepts schema and `['array.of.allowed.paths']`. Throws an error if provided something that doesn't fit allowed schema.\n\n### forbid\u003cT extends z.ZodTypeAny\u003e( schema: T, forbiddenPaths: string[] ): ZodEffects\u003cT, any, any\u003e\n\nSame as `allow` but works in opposite way.\n\n---\n\n#### Credits:\n- Super Kick Gym - [Brazilian Jiu Jitsu in Bangkok](https://en.bjj-bangkok.com)\n\n- Rememo - [Free Task Management and Corporate Chat](https://rememo.io)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmultipliedtwice%2Fprisma-generator-express","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmultipliedtwice%2Fprisma-generator-express","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmultipliedtwice%2Fprisma-generator-express/lists"}