Skip to content

Commit 3be4fc2

Browse files
committed
supported import path
1 parent 2286224 commit 3be4fc2

File tree

4 files changed

+48
-7
lines changed

4 files changed

+48
-7
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
node_modules
22
dist
33
.npmignore
4-
gen/schemas.ts
4+
gen/*.ts
55
package-lock.json
66
.DS_Store

codegen.yml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
overwrite: true
22
schema: "./test.graphql"
33
generates:
4-
gen/schemas.ts:
4+
gen/types.ts:
55
plugins:
66
- typescript
7+
gen/schemas.ts:
8+
plugins:
79
- ./dist/index.js:
8-
schema: yup
10+
schema: yup
11+
importFrom: ./types

src/index.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,32 @@ export const plugin: PluginFunction<ValidationSchemaPluginConfig> = async (
1111
): Promise<Types.PluginOutput> => {
1212
const { inputObjects, enums, scalars } = retrieveSchema(schema, config);
1313

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+
}
1427
return {
15-
prepend: [importSchema(config.schema)],
16-
content: [
17-
new YupGenerator({ inputObjects, enums, scalars }).generate(),
18-
].join("\n"),
28+
prepend,
29+
content:
30+
"\n" +
31+
[new YupGenerator({ inputObjects, enums, scalars }).generate()].join(
32+
"\n"
33+
),
1934
};
2035
};
2136

37+
const buildImportStatement = (types: string[], importFrom: string): string =>
38+
`import { ${types.join(", ")} } from "${importFrom}";`;
39+
2240
const importSchema = (schema?: ValidationSchema): string => {
2341
if (schema === "yup") {
2442
return ImportYup();

src/types.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,26 @@ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
2424
* ```
2525
*/
2626
schema?: ValidationSchema;
27+
28+
/**
29+
* @description import types from generated typescript type path
30+
* if not given, omit import statement.
31+
*
32+
* @exampeMarkdown
33+
* ```yml
34+
* generates:
35+
* path/to/types.ts:
36+
* plugins:
37+
* - typescript
38+
* path/to/schemas.ts:
39+
* plugins:
40+
* - graphql-codegen-validation-schema
41+
* config:
42+
* schema: yup
43+
* importFrom: ./path/to/types
44+
* ```
45+
*/
46+
importFrom?: string;
2747
}
2848

2949
export interface Nodes {

0 commit comments

Comments
 (0)