UNPKG

2.11 kBMarkdownView Raw
1# Custom Templates
2
3This generator also allow you to generate custom custom template from your GraphQL Schema.
4
5This way you can generate custom code based on your GraphQL schema / operations.
6
7To start using GraphQL code generator with custom templates, install the CLI module, and then create a JSON file called `gqlgen.json` in your project's root directory, specifying the following:
8
9```json
10{
11 "flattenTypes": true,
12 "primitives": {
13 "String": "string",
14 "Int": "number",
15 "Float": "number",
16 "Boolean": "boolean",
17 "ID": "string"
18 }
19}
20```
21
22> The purpose of this file to to tell the GraphQL code generate if you want to flatten selection set, and specify your environment's scalars transformation, for example: `String` from GraphQL is `string` in TypeScript.
23
24> To understand what `primitives` and `flattenTypes` are doing behind the scenes, [refer to `graphql-codegen-generators` package README](https://github.com/dotansimha/graphql-code-generators/blob/master/packages/graphql-codegen-core/README.md#flattentypes)
25
26Now create a simple template file with this special structure: `{file-prefix}.{file-extension}.{required-context}.gqlgen`, for example: `hoc.js.all.gqlgen`, and use any custom template, for example:
27
28```handlebars
29{{#each types}}
30 GraphQL Type: {{ name }}
31{{/each}}
32```
33
34This file will compile by the generator as Handlebars template, with the `all` context, and the result file name will be `hoc.js`.
35
36To see a full list of available contexts, [refer to `graphql-codegen-generators` package README](https://github.com/dotansimha/graphql-code-generators/blob/master/packages/graphql-codegen-core/README.md#templates)
37
38Next, run the generator from the CLI, but use `project` flag (instead of `template`), and specify the base path for you templates (the generator will look for the following file extensions: `template`, `tmpl`, `gqlgen`, `handlebars`):
39
40 $ gql-gen --project ./src/ --file ./schema.json "./src/graphql/**/*.graphql"
41
42> No need to specify the output directory, since the generator will create the generated files next to the template.
43