From 32d5b262cacdd03209a56027e4c2cbda1bc408c0 Mon Sep 17 00:00:00 2001 From: Yiming Date: Wed, 23 Aug 2023 16:16:24 +0800 Subject: [PATCH] fix: bugs related to model name casing (#645) --- packages/plugins/openapi/package.json | 1 + packages/plugins/openapi/src/rpc-generator.ts | 172 ++--- .../openapi/tests/baseline/rest.baseline.yaml | 132 ++-- .../openapi/tests/baseline/rpc.baseline.yaml | 599 ++++++++---------- .../openapi/tests/openapi-restful.test.ts | 16 +- .../plugins/openapi/tests/openapi-rpc.test.ts | 10 +- packages/plugins/swr/package.json | 2 + packages/plugins/swr/src/generator.ts | 30 +- packages/plugins/swr/tests/swr.test.ts | 12 +- packages/plugins/tanstack-query/package.json | 2 + .../plugins/tanstack-query/src/generator.ts | 36 +- .../tanstack-query/tests/plugin.test.ts | 13 +- packages/plugins/trpc/src/generator.ts | 4 +- packages/plugins/trpc/tests/trpc.test.ts | 42 +- .../runtime/src/enhancements/policy/logger.ts | 2 +- packages/schema/src/plugins/zod/generator.ts | 2 +- .../schema/src/plugins/zod/transformer.ts | 134 ++-- packages/sdk/package.json | 3 +- .../sdk/src/dmmf-helpers/aggregate-helpers.ts | 3 +- pnpm-lock.yaml | 21 +- script/test-prisma-v5.sh | 4 +- tests/integration/tests/cli/plugins.test.ts | 8 +- tests/integration/tests/plugins/zod.test.ts | 72 +++ 23 files changed, 703 insertions(+), 617 deletions(-) diff --git a/packages/plugins/openapi/package.json b/packages/plugins/openapi/package.json index edb993619..1d99618d7 100644 --- a/packages/plugins/openapi/package.json +++ b/packages/plugins/openapi/package.json @@ -31,6 +31,7 @@ "lower-case-first": "^2.0.2", "openapi-types": "^12.1.0", "tiny-invariant": "^1.3.1", + "upper-case-first": "^2.0.2", "yaml": "^2.2.1", "zod": "3.21.1", "zod-validation-error": "^0.2.1" diff --git a/packages/plugins/openapi/src/rpc-generator.ts b/packages/plugins/openapi/src/rpc-generator.ts index f3476d031..e80570e53 100644 --- a/packages/plugins/openapi/src/rpc-generator.ts +++ b/packages/plugins/openapi/src/rpc-generator.ts @@ -16,6 +16,7 @@ import { lowerCaseFirst } from 'lower-case-first'; import type { OpenAPIV3_1 as OAPI } from 'openapi-types'; import * as path from 'path'; import invariant from 'tiny-invariant'; +import { upperCaseFirst } from 'upper-case-first'; import YAML from 'yaml'; import { OpenAPIGeneratorBase } from './generator-base'; import { getModelResourceMeta } from './meta'; @@ -120,6 +121,8 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { return undefined; } + const modelName = upperCaseFirst(model.name); + type OperationDefinition = { method: 'get' | 'post' | 'put' | 'patch' | 'delete'; operation: string; @@ -141,21 +144,21 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'post', operation: 'create', inputType: this.component( - `${model.name}CreateArgs`, + `${modelName}CreateArgs`, { type: 'object', required: ['data'], properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - data: this.ref(`${model.name}CreateInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + data: this.ref(`${modelName}CreateInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.ref(model.name)), - description: `Create a new ${model.name}`, + outputType: this.response(this.ref(modelName)), + description: `Create a new ${modelName}`, successCode: 201, security: create === true ? [] : undefined, }); @@ -166,19 +169,19 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'post', operation: 'createMany', inputType: this.component( - `${model.name}CreateManyArgs`, + `${modelName}CreateManyArgs`, { type: 'object', required: ['data'], properties: { - data: this.ref(`${model.name}CreateManyInput`), + data: this.ref(`${modelName}CreateManyInput`), meta: this.ref('_Meta'), }, }, components ), outputType: this.response(this.ref('BatchPayload')), - description: `Create several ${model.name}`, + description: `Create several ${modelName}`, successCode: 201, security: create === true ? [] : undefined, }); @@ -189,21 +192,21 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'get', operation: 'findUnique', inputType: this.component( - `${model.name}FindUniqueArgs`, + `${modelName}FindUniqueArgs`, { type: 'object', required: ['where'], properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - where: this.ref(`${model.name}WhereUniqueInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + where: this.ref(`${modelName}WhereUniqueInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.ref(model.name)), - description: `Find one unique ${model.name}`, + outputType: this.response(this.ref(modelName)), + description: `Find one unique ${modelName}`, security: read === true ? [] : undefined, }); } @@ -213,20 +216,20 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'get', operation: 'findFirst', inputType: this.component( - `${model.name}FindFirstArgs`, + `${modelName}FindFirstArgs`, { type: 'object', properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - where: this.ref(`${model.name}WhereInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + where: this.ref(`${modelName}WhereInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.ref(model.name)), - description: `Find the first ${model.name} matching the given condition`, + outputType: this.response(this.ref(modelName)), + description: `Find the first ${modelName} matching the given condition`, security: read === true ? [] : undefined, }); } @@ -236,20 +239,20 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'get', operation: 'findMany', inputType: this.component( - `${model.name}FindManyArgs`, + `${modelName}FindManyArgs`, { type: 'object', properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - where: this.ref(`${model.name}WhereInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + where: this.ref(`${modelName}WhereInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.array(this.ref(model.name))), - description: `Find a list of ${model.name}`, + outputType: this.response(this.array(this.ref(modelName))), + description: `Find a list of ${modelName}`, security: read === true ? [] : undefined, }); } @@ -259,22 +262,22 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'patch', operation: 'update', inputType: this.component( - `${model.name}UpdateArgs`, + `${modelName}UpdateArgs`, { type: 'object', required: ['where', 'data'], properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - where: this.ref(`${model.name}WhereUniqueInput`), - data: this.ref(`${model.name}UpdateInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + where: this.ref(`${modelName}WhereUniqueInput`), + data: this.ref(`${modelName}UpdateInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.ref(model.name)), - description: `Update a ${model.name}`, + outputType: this.response(this.ref(modelName)), + description: `Update a ${modelName}`, security: update === true ? [] : undefined, }); } @@ -284,20 +287,20 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { operation: 'updateMany', method: 'patch', inputType: this.component( - `${model.name}UpdateManyArgs`, + `${modelName}UpdateManyArgs`, { type: 'object', required: ['data'], properties: { - where: this.ref(`${model.name}WhereInput`), - data: this.ref(`${model.name}UpdateManyMutationInput`), + where: this.ref(`${modelName}WhereInput`), + data: this.ref(`${modelName}UpdateManyMutationInput`), meta: this.ref('_Meta'), }, }, components ), outputType: this.response(this.ref('BatchPayload')), - description: `Update ${model.name}s matching the given condition`, + description: `Update ${modelName}s matching the given condition`, security: update === true ? [] : undefined, }); } @@ -307,23 +310,23 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'post', operation: 'upsert', inputType: this.component( - `${model.name}UpsertArgs`, + `${modelName}UpsertArgs`, { type: 'object', required: ['create', 'update', 'where'], properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - where: this.ref(`${model.name}WhereUniqueInput`), - create: this.ref(`${model.name}CreateInput`), - update: this.ref(`${model.name}UpdateInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + where: this.ref(`${modelName}WhereUniqueInput`), + create: this.ref(`${modelName}CreateInput`), + update: this.ref(`${modelName}UpdateInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.ref(model.name)), - description: `Upsert a ${model.name}`, + outputType: this.response(this.ref(modelName)), + description: `Upsert a ${modelName}`, security: create === true && update == true ? [] : undefined, }); } @@ -333,21 +336,21 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'delete', operation: 'delete', inputType: this.component( - `${model.name}DeleteUniqueArgs`, + `${modelName}DeleteUniqueArgs`, { type: 'object', required: ['where'], properties: { - select: this.ref(`${model.name}Select`), - include: hasRelation ? this.ref(`${model.name}Include`) : undefined, - where: this.ref(`${model.name}WhereUniqueInput`), + select: this.ref(`${modelName}Select`), + include: hasRelation ? this.ref(`${modelName}Include`) : undefined, + where: this.ref(`${modelName}WhereUniqueInput`), meta: this.ref('_Meta'), }, }, components ), - outputType: this.response(this.ref(model.name)), - description: `Delete one unique ${model.name}`, + outputType: this.response(this.ref(modelName)), + description: `Delete one unique ${modelName}`, security: del === true ? [] : undefined, }); } @@ -357,18 +360,18 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'delete', operation: 'deleteMany', inputType: this.component( - `${model.name}DeleteManyArgs`, + `${modelName}DeleteManyArgs`, { type: 'object', properties: { - where: this.ref(`${model.name}WhereInput`), + where: this.ref(`${modelName}WhereInput`), meta: this.ref('_Meta'), }, }, components ), outputType: this.response(this.ref('BatchPayload')), - description: `Delete ${model.name}s matching the given condition`, + description: `Delete ${modelName}s matching the given condition`, security: del === true ? [] : undefined, }); } @@ -378,21 +381,21 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'get', operation: 'count', inputType: this.component( - `${model.name}CountArgs`, + `${modelName}CountArgs`, { type: 'object', properties: { - select: this.ref(`${model.name}Select`), - where: this.ref(`${model.name}WhereInput`), + select: this.ref(`${modelName}Select`), + where: this.ref(`${modelName}WhereInput`), meta: this.ref('_Meta'), }, }, components ), outputType: this.response( - this.oneOf({ type: 'integer' }, this.ref(`${model.name}CountAggregateOutputType`)) + this.oneOf({ type: 'integer' }, this.ref(`${modelName}CountAggregateOutputType`)) ), - description: `Find a list of ${model.name}`, + description: `Find a list of ${modelName}`, security: read === true ? [] : undefined, }); @@ -401,13 +404,13 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'get', operation: 'aggregate', inputType: this.component( - `${model.name}AggregateArgs`, + `${modelName}AggregateArgs`, { type: 'object', properties: { - where: this.ref(`${model.name}WhereInput`), - orderBy: this.ref(`${model.name}OrderByWithRelationInput`), - cursor: this.ref(`${model.name}WhereUniqueInput`), + where: this.ref(`${modelName}WhereInput`), + orderBy: this.ref(`${modelName}OrderByWithRelationInput`), + cursor: this.ref(`${modelName}WhereUniqueInput`), take: { type: 'integer' }, skip: { type: 'integer' }, ...this.aggregateFields(model), @@ -416,8 +419,8 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { }, components ), - outputType: this.response(this.ref(`Aggregate${model.name}`)), - description: `Aggregate ${model.name}s`, + outputType: this.response(this.ref(`Aggregate${modelName}`)), + description: `Aggregate ${modelName}s`, security: read === true ? [] : undefined, }); } @@ -427,14 +430,14 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { method: 'get', operation: 'groupBy', inputType: this.component( - `${model.name}GroupByArgs`, + `${modelName}GroupByArgs`, { type: 'object', properties: { - where: this.ref(`${model.name}WhereInput`), - orderBy: this.ref(`${model.name}OrderByWithRelationInput`), - by: this.ref(`${model.name}ScalarFieldEnum`), - having: this.ref(`${model.name}ScalarWhereWithAggregatesInput`), + where: this.ref(`${modelName}WhereInput`), + orderBy: this.ref(`${modelName}OrderByWithRelationInput`), + by: this.ref(`${modelName}ScalarFieldEnum`), + having: this.ref(`${modelName}ScalarWhereWithAggregatesInput`), take: { type: 'integer' }, skip: { type: 'integer' }, ...this.aggregateFields(model), @@ -443,8 +446,8 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { }, components ), - outputType: this.response(this.array(this.ref(`${model.name}GroupByOutputType`))), - description: `Group ${model.name}s by fields`, + outputType: this.response(this.array(this.ref(`${modelName}GroupByOutputType`))), + description: `Group ${modelName}s by fields`, security: read === true ? [] : undefined, }); } @@ -472,7 +475,7 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { // eslint-disable-next-line @typescript-eslint/no-explicit-any const def: OAPI.OperationObject = { - operationId: `${operation}${model.name}`, + operationId: `${operation}${modelName}`, description: meta?.description ?? description, tags: meta?.tags || [lowerCaseFirst(model.name)], summary: meta?.summary, @@ -556,21 +559,22 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { private aggregateFields(model: DMMF.Model) { const result: Record = {}; const supportedOps = this.aggregateOperationSupport[model.name]; + const modelName = upperCaseFirst(model.name); if (supportedOps) { if (supportedOps.count) { - result._count = this.oneOf({ type: 'boolean' }, this.ref(`${model.name}CountAggregateInput`)); + result._count = this.oneOf({ type: 'boolean' }, this.ref(`${modelName}CountAggregateInput`)); } if (supportedOps.min) { - result._min = this.ref(`${model.name}MinAggregateInput`); + result._min = this.ref(`${modelName}MinAggregateInput`); } if (supportedOps.max) { - result._max = this.ref(`${model.name}MaxAggregateInput`); + result._max = this.ref(`${modelName}MaxAggregateInput`); } if (supportedOps.sum) { - result._sum = this.ref(`${model.name}SumAggregateInput`); + result._sum = this.ref(`${modelName}SumAggregateInput`); } if (supportedOps.avg) { - result._avg = this.ref(`${model.name}AvgAggregateInput`); + result._avg = this.ref(`${modelName}AvgAggregateInput`); } } return result; @@ -590,20 +594,20 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { // user-defined and built-in enums for (const _enum of [...(this.dmmf.schema.enumTypes.model ?? []), ...this.dmmf.schema.enumTypes.prisma]) { - schemas[_enum.name] = this.generateEnumComponent(_enum); + schemas[upperCaseFirst(_enum.name)] = this.generateEnumComponent(_enum); } // data models for (const model of this.dmmf.datamodel.models) { - schemas[model.name] = this.generateEntityComponent(model); + schemas[upperCaseFirst(model.name)] = this.generateEntityComponent(model); } for (const input of this.inputObjectTypes) { - schemas[input.name] = this.generateInputComponent(input); + schemas[upperCaseFirst(input.name)] = this.generateInputComponent(input); } for (const output of this.outputObjectTypes.filter((t) => !['Query', 'Mutation'].includes(t.name))) { - schemas[output.name] = this.generateOutputComponent(output); + schemas[upperCaseFirst(output.name)] = this.generateOutputComponent(output); } schemas['_Meta'] = { @@ -802,7 +806,7 @@ export class RPCOpenAPIGenerator extends OpenAPIGeneratorBase { if (rooted) { this.usedComponents.add(type); } - return { $ref: `#/components/schemas/${type}`, description }; + return { $ref: `#/components/schemas/${upperCaseFirst(type)}`, description }; } private response(schema: OAPI.SchemaObject): OAPI.SchemaObject { diff --git a/packages/plugins/openapi/tests/baseline/rest.baseline.yaml b/packages/plugins/openapi/tests/baseline/rest.baseline.yaml index 466556993..c7a1f0df9 100644 --- a/packages/plugins/openapi/tests/baseline/rest.baseline.yaml +++ b/packages/plugins/openapi/tests/baseline/rest.baseline.yaml @@ -5,7 +5,7 @@ info: tags: - name: user description: User operations - - name: post + - name: post_Item description: Post-related operations paths: /user: @@ -172,7 +172,7 @@ paths: style: form explode: false schema: - $ref: '#/components/schemas/Role' + $ref: '#/components/schemas/role' - name: filter[posts] required: false description: Equality filter for "posts" @@ -496,7 +496,7 @@ paths: style: form explode: false schema: - $ref: '#/components/schemas/Role' + $ref: '#/components/schemas/role' - name: filter[posts] required: false description: Equality filter for "posts" @@ -513,7 +513,7 @@ paths: content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostListResponse' + $ref: '#/components/schemas/post_ItemListResponse' '403': description: Request is forbidden content: @@ -690,7 +690,7 @@ paths: style: form explode: false schema: - $ref: '#/components/schemas/Role' + $ref: '#/components/schemas/role' - name: filter[posts] required: false description: Equality filter for "posts" @@ -813,12 +813,12 @@ paths: application/vnd.api+json: schema: $ref: '#/components/schemas/_errorResponse' - /post: + /post_Item: get: - operationId: list-Post - description: List "Post" resources + operationId: list-post_Item + description: List "post_Item" resources tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/include' - $ref: '#/components/parameters/sort' @@ -1032,7 +1032,7 @@ paths: content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostListResponse' + $ref: '#/components/schemas/post_ItemListResponse' '403': description: Request is forbidden content: @@ -1040,34 +1040,34 @@ paths: schema: $ref: '#/components/schemas/_errorResponse' post: - operationId: create-Post - description: Create a "Post" resource + operationId: create-post_Item + description: Create a "post_Item" resource tags: - - post + - post_Item requestBody: content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostCreateRequest' + $ref: '#/components/schemas/post_ItemCreateRequest' responses: '201': description: Successful operation content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostResponse' + $ref: '#/components/schemas/post_ItemResponse' '403': description: Request is forbidden content: application/vnd.api+json: schema: $ref: '#/components/schemas/_errorResponse' - '/post/{id}': + '/post_Item/{id}': get: - operationId: fetch-Post - description: Fetch a "Post" resource + operationId: fetch-post_Item + description: Fetch a "post_Item" resource tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' - $ref: '#/components/parameters/include' @@ -1077,7 +1077,7 @@ paths: content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostResponse' + $ref: '#/components/schemas/post_ItemResponse' '403': description: Request is forbidden content: @@ -1091,24 +1091,24 @@ paths: schema: $ref: '#/components/schemas/_errorResponse' put: - operationId: update-Post-put - description: Update a "Post" resource + operationId: update-post_Item-put + description: Update a "post_Item" resource tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' requestBody: content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostUpdateRequest' + $ref: '#/components/schemas/post_ItemUpdateRequest' responses: '200': description: Successful operation content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostResponse' + $ref: '#/components/schemas/post_ItemResponse' '403': description: Request is forbidden content: @@ -1122,24 +1122,24 @@ paths: schema: $ref: '#/components/schemas/_errorResponse' patch: - operationId: update-Post-patch - description: Update a "Post" resource + operationId: update-post_Item-patch + description: Update a "post_Item" resource tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' requestBody: content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostUpdateRequest' + $ref: '#/components/schemas/post_ItemUpdateRequest' responses: '200': description: Successful operation content: application/vnd.api+json: schema: - $ref: '#/components/schemas/PostResponse' + $ref: '#/components/schemas/post_ItemResponse' '403': description: Request is forbidden content: @@ -1153,10 +1153,10 @@ paths: schema: $ref: '#/components/schemas/_errorResponse' delete: - operationId: delete-Post - description: Delete a "Post" resource + operationId: delete-post_Item + description: Delete a "post_Item" resource tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' responses: @@ -1174,12 +1174,12 @@ paths: application/vnd.api+json: schema: $ref: '#/components/schemas/_errorResponse' - '/post/{id}/author': + '/post_Item/{id}/author': get: - operationId: fetch-Post-related-author - description: Fetch the related "author" resource for "Post" + operationId: fetch-post_Item-related-author + description: Fetch the related "author" resource for "post_Item" tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' - $ref: '#/components/parameters/include' @@ -1202,12 +1202,12 @@ paths: application/vnd.api+json: schema: $ref: '#/components/schemas/_errorResponse' - '/post/{id}/relationships/author': + '/post_Item/{id}/relationships/author': get: - operationId: fetch-Post-relationship-author - description: Fetch the "author" relationships for a "Post" + operationId: fetch-post_Item-relationship-author + description: Fetch the "author" relationships for a "post_Item" tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' responses: @@ -1230,10 +1230,10 @@ paths: schema: $ref: '#/components/schemas/_errorResponse' put: - operationId: update-Post-relationship-author-put - description: Update "author" relationship for a "Post" + operationId: update-post_Item-relationship-author-put + description: Update "author" relationship for a "post_Item" tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' requestBody: @@ -1261,10 +1261,10 @@ paths: schema: $ref: '#/components/schemas/_errorResponse' patch: - operationId: update-Post-relationship-author-patch - description: Update "author" relationship for a "Post" + operationId: update-post_Item-relationship-author-patch + description: Update "author" relationship for a "post_Item" tags: - - post + - post_Item parameters: - $ref: '#/components/parameters/id' requestBody: @@ -1503,9 +1503,9 @@ components: properties: jsonapi: $ref: '#/components/schemas/_jsonapi' - Role: + role: type: string - description: The "Role" Enum + description: The "role" Enum enum: - USER - ADMIN @@ -1533,7 +1533,7 @@ components: email: type: string role: - $ref: '#/components/schemas/Role' + $ref: '#/components/schemas/role' relationships: type: object properties: @@ -1572,7 +1572,7 @@ components: email: type: string role: - $ref: '#/components/schemas/Role' + $ref: '#/components/schemas/role' relationships: type: object properties: @@ -1610,7 +1610,7 @@ components: email: type: string role: - $ref: '#/components/schemas/Role' + $ref: '#/components/schemas/role' relationships: type: object properties: @@ -1673,9 +1673,9 @@ components: allOf: - $ref: '#/components/schemas/_links' - $ref: '#/components/schemas/_pagination' - Post: + post_Item: type: object - description: The "Post" model + description: The "post_Item" model required: - id - type @@ -1707,15 +1707,15 @@ components: properties: author: $ref: '#/components/schemas/_toOneRelationshipWithLinks' - PostCreateRequest: + post_ItemCreateRequest: type: object - description: Input for creating a "Post" + description: Input for creating a "post_Item" required: - data properties: data: type: object - description: The "Post" model + description: The "post_Item" model required: - id - type @@ -1752,15 +1752,15 @@ components: $ref: '#/components/schemas/_toOneRelationship' meta: $ref: '#/components/schemas/_meta' - PostUpdateRequest: + post_ItemUpdateRequest: type: object - description: Input for updating a "Post" + description: Input for updating a "post_Item" required: - data properties: data: type: object - description: The "Post" model + description: The "post_Item" model required: - id - type @@ -1794,9 +1794,9 @@ components: $ref: '#/components/schemas/_toOneRelationship' meta: $ref: '#/components/schemas/_meta' - PostResponse: + post_ItemResponse: type: object - description: Response for a "Post" + description: Response for a "post_Item" required: - data properties: @@ -1804,7 +1804,7 @@ components: $ref: '#/components/schemas/_jsonapi' data: allOf: - - $ref: '#/components/schemas/Post' + - $ref: '#/components/schemas/post_Item' - type: object properties: relationships: @@ -1820,9 +1820,9 @@ components: $ref: '#/components/schemas/_resource' links: $ref: '#/components/schemas/_links' - PostListResponse: + post_ItemListResponse: type: object - description: Response for a list of "Post" + description: Response for a list of "post_Item" required: - data - links @@ -1833,7 +1833,7 @@ components: type: array items: allOf: - - $ref: '#/components/schemas/Post' + - $ref: '#/components/schemas/post_Item' - type: object properties: relationships: diff --git a/packages/plugins/openapi/tests/baseline/rpc.baseline.yaml b/packages/plugins/openapi/tests/baseline/rpc.baseline.yaml index bc013f02b..4e87045be 100644 --- a/packages/plugins/openapi/tests/baseline/rpc.baseline.yaml +++ b/packages/plugins/openapi/tests/baseline/rpc.baseline.yaml @@ -5,7 +5,7 @@ info: tags: - name: user description: User operations - - name: post + - name: post_Item description: Post-related operations components: schemas: @@ -14,7 +14,7 @@ components: enum: - USER - ADMIN - PostScalarFieldEnum: + Post_ItemScalarFieldEnum: type: string enum: - id @@ -60,14 +60,14 @@ components: posts: type: array items: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' required: - id - createdAt - updatedAt - email - role - Post: + Post_Item: type: object properties: id: @@ -134,10 +134,10 @@ components: - type: string role: oneOf: - - $ref: '#/components/schemas/EnumRoleFilter' + - $ref: '#/components/schemas/EnumroleFilter' - $ref: '#/components/schemas/Role' posts: - $ref: '#/components/schemas/PostListRelationFilter' + $ref: '#/components/schemas/Post_ItemListRelationFilter' UserOrderByWithRelationInput: type: object properties: @@ -152,7 +152,7 @@ components: role: $ref: '#/components/schemas/SortOrder' posts: - $ref: '#/components/schemas/PostOrderByRelationAggregateInput' + $ref: '#/components/schemas/Post_ItemOrderByRelationAggregateInput' UserWhereUniqueInput: type: object properties: @@ -199,27 +199,27 @@ components: - type: string role: oneOf: - - $ref: '#/components/schemas/EnumRoleWithAggregatesFilter' + - $ref: '#/components/schemas/EnumroleWithAggregatesFilter' - $ref: '#/components/schemas/Role' - PostWhereInput: + Post_ItemWhereInput: type: object properties: AND: oneOf: - - $ref: '#/components/schemas/PostWhereInput' + - $ref: '#/components/schemas/Post_ItemWhereInput' - type: array items: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' OR: type: array items: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' NOT: oneOf: - - $ref: '#/components/schemas/PostWhereInput' + - $ref: '#/components/schemas/Post_ItemWhereInput' - type: array items: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' id: oneOf: - $ref: '#/components/schemas/StringFilter' @@ -254,7 +254,7 @@ components: oneOf: - $ref: '#/components/schemas/IntFilter' - type: integer - PostOrderByWithRelationInput: + Post_ItemOrderByWithRelationInput: type: object properties: id: @@ -273,30 +273,30 @@ components: $ref: '#/components/schemas/SortOrder' viewCount: $ref: '#/components/schemas/SortOrder' - PostWhereUniqueInput: + Post_ItemWhereUniqueInput: type: object properties: id: type: string - PostScalarWhereWithAggregatesInput: + Post_ItemScalarWhereWithAggregatesInput: type: object properties: AND: oneOf: - - $ref: '#/components/schemas/PostScalarWhereWithAggregatesInput' + - $ref: '#/components/schemas/Post_ItemScalarWhereWithAggregatesInput' - type: array items: - $ref: '#/components/schemas/PostScalarWhereWithAggregatesInput' + $ref: '#/components/schemas/Post_ItemScalarWhereWithAggregatesInput' OR: type: array items: - $ref: '#/components/schemas/PostScalarWhereWithAggregatesInput' + $ref: '#/components/schemas/Post_ItemScalarWhereWithAggregatesInput' NOT: oneOf: - - $ref: '#/components/schemas/PostScalarWhereWithAggregatesInput' + - $ref: '#/components/schemas/Post_ItemScalarWhereWithAggregatesInput' - type: array items: - $ref: '#/components/schemas/PostScalarWhereWithAggregatesInput' + $ref: '#/components/schemas/Post_ItemScalarWhereWithAggregatesInput' id: oneOf: - $ref: '#/components/schemas/StringWithAggregatesFilter' @@ -343,7 +343,7 @@ components: role: $ref: '#/components/schemas/Role' posts: - $ref: '#/components/schemas/PostCreateNestedManyWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemCreateNestedManyWithoutAuthorInput' required: - id - email @@ -371,9 +371,9 @@ components: role: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/EnumRoleFieldUpdateOperationsInput' + - $ref: '#/components/schemas/EnumroleFieldUpdateOperationsInput' posts: - $ref: '#/components/schemas/PostUpdateManyWithoutAuthorNestedInput' + $ref: '#/components/schemas/Post_ItemUpdateManyWithoutAuthorNestedInput' UserCreateManyInput: type: object properties: @@ -416,8 +416,8 @@ components: role: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/EnumRoleFieldUpdateOperationsInput' - PostCreateInput: + - $ref: '#/components/schemas/EnumroleFieldUpdateOperationsInput' + Post_ItemCreateInput: type: object properties: id: @@ -439,7 +439,7 @@ components: required: - id - title - PostUpdateInput: + Post_ItemUpdateInput: type: object properties: id: @@ -470,7 +470,7 @@ components: oneOf: - type: integer - $ref: '#/components/schemas/IntFieldUpdateOperationsInput' - PostCreateManyInput: + Post_ItemCreateManyInput: type: object properties: id: @@ -492,7 +492,7 @@ components: required: - id - title - PostUpdateManyMutationInput: + Post_ItemUpdateManyMutationInput: type: object properties: id: @@ -587,7 +587,7 @@ components: - type: string format: date-time - $ref: '#/components/schemas/NestedDateTimeFilter' - EnumRoleFilter: + EnumroleFilter: type: object properties: equals: @@ -603,17 +603,17 @@ components: not: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/NestedEnumRoleFilter' - PostListRelationFilter: + - $ref: '#/components/schemas/NestedEnumroleFilter' + Post_ItemListRelationFilter: type: object properties: every: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' some: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' none: - $ref: '#/components/schemas/PostWhereInput' - PostOrderByRelationAggregateInput: + $ref: '#/components/schemas/Post_ItemWhereInput' + Post_ItemOrderByRelationAggregateInput: type: object properties: _count: @@ -696,7 +696,7 @@ components: $ref: '#/components/schemas/NestedDateTimeFilter' _max: $ref: '#/components/schemas/NestedDateTimeFilter' - EnumRoleWithAggregatesFilter: + EnumroleWithAggregatesFilter: type: object properties: equals: @@ -712,13 +712,13 @@ components: not: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/NestedEnumRoleWithAggregatesFilter' + - $ref: '#/components/schemas/NestedEnumroleWithAggregatesFilter' _count: $ref: '#/components/schemas/NestedIntFilter' _min: - $ref: '#/components/schemas/NestedEnumRoleFilter' + $ref: '#/components/schemas/NestedEnumroleFilter' _max: - $ref: '#/components/schemas/NestedEnumRoleFilter' + $ref: '#/components/schemas/NestedEnumroleFilter' UserRelationFilter: type: object properties: @@ -882,33 +882,33 @@ components: $ref: '#/components/schemas/NestedIntFilter' _max: $ref: '#/components/schemas/NestedIntFilter' - PostCreateNestedManyWithoutAuthorInput: + Post_ItemCreateNestedManyWithoutAuthorInput: type: object properties: create: oneOf: - - $ref: '#/components/schemas/PostCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemCreateWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostCreateWithoutAuthorInput' - - $ref: '#/components/schemas/PostUncheckedCreateWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUncheckedCreateWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostUncheckedCreateWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemUncheckedCreateWithoutAuthorInput' connectOrCreate: oneOf: - - $ref: '#/components/schemas/PostCreateOrConnectWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemCreateOrConnectWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostCreateOrConnectWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemCreateOrConnectWithoutAuthorInput' createMany: - $ref: '#/components/schemas/PostCreateManyAuthorInputEnvelope' + $ref: '#/components/schemas/Post_ItemCreateManyAuthorInputEnvelope' connect: oneOf: - - $ref: '#/components/schemas/PostWhereUniqueInput' + - $ref: '#/components/schemas/Post_ItemWhereUniqueInput' - type: array items: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' StringFieldUpdateOperationsInput: type: object properties: @@ -920,80 +920,80 @@ components: set: type: string format: date-time - EnumRoleFieldUpdateOperationsInput: + EnumroleFieldUpdateOperationsInput: type: object properties: set: $ref: '#/components/schemas/Role' - PostUpdateManyWithoutAuthorNestedInput: + Post_ItemUpdateManyWithoutAuthorNestedInput: type: object properties: create: oneOf: - - $ref: '#/components/schemas/PostCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemCreateWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostCreateWithoutAuthorInput' - - $ref: '#/components/schemas/PostUncheckedCreateWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUncheckedCreateWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostUncheckedCreateWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemUncheckedCreateWithoutAuthorInput' connectOrCreate: oneOf: - - $ref: '#/components/schemas/PostCreateOrConnectWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemCreateOrConnectWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostCreateOrConnectWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemCreateOrConnectWithoutAuthorInput' upsert: oneOf: - - $ref: '#/components/schemas/PostUpsertWithWhereUniqueWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUpsertWithWhereUniqueWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostUpsertWithWhereUniqueWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemUpsertWithWhereUniqueWithoutAuthorInput' createMany: - $ref: '#/components/schemas/PostCreateManyAuthorInputEnvelope' + $ref: '#/components/schemas/Post_ItemCreateManyAuthorInputEnvelope' set: oneOf: - - $ref: '#/components/schemas/PostWhereUniqueInput' + - $ref: '#/components/schemas/Post_ItemWhereUniqueInput' - type: array items: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' disconnect: oneOf: - - $ref: '#/components/schemas/PostWhereUniqueInput' + - $ref: '#/components/schemas/Post_ItemWhereUniqueInput' - type: array items: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' delete: oneOf: - - $ref: '#/components/schemas/PostWhereUniqueInput' + - $ref: '#/components/schemas/Post_ItemWhereUniqueInput' - type: array items: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' connect: oneOf: - - $ref: '#/components/schemas/PostWhereUniqueInput' + - $ref: '#/components/schemas/Post_ItemWhereUniqueInput' - type: array items: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' update: oneOf: - - $ref: '#/components/schemas/PostUpdateWithWhereUniqueWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUpdateWithWhereUniqueWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostUpdateWithWhereUniqueWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemUpdateWithWhereUniqueWithoutAuthorInput' updateMany: oneOf: - - $ref: '#/components/schemas/PostUpdateManyWithWhereWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUpdateManyWithWhereWithoutAuthorInput' - type: array items: - $ref: '#/components/schemas/PostUpdateManyWithWhereWithoutAuthorInput' + $ref: '#/components/schemas/Post_ItemUpdateManyWithWhereWithoutAuthorInput' deleteMany: oneOf: - - $ref: '#/components/schemas/PostScalarWhereInput' + - $ref: '#/components/schemas/Post_ItemScalarWhereInput' - type: array items: - $ref: '#/components/schemas/PostScalarWhereInput' + $ref: '#/components/schemas/Post_ItemScalarWhereInput' UserCreateNestedOneWithoutPostsInput: type: object properties: @@ -1108,7 +1108,7 @@ components: - type: string format: date-time - $ref: '#/components/schemas/NestedDateTimeFilter' - NestedEnumRoleFilter: + NestedEnumroleFilter: type: object properties: equals: @@ -1124,7 +1124,7 @@ components: not: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/NestedEnumRoleFilter' + - $ref: '#/components/schemas/NestedEnumroleFilter' NestedStringWithAggregatesFilter: type: object properties: @@ -1226,7 +1226,7 @@ components: $ref: '#/components/schemas/NestedDateTimeFilter' _max: $ref: '#/components/schemas/NestedDateTimeFilter' - NestedEnumRoleWithAggregatesFilter: + NestedEnumroleWithAggregatesFilter: type: object properties: equals: @@ -1242,13 +1242,13 @@ components: not: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/NestedEnumRoleWithAggregatesFilter' + - $ref: '#/components/schemas/NestedEnumroleWithAggregatesFilter' _count: $ref: '#/components/schemas/NestedIntFilter' _min: - $ref: '#/components/schemas/NestedEnumRoleFilter' + $ref: '#/components/schemas/NestedEnumroleFilter' _max: - $ref: '#/components/schemas/NestedEnumRoleFilter' + $ref: '#/components/schemas/NestedEnumroleFilter' NestedStringNullableFilter: type: object properties: @@ -1426,7 +1426,7 @@ components: oneOf: - type: number - $ref: '#/components/schemas/NestedFloatFilter' - PostCreateWithoutAuthorInput: + Post_ItemCreateWithoutAuthorInput: type: object properties: id: @@ -1446,7 +1446,7 @@ components: required: - id - title - PostUncheckedCreateWithoutAuthorInput: + Post_ItemUncheckedCreateWithoutAuthorInput: type: object properties: id: @@ -1466,89 +1466,89 @@ components: required: - id - title - PostCreateOrConnectWithoutAuthorInput: + Post_ItemCreateOrConnectWithoutAuthorInput: type: object properties: where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' create: oneOf: - - $ref: '#/components/schemas/PostCreateWithoutAuthorInput' - - $ref: '#/components/schemas/PostUncheckedCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUncheckedCreateWithoutAuthorInput' required: - where - create - PostCreateManyAuthorInputEnvelope: + Post_ItemCreateManyAuthorInputEnvelope: type: object properties: data: type: array items: - $ref: '#/components/schemas/PostCreateManyAuthorInput' + $ref: '#/components/schemas/Post_ItemCreateManyAuthorInput' skipDuplicates: type: boolean required: - data - PostUpsertWithWhereUniqueWithoutAuthorInput: + Post_ItemUpsertWithWhereUniqueWithoutAuthorInput: type: object properties: where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' update: oneOf: - - $ref: '#/components/schemas/PostUpdateWithoutAuthorInput' - - $ref: '#/components/schemas/PostUncheckedUpdateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUpdateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUncheckedUpdateWithoutAuthorInput' create: oneOf: - - $ref: '#/components/schemas/PostCreateWithoutAuthorInput' - - $ref: '#/components/schemas/PostUncheckedCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemCreateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUncheckedCreateWithoutAuthorInput' required: - where - update - create - PostUpdateWithWhereUniqueWithoutAuthorInput: + Post_ItemUpdateWithWhereUniqueWithoutAuthorInput: type: object properties: where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' data: oneOf: - - $ref: '#/components/schemas/PostUpdateWithoutAuthorInput' - - $ref: '#/components/schemas/PostUncheckedUpdateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUpdateWithoutAuthorInput' + - $ref: '#/components/schemas/Post_ItemUncheckedUpdateWithoutAuthorInput' required: - where - data - PostUpdateManyWithWhereWithoutAuthorInput: + Post_ItemUpdateManyWithWhereWithoutAuthorInput: type: object properties: where: - $ref: '#/components/schemas/PostScalarWhereInput' + $ref: '#/components/schemas/Post_ItemScalarWhereInput' data: oneOf: - - $ref: '#/components/schemas/PostUpdateManyMutationInput' - - $ref: '#/components/schemas/PostUncheckedUpdateManyWithoutPostsInput' + - $ref: '#/components/schemas/Post_ItemUpdateManyMutationInput' + - $ref: '#/components/schemas/Post_ItemUncheckedUpdateManyWithoutPostsInput' required: - where - data - PostScalarWhereInput: + Post_ItemScalarWhereInput: type: object properties: AND: oneOf: - - $ref: '#/components/schemas/PostScalarWhereInput' + - $ref: '#/components/schemas/Post_ItemScalarWhereInput' - type: array items: - $ref: '#/components/schemas/PostScalarWhereInput' + $ref: '#/components/schemas/Post_ItemScalarWhereInput' OR: type: array items: - $ref: '#/components/schemas/PostScalarWhereInput' + $ref: '#/components/schemas/Post_ItemScalarWhereInput' NOT: oneOf: - - $ref: '#/components/schemas/PostScalarWhereInput' + - $ref: '#/components/schemas/Post_ItemScalarWhereInput' - type: array items: - $ref: '#/components/schemas/PostScalarWhereInput' + $ref: '#/components/schemas/Post_ItemScalarWhereInput' id: oneOf: - $ref: '#/components/schemas/StringFilter' @@ -1665,7 +1665,7 @@ components: role: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/EnumRoleFieldUpdateOperationsInput' + - $ref: '#/components/schemas/EnumroleFieldUpdateOperationsInput' UserUncheckedUpdateWithoutPostsInput: type: object properties: @@ -1690,8 +1690,8 @@ components: role: oneOf: - $ref: '#/components/schemas/Role' - - $ref: '#/components/schemas/EnumRoleFieldUpdateOperationsInput' - PostCreateManyAuthorInput: + - $ref: '#/components/schemas/EnumroleFieldUpdateOperationsInput' + Post_ItemCreateManyAuthorInput: type: object properties: id: @@ -1711,7 +1711,7 @@ components: required: - id - title - PostUpdateWithoutAuthorInput: + Post_ItemUpdateWithoutAuthorInput: type: object properties: id: @@ -1740,7 +1740,7 @@ components: oneOf: - type: integer - $ref: '#/components/schemas/IntFieldUpdateOperationsInput' - PostUncheckedUpdateWithoutAuthorInput: + Post_ItemUncheckedUpdateWithoutAuthorInput: type: object properties: id: @@ -1769,7 +1769,7 @@ components: oneOf: - type: integer - $ref: '#/components/schemas/IntFieldUpdateOperationsInput' - PostUncheckedUpdateManyWithoutPostsInput: + Post_ItemUncheckedUpdateManyWithoutPostsInput: type: object properties: id: @@ -1811,12 +1811,12 @@ components: posts: oneOf: - type: boolean - - $ref: '#/components/schemas/PostFindManyArgs' + - $ref: '#/components/schemas/Post_ItemFindManyArgs' _count: oneOf: - type: boolean - $ref: '#/components/schemas/UserCountOutputTypeArgs' - PostInclude: + Post_ItemInclude: type: object properties: author: @@ -1849,12 +1849,12 @@ components: posts: oneOf: - type: boolean - - $ref: '#/components/schemas/PostFindManyArgs' + - $ref: '#/components/schemas/Post_ItemFindManyArgs' _count: oneOf: - type: boolean - $ref: '#/components/schemas/UserCountOutputTypeArgs' - PostSelect: + Post_ItemSelect: type: object properties: id: @@ -1916,69 +1916,6 @@ components: type: boolean role: type: boolean - PostCountAggregateInput: - type: object - properties: - id: - type: boolean - createdAt: - type: boolean - updatedAt: - type: boolean - title: - type: boolean - authorId: - type: boolean - published: - type: boolean - viewCount: - type: boolean - _all: - type: boolean - PostAvgAggregateInput: - type: object - properties: - viewCount: - type: boolean - PostSumAggregateInput: - type: object - properties: - viewCount: - type: boolean - PostMinAggregateInput: - type: object - properties: - id: - type: boolean - createdAt: - type: boolean - updatedAt: - type: boolean - title: - type: boolean - authorId: - type: boolean - published: - type: boolean - viewCount: - type: boolean - PostMaxAggregateInput: - type: object - properties: - id: - type: boolean - createdAt: - type: boolean - updatedAt: - type: boolean - title: - type: boolean - authorId: - type: boolean - published: - type: boolean - viewCount: - type: boolean AggregateUser: type: object properties: @@ -2015,20 +1952,20 @@ components: - updatedAt - email - role - AggregatePost: + AggregatePost_Item: type: object properties: _count: - $ref: '#/components/schemas/PostCountAggregateOutputType' + $ref: '#/components/schemas/Post_ItemCountAggregateOutputType' _avg: - $ref: '#/components/schemas/PostAvgAggregateOutputType' + $ref: '#/components/schemas/Post_ItemAvgAggregateOutputType' _sum: - $ref: '#/components/schemas/PostSumAggregateOutputType' + $ref: '#/components/schemas/Post_ItemSumAggregateOutputType' _min: - $ref: '#/components/schemas/PostMinAggregateOutputType' + $ref: '#/components/schemas/Post_ItemMinAggregateOutputType' _max: - $ref: '#/components/schemas/PostMaxAggregateOutputType' - PostGroupByOutputType: + $ref: '#/components/schemas/Post_ItemMaxAggregateOutputType' + Post_ItemGroupByOutputType: type: object properties: id: @@ -2048,15 +1985,15 @@ components: viewCount: type: integer _count: - $ref: '#/components/schemas/PostCountAggregateOutputType' + $ref: '#/components/schemas/Post_ItemCountAggregateOutputType' _avg: - $ref: '#/components/schemas/PostAvgAggregateOutputType' + $ref: '#/components/schemas/Post_ItemAvgAggregateOutputType' _sum: - $ref: '#/components/schemas/PostSumAggregateOutputType' + $ref: '#/components/schemas/Post_ItemSumAggregateOutputType' _min: - $ref: '#/components/schemas/PostMinAggregateOutputType' + $ref: '#/components/schemas/Post_ItemMinAggregateOutputType' _max: - $ref: '#/components/schemas/PostMaxAggregateOutputType' + $ref: '#/components/schemas/Post_ItemMaxAggregateOutputType' required: - id - createdAt @@ -2116,7 +2053,7 @@ components: type: string role: $ref: '#/components/schemas/Role' - PostCountAggregateOutputType: + Post_ItemCountAggregateOutputType: type: object properties: id: @@ -2144,17 +2081,17 @@ components: - published - viewCount - _all - PostAvgAggregateOutputType: + Post_ItemAvgAggregateOutputType: type: object properties: viewCount: type: number - PostSumAggregateOutputType: + Post_ItemSumAggregateOutputType: type: object properties: viewCount: type: integer - PostMinAggregateOutputType: + Post_ItemMinAggregateOutputType: type: object properties: id: @@ -2173,7 +2110,7 @@ components: type: boolean viewCount: type: integer - PostMaxAggregateOutputType: + Post_ItemMaxAggregateOutputType: type: object properties: id: @@ -2413,91 +2350,91 @@ components: $ref: '#/components/schemas/UserMaxAggregateInput' meta: $ref: '#/components/schemas/_Meta' - PostCreateArgs: + Post_ItemCreateArgs: type: object required: - data properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' data: - $ref: '#/components/schemas/PostCreateInput' + $ref: '#/components/schemas/Post_ItemCreateInput' meta: $ref: '#/components/schemas/_Meta' - PostCreateManyArgs: + Post_ItemCreateManyArgs: type: object required: - data properties: data: - $ref: '#/components/schemas/PostCreateManyInput' + $ref: '#/components/schemas/Post_ItemCreateManyInput' meta: $ref: '#/components/schemas/_Meta' - PostFindUniqueArgs: + Post_ItemFindUniqueArgs: type: object required: - where properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' meta: $ref: '#/components/schemas/_Meta' - PostFindFirstArgs: + Post_ItemFindFirstArgs: type: object properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' meta: $ref: '#/components/schemas/_Meta' - PostFindManyArgs: + Post_ItemFindManyArgs: type: object properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' meta: $ref: '#/components/schemas/_Meta' - PostUpdateArgs: + Post_ItemUpdateArgs: type: object required: - where - data properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' data: - $ref: '#/components/schemas/PostUpdateInput' + $ref: '#/components/schemas/Post_ItemUpdateInput' meta: $ref: '#/components/schemas/_Meta' - PostUpdateManyArgs: + Post_ItemUpdateManyArgs: type: object required: - data properties: where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' data: - $ref: '#/components/schemas/PostUpdateManyMutationInput' + $ref: '#/components/schemas/Post_ItemUpdateManyMutationInput' meta: $ref: '#/components/schemas/_Meta' - PostUpsertArgs: + Post_ItemUpsertArgs: type: object required: - create @@ -2505,100 +2442,76 @@ components: - where properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' create: - $ref: '#/components/schemas/PostCreateInput' + $ref: '#/components/schemas/Post_ItemCreateInput' update: - $ref: '#/components/schemas/PostUpdateInput' + $ref: '#/components/schemas/Post_ItemUpdateInput' meta: $ref: '#/components/schemas/_Meta' - PostDeleteUniqueArgs: + Post_ItemDeleteUniqueArgs: type: object required: - where properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' include: - $ref: '#/components/schemas/PostInclude' + $ref: '#/components/schemas/Post_ItemInclude' where: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' meta: $ref: '#/components/schemas/_Meta' - PostDeleteManyArgs: + Post_ItemDeleteManyArgs: type: object properties: where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' meta: $ref: '#/components/schemas/_Meta' - PostCountArgs: + Post_ItemCountArgs: type: object properties: select: - $ref: '#/components/schemas/PostSelect' + $ref: '#/components/schemas/Post_ItemSelect' where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' meta: $ref: '#/components/schemas/_Meta' - PostAggregateArgs: + Post_ItemAggregateArgs: type: object properties: where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' orderBy: - $ref: '#/components/schemas/PostOrderByWithRelationInput' + $ref: '#/components/schemas/Post_ItemOrderByWithRelationInput' cursor: - $ref: '#/components/schemas/PostWhereUniqueInput' + $ref: '#/components/schemas/Post_ItemWhereUniqueInput' take: type: integer skip: type: integer - _count: - oneOf: - - type: boolean - - $ref: '#/components/schemas/PostCountAggregateInput' - _min: - $ref: '#/components/schemas/PostMinAggregateInput' - _max: - $ref: '#/components/schemas/PostMaxAggregateInput' - _sum: - $ref: '#/components/schemas/PostSumAggregateInput' - _avg: - $ref: '#/components/schemas/PostAvgAggregateInput' meta: $ref: '#/components/schemas/_Meta' - PostGroupByArgs: + Post_ItemGroupByArgs: type: object properties: where: - $ref: '#/components/schemas/PostWhereInput' + $ref: '#/components/schemas/Post_ItemWhereInput' orderBy: - $ref: '#/components/schemas/PostOrderByWithRelationInput' + $ref: '#/components/schemas/Post_ItemOrderByWithRelationInput' by: - $ref: '#/components/schemas/PostScalarFieldEnum' + $ref: '#/components/schemas/Post_ItemScalarFieldEnum' having: - $ref: '#/components/schemas/PostScalarWhereWithAggregatesInput' + $ref: '#/components/schemas/Post_ItemScalarWhereWithAggregatesInput' take: type: integer skip: type: integer - _count: - oneOf: - - type: boolean - - $ref: '#/components/schemas/PostCountAggregateInput' - _min: - $ref: '#/components/schemas/PostMinAggregateInput' - _max: - $ref: '#/components/schemas/PostMaxAggregateInput' - _sum: - $ref: '#/components/schemas/PostSumAggregateInput' - _avg: - $ref: '#/components/schemas/PostAvgAggregateInput' meta: $ref: '#/components/schemas/_Meta' paths: @@ -3188,12 +3101,12 @@ paths: content: application/json: schema: {} - /post/create: + /post_Item/create: post: - operationId: createPost - description: Create a new Post + operationId: createPost_Item + description: Create a new Post_Item tags: - - post + - post_Item responses: '201': description: Successful operation @@ -3205,7 +3118,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3226,13 +3139,13 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostCreateArgs' - /post/createMany: + $ref: '#/components/schemas/Post_ItemCreateArgs' + /post_Item/createMany: post: - operationId: createManyPost - description: Create several Post + operationId: createManyPost_Item + description: Create several Post_Item tags: - - post + - post_Item responses: '201': description: Successful operation @@ -3265,13 +3178,13 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostCreateManyArgs' - /post/findUnique: + $ref: '#/components/schemas/Post_ItemCreateManyArgs' + /post_Item/findUnique: get: - operationId: findUniquePost - description: Find one unique Post + operationId: findUniquePost_Item + description: Find one unique Post_Item tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3283,7 +3196,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3308,19 +3221,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostFindUniqueArgs' + $ref: '#/components/schemas/Post_ItemFindUniqueArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" content: application/json: schema: {} - /post/findFirst: + /post_Item/findFirst: get: - operationId: findFirstPost - description: Find the first Post matching the given condition + operationId: findFirstPost_Item + description: Find the first Post_Item matching the given condition tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3332,7 +3245,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3357,19 +3270,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostFindFirstArgs' + $ref: '#/components/schemas/Post_ItemFindFirstArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" content: application/json: schema: {} - /post/update: + /post_Item/update: patch: - operationId: updatePost - description: Update a Post + operationId: updatePost_Item + description: Update a Post_Item tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3381,7 +3294,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3402,13 +3315,13 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostUpdateArgs' - /post/updateMany: + $ref: '#/components/schemas/Post_ItemUpdateArgs' + /post_Item/updateMany: patch: - operationId: updateManyPost - description: Update Posts matching the given condition + operationId: updateManyPost_Item + description: Update Post_Items matching the given condition tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3441,13 +3354,13 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostUpdateManyArgs' - /post/upsert: + $ref: '#/components/schemas/Post_ItemUpdateManyArgs' + /post_Item/upsert: post: - operationId: upsertPost - description: Upsert a Post + operationId: upsertPost_Item + description: Upsert a Post_Item tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3459,7 +3372,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3480,13 +3393,13 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostUpsertArgs' - /post/delete: + $ref: '#/components/schemas/Post_ItemUpsertArgs' + /post_Item/delete: delete: - operationId: deletePost - description: Delete one unique Post + operationId: deletePost_Item + description: Delete one unique Post_Item tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3498,7 +3411,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/Post' + $ref: '#/components/schemas/Post_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3523,19 +3436,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostDeleteUniqueArgs' + $ref: '#/components/schemas/Post_ItemDeleteUniqueArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" content: application/json: schema: {} - /post/deleteMany: + /post_Item/deleteMany: delete: - operationId: deleteManyPost - description: Delete Posts matching the given condition + operationId: deleteManyPost_Item + description: Delete Post_Items matching the given condition tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3572,19 +3485,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostDeleteManyArgs' + $ref: '#/components/schemas/Post_ItemDeleteManyArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" content: application/json: schema: {} - /post/count: + /post_Item/count: get: - operationId: countPost - description: Find a list of Post + operationId: countPost_Item + description: Find a list of Post_Item tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3598,7 +3511,7 @@ paths: data: oneOf: - type: integer - - $ref: '#/components/schemas/PostCountAggregateOutputType' + - $ref: '#/components/schemas/Post_ItemCountAggregateOutputType' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3623,19 +3536,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostCountArgs' + $ref: '#/components/schemas/Post_ItemCountArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" content: application/json: schema: {} - /post/aggregate: + /post_Item/aggregate: get: - operationId: aggregatePost - description: Aggregate Posts + operationId: aggregatePost_Item + description: Aggregate Post_Items tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3647,7 +3560,7 @@ paths: - data properties: data: - $ref: '#/components/schemas/AggregatePost' + $ref: '#/components/schemas/AggregatePost_Item' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3672,19 +3585,19 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostAggregateArgs' + $ref: '#/components/schemas/Post_ItemAggregateArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" content: application/json: schema: {} - /post/groupBy: + /post_Item/groupBy: get: - operationId: groupByPost - description: Group Posts by fields + operationId: groupByPost_Item + description: Group Post_Items by fields tags: - - post + - post_Item responses: '200': description: Successful operation @@ -3698,7 +3611,7 @@ paths: data: type: array items: - $ref: '#/components/schemas/PostGroupByOutputType' + $ref: '#/components/schemas/Post_ItemGroupByOutputType' description: The Prisma response data serialized with superjson meta: $ref: '#/components/schemas/_Meta' @@ -3723,7 +3636,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/PostGroupByArgs' + $ref: '#/components/schemas/Post_ItemGroupByArgs' - name: meta in: query description: Superjson serialization metadata for parameter "q" diff --git a/packages/plugins/openapi/tests/openapi-restful.test.ts b/packages/plugins/openapi/tests/openapi-restful.test.ts index 6dc0649d0..13d6b5ac5 100644 --- a/packages/plugins/openapi/tests/openapi-restful.test.ts +++ b/packages/plugins/openapi/tests/openapi-restful.test.ts @@ -17,7 +17,7 @@ plugin openapi { provider = '${process.cwd()}/dist' } -enum Role { +enum role { USER ADMIN } @@ -27,11 +27,11 @@ model User { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt email String @unique - role Role @default(USER) - posts Post[] + role role @default(USER) + posts post_Item[] } -model Post { +model post_Item { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -69,7 +69,7 @@ model Bar { expect(api.tags).toEqual( expect.arrayContaining([ expect.objectContaining({ name: 'user', description: 'User operations' }), - expect.objectContaining({ name: 'post', description: 'Post-related operations' }), + expect.objectContaining({ name: 'post_Item', description: 'Post-related operations' }), ]) ); @@ -83,9 +83,9 @@ model Bar { expect(api.paths?.['/user/{id}/relationships/posts']?.['get']).toBeTruthy(); expect(api.paths?.['/user/{id}/relationships/posts']?.['post']).toBeTruthy(); expect(api.paths?.['/user/{id}/relationships/posts']?.['patch']).toBeTruthy(); - expect(api.paths?.['/post/{id}/relationships/author']?.['get']).toBeTruthy(); - expect(api.paths?.['/post/{id}/relationships/author']?.['post']).toBeUndefined(); - expect(api.paths?.['/post/{id}/relationships/author']?.['patch']).toBeTruthy(); + expect(api.paths?.['/post_Item/{id}/relationships/author']?.['get']).toBeTruthy(); + expect(api.paths?.['/post_Item/{id}/relationships/author']?.['post']).toBeUndefined(); + expect(api.paths?.['/post_Item/{id}/relationships/author']?.['patch']).toBeTruthy(); expect(api.paths?.['/foo']).toBeUndefined(); expect(api.paths?.['/bar']).toBeUndefined(); diff --git a/packages/plugins/openapi/tests/openapi-rpc.test.ts b/packages/plugins/openapi/tests/openapi-rpc.test.ts index 8af6bc086..cb9202863 100644 --- a/packages/plugins/openapi/tests/openapi-rpc.test.ts +++ b/packages/plugins/openapi/tests/openapi-rpc.test.ts @@ -17,7 +17,7 @@ plugin openapi { provider = '${process.cwd()}/dist' } -enum Role { +enum role { USER ADMIN } @@ -27,8 +27,8 @@ model User { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt email String @unique - role Role @default(USER) - posts Post[] + role role @default(USER) + posts post_Item[] @@openapi.meta({ findMany: { @@ -45,7 +45,7 @@ model User { }) } -model Post { +model post_Item { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -91,7 +91,7 @@ model Bar { expect(api.tags).toEqual( expect.arrayContaining([ expect.objectContaining({ name: 'user', description: 'User operations' }), - expect.objectContaining({ name: 'post', description: 'Post-related operations' }), + expect.objectContaining({ name: 'post_Item', description: 'Post-related operations' }), ]) ); diff --git a/packages/plugins/swr/package.json b/packages/plugins/swr/package.json index 96c0a88ea..db6abaef5 100644 --- a/packages/plugins/swr/package.json +++ b/packages/plugins/swr/package.json @@ -31,6 +31,7 @@ "change-case": "^4.1.2", "decimal.js": "^10.4.2", "lower-case-first": "^2.0.2", + "semver": "^7.3.8", "ts-morph": "^16.0.0", "upper-case-first": "^2.0.2" }, @@ -39,6 +40,7 @@ "@types/jest": "^29.5.0", "@types/node": "^18.0.0", "@types/react": "18.2.0", + "@types/semver": "^7.3.13", "@types/tmp": "^0.2.3", "@zenstackhq/testtools": "workspace:*", "copyfiles": "^2.4.1", diff --git a/packages/plugins/swr/src/generator.ts b/packages/plugins/swr/src/generator.ts index 47c68aeda..31431e74e 100644 --- a/packages/plugins/swr/src/generator.ts +++ b/packages/plugins/swr/src/generator.ts @@ -4,6 +4,7 @@ import { createProject, getDataModels, getPrismaClientImportSpec, + getPrismaVersion, requireOption, resolvePath, saveProject, @@ -12,6 +13,7 @@ import { DataModel, Model } from '@zenstackhq/sdk/ast'; import { paramCase } from 'change-case'; import { lowerCaseFirst } from 'lower-case-first'; import path from 'path'; +import semver from 'semver'; import { FunctionDeclaration, Project, SourceFile } from 'ts-morph'; import { upperCaseFirst } from 'upper-case-first'; @@ -63,6 +65,9 @@ function generateModelHooks(project: Project, outDir: string, model: DataModel, `import * as request from '@zenstackhq/swr/runtime';`, ]); + const modelNameCap = upperCaseFirst(model.name); + const prismaVersion = getPrismaVersion(); + const prefixesToMutate = ['find', 'aggregate', 'count', 'groupBy']; const useMutation = sf.addFunction({ name: `useMutate${model.name}`, @@ -180,18 +185,23 @@ function generateModelHooks(project: Project, outDir: string, model: DataModel, // aggregate if (mapping.aggregate) { - const argsType = `Prisma.${model.name}AggregateArgs`; + const argsType = `Prisma.${modelNameCap}AggregateArgs`; const inputType = `Prisma.Subset`; - const returnType = `Prisma.Get${model.name}AggregateType`; + const returnType = `Prisma.Get${modelNameCap}AggregateType`; generateQueryHook(sf, model, 'aggregate', argsType, inputType, returnType); } // groupBy if (mapping.groupBy) { + let useName = modelNameCap; + if (prismaVersion && semver.gte(prismaVersion, '5.0.0')) { + // prisma 4 and 5 different typing for "groupBy" and we have to deal with it separately + useName = model.name; + } const typeParameters = [ - `T extends Prisma.${model.name}GroupByArgs`, + `T extends Prisma.${useName}GroupByArgs`, `HasSelectOrTake extends Prisma.Or>, Prisma.Extends<'take', Prisma.Keys>>`, - `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${model.name}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${model.name}GroupByArgs['orderBy'] },`, + `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${useName}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${useName}GroupByArgs['orderBy'] },`, `OrderFields extends Prisma.ExcludeUnderscoreKeys>>`, `ByFields extends Prisma.MaybeTupleToUnion`, `ByValid extends Prisma.Has`, @@ -241,15 +251,15 @@ function generateModelHooks(project: Project, outDir: string, model: DataModel, : \`Error: Field "\${P}" in "orderBy" needs to be provided in "by"\` }[OrderFields]`, ]; - const inputType = `Prisma.SubsetIntersection & InputErrors`; + const inputType = `Prisma.SubsetIntersection & InputErrors`; const returnType = `{} extends InputErrors ? - Array & + Array & { - [P in ((keyof T) & (keyof Prisma.${model.name}GroupByOutputType))]: P extends '_count' + [P in ((keyof T) & (keyof Prisma.${modelNameCap}GroupByOutputType))]: P extends '_count' ? T[P] extends boolean ? number - : Prisma.GetScalarType - : Prisma.GetScalarType + : Prisma.GetScalarType + : Prisma.GetScalarType } > : InputErrors`; generateQueryHook(sf, model, 'groupBy', '', inputType, returnType, typeParameters); @@ -259,7 +269,7 @@ function generateModelHooks(project: Project, outDir: string, model: DataModel, { const argsType = `Prisma.${model.name}CountArgs`; const inputType = `Prisma.Subset`; - const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType : number`; + const returnType = `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType : number`; generateQueryHook(sf, model, 'count', argsType, inputType, returnType); } diff --git a/packages/plugins/swr/tests/swr.test.ts b/packages/plugins/swr/tests/swr.test.ts index 95e0aecfb..4659718da 100644 --- a/packages/plugins/swr/tests/swr.test.ts +++ b/packages/plugins/swr/tests/swr.test.ts @@ -19,11 +19,16 @@ model User { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt email String @unique - role String @default('USER') - posts Post[] + role role @default(USER) + posts post_Item[] } -model Post { +enum role { + USER + ADMIN +} + +model post_Item { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -51,6 +56,7 @@ plugin swr { ${sharedModel} `, { + provider: 'postgresql', pushDb: false, extraDependencies: [`${origDir}/dist`, 'react', '@types/react', 'swr'], compile: true, diff --git a/packages/plugins/tanstack-query/package.json b/packages/plugins/tanstack-query/package.json index 695a245da..f1aa1cc91 100644 --- a/packages/plugins/tanstack-query/package.json +++ b/packages/plugins/tanstack-query/package.json @@ -51,6 +51,7 @@ "change-case": "^4.1.2", "decimal.js": "^10.4.2", "lower-case-first": "^2.0.2", + "semver": "^7.3.8", "superjson": "^1.11.0", "ts-morph": "^16.0.0", "upper-case-first": "^2.0.2" @@ -61,6 +62,7 @@ "@types/jest": "^29.5.0", "@types/node": "^18.0.0", "@types/react": "18.2.0", + "@types/semver": "^7.3.13", "@types/tmp": "^0.2.3", "@zenstackhq/testtools": "workspace:*", "copyfiles": "^2.4.1", diff --git a/packages/plugins/tanstack-query/src/generator.ts b/packages/plugins/tanstack-query/src/generator.ts index ba8bb82ca..1b5e4178e 100644 --- a/packages/plugins/tanstack-query/src/generator.ts +++ b/packages/plugins/tanstack-query/src/generator.ts @@ -5,6 +5,7 @@ import { createProject, getDataModels, getPrismaClientImportSpec, + getPrismaVersion, requireOption, resolvePath, saveProject, @@ -13,6 +14,7 @@ import { DataModel, Model } from '@zenstackhq/sdk/ast'; import { paramCase } from 'change-case'; import { lowerCaseFirst } from 'lower-case-first'; import path from 'path'; +import semver from 'semver'; import { Project, SourceFile, VariableDeclarationKind } from 'ts-morph'; import { upperCaseFirst } from 'upper-case-first'; import { name } from '.'; @@ -218,6 +220,8 @@ function generateModelHooks( model: DataModel, mapping: DMMF.ModelMapping ) { + const modelNameCap = upperCaseFirst(model.name); + const prismaVersion = getPrismaVersion(); const fileName = paramCase(model.name); const sf = project.createSourceFile(path.join(outDir, `${fileName}.ts`), undefined, { overwrite: true }); @@ -290,15 +294,29 @@ function generateModelHooks( // aggregate if (mapping.aggregate) { - generateQueryHook(target, sf, model.name, 'aggregate', false, false, `Prisma.Get${model.name}AggregateType`); + generateQueryHook( + target, + sf, + modelNameCap, + 'aggregate', + false, + false, + `Prisma.Get${modelNameCap}AggregateType` + ); } // groupBy if (mapping.groupBy) { + let useName = modelNameCap; + // prisma 4 and 5 different typing for "groupBy" and we have to deal with it separately + if (prismaVersion && semver.gte(prismaVersion, '5.0.0')) { + useName = model.name; + } + const typeParameters = [ - `T extends Prisma.${model.name}GroupByArgs`, + `T extends Prisma.${useName}GroupByArgs`, `HasSelectOrTake extends Prisma.Or>, Prisma.Extends<'take', Prisma.Keys>>`, - `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${model.name}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${model.name}GroupByArgs['orderBy'] },`, + `OrderByArg extends Prisma.True extends HasSelectOrTake ? { orderBy: Prisma.${useName}GroupByArgs['orderBy'] }: { orderBy?: Prisma.${useName}GroupByArgs['orderBy'] },`, `OrderFields extends Prisma.ExcludeUnderscoreKeys>>`, `ByFields extends Prisma.MaybeTupleToUnion`, `ByValid extends Prisma.Has`, @@ -350,13 +368,13 @@ function generateModelHooks( ]; const returnType = `{} extends InputErrors ? - Array & + Array & { - [P in ((keyof T) & (keyof Prisma.${model.name}GroupByOutputType))]: P extends '_count' + [P in ((keyof T) & (keyof Prisma.${modelNameCap}GroupByOutputType))]: P extends '_count' ? T[P] extends boolean ? number - : Prisma.GetScalarType - : Prisma.GetScalarType + : Prisma.GetScalarType + : Prisma.GetScalarType } > : InputErrors`; @@ -368,7 +386,7 @@ function generateModelHooks( false, false, returnType, - `Prisma.SubsetIntersection & InputErrors`, + `Prisma.SubsetIntersection & InputErrors`, typeParameters ); } @@ -382,7 +400,7 @@ function generateModelHooks( 'count', false, true, - `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType : number` + `T extends { select: any; } ? T['select'] extends true ? number : Prisma.GetScalarType : number` ); } } diff --git a/packages/plugins/tanstack-query/tests/plugin.test.ts b/packages/plugins/tanstack-query/tests/plugin.test.ts index 62d605f74..43f562cf0 100644 --- a/packages/plugins/tanstack-query/tests/plugin.test.ts +++ b/packages/plugins/tanstack-query/tests/plugin.test.ts @@ -19,11 +19,16 @@ model User { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt email String @unique - role String @default('USER') - posts Post[] + role role @default(USER) + posts post_Item[] } -model Post { +enum role { + USER + ADMIN +} + +model post_Item { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -52,6 +57,7 @@ plugin tanstack { ${sharedModel} `, { + provider: 'postgresql', pushDb: false, extraDependencies: [ `${origDir}/dist`, @@ -76,6 +82,7 @@ plugin tanstack { ${sharedModel} `, { + provider: 'postgresql', pushDb: false, extraDependencies: [`${origDir}/dist`, 'svelte@^3.0.0', '@tanstack/svelte-query@4.29.7'], compile: true, diff --git a/packages/plugins/trpc/src/generator.ts b/packages/plugins/trpc/src/generator.ts index b8f239b28..9a4f2e894 100644 --- a/packages/plugins/trpc/src/generator.ts +++ b/packages/plugins/trpc/src/generator.ts @@ -236,7 +236,7 @@ function generateModelCreateRouter( }, ]); - generateRouterSchemaImports(modelRouter, model, zodSchemasImport); + generateRouterSchemaImports(modelRouter, upperCaseFirst(model), zodSchemasImport); generateHelperImport(modelRouter); if (generateClientHelpers) { generateRouterTypingImports(modelRouter, zmodel); @@ -278,7 +278,7 @@ function generateModelCreateRouter( inputType && (!generateModelActions || generateModelActions.includes(generateOpName)) ) { - generateProcedure(funcWriter, generateOpName, inputType, model, baseOpType); + generateProcedure(funcWriter, generateOpName, upperCaseFirst(inputType), model, baseOpType); if (routerTypingStructure) { routerTypingStructure.properties?.push({ diff --git a/packages/plugins/trpc/tests/trpc.test.ts b/packages/plugins/trpc/tests/trpc.test.ts index 617bbe66c..c00589b4e 100644 --- a/packages/plugins/trpc/tests/trpc.test.ts +++ b/packages/plugins/trpc/tests/trpc.test.ts @@ -28,11 +28,16 @@ model User { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt email String @unique - role String @default('USER') - posts Post[] + role role @default(USER) + posts post_Item[] } -model Post { +enum role { + USER + ADMIN +} + +model post_Item { id String @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -49,6 +54,7 @@ model Foo { } `, { + provider: 'postgresql', pushDb: false, extraDependencies: [`${origDir}/dist`, '@trpc/client', '@trpc/server'], compile: true, @@ -249,4 +255,34 @@ model Post { } ); }); + + it('mixed casing', async () => { + await loadSchema( + ` +plugin trpc { + provider = '${process.cwd()}/dist' + output = '$projectRoot/trpc' +} + +model User { + id String @id + email String @unique + posts post_item[] +} + +model post_item { + id String @id + title String + author User? @relation(fields: [authorId], references: [id]) + authorId String? +} + `, + { + pushDb: false, + extraDependencies: [`${origDir}/dist`, '@trpc/client', '@trpc/server'], + compile: true, + fullZod: true, + } + ); + }); }); diff --git a/packages/runtime/src/enhancements/policy/logger.ts b/packages/runtime/src/enhancements/policy/logger.ts index 916f7fda2..dc61c471e 100644 --- a/packages/runtime/src/enhancements/policy/logger.ts +++ b/packages/runtime/src/enhancements/policy/logger.ts @@ -10,7 +10,7 @@ export class Logger { private eventNames: Array = []; constructor(private readonly prisma: any) { - const engine = (this.prisma as any).getEngine(); + const engine = (this.prisma as any)._engine; this.emitter = engine ? (engine.logEmitter as EventEmitter) : undefined; if (this.emitter) { this.eventNames = this.emitter.eventNames(); diff --git a/packages/schema/src/plugins/zod/generator.ts b/packages/schema/src/plugins/zod/generator.ts index 678952678..49b5f9326 100644 --- a/packages/schema/src/plugins/zod/generator.ts +++ b/packages/schema/src/plugins/zod/generator.ts @@ -143,7 +143,7 @@ async function generateEnumSchemas( zmodel: Model ) { const enumTypes = [...prismaSchemaEnum, ...modelSchemaEnum]; - const enumNames = enumTypes.map((enumItem) => enumItem.name); + const enumNames = enumTypes.map((enumItem) => upperCaseFirst(enumItem.name)); Transformer.enumNames = enumNames ?? []; const transformer = new Transformer({ enumTypes, diff --git a/packages/schema/src/plugins/zod/transformer.ts b/packages/schema/src/plugins/zod/transformer.ts index 5471a843a..a05f6d27d 100644 --- a/packages/schema/src/plugins/zod/transformer.ts +++ b/packages/schema/src/plugins/zod/transformer.ts @@ -5,13 +5,14 @@ import { AUXILIARY_FIELDS, getPrismaClientImportSpec, getPrismaVersion } from '@ import { checkModelHasModelRelation, findModelByName, isAggregateInputType } from '@zenstackhq/sdk/dmmf-helpers'; import indentString from '@zenstackhq/sdk/utils'; import path from 'path'; +import * as semver from 'semver'; import { Project } from 'ts-morph'; import { upperCaseFirst } from 'upper-case-first'; import { AggregateOperationSupport, TransformerParams } from './types'; -import * as semver from 'semver'; export default class Transformer { name: string; + originalName: string; fields: PrismaDMMF.SchemaArg[]; schemaImports = new Set(); models: PrismaDMMF.Model[]; @@ -29,7 +30,8 @@ export default class Transformer { private zmodel: Model; constructor(params: TransformerParams) { - this.name = params.name ?? ''; + this.originalName = params.name ?? ''; + this.name = params.name ? upperCaseFirst(params.name) : ''; this.fields = params.fields ?? []; this.models = params.models ?? []; this.modelOperations = params.modelOperations ?? []; @@ -49,8 +51,8 @@ export default class Transformer { async generateEnumSchemas() { for (const enumType of this.enumTypes) { - const { name, values } = enumType; - const filteredValues = values.filter((v) => !AUXILIARY_FIELDS.includes(v)); + const name = upperCaseFirst(enumType.name); + const filteredValues = enumType.values.filter((v) => !AUXILIARY_FIELDS.includes(v)); const filePath = path.join(Transformer.outputPath, `enums/${name}.schema.ts`); const content = `/* eslint-disable */\n${this.generateImportZodStatement()}\n${this.generateExportSchemaStatement( @@ -61,7 +63,7 @@ export default class Transformer { } this.project.createSourceFile( path.join(Transformer.outputPath, `enums/index.ts`), - this.enumTypes.map((enumType) => `export * from './${enumType.name}.schema';`).join('\n'), + this.enumTypes.map((enumType) => `export * from './${upperCaseFirst(enumType.name)}.schema';`).join('\n'), { overwrite: true } ); } @@ -77,12 +79,11 @@ export default class Transformer { generateObjectSchema() { const zodObjectSchemaFields = this.generateObjectSchemaFields(); const objectSchema = this.prepareObjectSchema(zodObjectSchemaFields); - const objectSchemaName = this.resolveObjectSchemaName(); - const filePath = path.join(Transformer.outputPath, `objects/${objectSchemaName}.schema.ts`); + const filePath = path.join(Transformer.outputPath, `objects/${this.name}.schema.ts`); const content = '/* eslint-disable */\n' + objectSchema; this.project.createSourceFile(filePath, content, { overwrite: true }); - return `${objectSchemaName}.schema`; + return `${this.name}.schema`; } generateObjectSchemaFields() { @@ -141,7 +142,7 @@ export default class Transformer { !isFieldRef && ('prisma' || isEnum) ) { - if (inputType.type !== this.name && typeof inputType.type === 'string') { + if (inputType.type !== this.originalName && typeof inputType.type === 'string') { this.addSchemaImport(inputType.type); } @@ -204,7 +205,7 @@ export default class Transformer { } addSchemaImport(name: string) { - this.schemaImports.add(name); + this.schemaImports.add(upperCaseFirst(name)); } generatePrismaStringLine( @@ -219,8 +220,8 @@ export default class Transformer { const objectSchemaLine = isModelQueryType ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.resolveModelQuerySchemaName(modelName!, queryName!) - : `${inputType.type}ObjectSchema`; - const enumSchemaLine = `${inputType.type}Schema`; + : `${upperCaseFirst(inputType.type.toString())}ObjectSchema`; + const enumSchemaLine = `${upperCaseFirst(inputType.type.toString())}Schema`; const schema = inputType.type === this.name ? objectSchemaLine : isEnum ? enumSchemaLine : objectSchemaLine; @@ -261,11 +262,13 @@ export default class Transformer { generateExportObjectSchemaStatement(schema: string) { let name = this.name; + let origName = this.originalName; if (isAggregateInputType(name)) { name = `${name}Type`; + origName = `${origName}Type`; } - const outType = `z.ZodType>`; + const outType = `z.ZodType>`; return `type SchemaType = ${outType}; export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; } @@ -339,7 +342,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; const modelQueryTypeSuffixIndex = type.indexOf(modelQueryType); return { isModelQueryType: true, - modelName: type.substring(0, modelQueryTypeSuffixIndex), + modelName: upperCaseFirst(type.substring(0, modelQueryTypeSuffixIndex)), queryName: modelQueryTypeSuffixToQueryName[modelQueryType], }; } @@ -348,8 +351,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; } resolveModelQuerySchemaName(modelName: string, queryName: string) { - const modelNameCapitalized = upperCaseFirst(modelName); - return `${modelNameCapitalized}InputSchema.${queryName}`; + return `${modelName}InputSchema.${queryName}`; } wrapWithZodUnion(zodStringFields: string[]) { @@ -374,16 +376,12 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; return wrapped; } - resolveObjectSchemaName() { - return this.name; - } - async generateInputSchemas() { const globalExports: string[] = []; for (const modelOperation of this.modelOperations) { const { - model: modelName, + model: origModelName, findUnique, findFirst, findMany, @@ -403,10 +401,12 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; // eslint-disable-next-line @typescript-eslint/no-explicit-any } = modelOperation; + const modelName = upperCaseFirst(origModelName); + globalExports.push(`export * from './${modelName}Input.schema'`); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const model = findModelByName(this.models, modelName)!; + const model = findModelByName(this.models, origModelName)!; const { selectImport, includeImport, selectZodSchemaLineLazy, includeZodSchemaLineLazy } = this.resolveSelectIncludeImportAndZodSchemaLine(model); @@ -425,7 +425,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'` ); codeBody += `findUnique: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema }),`; - operations.push(['findUnique', modelName]); + operations.push(['findUnique', origModelName]); } if (findFirst) { @@ -433,14 +433,10 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'`, `import { ${modelName}OrderByWithRelationInputObjectSchema } from '../objects/${modelName}OrderByWithRelationInput.schema'`, `import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`, - `import { ${upperCaseFirst(modelName)}ScalarFieldEnumSchema } from '../enums/${upperCaseFirst( - modelName - )}ScalarFieldEnum.schema'` + `import { ${modelName}ScalarFieldEnumSchema } from '../enums/${modelName}ScalarFieldEnum.schema'` ); - codeBody += `findFirst: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${upperCaseFirst( - modelName - )}ScalarFieldEnumSchema).optional() }),`; - operations.push(['findFirst', modelName]); + codeBody += `findFirst: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional() }),`; + operations.push(['findFirst', origModelName]); } if (findMany) { @@ -448,14 +444,10 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'`, `import { ${modelName}OrderByWithRelationInputObjectSchema } from '../objects/${modelName}OrderByWithRelationInput.schema'`, `import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'`, - `import { ${upperCaseFirst(modelName)}ScalarFieldEnumSchema } from '../enums/${upperCaseFirst( - modelName - )}ScalarFieldEnum.schema'` + `import { ${modelName}ScalarFieldEnumSchema } from '../enums/${modelName}ScalarFieldEnum.schema'` ); - codeBody += `findMany: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${upperCaseFirst( - modelName - )}ScalarFieldEnumSchema).optional() }),`; - operations.push(['findMany', modelName]); + codeBody += `findMany: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional() }),`; + operations.push(['findMany', origModelName]); } if (createOne) { @@ -464,7 +456,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}UncheckedCreateInputObjectSchema } from '../objects/${modelName}UncheckedCreateInput.schema'` ); codeBody += `create: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: z.union([${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema]) }),`; - operations.push(['create', modelName]); + operations.push(['create', origModelName]); } if (createMany) { @@ -472,7 +464,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}CreateManyInputObjectSchema } from '../objects/${modelName}CreateManyInput.schema'` ); codeBody += `createMany: z.object({ data: z.union([${modelName}CreateManyInputObjectSchema, z.array(${modelName}CreateManyInputObjectSchema)]) }),`; - operations.push(['createMany', modelName]); + operations.push(['createMany', origModelName]); } if (deleteOne) { @@ -480,7 +472,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'` ); codeBody += `'delete': z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema }),`; - operations.push(['delete', modelName]); + operations.push(['delete', origModelName]); } if (deleteMany) { @@ -488,7 +480,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'` ); codeBody += `deleteMany: z.object({ where: ${modelName}WhereInputObjectSchema.optional() }),`; - operations.push(['deleteMany', modelName]); + operations.push(['deleteMany', origModelName]); } if (updateOne) { @@ -498,7 +490,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereUniqueInputObjectSchema } from '../objects/${modelName}WhereUniqueInput.schema'` ); codeBody += `update: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} data: z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema]), where: ${modelName}WhereUniqueInputObjectSchema }),`; - operations.push(['update', modelName]); + operations.push(['update', origModelName]); } if (updateMany) { @@ -508,7 +500,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'` ); codeBody += `updateMany: z.object({ data: z.union([${modelName}UpdateManyMutationInputObjectSchema, ${modelName}UncheckedUpdateManyInputObjectSchema]), where: ${modelName}WhereInputObjectSchema.optional() }),`; - operations.push(['updateMany', modelName]); + operations.push(['updateMany', origModelName]); } if (upsertOne) { @@ -520,47 +512,46 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}UncheckedUpdateInputObjectSchema } from '../objects/${modelName}UncheckedUpdateInput.schema'` ); codeBody += `upsert: z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} where: ${modelName}WhereUniqueInputObjectSchema, create: z.union([${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema]), update: z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema]) }),`; - operations.push(['upsert', modelName]); + operations.push(['upsert', origModelName]); } const aggregateOperations = []; // DMMF messed up the model name casing used in the aggregate operations, // AND the casing behavior varies from version to version -_-|| - const modelNameCap = upperCaseFirst(modelName); const prismaVersion = getPrismaVersion(); - if (this.aggregateOperationSupport[modelNameCap]?.count) { + if (this.aggregateOperationSupport[modelName]?.count) { imports.push( - `import { ${modelNameCap}CountAggregateInputObjectSchema } from '../objects/${modelNameCap}CountAggregateInput.schema'` + `import { ${modelName}CountAggregateInputObjectSchema } from '../objects/${modelName}CountAggregateInput.schema'` ); aggregateOperations.push( - `_count: z.union([ z.literal(true), ${modelNameCap}CountAggregateInputObjectSchema ]).optional()` + `_count: z.union([ z.literal(true), ${modelName}CountAggregateInputObjectSchema ]).optional()` ); } - if (this.aggregateOperationSupport[modelNameCap]?.min) { + if (this.aggregateOperationSupport[modelName]?.min) { imports.push( - `import { ${modelNameCap}MinAggregateInputObjectSchema } from '../objects/${modelNameCap}MinAggregateInput.schema'` + `import { ${modelName}MinAggregateInputObjectSchema } from '../objects/${modelName}MinAggregateInput.schema'` ); - aggregateOperations.push(`_min: ${modelNameCap}MinAggregateInputObjectSchema.optional()`); + aggregateOperations.push(`_min: ${modelName}MinAggregateInputObjectSchema.optional()`); } - if (this.aggregateOperationSupport[modelNameCap]?.max) { + if (this.aggregateOperationSupport[modelName]?.max) { imports.push( - `import { ${modelNameCap}MaxAggregateInputObjectSchema } from '../objects/${modelNameCap}MaxAggregateInput.schema'` + `import { ${modelName}MaxAggregateInputObjectSchema } from '../objects/${modelName}MaxAggregateInput.schema'` ); - aggregateOperations.push(`_max: ${modelNameCap}MaxAggregateInputObjectSchema.optional()`); + aggregateOperations.push(`_max: ${modelName}MaxAggregateInputObjectSchema.optional()`); } - if (this.aggregateOperationSupport[modelNameCap]?.avg) { + if (this.aggregateOperationSupport[modelName]?.avg) { imports.push( - `import { ${modelNameCap}AvgAggregateInputObjectSchema } from '../objects/${modelNameCap}AvgAggregateInput.schema'` + `import { ${modelName}AvgAggregateInputObjectSchema } from '../objects/${modelName}AvgAggregateInput.schema'` ); - aggregateOperations.push(`_avg: ${modelNameCap}AvgAggregateInputObjectSchema.optional()`); + aggregateOperations.push(`_avg: ${modelName}AvgAggregateInputObjectSchema.optional()`); } - if (this.aggregateOperationSupport[modelNameCap]?.sum) { + if (this.aggregateOperationSupport[modelName]?.sum) { imports.push( - `import { ${modelNameCap}SumAggregateInputObjectSchema } from '../objects/${modelNameCap}SumAggregateInput.schema'` + `import { ${modelName}SumAggregateInputObjectSchema } from '../objects/${modelName}SumAggregateInput.schema'` ); - aggregateOperations.push(`_sum: ${modelNameCap}SumAggregateInputObjectSchema.optional()`); + aggregateOperations.push(`_sum: ${modelName}SumAggregateInputObjectSchema.optional()`); } if (aggregate) { @@ -573,7 +564,7 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; codeBody += `aggregate: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithRelationInputObjectSchema, ${modelName}OrderByWithRelationInputObjectSchema.array()]).optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), ${aggregateOperations.join( ', ' )} }),`; - operations.push(['aggregate', modelNameCap]); + operations.push(['aggregate', modelName]); } if (groupBy) { @@ -581,17 +572,17 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; `import { ${modelName}WhereInputObjectSchema } from '../objects/${modelName}WhereInput.schema'`, `import { ${modelName}OrderByWithAggregationInputObjectSchema } from '../objects/${modelName}OrderByWithAggregationInput.schema'`, `import { ${modelName}ScalarWhereWithAggregatesInputObjectSchema } from '../objects/${modelName}ScalarWhereWithAggregatesInput.schema'`, - `import { ${modelNameCap}ScalarFieldEnumSchema } from '../enums/${modelNameCap}ScalarFieldEnum.schema'` + `import { ${modelName}ScalarFieldEnumSchema } from '../enums/${modelName}ScalarFieldEnum.schema'` ); - codeBody += `groupBy: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithAggregationInputObjectSchema, ${modelName}OrderByWithAggregationInputObjectSchema.array()]).optional(), having: ${modelName}ScalarWhereWithAggregatesInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), by: z.array(${upperCaseFirst( - modelName - )}ScalarFieldEnumSchema), ${aggregateOperations.join(', ')} }),`; + codeBody += `groupBy: z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithAggregationInputObjectSchema, ${modelName}OrderByWithAggregationInputObjectSchema.array()]).optional(), having: ${modelName}ScalarWhereWithAggregatesInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), by: z.array(${modelName}ScalarFieldEnumSchema), ${aggregateOperations.join( + ', ' + )} }),`; + // prisma 4 and 5 different typing for "groupBy" and we have to deal with it separately if (prismaVersion && semver.gte(prismaVersion, '5.0.0')) { - // Prisma V5 has a different casing for this guy ... - operations.push(['groupBy', modelName]); + operations.push(['groupBy', origModelName]); } else { - operations.push(['groupBy', modelNameCap]); + operations.push(['groupBy', modelName]); } } @@ -604,7 +595,9 @@ export const ${this.name}ObjectSchema: SchemaType = ${schema} as SchemaType;`; type ${modelName}InputSchemaType = { ${operations - .map((op) => indentString(`${op[0]}: z.ZodType`, 4)) + .map(([operation, typeName]) => + indentString(`${operation}: z.ZodType`, 4) + ) .join(',\n')} } @@ -632,7 +625,8 @@ ${globalExports.join(';\n')} } resolveSelectIncludeImportAndZodSchemaLine(model: PrismaDMMF.Model) { - const { name: modelName } = model; + const { name } = model; + const modelName = upperCaseFirst(name); const hasRelationToAnotherModel = checkModelHasModelRelation(model); diff --git a/packages/sdk/package.json b/packages/sdk/package.json index ce0256986..25a894254 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -26,7 +26,8 @@ "@zenstackhq/runtime": "workspace:*", "prettier": "^2.8.3", "semver": "^7.3.8", - "ts-morph": "^16.0.0" + "ts-morph": "^16.0.0", + "upper-case-first": "^2.0.2" }, "devDependencies": { "@types/node": "^18.0.0", diff --git a/packages/sdk/src/dmmf-helpers/aggregate-helpers.ts b/packages/sdk/src/dmmf-helpers/aggregate-helpers.ts index e2a2c05fa..662f0b8a4 100644 --- a/packages/sdk/src/dmmf-helpers/aggregate-helpers.ts +++ b/packages/sdk/src/dmmf-helpers/aggregate-helpers.ts @@ -1,4 +1,5 @@ import type { DMMF } from '@prisma/generator-helper'; +import { upperCaseFirst } from 'upper-case-first'; import { AggregateOperationSupport } from './types'; const isAggregateOutputType = (name: string) => /(?:Count|Avg|Sum|Min|Max)AggregateOutputType$/.test(name); @@ -19,7 +20,7 @@ export function addMissingInputObjectTypesForAggregate( const name = aggregateOutputType.name.replace(/(?:OutputType|Output)$/, ''); inputObjectTypes.push({ constraints: { maxNumFields: null, minNumFields: null }, - name: `${name}Input`, + name: `${upperCaseFirst(name)}Input`, fields: aggregateOutputType.fields.map((field) => ({ name: field.name, isNullable: false, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ea10d647f..39e590778 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -67,6 +67,9 @@ importers: tiny-invariant: specifier: ^1.3.1 version: 1.3.1 + upper-case-first: + specifier: ^2.0.2 + version: 2.0.2 yaml: specifier: ^2.2.1 version: 2.2.1 @@ -150,6 +153,9 @@ importers: lower-case-first: specifier: ^2.0.2 version: 2.0.2 + semver: + specifier: ^7.3.8 + version: 7.5.3 ts-morph: specifier: ^16.0.0 version: 16.0.0 @@ -169,6 +175,9 @@ importers: '@types/react': specifier: 18.2.0 version: 18.2.0 + '@types/semver': + specifier: ^7.3.13 + version: 7.5.0 '@types/tmp': specifier: ^0.2.3 version: 0.2.3 @@ -218,6 +227,9 @@ importers: lower-case-first: specifier: ^2.0.2 version: 2.0.2 + semver: + specifier: ^7.3.8 + version: 7.5.3 superjson: specifier: ^1.11.0 version: 1.11.0 @@ -243,6 +255,9 @@ importers: '@types/react': specifier: 18.2.0 version: 18.2.0 + '@types/semver': + specifier: ^7.3.13 + version: 7.5.0 '@types/tmp': specifier: ^0.2.3 version: 0.2.3 @@ -619,6 +634,9 @@ importers: ts-morph: specifier: ^16.0.0 version: 16.0.0 + upper-case-first: + specifier: ^2.0.2 + version: 2.0.2 devDependencies: '@types/node': specifier: ^18.0.0 @@ -3370,7 +3388,7 @@ packages: /@swc/helpers@0.5.1: resolution: {integrity: sha512-sJ902EfIzn1Fa+qYmjdQqh8tPsoxyBz+8yBKC2HKUxyezKJFwPGOn7pv4WY6QuQW//ySQi5lJjA/ZT9sNWWNTg==} dependencies: - tslib: 2.4.1 + tslib: 2.6.0 dev: true /@tanstack/query-core@4.27.0: @@ -10947,6 +10965,7 @@ packages: /tslib@2.4.1: resolution: {integrity: sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==} + dev: false /tslib@2.6.0: resolution: {integrity: sha512-7At1WUettjcSRHXCyYtTselblcHl9PJFFVKiCAy/bY97+BPZXSQ2wbq0P9s8tK2G7dFQfNnlJnPAiArVBVBsfA==} diff --git a/script/test-prisma-v5.sh b/script/test-prisma-v5.sh index 853c75b02..51fc8e3cb 100755 --- a/script/test-prisma-v5.sh +++ b/script/test-prisma-v5.sh @@ -1,3 +1,3 @@ echo Setting Prisma Versions to V5 -npx replace-in-file '/"prisma":\s*"\^4.0.0"/g' '"prisma": "^5.0.0"' 'packages/testtools/**/package*.json' 'tests/integration/**/package*.json' --isRegex -npx replace-in-file '/"@prisma/client":\s*"\^4.0.0"/g' '"@prisma/client": "^5.0.0"' 'packages/testtools/**/package*.json' 'tests/integration/**/package*.json' --isRegex +npx replace-in-file '/"prisma":\s*"\^4.\d.\d"/g' '"prisma": "^5.0.0"' 'packages/testtools/**/package*.json' 'tests/integration/**/package*.json' --isRegex +npx replace-in-file '/"@prisma/client":\s*"\^4.\d.\d"/g' '"@prisma/client": "^5.0.0"' 'packages/testtools/**/package*.json' 'tests/integration/**/package*.json' --isRegex \ No newline at end of file diff --git a/tests/integration/tests/cli/plugins.test.ts b/tests/integration/tests/cli/plugins.test.ts index cff7d30d8..d2461c4ec 100644 --- a/tests/integration/tests/cli/plugins.test.ts +++ b/tests/integration/tests/cli/plugins.test.ts @@ -173,7 +173,7 @@ describe('CLI Plugins Tests', () => { url = env('DATABASE_URL') } - enum Role { + enum role { USER ADMIN } @@ -181,13 +181,13 @@ describe('CLI Plugins Tests', () => { model User { id String @id @default(cuid()) email String @unique @email - role Role @default(USER) - posts Post[] + role role @default(USER) + posts post_item[] @@allow('create', true) @@allow('all', auth() == this || role == ADMIN) } - model Post { + model post_item { id String @id @default(cuid()) createdAt DateTime @default(now()) published Boolean @default(false) diff --git a/tests/integration/tests/plugins/zod.test.ts b/tests/integration/tests/plugins/zod.test.ts index 136155aaf..db1fa58f8 100644 --- a/tests/integration/tests/plugins/zod.test.ts +++ b/tests/integration/tests/plugins/zod.test.ts @@ -25,6 +25,10 @@ describe('Zod plugin tests', () => { provider = 'prisma-client-js' } + plugin zod { + provider = "@core/zod" + } + enum Role { USER ADMIN @@ -108,6 +112,66 @@ describe('Zod plugin tests', () => { expect(schemas.PostCreateSchema.safeParse({ title: 'abcde' }).success).toBeTruthy(); }); + it('mixed casing', async () => { + const model = ` + datasource db { + provider = 'postgresql' + url = env('DATABASE_URL') + } + + generator js { + provider = 'prisma-client-js' + } + + plugin zod { + provider = "@core/zod" + } + + enum role { + USER + ADMIN + } + + model User { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + email String @unique @email @endsWith('@zenstack.dev') + password String @omit + role role @default(USER) + posts post_item[] + profile userProfile? + } + + model userProfile { + id Int @id @default(autoincrement()) + bio String + user User @relation(fields: [userId], references: [id]) + userId Int @unique + } + + model post_item { + id Int @id @default(autoincrement()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + title String @length(5, 10) + author User? @relation(fields: [authorId], references: [id]) + authorId Int? + published Boolean @default(false) + viewCount Int @default(0) + reviews review[] + } + + model review { + id Int @id @default(autoincrement()) + post post_item @relation(fields: [postId], references: [id]) + postId Int @unique + } + `; + + await loadSchema(model, { addPrelude: false, pushDb: false }); + }); + it('attribute coverage', async () => { const model = ` datasource db { @@ -119,6 +183,10 @@ describe('Zod plugin tests', () => { provider = 'prisma-client-js' } + plugin zod { + provider = "@core/zod" + } + model M { id Int @id @default(autoincrement()) a String? @length(5, 10, 'must be between 5 and 10') @@ -274,6 +342,10 @@ describe('Zod plugin tests', () => { provider = 'prisma-client-js' } + plugin zod { + provider = "@core/zod" + } + model M { id Int @id @default(autoincrement()) arr Int[]