Skip to content

Commit

Permalink
Fix type issue with zod and Prisma's XOR by introducing a dirty type …
Browse files Browse the repository at this point in the history
…cast on the problematic schemas.
  • Loading branch information
kevin-dp committed Dec 6, 2023
1 parent ea8fbf1 commit 3317429
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
22 changes: 20 additions & 2 deletions generator/src/functions/contentWriters/writeOutputObjectType.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import { writeSelect } from './writeSelect'
import { writeNonScalarType, writeScalarType, writeSpecialType } from '..'
import { ExtendedDMMFSchemaField } from '../../classes'
import { ExtendedDMMF, ExtendedDMMFSchemaField } from '../../classes'
import { type ContentWriterOptions } from '../../types'

function modelHasRelation(
model: ExtendedDMMFSchemaField['modelType'],
dmmf: ExtendedDMMF
): boolean {
if (typeof model === 'string') {
const maybeModel = dmmf.datamodel.models.find((m) => m.name === model)
return maybeModel?.hasRelationFields ?? false
}
return false
}

export const writeOutputObjectType = (
{ fileWriter, dmmf, getSingleFileContent = false }: ContentWriterOptions,
field: ExtendedDMMFSchemaField
Expand Down Expand Up @@ -120,7 +131,14 @@ export const writeOutputObjectType = (
writer.newLine()
})
})
.write(`).strict()`)
.write(`).strict() `)
// There is a typing bug that occurs only with models that have relations.
// a dirty fix here is to typecast the value to the expected type:
// cf. https://github.com/chrishoermann/zod-prisma-types/issues/98#issuecomment-1800112669
.conditionalWrite(
modelHasRelation(field.modelType, dmmf),
`as ${field.customArgType}`
)

if (useMultipleFiles && !getSingleFileContent) {
writer.blankLine().writeLine(`export default ${field.argName}Schema;`)
Expand Down
3 changes: 2 additions & 1 deletion generator/src/functions/writeSingleFileArgTypeStatements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export const writeSingleFileArgTypeStatements: WriteStatements = (

fileWriter.writeHeading(`ARGS`, 'FAT')

dmmf.schema.outputObjectTypes.argTypes.forEach((outputType) => {
const types = dmmf.schema.outputObjectTypes
types.argTypes.forEach((outputType) => {
outputType.prismaActionFields.forEach((field) => {
writeOutputObjectType({ dmmf, fileWriter }, field)
})
Expand Down

0 comments on commit 3317429

Please sign in to comment.