feat: Allow specifying a node module for type imports (#604)

This commit is contained in:
Tim Griesser 2020-11-03 15:29:10 -05:00 committed by GitHub
parent 0064dc9be4
commit b19e83ebfc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 6 deletions

View File

@ -36,6 +36,7 @@ import {
mapObj,
PrintedGenTypingImport,
relativePathTo,
isNodeModule,
} from './utils'
const SpecifiedScalars = {
@ -167,19 +168,30 @@ export class TypegenPrinter {
if (typeof rootType !== 'string') {
const rootTypePath = rootType.path
if (typeof rootTypePath !== 'string' || !path.isAbsolute(rootTypePath)) {
if (
typeof rootTypePath !== 'string' ||
(!path.isAbsolute(rootTypePath) && !isNodeModule(rootTypePath))
) {
throw new Error(
`Expected an absolute path for the root typing path of the type ${typeName}, saw ${rootTypePath}`
)
}
if (!fs.existsSync(rootTypePath)) {
throw new Error(`Root typing path ${rootTypePath} of the type ${typeName} does not exist`)
if (isNodeModule(rootTypePath)) {
try {
require.resolve(rootTypePath)
} catch (e) {
throw new Error(`Module ${rootTypePath} for the type ${typeName} does not exist`)
}
} else if (!fs.existsSync(rootTypePath)) {
throw new Error(`Root typing path ${rootTypePath} for the type ${typeName} does not exist`)
}
const importPath = relativePathTo(rootType.path, outputPath)
.replace(/(\.d)?\.ts/, '')
.replace(/\\+/g, '/')
const importPath = isNodeModule(rootTypePath)
? rootTypePath
: relativePathTo(rootTypePath, outputPath)
.replace(/(\.d)?\.ts/, '')
.replace(/\\+/g, '/')
importMap[importPath] = importMap[importPath] || new Set()
importMap[importPath].add(rootType.alias ? `${rootType.name} as ${rootType.alias}` : rootType.name)

View File

@ -427,3 +427,7 @@ export type IsEqual<A, B> = A extends B ? (B extends A ? true : false) : false
export function dump(x: any) {
console.log(require('util').inspect(x, { depth: null }))
}
export function isNodeModule(path: string) {
return /^([A-z0-9@])/.test(path)
}

View File

@ -8,6 +8,7 @@ import {
objectType,
queryField,
resolveTypegenConfig,
scalarType,
} from '../src/core'
import { TypegenMetadata } from '../src/typegenMetadata'
@ -69,4 +70,23 @@ describe('scalarType', () => {
)
).toMatchSnapshot()
})
it('rootTyping: allows importing a node module for the typing path', async () => {
const schema = makeSchemaInternal({
types: [
scalarType({
name: 'TestScalar',
rootTyping: {
path: 'graphql',
name: 'GraphQLScalar',
},
}),
],
outputs: false,
shouldExitAfterGenerateArtifacts: false,
})
const generator = new TypegenMetadata(resolveTypegenConfig(schema.finalConfig))
const typegen = await generator.generateTypesFile(schema.schema, 'foo.ts')
expect(typegen).toMatch(/import { GraphQLScalar } from \"graphql\"/)
})
})