How to use @graphql-codegen/core - 10 common examples

To help you get started, we’ve selected a few @graphql-codegen/core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github atomist / automation-client / bin / gql-gen.ts View on Github external
if (graphqlFiles && graphqlFiles.length > 0) {
            for (const graphqlFile of graphqlFiles) {
                const content = (await fs.readFile(graphqlFile)).toString();
                const document = parse(content);
                documents.push({
                    content: document,
                    filePath: graphqlFile,
                });
            }
            config.documents = documents;

            await fs.ensureDir(path.dirname(gqlGenOutput));

            // Make all properties optional to retain backwards compatibility
            const typesContent = (await codegen(config)).replace(/ ([a-zA-Z_\-0-9]+): Maybe/g, ` $1?: Maybe`);

            // Write the new types.ts content back out
            await fs.writeFile(gqlGenOutput, `/* tslint:disable */\n\n${typesContent}`, "utf8");
        }
        process.exit(0);

    } catch (e) {
        console.error(`Generating GraphQL types failed: ${e.message}`);
        process.exit(1);
    }
    throw new Error("Should never get here, process.exit() called above");
}
github arackaf / mongo-graphql-starter / src / codeGen / createTypeScriptTypes.js View on Github external
// used by a plugin internally, although the 'typescript' plugin currently returns the string output, rather than writing to a file
    filename: outputFile,
    schema: parse(printSchema(schema)),
    plugins: [{ typescript: { skipTypename: true, avoidOptionals: true } }, { typescriptOperations: {} }],
    documents: [], //needed, for now
    pluginMap: {
      typescript: {
        plugin: typescriptPlugin
      },
      typescriptOperations: {
        plugin: typescriptOperationsPlugin
      }
    }
  };

  const output = await codegen(config);
  fs.writeFileSync(outputFile, additionalTypes + "\n\n" + output);

  console.log("TypeScript Types Generated!");
}
github dotansimha / graphql-code-generator / packages / graphql-codegen-cli / src / load.ts View on Github external
export const loadSchema = async (schemaPointers: UnnormalizedTypeDefPointer, config: Types.Config, out?: 'GraphQLSchema' | 'DocumentNode'): Promise => {
  try {
    const loaders = [new CodeFileLoader(), new GitLoader(), new GithubLoader(), new GraphQLFileLoader(), new JsonFileLoader(), new UrlLoader(), new ApolloEngineLoader(), new PrismaLoader()];
    if (out === 'DocumentNode') {
      const documents = await loadTypedefsUsingLoaders(loaders, schemaPointers, config);
      return mergeTypeDefs(documents.map(doc => doc.document));
    } else {
      const schema = await loadSchemaUsingLoaders(loaders, schemaPointers, config);
      return schema;
    }
  } catch (e) {
    throw new DetailedError(
      'Failed to load schema',
      `
        Failed to load schema from ${Object.keys(schemaPointers).join(',')}:

        ${e.message || e}
        ${e.stack || ''}
    
        GraphQL Code Generator supports:
          - ES Modules and CommonJS exports (export as default or named export "schema")
          - Introspection JSON File
          - URL of GraphQL endpoint
          - Multiple files with type definitions (glob expression)
          - String in config file
    
        Try to use one of above options and run codegen again.
github dotansimha / graphql-code-generator / packages / graphql-codegen-cli / src / config.ts View on Github external
Please make sure the --config points to a correct file.
      `
      );
    }

    throw new DetailedError(
      `Unable to find Codegen config file!`,
      `
        Please make sure that you have a configuration file under the current directory! 
      `
    );
  }

  if (result.isEmpty) {
    throw new DetailedError(
      `Found Codegen config file but it was empty!`,
      `
        Please make sure that you have a valid configuration file under the current directory!
      `
    );
  }

  return new CodegenContext({
    filepath: result.filepath,
    config: result.config as Types.Config,
  });
}
github dotansimha / graphql-code-generator / packages / graphql-codegen-cli / src / plugins.ts View on Github external
${err.message}
            `
        );
      }
    }
  }

  const possibleNamesMsg = possibleNames
    .map(name =>
      `
        - ${name}
    `.trimRight()
    )
    .join('');

  throw new DetailedError(
    `Unable to find template plugin matching ${name}`,
    `
        Unable to find template plugin matching '${name}'
        Install one of the following packages:
        
        ${possibleNamesMsg}
      `
  );
}
github dotansimha / graphql-code-generator / packages / graphql-codegen-cli / src / codegen.ts View on Github external
It should looks like that:
  
          schema:
            - my-schema.graphql
          generates:
            my-file.ts:
              - plugin1
              - plugin2
              - plugin3
          `
        );
      }
    }

    if (rootSchemas.length === 0 && Object.keys(generates).some(filename => !generates[filename].schema || generates[filename].schema.length === 0)) {
      throw new DetailedError(
        'Invalid Codegen Configuration!',
        `
        Please make sure that your codegen config file contains either the "schema" field 
        or every generated file has its own "schema" field.
        
        It should looks like that:
        schema:
          - my-schema.graphql

        or:
        generates:
          path/to/output:
            schema: my-schema.graphql
      `
      );
    }
github dotansimha / graphql-code-generator / packages / plugins / other / visitor-plugin-common / src / enum-values.ts View on Github external
for (const enumTypeName of allEnums) {
      const enumType = schema.getType(enumTypeName) as GraphQLEnumType;
      for (const { name, value } of enumType.getValues()) {
        if (value && value !== name) {
          mapOrStr[enumTypeName] = mapOrStr[enumTypeName] || {};
          if (typeof mapOrStr[enumTypeName] !== 'string' && !mapOrStr[enumTypeName][name]) {
            mapOrStr[enumTypeName][name] = value;
          }
        }
      }
    }

    const invalidMappings = Object.keys(mapOrStr).filter(gqlName => !allEnums.includes(gqlName));

    if (invalidMappings.length > 0) {
      throw new DetailedError(`Invalid 'enumValues' mapping!`, `The following types does not exist in your GraphQL schema: ${invalidMappings.join(', ')}`);
    }

    return Object.keys(mapOrStr).reduce((prev, gqlIdentifier) => {
      const pointer = mapOrStr[gqlIdentifier];

      if (typeof pointer === 'string') {
        const mapper = parseMapper(pointer, gqlIdentifier);

        return {
          ...prev,
          [gqlIdentifier]: {
            typeIdentifier: gqlIdentifier,
            sourceFile: mapper.isExternal ? mapper.source : undefined,
            sourceIdentifier: mapper.type,
            mappedValues: null,
          },
github d4rekanguok / gatsby-typescript / packages / gatsby-plugin-ts / src / graphql-codegen.config.ts View on Github external
return async (schema) => {
    const config = await createConfigFromSchema(schema)
    const output = await codegen(config)
    return fs.writeFile(config.filename, output)
  }
}
github dotansimha / graphql-code-generator / packages / graphql-codegen-cli / src / codegen.ts View on Github external
const process = async (outputArgs: Types.GenerateOptions) => {
                        const output = await codegen(outputArgs);
                        result.push({
                          filename: outputArgs.filename,
                          content: output,
                          hooks: outputConfig.hooks || {},
                        });
                      };
github d4rekanguok / gatsby-typescript / packages / gatsby-plugin-graphql-codegen / src / graphql-codegen.config.ts View on Github external
return async (schema) => {
    const config = await createConfigFromSchema(schema)
    const output = await codegen(config)
    return fs.writeFile(config.filename, output)
  }
}

@graphql-codegen/core

<p align="center"> <img src="https://github.com/dotansimha/graphql-code-generator/blob/master/logo.png?raw=true" /> </p>

MIT
Latest version published 10 months ago

Package Health Score

86 / 100
Full package analysis