super bug

This commit is contained in:
2024-11-18 15:34:32 +07:00
parent 3430971449
commit 88941394eb
6 changed files with 186 additions and 382 deletions

View File

@@ -1,12 +1,7 @@
import { JSONObjectResolver } from 'graphql-scalars'
import PrismaPlugin, {
PothosPrismaDatamodel,
PrismaClient,
} from '@pothos/plugin-prisma'
import PrismaPlugin, { PothosPrismaDatamodel, PrismaClient } from '@pothos/plugin-prisma'
import { Request, Response } from 'express'
import SmartSubscriptionPlugin, {
subscribeOptionsFromIterator,
} from '@pothos/plugin-smart-subscriptions'
import SmartSubscriptionPlugin, { subscribeOptionsFromIterator } from '@pothos/plugin-smart-subscriptions'
import ZodPlugin from '@pothos/plugin-zod'
import AuthzPlugin from '@pothos/plugin-authz'
import ErrorsPlugin from '@pothos/plugin-errors'
@@ -90,22 +85,11 @@ export class Builder extends SchemaBuilder<SchemaBuilderOption> {
constructor(private readonly prisma: PrismaClient) {
super({
plugins: [
PrismaPlugin,
PrismaUtils,
SimpleObjectPlugin,
SmartSubscriptionPlugin,
RelayPlugin,
ErrorsPlugin,
AuthzPlugin,
ZodPlugin,
],
plugins: [PrismaPlugin, PrismaUtils, SimpleObjectPlugin, SmartSubscriptionPlugin, RelayPlugin, ErrorsPlugin, AuthzPlugin, ZodPlugin],
smartSubscriptions: {
debounceDelay: 1000,
...subscribeOptionsFromIterator((name, context) => {
return context.isSubscription
? context.websocket.pubSub.asyncIterator(name)
: context.http.pubSub.asyncIterator(name)
return context.isSubscription ? context.websocket.pubSub.asyncIterator(name) : context.http.pubSub.asyncIterator(name)
}),
},
zod: {
@@ -174,13 +158,9 @@ export class Builder extends SchemaBuilder<SchemaBuilderOption> {
this.globalConnectionField('totalCount', (t) =>
t.int({
nullable: true,
resolve: (parent) =>
typeof parent.totalCount === 'function'
? parent.totalCount()
: parent.totalCount,
resolve: (parent) => (typeof parent.totalCount === 'function' ? parent.totalCount() : parent.totalCount),
}),
)
}
}
export type BuilderTypes =
PothosSchemaTypes.ExtendDefaultTypes<SchemaBuilderOption>
export type BuilderTypes = PothosSchemaTypes.ExtendDefaultTypes<SchemaBuilderOption>

View File

@@ -1,13 +1,6 @@
import { Inject, Injectable } from '@nestjs/common'
import {
type BaseEnum,
type EnumRef,
InputObjectRef,
type InputType,
type InputTypeParam,
type SchemaTypes,
} from '@pothos/core'
import { type BaseEnum, type EnumRef, InputObjectRef, type InputType, type InputTypeParam, type SchemaTypes } from '@pothos/core'
import { type PrismaModelTypes, getModel } from '@pothos/plugin-prisma'
import type { FilterOps } from '@pothos/plugin-prisma-utils'
import * as Prisma from '@prisma/client'
@@ -15,31 +8,15 @@ import { SchemaBuilderToken } from '@smatch-corp/nestjs-pothos'
const filterOps = ['equals', 'in', 'notIn', 'not'] as const
const sortableFilterProps = ['lt', 'lte', 'gt', 'gte'] as const
const stringFilterOps = [
...filterOps,
'contains',
'startsWith',
'endsWith',
'mode',
'search',
] as const
const stringFilterOps = [...filterOps, 'contains', 'startsWith', 'endsWith', 'mode', 'search'] as const
const sortableTypes = ['String', 'Int', 'Float', 'DateTime', 'BigInt'] as const
const listOps = ['every', 'some', 'none'] as const
const scalarListOps = [
'has',
'hasSome',
'hasEvery',
'isEmpty',
'equals',
] as const
const scalarListOps = ['has', 'hasSome', 'hasEvery', 'isEmpty', 'equals'] as const
const JsonFilterOps = ['equals', 'in', 'notIn', 'not'] as const
const EnumFilterOps = ['equals', 'not'] as const
@Injectable()
export class PrismaCrudGenerator<Types extends SchemaTypes> {
private refCache = new Map<
InputType<Types> | string,
Map<string, InputObjectRef<Types, unknown>>
>()
private refCache = new Map<InputType<Types> | string, Map<string, InputObjectRef<Types, unknown>>>()
private enumRefs = new Map<string, EnumRef<Types, unknown>>()
@@ -49,9 +26,7 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
private builder: PothosSchemaTypes.SchemaBuilder<Types>,
) {}
findManyArgs<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
) {
findManyArgs<Name extends string & keyof Types['PrismaTypes']>(modelName: Name) {
return this.builder.args((t) => ({
filter: t.field({
type: this.getWhere(modelName),
@@ -78,9 +53,7 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
}))
}
findUniqueArgs<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
) {
findUniqueArgs<Name extends string & keyof Types['PrismaTypes']>(modelName: Name) {
return this.builder.args((t) => ({
where: t.field({
type: this.getWhereUnique(modelName),
@@ -89,13 +62,8 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
}))
}
getWhere<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
without?: string[],
) {
const withoutName = (without ?? [])
.map((name) => `Without${capitalize(name)}`)
.join('')
getWhere<Name extends string & keyof Types['PrismaTypes']>(modelName: Name, without?: string[]) {
const withoutName = (without ?? []).map((name) => `Without${capitalize(name)}`).join('')
const fullName = `${modelName}${withoutName}Filter`
return this.getRef(modelName, fullName, () => {
@@ -105,40 +73,21 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
name: fullName,
fields: (() => {
const fields: Record<string, InputType<Types>> = {}
const withoutFields = model.fields.filter((field) =>
without?.includes(field.name),
)
const withoutFields = model.fields.filter((field) => without?.includes(field.name))
model.fields
.filter(
(field) =>
!withoutFields.some(
(f) =>
f.name === field.name ||
f.relationFromFields?.includes(field.name),
),
)
.filter((field) => !withoutFields.some((f) => f.name === field.name || f.relationFromFields?.includes(field.name)))
.forEach((field) => {
let type
switch (field.kind) {
case 'scalar':
type = field.isList
? this.getScalarListFilter(
this.mapScalarType(field.type) as InputType<Types>,
)
: this.getFilter(
this.mapScalarType(field.type) as InputType<Types>,
)
type = field.isList ? this.getScalarListFilter(this.mapScalarType(field.type) as InputType<Types>) : this.getFilter(this.mapScalarType(field.type) as InputType<Types>)
break
case 'enum':
type = field.isList
? this.getScalarListFilter(this.getEnum(field.type))
: this.getFilter(this.getEnum(field.type))
type = field.isList ? this.getScalarListFilter(this.getEnum(field.type)) : this.getFilter(this.getEnum(field.type))
break
case 'object':
type = field.isList
? this.getListFilter(this.getWhere(field.type as Name))
: this.getWhere(field.type as Name)
type = field.isList ? this.getListFilter(this.getWhere(field.type as Name)) : this.getWhere(field.type as Name)
break
case 'unsupported':
break
@@ -154,15 +103,10 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
return fields
}) as never,
}) as InputObjectRef<
Types,
(PrismaModelTypes & Types['PrismaTypes'][Name])['Where']
>
}) as InputObjectRef<Types, (PrismaModelTypes & Types['PrismaTypes'][Name])['Where']>
})
}
getWhereUnique<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
) {
getWhereUnique<Name extends string & keyof Types['PrismaTypes']>(modelName: Name) {
const name = `${modelName}UniqueFilter`
return this.getRef(modelName, name, () => {
@@ -173,15 +117,7 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
const fields: Record<string, InputType<Types>> = {}
model.fields
.filter(
(field) =>
field.isUnique ||
field.isId ||
model.uniqueIndexes.some((index) =>
index.fields.includes(field.name),
) ||
model.primaryKey?.fields.includes(field.name),
)
.filter((field) => field.isUnique || field.isId || model.uniqueIndexes.some((index) => index.fields.includes(field.name)) || model.primaryKey?.fields.includes(field.name))
.forEach((field) => {
let type
switch (field.kind) {
@@ -207,15 +143,10 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
return fields
}) as never,
}) as InputObjectRef<
Types,
(PrismaModelTypes & Types['PrismaTypes'][Name])['WhereUnique']
>
}) as InputObjectRef<Types, (PrismaModelTypes & Types['PrismaTypes'][Name])['WhereUnique']>
})
}
getOrderBy<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
) {
getOrderBy<Name extends string & keyof Types['PrismaTypes']>(modelName: Name) {
const name = `${modelName}OrderBy`
return this.getRef(modelName, name, () => {
const model = getModel(modelName, this.builder)
@@ -252,13 +183,8 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
})
}
getCreateInput<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
without?: string[],
) {
const withoutName = (without ?? [])
.map((name) => `Without${capitalize(name)}`)
.join('')
getCreateInput<Name extends string & keyof Types['PrismaTypes']>(modelName: Name, without?: string[]) {
const withoutName = (without ?? []).map((name) => `Without${capitalize(name)}`).join('')
const fullName = `${modelName}Create${withoutName}Input`
return this.getRef(modelName, fullName, () => {
@@ -267,22 +193,11 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
name: fullName,
fields: (() => {
const fields: Record<string, InputTypeParam<Types>> = {}
const withoutFields = model.fields.filter((field) =>
without?.includes(field.name),
)
const relationIds = model.fields.flatMap(
(field) => field.relationFromFields ?? [],
)
const withoutFields = model.fields.filter((field) => without?.includes(field.name))
const relationIds = model.fields.flatMap((field) => field.relationFromFields ?? [])
model.fields
.filter(
(field) =>
!withoutFields.some(
(f) =>
f.name === field.name ||
f.relationFromFields?.includes(field.name),
) && !relationIds.includes(field.name),
)
.filter((field) => !withoutFields.some((f) => f.name === field.name || f.relationFromFields?.includes(field.name)) && !relationIds.includes(field.name))
.forEach((field) => {
let type
switch (field.kind) {
@@ -308,58 +223,33 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
return fields
}) as never,
}) as InputObjectRef<
Types,
(PrismaModelTypes & Types['PrismaTypes'][Name])['Create']
>
}) as InputObjectRef<Types, (PrismaModelTypes & Types['PrismaTypes'][Name])['Create']>
})
}
getCreateRelationInput<
Name extends string & keyof Types['PrismaTypes'],
Relation extends Model['RelationName'],
Model extends
PrismaModelTypes = Types['PrismaTypes'][Name] extends PrismaModelTypes
? Types['PrismaTypes'][Name]
: never,
>(modelName: Name, relation: Relation) {
return this.getRef(
`${modelName}${capitalize(relation)}`,
'CreateRelationInput',
() => {
const model = getModel(modelName, this.builder)
return this.builder.prismaCreateRelation(modelName, relation, {
fields: () => {
const relationField = model.fields.find(
(field) => field.name === relation,
)!
const relatedModel = getModel(relationField.type, this.builder)
const relatedFieldName = relatedModel.fields.find(
(field) => field.relationName === relationField.relationName,
)!
getCreateRelationInput<Name extends string & keyof Types['PrismaTypes'], Relation extends Model['RelationName'], Model extends PrismaModelTypes = Types['PrismaTypes'][Name] extends PrismaModelTypes ? Types['PrismaTypes'][Name] : never>(
modelName: Name,
relation: Relation,
) {
return this.getRef(`${modelName}${capitalize(relation)}`, 'CreateRelationInput', () => {
const model = getModel(modelName, this.builder)
return this.builder.prismaCreateRelation(modelName, relation, {
fields: () => {
const relationField = model.fields.find((field) => field.name === relation)!
const relatedModel = getModel(relationField.type, this.builder)
const relatedFieldName = relatedModel.fields.find((field) => field.relationName === relationField.relationName)!
return {
create: this.getCreateInput(relationField.type as Name, [
relatedFieldName.name,
]),
connect: this.getWhereUnique(relationField.type as Name),
}
},
} as never) as InputObjectRef<
Types,
NonNullable<Model['Create'][Relation & keyof Model['Update']]>
>
},
)
return {
create: this.getCreateInput(relationField.type as Name, [relatedFieldName.name]),
connect: this.getWhereUnique(relationField.type as Name),
}
},
} as never) as InputObjectRef<Types, NonNullable<Model['Create'][Relation & keyof Model['Update']]>>
})
}
getCreateManyInput<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
without?: string[],
) {
const withoutName = (without ?? [])
.map((name) => `Without${capitalize(name)}`)
.join('')
getCreateManyInput<Name extends string & keyof Types['PrismaTypes']>(modelName: Name, without?: string[]) {
const withoutName = (without ?? []).map((name) => `Without${capitalize(name)}`).join('')
const fullName = `${modelName}Create${withoutName}Input`
return this.getRef(modelName, fullName, () => {
@@ -369,22 +259,11 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
name: fullName,
fields: (() => {
const fields: Record<string, InputTypeParam<Types>> = {}
const withoutFields = model.fields.filter((field) =>
without?.includes(field.name),
)
const relationIds = model.fields.flatMap(
(field) => field.relationFromFields ?? [],
)
const withoutFields = model.fields.filter((field) => without?.includes(field.name))
const relationIds = model.fields.flatMap((field) => field.relationFromFields ?? [])
model.fields
.filter(
(field) =>
!withoutFields.some(
(f) =>
f.name === field.name ||
f.relationFromFields?.includes(field.name),
) && !relationIds.includes(field.name),
)
.filter((field) => !withoutFields.some((f) => f.name === field.name || f.relationFromFields?.includes(field.name)) && !relationIds.includes(field.name))
.forEach((field) => {
let type
switch (field.kind) {
@@ -407,20 +286,12 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
return fields
}) as never,
}) as InputObjectRef<
Types,
(PrismaModelTypes & Types['PrismaTypes'][Name])['Create']
>
}) as InputObjectRef<Types, (PrismaModelTypes & Types['PrismaTypes'][Name])['Create']>
})
}
getUpdateInput<Name extends string & keyof Types['PrismaTypes']>(
modelName: Name,
without?: string[],
) {
const withoutName = (without ?? [])
.map((name) => `Without${capitalize(name)}`)
.join('')
getUpdateInput<Name extends string & keyof Types['PrismaTypes']>(modelName: Name, without?: string[]) {
const withoutName = (without ?? []).map((name) => `Without${capitalize(name)}`).join('')
const fullName = `${modelName}Update${withoutName}Input`
return this.getRef(modelName, fullName, () => {
@@ -429,22 +300,11 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
name: fullName,
fields: (() => {
const fields: Record<string, InputTypeParam<Types>> = {}
const withoutFields = model.fields.filter((field) =>
without?.includes(field.name),
)
const relationIds = model.fields.flatMap(
(field) => field.relationFromFields ?? [],
)
const withoutFields = model.fields.filter((field) => without?.includes(field.name))
const relationIds = model.fields.flatMap((field) => field.relationFromFields ?? [])
model.fields
.filter(
(field) =>
!withoutFields.some(
(f) =>
f.name === field.name ||
f.relationFromFields?.includes(field.name),
) && !relationIds.includes(field.name),
)
.filter((field) => !withoutFields.some((f) => f.name === field.name || f.relationFromFields?.includes(field.name)) && !relationIds.includes(field.name))
.forEach((field) => {
let type
switch (field.kind) {
@@ -470,88 +330,54 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
return fields
}) as never,
}) as InputObjectRef<
Types,
(PrismaModelTypes & Types['PrismaTypes'][Name])['Update']
>
}) as InputObjectRef<Types, (PrismaModelTypes & Types['PrismaTypes'][Name])['Update']>
})
}
getUpdateRelationInput<
Name extends string & keyof Types['PrismaTypes'],
Relation extends Model['RelationName'],
Model extends
PrismaModelTypes = Types['PrismaTypes'][Name] extends PrismaModelTypes
? Types['PrismaTypes'][Name]
: never,
>(modelName: Name, relation: Relation) {
return this.getRef(
`${modelName}${capitalize(relation)}`,
'UpdateRelationInput',
() => {
const model = getModel(modelName, this.builder)
return this.builder.prismaUpdateRelation(modelName, relation, {
fields: () => {
const relationField = model.fields.find(
(field) => field.name === relation,
)!
const relatedModel = getModel(relationField.type, this.builder)
const relatedFieldName = relatedModel.fields.find(
(field) => field.relationName === relationField.relationName,
)!.name
if (relationField.isList) {
return {
create: this.getCreateInput(relationField.type as Name, [
relatedFieldName,
]),
createMany: {
skipDuplicates: 'Boolean',
data: this.getCreateInput(relationField.type as Name, [
relatedFieldName,
]),
},
set: this.getWhereUnique(relationField.type as Name),
disconnect: this.getWhereUnique(relationField.type as Name),
delete: this.getWhereUnique(relationField.type as Name),
connect: this.getWhereUnique(relationField.type as Name),
update: {
where: this.getWhereUnique(relationField.type as Name),
data: this.getUpdateInput(relationField.type as Name, [
relatedFieldName,
]),
},
updateMany: {
where: this.getWhere(relationField.type as Name, [
relatedFieldName,
]),
data: this.getUpdateInput(relationField.type as Name, [
relatedFieldName,
]),
},
deleteMany: this.getWhere(relationField.type as Name, [
relatedFieldName,
]),
}
}
getUpdateRelationInput<Name extends string & keyof Types['PrismaTypes'], Relation extends Model['RelationName'], Model extends PrismaModelTypes = Types['PrismaTypes'][Name] extends PrismaModelTypes ? Types['PrismaTypes'][Name] : never>(
modelName: Name,
relation: Relation,
) {
return this.getRef(`${modelName}${capitalize(relation)}`, 'UpdateRelationInput', () => {
const model = getModel(modelName, this.builder)
return this.builder.prismaUpdateRelation(modelName, relation, {
fields: () => {
const relationField = model.fields.find((field) => field.name === relation)!
const relatedModel = getModel(relationField.type, this.builder)
const relatedFieldName = relatedModel.fields.find((field) => field.relationName === relationField.relationName)!.name
if (relationField.isList) {
return {
create: this.getCreateInput(relationField.type as Name, [
relatedFieldName,
]),
update: this.getUpdateInput(relationField.type as Name, [
relatedFieldName,
]),
create: this.getCreateInput(relationField.type as Name, [relatedFieldName]),
createMany: {
skipDuplicates: 'Boolean',
data: this.getCreateInput(relationField.type as Name, [relatedFieldName]),
},
set: this.getWhereUnique(relationField.type as Name),
disconnect: this.getWhereUnique(relationField.type as Name),
delete: this.getWhereUnique(relationField.type as Name),
connect: this.getWhereUnique(relationField.type as Name),
disconnect: relationField.isRequired ? undefined : 'Boolean',
delete: relationField.isRequired ? undefined : 'Boolean',
update: {
where: this.getWhereUnique(relationField.type as Name),
data: this.getUpdateInput(relationField.type as Name, [relatedFieldName]),
},
updateMany: {
where: this.getWhere(relationField.type as Name, [relatedFieldName]),
data: this.getUpdateInput(relationField.type as Name, [relatedFieldName]),
},
deleteMany: this.getWhere(relationField.type as Name, [relatedFieldName]),
}
},
} as never) as InputObjectRef<
Types,
NonNullable<Model['Update'][Relation & keyof Model['Update']]>
>
},
)
}
return {
create: this.getCreateInput(relationField.type as Name, [relatedFieldName]),
update: this.getUpdateInput(relationField.type as Name, [relatedFieldName]),
connect: this.getWhereUnique(relationField.type as Name),
disconnect: relationField.isRequired ? undefined : 'Boolean',
delete: relationField.isRequired ? undefined : 'Boolean',
}
},
} as never) as InputObjectRef<Types, NonNullable<Model['Update'][Relation & keyof Model['Update']]>>
})
}
private getFilter(type: InputType<Types>) {
@@ -596,12 +422,9 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
private getEnum(name: string) {
if (!this.enumRefs.has(name)) {
const enumRef = this.builder.enumType(
(Prisma as unknown as Record<string, BaseEnum>)[name],
{
name,
},
)
const enumRef = this.builder.enumType((Prisma as unknown as Record<string, BaseEnum>)[name], {
name,
})
this.enumRefs.set(name, enumRef)
}
@@ -623,11 +446,7 @@ export class PrismaCrudGenerator<Types extends SchemaTypes> {
}
}
private getRef<T extends InputObjectRef<Types, unknown>>(
key: InputType<Types> | string,
name: string,
create: () => T,
): T {
private getRef<T extends InputObjectRef<Types, unknown>>(key: InputType<Types> | string, name: string, create: () => T): T {
if (!this.refCache.has(key)) {
this.refCache.set(key, new Map())
}