graphql-nexus / nexus

Code-First, Type-Safe, GraphQL Schema Construction
https://nexusjs.org
MIT License
3.4k stars 274 forks source link

New typegen auto config configuration #727

Open jasonkuhrt opened 3 years ago

jasonkuhrt commented 3 years ago

The follow proposal comes from an unplanned brainstorm session with @Weakky.

Example:

const schema = makeSchema({
  sourceTypes: {
    modules: [
      { style: 'as', name: 'Prisma', from: '@prisma/client' },
      { style: 'as', name: 'Foo', from: '@foo/bar' },
    ],
    mappings: {
      User: 'Prisma.User',
      Foo: { raw: 'ReturnType<typeof Prisma.User["abc"]>' },
    },
    mappingPatterns: [
      // lowest level
      (gqlTypeName, fullyQualifiedTSTypeName) => {
        if (!gqlTypeName.match(/.../)) {
          if (fullyQualifiedTSTypeName.startsWith('Foo')) {
            return `${gqlTypeName}Entity` as const
          }
          return undefined
        }

        return `${gqlTypeName}Entity` as const
      },
      // helper functions, we can bundle some, users can provide others
      // exactMatch(),
      // ExcludeTypes(/^Foo/)((gqlTypeName, fqtn) => ...),
      // pattern('${GraphQLTypeName}Entity'),
      // regexPattern((graphqlTypeName) => `${graphqlTypeName}Entity`),
    ],
  },
})

Types

// inject arbitrary TS types/type-logic into typegen TS file
type RawMapping = {
  raw: string
}

type NexusGenOutputTypeNames = '...'

// The types extracted from specified modules
type NexusGenTypePoolNames = '...'

// no way to express named imports, intentional
type ImportSpec = 
  | { from: string; name: string; style: 'as' | 'default'}
  | { from: RegExp; import: (path: string) => { name: string, style: 'as' | 'default' } } 

type MappingPattern = (
  graphQLSchemaTypeName: NexusGenOutputTypeNames,
  fullyQualifiedTypeScriptTypeName: NexusGenTypePoolNames
) => undefined | null | NexusGenTypePoolNames | RawMapping

type SourceTypesConfig = {
  modules: ImportSpec[]
  mappings: Record<NexusGenOutputTypeNames, NexusGenTypePoolNames | RawMapping>
  mappingPatterns: MappingPattern[]
}

Points:

jasonkuhrt commented 3 years ago

@tgriesser wdty?