|
1 | | -import { ImportYup, YupGenerator } from "./yup/index"; |
2 | | -import { ValidationSchema, ValidationSchemaPluginConfig } from "./types"; |
| 1 | +import { transformSchemaAST } from "@graphql-codegen/schema-ast"; |
| 2 | +import { YupSchemaVisitor } from "./yup/index"; |
| 3 | +import { ValidationSchemaPluginConfig } from "./types"; |
3 | 4 | import { PluginFunction, Types } from "@graphql-codegen/plugin-helpers"; |
4 | | -import { GraphQLSchema } from "graphql"; |
5 | | -import { retrieveSchema } from "./graphql"; |
| 5 | +import { GraphQLSchema, visit } from "graphql"; |
6 | 6 |
|
7 | 7 | export const plugin: PluginFunction<ValidationSchemaPluginConfig> = async ( |
8 | 8 | schema: GraphQLSchema, |
9 | 9 | _documents: Types.DocumentFile[], |
10 | 10 | config: ValidationSchemaPluginConfig |
11 | 11 | ): Promise<Types.PluginOutput> => { |
12 | | - const { inputObjects, enums, scalars } = retrieveSchema(schema, config); |
| 12 | + const { schema: _schema, ast } = transformSchemaAST(schema, config); |
| 13 | + const { buildImports, ...visitor } = YupSchemaVisitor(_schema, config); |
13 | 14 |
|
14 | | - const prepend = [importSchema(config.schema)]; |
15 | | - if (config.importFrom) { |
16 | | - prepend.push( |
17 | | - buildImportStatement( |
18 | | - [ |
19 | | - // Should put on Scalar here? |
20 | | - ...Object.values(enums).map((enumdef) => enumdef.name.value), |
21 | | - ...inputObjects.map((inputObject) => inputObject.name.value), |
22 | | - ], |
23 | | - config.importFrom |
24 | | - ) |
25 | | - ); |
26 | | - } |
27 | | - return { |
28 | | - prepend, |
29 | | - content: |
30 | | - "\n" + |
31 | | - [new YupGenerator({ inputObjects, enums, scalars }).generate()].join( |
32 | | - "\n" |
33 | | - ), |
34 | | - }; |
35 | | -}; |
| 15 | + const result = visit(ast, { |
| 16 | + leave: visitor, |
| 17 | + }); |
36 | 18 |
|
37 | | -const buildImportStatement = (types: string[], importFrom: string): string => |
38 | | - `import { ${types.join(", ")} } from "${importFrom}";`; |
| 19 | + // @ts-ignore |
| 20 | + const generated = result.definitions.filter((def) => typeof def === "string"); |
39 | 21 |
|
40 | | -const importSchema = (schema?: ValidationSchema): string => { |
41 | | - if (schema === "yup") { |
42 | | - return ImportYup(); |
43 | | - } |
44 | | - // TODO(codehex): support zod |
45 | | - return ImportYup(); |
| 22 | + return { |
| 23 | + prepend: buildImports(), |
| 24 | + content: "\n" + [...generated].join("\n"), |
| 25 | + }; |
46 | 26 | }; |
0 commit comments