Skip to content

feat: add support for namespaced imports #846

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,34 @@ import { GeneratedInput } from './graphql'
/* generates validation schema here */
```

### `schemaNamespacedImportName`

type: `string`

If defined, will use named imports from the specified module (defined in `importFrom`) rather than individual imports for each type.

```yml
generates:
path/to/types.ts:
plugins:
- typescript
path/to/schemas.ts:
plugins:
- graphql-codegen-validation-schema
config:
schema: yup
importFrom: ./path/to/types
schemaNamespacedImportName: types
```

Then the generator generates code with import statement like below.

```ts
import * as types from './graphql'

/* generates validation schema here */
```

### `useTypeImports`

type: `boolean` default: `false`
Expand Down
20 changes: 20 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,26 @@ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
* ```
*/
importFrom?: string
/**
* @description If defined, will use named imports from the specified module (defined in `importFrom`)
* rather than individual imports for each type.
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/types.ts:
* plugins:
* - typescript
* path/to/schemas.ts:
* plugins:
* - graphql-codegen-validation-schema
* config:
* schema: yup
* importFrom: ./path/to/types
* schemaNamespacedImportName: types
* ```
*/
schemaNamespacedImportName?: string
/**
* @description Will use `import type {}` rather than `import {}` when importing generated typescript types.
* This gives compatibility with TypeScript's "importsNotUsedAsValues": "error" option
Expand Down
18 changes: 11 additions & 7 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
leave: InterfaceTypeDefinitionBuilder(this.config.withObjectType, (node: InterfaceTypeDefinitionNode) => {
const visitor = this.createVisitor('output');
const name = visitor.convertName(node.name.value);
const typeName = visitor.prefixTypeNamespace(name);
this.importTypes.push(name);

// Building schema for field arguments.
Expand All @@ -82,7 +83,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`)
.withName(`${name}Schema: myzod.Type<${typeName}>`)
.withContent([`myzod.object({`, shape, '})'].join('\n'))
.string + appendArguments
);
Expand All @@ -93,7 +94,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withName(`${name}Schema(): myzod.Type<${typeName}>`)
.withBlock([indent(`return myzod.object({`), shape, indent('})')].join('\n'))
.string + appendArguments
);
Expand All @@ -107,6 +108,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
leave: ObjectTypeDefinitionBuilder(this.config.withObjectType, (node: ObjectTypeDefinitionNode) => {
const visitor = this.createVisitor('output');
const name = visitor.convertName(node.name.value);
const typeName = visitor.prefixTypeNamespace(name);
this.importTypes.push(name);

// Building schema for field arguments.
Expand All @@ -122,7 +124,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`)
.withName(`${name}Schema: myzod.Type<${typeName}>`)
.withContent(
[
`myzod.object({`,
Expand All @@ -140,7 +142,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withName(`${name}Schema(): myzod.Type<${typeName}>`)
.withBlock(
[
indent(`return myzod.object({`),
Expand All @@ -161,6 +163,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
leave: (node: EnumTypeDefinitionNode) => {
const visitor = this.createVisitor('both');
const enumname = visitor.convertName(node.name.value);
const enumTypeName = visitor.prefixTypeNamespace(enumname);
this.importTypes.push(enumname);
// z.enum are basically myzod.literals
// hoist enum declarations
Expand All @@ -178,7 +181,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`myzod.enum(${enumname})`)
.withContent(`myzod.enum(${enumTypeName})`)
.string,
);
},
Expand Down Expand Up @@ -233,14 +236,15 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
visitor: Visitor,
name: string,
) {
const typeName = visitor.prefixTypeNamespace(name);
const shape = fields.map(field => generateFieldMyZodSchema(this.config, visitor, field, 2)).join(',\n');

switch (this.config.validationSchemaExportType) {
case 'const':
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`)
.withName(`${name}Schema: myzod.Type<${typeName}>`)
.withContent(['myzod.object({', shape, '})'].join('\n'))
.string;

Expand All @@ -249,7 +253,7 @@ export class MyZodSchemaVisitor extends BaseSchemaVisitor {
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withName(`${name}Schema(): myzod.Type<${typeName}>`)
.withBlock([indent(`return myzod.object({`), shape, indent('})')].join('\n'))
.string;
}
Expand Down
10 changes: 7 additions & 3 deletions src/schema_visitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,15 @@ export abstract class BaseSchemaVisitor implements SchemaVisitor {

buildImports(): string[] {
if (this.config.importFrom && this.importTypes.length > 0) {
const namedImportPrefix = this.config.useTypeImports ? 'type ' : '';

const importCore = this.config.schemaNamespacedImportName
? `* as ${this.config.schemaNamespacedImportName}`
: `${namedImportPrefix}{ ${this.importTypes.join(', ')} }`;

return [
this.importValidationSchema(),
`import ${this.config.useTypeImports ? 'type ' : ''}{ ${this.importTypes.join(', ')} } from '${
this.config.importFrom
}'`,
`import ${importCore} from '${this.config.importFrom}'`,
];
}
return [this.importValidationSchema()];
Expand Down
12 changes: 8 additions & 4 deletions src/valibot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
leave: InterfaceTypeDefinitionBuilder(this.config.withObjectType, (node: InterfaceTypeDefinitionNode) => {
const visitor = this.createVisitor('output');
const name = visitor.convertName(node.name.value);
const typeName = visitor.prefixTypeNamespace(name);
this.importTypes.push(name);

// Building schema for field arguments.
Expand All @@ -73,7 +74,7 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): v.GenericSchema<${name}>`)
.withName(`${name}Schema(): v.GenericSchema<${typeName}>`)
.withBlock([indent(`return v.object({`), shape, indent('})')].join('\n'))
.string + appendArguments
);
Expand All @@ -87,6 +88,7 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
leave: ObjectTypeDefinitionBuilder(this.config.withObjectType, (node: ObjectTypeDefinitionNode) => {
const visitor = this.createVisitor('output');
const name = visitor.convertName(node.name.value);
const typeName = visitor.prefixTypeNamespace(name);
this.importTypes.push(name);

// Building schema for field arguments.
Expand All @@ -102,7 +104,7 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): v.GenericSchema<${name}>`)
.withName(`${name}Schema(): v.GenericSchema<${typeName}>`)
.withBlock(
[
indent(`return v.object({`),
Expand All @@ -123,6 +125,7 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
leave: (node: EnumTypeDefinitionNode) => {
const visitor = this.createVisitor('both');
const enumname = visitor.convertName(node.name.value);
const enumTypeName = visitor.prefixTypeNamespace(enumname);
this.importTypes.push(enumname);

// hoist enum declarations
Expand All @@ -138,7 +141,7 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`v.enum_(${enumname})`)
.withContent(`v.enum_(${enumTypeName})`)
.string,
);
},
Expand Down Expand Up @@ -185,14 +188,15 @@ export class ValibotSchemaVisitor extends BaseSchemaVisitor {
visitor: Visitor,
name: string,
) {
const typeName = visitor.prefixTypeNamespace(name);
const shape = fields.map(field => generateFieldValibotSchema(this.config, visitor, field, 2)).join(',\n');

switch (this.config.validationSchemaExportType) {
default:
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): v.GenericSchema<${name}>`)
.withName(`${name}Schema(): v.GenericSchema<${typeName}>`)
.withBlock([indent(`return v.object({`), shape, indent('})')].join('\n'))
.string;
}
Expand Down
10 changes: 10 additions & 0 deletions src/visitor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { BaseVisitorConvertOptions, ConvertOptions } from '@graphql-codegen/visitor-plugin-common';
import type {
ASTNode,
FieldDefinitionNode,
GraphQLSchema,
InterfaceTypeDefinitionNode,
Expand All @@ -21,6 +23,14 @@ export class Visitor extends TsVisitor {
super(schema, pluginConfig);
}

public prefixTypeNamespace(type: string): string {
if (this.pluginConfig.importFrom && this.pluginConfig.schemaNamespacedImportName) {
return `${this.pluginConfig.schemaNamespacedImportName}.${type}`;
}

return type;
}

private isSpecifiedScalarName(scalarName: string) {
return specifiedScalarTypes.some(({ name }) => name === scalarName);
}
Expand Down
27 changes: 16 additions & 11 deletions src/yup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
leave: InterfaceTypeDefinitionBuilder(this.config.withObjectType, (node: InterfaceTypeDefinitionNode) => {
const visitor = this.createVisitor('output');
const name = visitor.convertName(node.name.value);
const typeName = visitor.prefixTypeNamespace(name);
this.importTypes.push(name);

// Building schema for field arguments.
Expand All @@ -94,7 +95,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: yup.ObjectSchema<${name}>`)
.withName(`${name}Schema: yup.ObjectSchema<${typeName}>`)
.withContent([`yup.object({`, shape, '})'].join('\n'))
.string + appendArguments
);
Expand All @@ -105,7 +106,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.ObjectSchema<${name}>`)
.withName(`${name}Schema(): yup.ObjectSchema<${typeName}>`)
.withBlock([indent(`return yup.object({`), shape, indent('})')].join('\n'))
.string + appendArguments
);
Expand All @@ -119,6 +120,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
leave: ObjectTypeDefinitionBuilder(this.config.withObjectType, (node: ObjectTypeDefinitionNode) => {
const visitor = this.createVisitor('output');
const name = visitor.convertName(node.name.value);
const typeName = visitor.prefixTypeNamespace(name);
this.importTypes.push(name);

// Building schema for field arguments.
Expand All @@ -134,7 +136,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: yup.ObjectSchema<${name}>`)
.withName(`${name}Schema: yup.ObjectSchema<${typeName}>`)
.withContent(
[
`yup.object({`,
Expand All @@ -152,7 +154,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.ObjectSchema<${name}>`)
.withName(`${name}Schema(): yup.ObjectSchema<${typeName}>`)
.withBlock(
[
indent(`return yup.object({`),
Expand All @@ -173,6 +175,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
leave: (node: EnumTypeDefinitionNode) => {
const visitor = this.createVisitor('both');
const enumname = visitor.convertName(node.name.value);
const enumTypeName = visitor.prefixTypeNamespace(enumname);
this.importTypes.push(enumname);

// hoise enum declarations
Expand All @@ -193,7 +196,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`yup.string<${enumname}>().oneOf(Object.values(${enumname})).defined()`).string,
.withContent(`yup.string<${enumTypeName}>().oneOf(Object.values(${enumTypeName})).defined()`).string,
);
}
},
Expand All @@ -208,6 +211,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
const visitor = this.createVisitor('output');

const unionName = visitor.convertName(node.name.value);
const unionTypeName = visitor.prefixTypeNamespace(unionName);
this.importTypes.push(unionName);

const unionElements = node.types?.map((t) => {
Expand All @@ -230,16 +234,16 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${unionName}Schema: yup.MixedSchema<${unionName}>`)
.withContent(`union<${unionName}>(${unionElements})`)
.withName(`${unionName}Schema: yup.MixedSchema<${unionTypeName}>`)
.withContent(`union<${unionTypeName}>(${unionElements})`)
.string;
case 'function':
default:
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${unionName}Schema(): yup.MixedSchema<${unionName}>`)
.withBlock(indent(`return union<${unionName}>(${unionElements})`))
.withName(`${unionName}Schema(): yup.MixedSchema<${unionTypeName}>`)
.withBlock(indent(`return union<${unionTypeName}>(${unionElements})`))
.string;
}
},
Expand All @@ -251,14 +255,15 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
visitor: Visitor,
name: string,
) {
const typeName = visitor.prefixTypeNamespace(name);
const shape = shapeFields(fields, this.config, visitor);

switch (this.config.validationSchemaExportType) {
case 'const':
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: yup.ObjectSchema<${name}>`)
.withName(`${name}Schema: yup.ObjectSchema<${typeName}>`)
.withContent(['yup.object({', shape, '})'].join('\n'))
.string;

Expand All @@ -267,7 +272,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.ObjectSchema<${name}>`)
.withName(`${name}Schema(): yup.ObjectSchema<${typeName}>`)
.withBlock([indent(`return yup.object({`), shape, indent('})')].join('\n'))
.string;
}
Expand Down
Loading
Loading