prisma-generator-express 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -0
  3. package/package.json +1 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 multipliedtwice
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,179 @@
1
+ # Prisma Generator Express
2
+
3
+ [![npm version](https://badge.fury.io/js/prisma-generator-express.svg)](https://badge.fury.io/js/prisma-generator-express)
4
+ [![npm](https://img.shields.io/npm/dt/prisma-generator-express.svg)](https://www.npmjs.com/package/prisma-generator-express)
5
+ [![HitCount](https://hits.dwyl.com/multipliedtwice/prisma-generator-express.svg?style=flat)](http://hits.dwyl.com/multipliedtwice/prisma-generator-express)
6
+ [![npm](https://img.shields.io/npm/l/prisma-generator-express.svg)](LICENSE)
7
+
8
+ This tool helps you quickly create API endpoints in your Express app using your Prisma models.
9
+
10
+ When you run `npx prisma generate`, it automatically creates two things:
11
+
12
+ - Service functions that you can import into your Express routes. By default these functions handle CRUD operations and output validation. This behavior can be controlled.
13
+ - Router generator function that lets you select which routes to add to the application and which middlewares to apply.
14
+
15
+ ## Table of Contents
16
+
17
+ - [Installation](#installation)
18
+ - [Usage](#usage)
19
+ - [Customizations](#customizations)
20
+ - [Request Object Properties](#request-object-properties)
21
+
22
+ # Installation
23
+
24
+ Using npm:
25
+
26
+ ```bash
27
+ npm install prisma-generator-express
28
+ ```
29
+
30
+ Using yarn:
31
+
32
+ ```bash
33
+ yarn add prisma-generator-express
34
+ ```
35
+
36
+ # Basic usage
37
+
38
+ - Include this generator in your schema.prisma file:
39
+
40
+ ```prisma
41
+ generator express {
42
+ provider = "prisma-generator-express"
43
+ }
44
+ ```
45
+
46
+ - Generate your middleware functions by running:
47
+
48
+ ```bash
49
+ npx prisma generate
50
+ ```
51
+
52
+ - Attach Prisma instance
53
+
54
+ ```ts
55
+ import { PrismaClient } from '@prisma/client'
56
+ import express from 'express'
57
+
58
+ const prisma = new PrismaClient()
59
+ const app = express()
60
+
61
+ app.use(express.json()) // for parsing application/json
62
+
63
+ // Attach Prisma to every request
64
+ app.use((req, res, next) => {
65
+ req.prisma = prisma
66
+ next()
67
+ })
68
+ ```
69
+
70
+ - Here’s how you can use a generated function in your Express app:
71
+
72
+ ```ts
73
+ import { UserFindUnique } from './generated/UserFindUnique' // Adjust the path as necessary
74
+ import { FindUniqueUserSchema } from './prisma-zod-generator/schemas/FindUniqueUser.schema' // Adjust the path as necessary
75
+ import { FindUniqueUserSchemaOutput } from './prisma-zod-generator/schemas/FindUniqueUserOutput.schema' // Adjust the path as necessary
76
+
77
+ // move this to /helpers
78
+ export function validateQuery(schema: ZodSchema) {
79
+ return async (req: Request, res: Response, next: NextFunction) => {
80
+ try {
81
+ req.query = schema.parse(req.query)
82
+ next()
83
+ } catch (error) {
84
+ res.status(400).json({
85
+ error: 'Input Validation failed',
86
+ details: error.errors,
87
+ })
88
+ }
89
+ }
90
+ }
91
+
92
+ app.get(
93
+ '/user/:id',
94
+ validateQuery(FindUniqueUserSchema),
95
+ async (req, res, next) => {
96
+ // Attach generated Zod schema for output validation
97
+ req.outputValidation = FindUniqueUserOutput
98
+
99
+ // Use the generated middleware to handle the request
100
+ await UserFindUnique(req, res, next)
101
+ },
102
+ )
103
+ ```
104
+
105
+ The `UserFindUnique` function will fetch the user details from the database, validate the output with Zod, and handle the API response.
106
+
107
+ # Router generator usage
108
+
109
+ The 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.
110
+
111
+ ```ts
112
+ import express from 'express'
113
+ import { UserRouter } from './path/to/generated/UserRouter' // Adjust the path as necessary
114
+ import { UserFindManyArgs } from './prisma-zod-generator/schemas/UserFindManyArgs.schema' // Adjust the path as necessary
115
+
116
+ const app = express()
117
+
118
+ export const validateUserQuery = (
119
+ req: Request,
120
+ res: Response,
121
+ next: NextFunction,
122
+ ) => {
123
+ try {
124
+ UserFindManyArgs.parse(req.query)
125
+ next()
126
+ } catch (error) {
127
+ if (error instanceof ZodError) {
128
+ return res.status(400).json({
129
+ message: 'Validation failed',
130
+ errors: error.errors,
131
+ })
132
+ }
133
+ next(error)
134
+ }
135
+ }
136
+
137
+ const userRouterConfig = {
138
+ findManyMiddleware: [validateUserQuery], // Add other middleware as needed
139
+ findUniqueMiddleware: undefined, // This can be omitted, route won't be generated if middleware is not provided
140
+ }
141
+
142
+ // Use the router in your application
143
+ app.use('/users', UserRouter(userRouterConfig))
144
+
145
+ app.listen(3000, () => {
146
+ console.log('Server is running on http://localhost:3000')
147
+ })
148
+ ```
149
+
150
+ ## Request Object Properties
151
+
152
+ The following properties can be attached to the `req` object to control the behavior of generated middleware:
153
+
154
+ | Property | Type | Description |
155
+ | ---------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
156
+ | `prisma` | PrismaClient | An instance of PrismaClient that allows the middleware to interact with your database. |
157
+ | `passToNext` | boolean | Optional, if `true` - the result of a Prisma request will be passed to a next middleware as `req.locals.data` |
158
+ | `query` | Object | A structured object that conforms to Prisma's API for the selected method. |
159
+ | `outputValidation` | ZodTypeAny | (Optional) A Zod schema used to validate the data returned from the Prisma query before sending it to the client. This helps ensure the response adheres to expected data formats. |
160
+ | `omitOutputValidation` | Boolean | (Optional) A flag that, if set to `true`, disables output validation even if a Zod schema is provided. |
161
+
162
+ ## Roadmap
163
+
164
+ | Function | Supported | Notes |
165
+ | -------------- | ------------------ | ---------- |
166
+ | `Model router` | :white_check_mark: | Available. |
167
+ | `findUnique` | :white_check_mark: | Available. |
168
+ | `findFirst` | :white_check_mark: | Available. |
169
+ | `findMany` | :white_check_mark: | Available. |
170
+ | `create` | :white_check_mark: | Available. |
171
+ | `createMany` | :white_check_mark: | Available. |
172
+ | `update` | :white_check_mark: | Available. |
173
+ | `updateMany` | :white_check_mark: | Available. |
174
+ | `upsert` | :white_check_mark: | Available. |
175
+ | `delete` | :white_check_mark: | Available. |
176
+ | `deleteMany` | :white_check_mark: | Available. |
177
+ | `aggregate` | :white_check_mark: | Available. |
178
+ | `count` | :white_check_mark: | Available. |
179
+ | `groupBy` | :white_check_mark: | Available. |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "prisma-generator-express",
3
3
  "description": "Prisma generator of Express CRUD API",
4
- "version": "1.0.0",
4
+ "version": "1.0.2",
5
5
  "main": "dist/generator.js",
6
6
  "license": "MIT",
7
7
  "bin": {