@wokcito/prisma-generator-pothos-codegen 1.0.0

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 (78) hide show
  1. package/README.md +416 -0
  2. package/package.json +76 -0
  3. package/src/bin.d.ts +2 -0
  4. package/src/bin.js +5 -0
  5. package/src/bin.js.map +1 -0
  6. package/src/crudGenerator/index.d.ts +3 -0
  7. package/src/crudGenerator/index.js +96 -0
  8. package/src/crudGenerator/index.js.map +1 -0
  9. package/src/crudGenerator/templates/mutation.d.ts +9 -0
  10. package/src/crudGenerator/templates/mutation.js +59 -0
  11. package/src/crudGenerator/templates/mutation.js.map +1 -0
  12. package/src/crudGenerator/templates/object.d.ts +4 -0
  13. package/src/crudGenerator/templates/object.js +59 -0
  14. package/src/crudGenerator/templates/object.js.map +1 -0
  15. package/src/crudGenerator/templates/query.d.ts +6 -0
  16. package/src/crudGenerator/templates/query.js +37 -0
  17. package/src/crudGenerator/templates/query.js.map +1 -0
  18. package/src/crudGenerator/templates/resolver.d.ts +2 -0
  19. package/src/crudGenerator/templates/resolver.js +35 -0
  20. package/src/crudGenerator/templates/resolver.js.map +1 -0
  21. package/src/crudGenerator/templates/root.d.ts +20 -0
  22. package/src/crudGenerator/templates/root.js +305 -0
  23. package/src/crudGenerator/templates/root.js.map +1 -0
  24. package/src/crudGenerator/utils/generator.d.ts +10 -0
  25. package/src/crudGenerator/utils/generator.js +20 -0
  26. package/src/crudGenerator/utils/generator.js.map +1 -0
  27. package/src/crudGenerator/utils/objectFields.d.ts +7 -0
  28. package/src/crudGenerator/utils/objectFields.js +58 -0
  29. package/src/crudGenerator/utils/objectFields.js.map +1 -0
  30. package/src/crudGenerator/utils/parts.d.ts +25 -0
  31. package/src/crudGenerator/utils/parts.js +132 -0
  32. package/src/crudGenerator/utils/parts.js.map +1 -0
  33. package/src/env.d.ts +3 -0
  34. package/src/env.js +7 -0
  35. package/src/env.js.map +1 -0
  36. package/src/generator.d.ts +6 -0
  37. package/src/generator.js +22 -0
  38. package/src/generator.js.map +1 -0
  39. package/src/index.d.ts +2 -0
  40. package/src/index.js +3 -0
  41. package/src/index.js.map +1 -0
  42. package/src/inputsGenerator/index.d.ts +34 -0
  43. package/src/inputsGenerator/index.js +19 -0
  44. package/src/inputsGenerator/index.js.map +1 -0
  45. package/src/inputsGenerator/utils/dmmf.d.ts +20 -0
  46. package/src/inputsGenerator/utils/dmmf.js +113 -0
  47. package/src/inputsGenerator/utils/dmmf.js.map +1 -0
  48. package/src/inputsGenerator/utils/inputFields.d.ts +4 -0
  49. package/src/inputsGenerator/utils/inputFields.js +74 -0
  50. package/src/inputsGenerator/utils/inputFields.js.map +1 -0
  51. package/src/inputsGenerator/utils/parser.d.ts +5 -0
  52. package/src/inputsGenerator/utils/parser.js +23 -0
  53. package/src/inputsGenerator/utils/parser.js.map +1 -0
  54. package/src/inputsGenerator/utils/parts.d.ts +7 -0
  55. package/src/inputsGenerator/utils/parts.js +158 -0
  56. package/src/inputsGenerator/utils/parts.js.map +1 -0
  57. package/src/inputsGenerator/utils/templates.d.ts +8 -0
  58. package/src/inputsGenerator/utils/templates.js +60 -0
  59. package/src/inputsGenerator/utils/templates.js.map +1 -0
  60. package/src/utils/config.d.ts +85 -0
  61. package/src/utils/config.js +113 -0
  62. package/src/utils/config.js.map +1 -0
  63. package/src/utils/configUtils.d.ts +2 -0
  64. package/src/utils/configUtils.js +9 -0
  65. package/src/utils/configUtils.js.map +1 -0
  66. package/src/utils/filesystem.d.ts +7 -0
  67. package/src/utils/filesystem.js +38 -0
  68. package/src/utils/filesystem.js.map +1 -0
  69. package/src/utils/replacer.d.ts +4 -0
  70. package/src/utils/replacer.js +3 -0
  71. package/src/utils/replacer.js.map +1 -0
  72. package/src/utils/string.d.ts +4 -0
  73. package/src/utils/string.js +18 -0
  74. package/src/utils/string.js.map +1 -0
  75. package/src/utils/template.d.ts +3 -0
  76. package/src/utils/template.js +13 -0
  77. package/src/utils/template.js.map +1 -0
  78. package/tsconfig.tsbuildinfo +1 -0
package/README.md ADDED
@@ -0,0 +1,416 @@
1
+ # Prisma Generator Pothos Codegen
2
+
3
+ ![Group 1](https://github.com/Cauen/prisma-generator-pothos-codegen/assets/8796757/19f6cdbe-44f5-40ac-8b9b-326c49c1c281)
4
+
5
+ A [prisma](https://www.prisma.io/) [generator](https://www.prisma.io/docs/concepts/components/prisma-schema/generators) plugin that auto-generates [Pothos](https://pothos-graphql.dev/) GraphQL input types and crud operations (all queries and mutations).
6
+
7
+ Easily convert a prisma schema into a full graphql CRUD API.
8
+
9
+ On `prisma generate` we create:
10
+
11
+ - All [input types](https://pothos-graphql.dev/docs/guide/inputs) for `Create`, `Find`, `Update`, `Sort` and `Delete` operations (to be used as args in [fields](https://pothos-graphql.dev/docs/guide/fields#arguments)).
12
+ - (Optional): Create all `Objects`, `Queries` and `Mutations` base files (to create customizable resolvers).
13
+ - (Optional): Execute all these base files without customization to create a default CRUD.
14
+
15
+ ## Table of Contents
16
+
17
+ <!-- toc -->
18
+
19
+ - [Getting Started](#getting-started)
20
+ * [Install](#install)
21
+ * [Peer dependencies](#peer-dependencies)
22
+ * [Set Up](#set-up)
23
+ + [Add the generator to your schema.prisma](#add-the-generator-to-your-schemaprisma)
24
+ + [Add scalar types to the builder](#add-scalar-types-to-the-builder)
25
+ + [Create a configuration file (optional)](#create-a-configuration-file--optional-)
26
+ + [Run the generator](#run-the-generator)
27
+ - [Usage](#usage)
28
+ * [Inputs](#inputs)
29
+ * [Objects](#objects)
30
+ * [Queries and Mutations](#queries-and-mutations)
31
+ * [Auto define all `objects`, `queries` and `mutations` (crud operations)](#auto-define-all--objects----queries--and--mutations---crud-operations-)
32
+ * [Examples](#examples)
33
+ - [Disclosures](#disclosures)
34
+ * [Models with only relations](#models-with-only-relations)
35
+ * [BigInt rename](#bigint-rename)
36
+
37
+ <!-- tocstop -->
38
+
39
+ ## Getting Started
40
+
41
+ ### Install
42
+
43
+ Using yarn
44
+
45
+ ```sh
46
+ yarn add -D prisma-generator-pothos-codegen
47
+ ```
48
+
49
+ or using npm
50
+
51
+ ```sh
52
+ npm install --save-dev prisma-generator-pothos-codegen
53
+ ```
54
+
55
+ ### Peer dependencies
56
+
57
+ The package has been developed and tested up to the following peer dependencies (see updated [example](/examples/inputs-simple-sqlite)):
58
+
59
+ <!-- TODO Maybe we could have some sort of automated pipeline that tests different versions of these peer deps? -->
60
+
61
+ ```
62
+ "@pothos/core": "^4.0.2",
63
+ "@pothos/plugin-prisma": "^4.0.3"",
64
+ "@prisma/client": "^7.10.0",
65
+ "prisma": "^7.10.0",
66
+ ```
67
+
68
+ Using higher versions may break something. In these cases, please open a new issue.
69
+
70
+ ### Set Up
71
+
72
+ #### Add the generator to your schema.prisma
73
+
74
+ ```prisma
75
+ generator client {
76
+ provider = "prisma-client-js"
77
+ // Optional. If you set a custom `output` here (recommended since Prisma 7, as the new
78
+ // "prisma-client" provider requires it), also set a matching `clientOutput` on the `pothos`
79
+ // generator below. See the updated example for a full working setup with a custom output.
80
+ }
81
+
82
+ generator pothos {
83
+ provider = "prisma-pothos-types"
84
+ // Recent @pothos/plugin-prisma versions need the full datamodel (with unique indexes, etc.) at
85
+ // runtime, which Prisma 7's client no longer embeds. `generateDatamodel` emits a `getDatamodel()`
86
+ // function you must pass to the builder (see below) — but its implementation is only emitted
87
+ // when `output` is a plain `.ts` file (not `.d.ts`), so use a `.ts` extension here.
88
+ output = "./pothos-types.ts"
89
+ generateDatamodel = "true"
90
+ }
91
+
92
+ generator pothosCrud {
93
+ provider = "prisma-generator-pothos-codegen"
94
+ generatorConfigPath = "./pothos.config.js"
95
+ // You may also set the `generatorConfigPath` via the `POTHOS_CRUD_CONFIG_PATH` environment variable.
96
+ // The environment variable will override the path hardcoded here.
97
+ }
98
+
99
+ /// This is a user!
100
+ model User {
101
+ /// This is an id!
102
+ id String @id
103
+ }
104
+ ```
105
+
106
+ #### Add scalar types to the builder
107
+
108
+ ```ts
109
+ import SchemaBuilder from '@pothos/core';
110
+ import PrismaPlugin from '@pothos/plugin-prisma';
111
+ import { Scalars } from 'prisma-generator-pothos-codegen';
112
+ // Import from your Prisma Client `output` path (the `.prisma/client` default location is no
113
+ // longer generated since Prisma 7 when a custom `output` is set).
114
+ import { Prisma } from './generated/prisma';
115
+ import { db } from './db';
116
+ import PrismaTypes, { getDatamodel } from './pothos-types';
117
+
118
+ export const builder = new SchemaBuilder<{
119
+ // ... Context ...
120
+ PrismaTypes: PrismaTypes; // required for @pothos/plugin-prisma integration (which is required)
121
+ Scalars: Scalars<Prisma.Decimal, Prisma.InputJsonValue | null, Prisma.InputJsonValue>; // required to define correct types for created scalars.
122
+ }>({
123
+ plugins: [PrismaPlugin],
124
+ prisma: {
125
+ client: db,
126
+ // Required by recent @pothos/plugin-prisma versions (see `generateDatamodel` above) —
127
+ // do NOT use `Prisma.dmmf`, it's missing fields (like unique indexes) since Prisma 7.
128
+ dmmf: getDatamodel(),
129
+ },
130
+ });
131
+ ```
132
+
133
+ #### Create a configuration file (optional)
134
+
135
+ ```js
136
+ // ./pothos.config.js
137
+
138
+ /** @type {import('prisma-generator-pothos-codegen').Config} */
139
+ module.exports = {
140
+ inputs: {
141
+ outputFilePath: './src/graphql/__generated__/inputs.ts',
142
+ },
143
+ crud: {
144
+ outputDir: './src/graphql/__generated__/',
145
+ inputsImporter: `import * as Inputs from '@graphql/__generated__/inputs';`,
146
+ resolverImports: `import prisma from '@lib/prisma';`,
147
+ prismaCaller: 'prisma',
148
+ },
149
+ global: {
150
+ },
151
+ };
152
+ ```
153
+
154
+ <details>
155
+ <summary>Click to see all configuration options</summary>
156
+
157
+ ```ts
158
+ {
159
+ /** Input type generation config */
160
+ inputs?: {
161
+ /** Create simpler inputs for easier customization and ~65% less generated code. Default: `false` */
162
+ simple?: boolean;
163
+ /** How to import the Prisma namespace. Default: `"import { Prisma } from '.prisma/client';"` */
164
+ prismaImporter?: string;
165
+ /** Path to generate the inputs file to from project root. Default: `'./generated/inputs.ts'` */
166
+ outputFilePath?: string;
167
+ /** List of excluded scalars from generated output */
168
+ excludeScalars?: string[];
169
+ /** A function to replace generated source. Combined with global replacer config */
170
+ replacer?: Replacer<'inputs'>;
171
+ /** Map all Prisma fields with "@id" attribute to Graphql "ID" Scalar.
172
+ *
173
+ * ATTENTION: Mapping non String requires a conversion inside resolver, once GraphQl ID Input are coerced to String by definition. Default: false */
174
+ mapIdFieldsToGraphqlId?: false | 'WhereUniqueInputs';
175
+ };
176
+ /** CRUD generation config */
177
+ crud?: {
178
+ /** Disable generaton of crud. Default: `false` */
179
+ disabled?: boolean;
180
+ /** How to import the inputs. Default `"import * as Inputs from '../inputs';"` */
181
+ inputsImporter?: string;
182
+ /** How to import the Prisma namespace at the objects.ts file. Default `"import { Prisma } from '.prisma/client';"`. Please use "resolverImports" to import prismaClient at resolvers. */
183
+ prismaImporter?: string;
184
+ /** How to call the prisma client. Default `'_context.prisma'` */
185
+ prismaCaller?: string;
186
+ /** Any additional imports you might want to add to the resolvers (e.g. your prisma client). Default: `''` */
187
+ resolverImports?: string;
188
+ /** Directory to generate crud code into from project root. Default: `'./generated'` */
189
+ outputDir?: string;
190
+ /** A function to replace generated source. Combined with global replacer config */
191
+ replacer?: Replacer<'crud'>;
192
+ /** A boolean to enable/disable generation of `autocrud.ts` which can be imported in schema root to auto generate all crud objects, queries and mutations. Default: `true` */
193
+ generateAutocrud?: boolean;
194
+ /** An array of parts of resolver names to be excluded from generation. Ie: ["User"] Default: [] */
195
+ excludeResolversContain?: string[];
196
+ /** An array of resolver names to be excluded from generation. Ie: ["upsertOneComment"] Default: [] */
197
+ excludeResolversExact?: string[];
198
+ /** An array of parts of resolver names to be included from generation (to bypass exclude contain). Ie: if exclude ["User"], include ["UserReputation"] Default: [] */
199
+ includeResolversContain?: string[];
200
+ /** An array of resolver names to be included from generation (to bypass exclude contain). Ie: if exclude ["User"], include ["UserReputation"] Default: [] */
201
+ includeResolversExact?: string[];
202
+ /** Caution: This delete the whole folder (Only use if the folder only has auto generated contents). A boolean to delete output dir before generate. Default: False */
203
+ deleteOutputDirBeforeGenerate?: boolean;
204
+ /** Export all crud queries/mutations/objects in objects.ts at root dir. Default: true */
205
+ exportEverythingInObjectsDotTs?: boolean;
206
+ /** Map all Prisma fields with "@id" attribute to Graphql "ID" Scalar. Default: 'Objects' */
207
+ mapIdFieldsToGraphqlId?: false | 'Objects';
208
+ /** Change the generated variables from object.base.ts from something like `UserName` to `User_Name`. This avoids generated duplicated names in some cases. See [issue #58](https://github.com/Cauen/prisma-generator-pothos-codegen/issues/58). Default: false */
209
+ underscoreBetweenObjectVariableNames?: false | 'Objects';
210
+ };
211
+ /** Global config */
212
+ global?: {
213
+ /** A function to replace generated source */
214
+ replacer?: Replacer;
215
+ /** Location of builder to replace in all files. Relative to package root. ie: './src/schema/builder'. Default: './builder' */
216
+ builderLocation?: string;
217
+ /** Run function before generate */
218
+ beforeGenerate?: (dmmf: DMMF.Document) => void;
219
+ /** Run function after generate */
220
+ afterGenerate?: (dmmf: DMMF.Document) => void;
221
+ };
222
+ }
223
+ ```
224
+ </details>
225
+ <br/>
226
+
227
+ #### Run the generator
228
+
229
+ ```sh
230
+ yarn prisma generate
231
+ ```
232
+
233
+ or
234
+
235
+ ```sh
236
+ npx prisma generate
237
+ ```
238
+
239
+ ## Usage
240
+
241
+ ### Inputs
242
+
243
+ You can use `@Pothos.omit()` function calls in your prisma schema field descriptions to control which fields are used in the generated input types.
244
+
245
+ - `@Pothos.omit()` Omits the field from all inputs
246
+ - `@Pothos.omit(create)` Omits field from the create input
247
+ - `@Pothos.omit(orderBy, where, update)` Omits field from the orderBy, where, and update inputs, but not the create input
248
+
249
+ The available options are `create`, `update`, `where`, and `orderBy`.
250
+
251
+ ```prisma
252
+ model User {
253
+ /// @Pothos.omit(create, update)
254
+ id String @id @default(uuid())
255
+ email String
256
+ /// @Pothos.omit()
257
+ password String
258
+ }
259
+ ```
260
+
261
+ You can also augment/derive new inputs from the generated `inputs.ts` file.
262
+
263
+ ```ts
264
+ // ./src/graphql/User/inputs.ts
265
+
266
+ import { Prisma } from '@prisma/client';
267
+ // Import generated input fields definition
268
+ import { UserUpdateInputFields } from '@/graphql/__generated__/inputs';
269
+
270
+ // Note: you can't use `builder.inputType` to generate this new input
271
+ export const UserUpdateInputCustom = builder
272
+ .inputRef<Prisma.UserUpdateInput & { customArg: string }>('UserUpdateInputCustom')
273
+ .implement({
274
+ fields: (t) => ({
275
+ ...UserUpdateInputFields(t),
276
+ customArg: t.field({ required: true, type: 'String' }),
277
+ }),
278
+ });
279
+ ```
280
+
281
+ ### Objects
282
+
283
+ ```ts
284
+ // ./src/graphql/User/object.ts
285
+
286
+ import { UserObject } from '@/graphql/__generated__/User';
287
+ import { builder } from '@/graphql/builder'; // Pothos schema builder
288
+
289
+ // Use the Object export to accept all default generated query code
290
+ builder.prismaObject('User', UserObject);
291
+
292
+ // Or modify it as you wish
293
+ builder.prismaObject('User', {
294
+ ...UserObject,
295
+ fields: (t) => {
296
+ // Type-safely omit and rename fields
297
+ const { password: _password, email: emailAddress, ...fields } = UserObject.fields(t);
298
+ const sessionsField = UserSessionsFieldObject(t);
299
+
300
+ return {
301
+ ...fields,
302
+ // Renamed field
303
+ emailAddress,
304
+ // Edit and extend field
305
+ sessions: t.relation('sessions', {
306
+ ...sessionsField,
307
+ args: { ...sessionsField.args, customArg: t.arg({ type: 'String', required: false }) },
308
+ authScopes: { admin: true },
309
+ }),
310
+ // Add custom fields
311
+ customField: t.field({ type: 'String', resolve: () => 'Hello world!' }),
312
+ };
313
+ },
314
+ });
315
+ ```
316
+
317
+ ### Queries and Mutations
318
+
319
+ ```ts
320
+ // ./src/graphql/User/query.ts
321
+
322
+ import { findManyUserQuery, findManyUserQueryObject } from '@/graphql/__generated__/User';
323
+ import { builder } from '@/graphql/builder'; // Pothos schema builder
324
+
325
+ // Use the Query exports to accept all default generated query code
326
+ builder.queryFields(findManyUserQuery);
327
+
328
+ // Use the QueryObject exports to override or add to the generated code
329
+ builder.queryFields((t) => {
330
+ const field = findManyUserQueryObject(t);
331
+ return {
332
+ findManyUser: t.prismaField({
333
+ // Inherit all the generated properties
334
+ ...field,
335
+
336
+ // Modify the args and use custom arg in a custom resolver
337
+ args: { ...field.args, customArg: t.arg({ type: 'String', required: false }) },
338
+ resolve: async (query, root, args, context, info) => {
339
+ const { customArg } = args;
340
+ console.log(customArg);
341
+ return field.resolve(query, root, args, context, info);
342
+ },
343
+
344
+ // Add an custom extension
345
+ authScopes: { admin: true },
346
+ }),
347
+ };
348
+ });
349
+ ```
350
+
351
+ ### Auto define all `objects`, `queries` and `mutations` (crud operations)
352
+
353
+ First, make sure that `options.crud.generateAutocrud` isn't set to `false`
354
+
355
+ ```ts
356
+ // ./src/schema/index.ts (import autocrud.ts)
357
+ import {
358
+ generateAllCrud,
359
+ generateAllObjects,
360
+ generateAllQueries,
361
+ generateAllMutations
362
+ } from '@/graphql/__generated__/autocrud.ts',
363
+ import { builder } from '@/graphql/builder'; // Pothos schema builder
364
+
365
+ // (option 1) generate all objects, queries and mutations
366
+ generateAllCrud()
367
+
368
+ // (option 2) or create them separately
369
+ generateAllObjects()
370
+ generateAllQueries()
371
+ generateAllMutations()
372
+
373
+ // (option 3) or limit crud generation
374
+ generateAllObjects({ include: ["User", "Profile", 'Comment'] })
375
+ generateAllQueries({ exclude: ["Comment"] })
376
+ generateAllMutations({ exclude: ["User"] })
377
+
378
+ // Defining schema roots
379
+ builder.queryType({});
380
+ builder.mutationType({});
381
+
382
+ export const schema = builder.toSchema({});
383
+ ```
384
+
385
+ Generated queries:
386
+
387
+ - count
388
+ - findFirst
389
+ - findMany
390
+ - findUnique
391
+
392
+ Generated mutations:
393
+
394
+ - createMany
395
+ - createOne
396
+ - deleteMany
397
+ - deleteOne
398
+ - updateMany
399
+ - updateOne
400
+ - upsertOne
401
+
402
+ ### Examples
403
+
404
+ Check for the [example](/examples/inputs-simple-sqlite) for a running sample
405
+
406
+ ![image](https://user-images.githubusercontent.com/8796757/222917186-9a88f5e9-27c6-44b5-8653-fa9efb0aa255.png)
407
+
408
+ ## Disclosures
409
+
410
+ ### Models with only relations
411
+
412
+ - We create a custom scalar `NEVER` that avoids this error: `Input Object type FollowUpdateManyMutationInput must define one or more fields.` from Graphql. if you have models that are relations-only. Like N-N fields without `no relation fields` or id-only models, we set field `_` of some operations to this scalar. If you fill this fake property, the operation will result in a error.
413
+
414
+ ### BigInt rename
415
+
416
+ - As `BigInt` is reserved, we export `Bigint` for the BigInt scalar.
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@wokcito/prisma-generator-pothos-codegen",
3
+ "version": "1.0.0",
4
+ "license": "MIT",
5
+ "description": "A prisma generator that generate input types for Pothos. And optionally generate all crud.",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
8
+ "module": "./src/index.js",
9
+ "exports": {
10
+ "import": "./src/index.js",
11
+ "require": "./src/index.js"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/wokcito/prisma-generator-pothos-codegen.git"
16
+ },
17
+ "author": "Maximiliano Kazanski",
18
+ "keywords": [
19
+ "pothos",
20
+ "graphql",
21
+ "typescript",
22
+ "prisma",
23
+ "db",
24
+ "postgres",
25
+ "codegen"
26
+ ],
27
+ "scripts": {
28
+ "test": "jest",
29
+ "build": "tsc",
30
+ "tscheck": "tsc -noEmit",
31
+ "prebuild": "bun run clean",
32
+ "postbuild": "shx cp ./README.md ./dist && shx chmod +x ./dist/src/bin.js",
33
+ "clean": "shx rm -rf dist",
34
+ "pub": "cd dist && npm publish",
35
+ "format": "eslint --fix ./src",
36
+ "check-src-and-examples": "bun run test && bun run tscheck && cd examples/inputs-simple-sqlite && bun run generate && bun run tscheck",
37
+ "fullcheck": "bun run check-src-and-examples"
38
+ },
39
+ "bin": {
40
+ "prisma-generator-pothos-codegen": "./src/bin.js"
41
+ },
42
+ "peerDependencies": {
43
+ "@pothos/core": "^4.0.2",
44
+ "@pothos/plugin-prisma": "^4.0.3",
45
+ "@prisma/client": "^7.10.0",
46
+ "prisma": "^7.10.0"
47
+ },
48
+ "engines": {
49
+ "node": ">=20.19.0"
50
+ },
51
+ "devDependencies": {
52
+ "@eslint/eslintrc": "3.3.7",
53
+ "@prisma/internals": "7.10.0",
54
+ "@types/jest": "30.0.0",
55
+ "@types/node": "22.20.2",
56
+ "@typescript-eslint/eslint-plugin": "8.70.0",
57
+ "@typescript-eslint/parser": "8.70.0",
58
+ "eslint": "10.10.0",
59
+ "eslint-config-prettier": "10.1.8",
60
+ "eslint-config-standard": "17.1.0",
61
+ "eslint-plugin-import": "2.32.0",
62
+ "eslint-plugin-n": "18.3.0",
63
+ "eslint-plugin-prettier": "5.5.6",
64
+ "eslint-plugin-promise": "7.3.0",
65
+ "jest": "30.5.1",
66
+ "prettier": "3.9.6",
67
+ "shx": "0.4.0",
68
+ "ts-jest": "29.4.12",
69
+ "ts-node": "10.9.2",
70
+ "typescript": "5.9.3"
71
+ },
72
+ "dependencies": {
73
+ "@prisma/generator-helper": "7.10.0"
74
+ },
75
+ "packageManager": "bun@1.4.2"
76
+ }
package/src/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import './generator';
package/src/bin.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ require("./generator");
5
+ //# sourceMappingURL=bin.js.map
package/src/bin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../../src/bin.ts"],"names":[],"mappings":";;;AACA,uBAAoB"}
@@ -0,0 +1,3 @@
1
+ import { ConfigInternal } from '../utils/config';
2
+ import type { DMMF } from '@prisma/generator-helper';
3
+ export declare function generateCrud(config: ConfigInternal, dmmf: DMMF.Document): Promise<void>;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateCrud = generateCrud;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const configUtils_1 = require("../utils/configUtils");
9
+ const filesystem_1 = require("../utils/filesystem");
10
+ const template_1 = require("../utils/template");
11
+ const root_1 = require("./templates/root");
12
+ const generator_1 = require("./utils/generator");
13
+ const parts_1 = require("./utils/parts");
14
+ async function generateCrud(config, dmmf) {
15
+ if (config.crud.disabled)
16
+ return;
17
+ if (config.crud.deleteOutputDirBeforeGenerate)
18
+ await (0, filesystem_1.deleteFolder)(node_path_1.default.join(config.crud.outputDir));
19
+ const modelNames = dmmf.datamodel.models.map((model) => model.name);
20
+ // Generate CRUD directories (e.g. User, Comment, ...)
21
+ const generatedModels = await Promise.all(modelNames.map(async (model) => {
22
+ const generated = await (0, generator_1.generateModel)(config, dmmf, model);
23
+ return { model, generated };
24
+ }));
25
+ const exportAllInObjects = generatedModels
26
+ .map((el) => {
27
+ return {
28
+ model: el.model,
29
+ exports: el.generated.index.map((el) => el.exports).flat(),
30
+ };
31
+ })
32
+ .filter((el) => Boolean(el.exports.length));
33
+ // Generate root objects.ts file (export all models + prisma objects)
34
+ const modelNamesEachLine = modelNames.map((model) => `'${model}',`).join('\n ');
35
+ const fileLocationObjects = node_path_1.default.join(config.crud.outputDir, 'objects.ts');
36
+ const builderCalculatedImportObjects = (0, parts_1.getBuilderCalculatedImport)({
37
+ config,
38
+ fileLocation: fileLocationObjects,
39
+ });
40
+ await (0, filesystem_1.writeFile)(config, 'crud.objects', (0, template_1.useTemplate)(root_1.objectsTemplate, {
41
+ crudExportRoot: config.crud.exportEverythingInObjectsDotTs
42
+ ? `\n${exportAllInObjects
43
+ .map((el) => `export {\n ${el.exports.join(',\n ')}\n} from './${el.model}';`)
44
+ .join('\n')}`
45
+ : '',
46
+ ...config.crud,
47
+ modelNames: modelNamesEachLine,
48
+ builderCalculatedImport: builderCalculatedImportObjects,
49
+ }), fileLocationObjects);
50
+ const fileLocation = node_path_1.default.join(config.crud.outputDir, 'utils.ts');
51
+ const builderCalculatedImport = (0, parts_1.getBuilderCalculatedImport)({ config, fileLocation });
52
+ // Generate root utils.ts file
53
+ await (0, filesystem_1.writeFile)(config, 'crud.utils', (0, template_1.useTemplate)(root_1.utilsTemplate, {
54
+ builderCalculatedImport,
55
+ }), fileLocation);
56
+ // Generate root autocrud.ts file
57
+ // TODO REFACTOR AND TESTS
58
+ if (config.crud.generateAutocrud) {
59
+ const imports = dmmf.datamodel.models.map((model) => `import * as ${model.name} from './${model.name}';`).join('\n');
60
+ const models = generatedModels.map((el) => ({
61
+ model: el.model,
62
+ generated: el.generated.resolvers,
63
+ }));
64
+ const modelsGenerated = dmmf.datamodel.models
65
+ .map((model) => {
66
+ const { name } = model;
67
+ return ` ${name}: {
68
+ Object: ${name}.${name}${(0, configUtils_1.getConfigCrudUnderscore)(config)}Object,
69
+ queries: ${(() => {
70
+ var _a;
71
+ const queries = ((_a = models.find((el) => el.model === name)) === null || _a === void 0 ? void 0 : _a.generated.filter((el) => el.type === 'queries')) || [];
72
+ return `{\n${queries
73
+ .map((el) => ` ${el.resolverName}: ${el.modelName}.${el.resolverName}${el.modelName}QueryObject,`)
74
+ .join('\n')}\n }`;
75
+ })()},
76
+ mutations: ${(() => {
77
+ var _a;
78
+ const mutations = ((_a = models.find((el) => el.model === name)) === null || _a === void 0 ? void 0 : _a.generated.filter((el) => el.type === 'mutations')) || [];
79
+ return `{\n${mutations
80
+ .map((el) => ` ${el.resolverName}: ${el.modelName}.${el.resolverName}${el.modelName}MutationObject,`)
81
+ .join('\n')}\n }`;
82
+ })()},
83
+ },`;
84
+ })
85
+ .join('\n');
86
+ const fileLocation = node_path_1.default.join(config.crud.outputDir, 'autocrud.ts');
87
+ const builderCalculatedImport = (0, parts_1.getBuilderCalculatedImport)({ config, fileLocation });
88
+ await (0, filesystem_1.writeFile)(config, 'crud.autocrud', (0, template_1.useTemplate)(root_1.autoCrudTemplate, {
89
+ ...config.crud,
90
+ imports,
91
+ modelsGenerated,
92
+ builderCalculatedImport,
93
+ }), fileLocation);
94
+ }
95
+ }
96
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/crudGenerator/index.ts"],"names":[],"mappings":";;;;;AAUA,oCAyGC;AAnHD,0DAA4B;AAE5B,sDAA8D;AAC9D,oDAA6D;AAC7D,gDAA+C;AAC/C,2CAAmF;AACnF,iDAAiD;AACjD,yCAA0D;AAGnD,KAAK,UAAU,YAAY,CAAC,MAAsB,EAAE,IAAmB;IAC5E,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ;QAAE,OAAM;IAEhC,IAAI,MAAM,CAAC,IAAI,CAAC,6BAA6B;QAAE,MAAM,IAAA,yBAAY,EAAC,mBAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAA;IAEnG,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAEnE,sDAAsD;IACtD,MAAM,eAAe,GAAG,MAAM,OAAO,CAAC,GAAG,CACvC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAC7B,MAAM,SAAS,GAAG,MAAM,IAAA,yBAAa,EAAC,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;QAC1D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;IAC7B,CAAC,CAAC,CACH,CAAA;IACD,MAAM,kBAAkB,GAAG,eAAe;SACvC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE;QACV,OAAO;YACL,KAAK,EAAE,EAAE,CAAC,KAAK;YACf,OAAO,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CA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AAS,IAAI,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,SAAS,cAAc,CAAC;qBACtG,IAAI,CAAC,IAAI,CAAC,SAAS,CAAA;YACxB,CAAC,CAAC,EAAE;iBACS,CAAC,GAAG,EAAE;;gBACjB,MAAM,SAAS,GAAG,CAAA,MAAA,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,0CAAE,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,KAAK,WAAW,CAAC,KAAI,EAAE,CAAA;gBACjH,OAAO,MAAM,SAAS;qBACnB,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,SAAS,EAAE,CAAC,YAAY,KAAK,EAAE,CAAC,SAAS,IAAI,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,SAAS,iBAAiB,CAAC;qBACzG,IAAI,CAAC,IAAI,CAAC,SAAS,CAAA;YACxB,CAAC,CAAC,EAAE;KACH,CAAA;QACC,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAA;QAEb,MAAM,YAAY,GAAG,mBAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,CAAA;QACpE,MAAM,uBAAuB,GAAG,IAAA,kCAA0B,EAAC,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,CAAA;QAEpF,MAAM,IAAA,sBAAS,EACb,MAAM,EACN,eAAe,EACf,IAAA,sBAAW,EAAC,uBAAgB,EAAE;YAC5B,GAAG,MAAM,CAAC,IAAI;YACd,OAAO;YACP,eAAe;YACf,uBAAuB;SACxB,CAAC,EACF,YAAY,CACb,CAAA;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,9 @@
1
+ export declare const mutations: {
2
+ createMany: string;
3
+ createOne: string;
4
+ deleteMany: string;
5
+ deleteOne: string;
6
+ updateMany: string;
7
+ updateOne: string;
8
+ upsertOne: string;
9
+ };