How to use relay-compiler - 10 common examples

To help you get started, we’ve selected a few relay-compiler 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 facebook / relay / packages / relay-test-utils / parseGraphQLText.js View on Github external
function parseGraphQLText(
  schema: GraphQLSchema,
  text: string,
): {
  definitions: $ReadOnlyArray,
  schema: ?GraphQLSchema,
} {
  const ast = parse(text);
  // TODO T24511737 figure out if this is dangerous
  const extendedSchema = extendSchema(schema, ast, {assumeValid: true});
  const definitions = convertASTDocuments(
    extendedSchema,
    [ast],
    [],
    Parser.transform.bind(Parser),
  );
  return {
    definitions,
    schema: extendedSchema !== schema ? extendedSchema : null,
  };
}
github kiwicom / mobile / app / relay / scripts / RelayCompiler.js View on Github external
getFileFilter: RelayJSModuleParser.getFileFilter,
      getParser: RelayJSModuleParser.getParser,
      getSchema: () => getSchema(schemaPath),
      watchmanExpression: useWatchman ? buildWatchExpression(options) : null,
      filepaths: useWatchman ? null : getFilepathsFromGlob(srcDir, options),
    },
  };
  const writerConfigs = {
    default: {
      getWriter: getRelayFileWriter(srcDir),
      isGeneratedFile: (filePath: string) =>
        filePath.endsWith('.js') && filePath.includes('__generated__'),
      parser: 'default',
    },
  };
  const codegenRunner = new CodegenRunner({
    reporter,
    parserConfigs,
    writerConfigs,
    onlyValidate: options.validate,
  });
  if (!options.validate && !options.watch) {
    // eslint-disable-next-line no-console
    console.log('HINT: pass --watch to keep watching for changes.');
  }
  const result = options.watch
    ? await codegenRunner.watchAll()
    : await codegenRunner.compileAll();

  if (result === 'ERROR') {
    process.exit(100);
  }
github n1ru4l / graphql-codegen-relay-plugins / packages / graphql-codegen-relay-plugin / index.js View on Github external
if (!config.withFragmentContainer) {
      return "";
    }
    let queryName = doc.name.split("_")[0];
    if (!queryName) {
      return "";
    }
    const query = queryDocuments.find(query => query.name === queryName);

    if (!query) {
      console.warn(
        `Fragment '${doc.name}' uses relay notation but no query was found.`
      );
      return "";
    }
    const queryAst = parse(GraphQLIRPrinter.print(query));

    // @TODO: there might be multiple selection paths that use this fragment
    // build path on generated type
    const selectionPath = [];
    let currentSelectionSet = null;

    visit(queryAst, {
      enter: (node, key, parent) => {
        if (node.kind === "SelectionSet") {
          currentSelectionSet = node;
          if (parent.kind === "OperationDefinition") {
            selectionPath.push({
              type: "query",
              name: parent.name.value
            });
          } else {
github yusinto / relay-compiler-plus / src / compiler / main.js View on Github external
extensions: ['graphql'],
        include: ['**'],
        exclude: excludeGraphql,
      }),
    },
  };
  const writerConfigs = {
    js: {
      getWriter: getRelayFileWriter(srcDir, persistQuery),
      isGeneratedFile: (filePath: string) =>
        filePath.endsWith('.js') && filePath.includes('__generated__'),
      parser: 'js',
      baseParsers: ['graphql'],
    },
  };
  const codegenRunner = new CodegenRunner({
    reporter,
    parserConfigs,
    writerConfigs,
    onlyValidate: false,
    sourceControl: null,
  });

  let result = '';
  try {
    // the real work is done here
    result = await codegenRunner.compileAll();
  } catch (err) {
    console.log(`Error codegenRunner.compileAll(): ${err}`);
    throw err;
  }
github yusinto / relay-compiler-plus / src / compiler / main.js View on Github external
extensions: ['graphql'],
        include: options.include,
        exclude: options.exclude,
      }),
    },
  };
  const writerConfigs = {
    js: {
      getWriter: getRelayFileWriter(srcDir, persistQuery),
      isGeneratedFile: (filePath: string) =>
        filePath.endsWith('.js') && filePath.includes('__generated__'),
      parser: 'js',
      baseParsers: ['graphql'],
    },
  };
  const codegenRunner = new CodegenRunner({
    reporter,
    parserConfigs,
    writerConfigs,
    onlyValidate: false,
    sourceControl: null,
  });

  let result = '';
  try {
    // the real work is done here
    result = await codegenRunner.compileAll();
  } catch (err) {
    console.log(`Error codegenRunner.compileAll(): ${err}`);
    throw err;
  }
github relay-tools / relay-compiler-language-typescript / src / TypeScriptGenerator.ts View on Github external
ts.createTypeReferenceNode(responseType.name, undefined)
          ),
          objectTypeProperty(
            "variables",
            ts.createTypeReferenceNode(inputVariablesType.name, undefined)
          )
        ];

        // Generate raw response type
        let rawResponseType;
        const { normalizationIR } = options;
        if (
          normalizationIR &&
          node.directives.some(d => d.name === DIRECTIVE_NAME)
        ) {
          rawResponseType = IRVisitor.visit(
            normalizationIR,
            createRawResponseTypeVisitor(schema, state)
          );
        }
        const refetchableFragmentName = getRefetchableQueryParentFragmentName(
          state,
          node.metadata
        );
        if (state.hasConnectionResolver) {
          state.runtimeImports.add("ConnectionReference");
        }
        if (refetchableFragmentName !== null) {
          state.runtimeImports.add("FragmentReference");
        }
        const nodes = [];
        if (state.runtimeImports.size) {
github n1ru4l / graphql-codegen-relay-plugins / packages / graphql-codegen-relay-optimizer-plugin / src / index.ts View on Github external
const adjustedSchema = transformASTSchema(schema, [
    /* GraphQL */ `
      directive @connection(key: String!) on FIELD
      directive @client on FIELD
    `
  ]);
  const documentAsts = documents.reduce(
    (prev, v) => {
      return [...prev, ...v.content.definitions];
    },
    [] as DefinitionNode[]
  );

  const relayDocuments = RelayParser.transform(adjustedSchema, documentAsts);

  const fragmentCompilerContext = new GraphQLCompilerContext(
    adjustedSchema
  ).addAll(relayDocuments);

  const fragmentDocuments = fragmentCompilerContext
    .applyTransforms([
      RelayApplyFragmentArgumentTransform.transform,
      FlattenTransform.transformWithOptions({ flattenAbstractTypes: false }),
      SkipRedundantNodesTransform.transform
    ])
    .documents()
    .filter(doc => doc.kind === "Fragment");

  const queryCompilerContext = new GraphQLCompilerContext(adjustedSchema)
    .addAll(relayDocuments)
    .applyTransforms([
      RelayApplyFragmentArgumentTransform.transform,
github convoyinc / graphql-client-benchmarks / clients / relay.ts View on Github external
transformRawExample(rawExample: SingleRawExample, schema: string): RelayExample {
    const schemaAst = graphql.buildASTSchema(graphql.parse(schema));
    let context = new graphqlCompiler.CompilerContext(schemaAst);
    // In some queries, we leverage Hermes' @static directive; but Relay doesn't
    // like unknown directives. Quick hack to remove it.
    const scrubbedOperation = rawExample.operation.replace(/@static/g, '');
    context = context.addAll(graphqlCompiler.Parser.parse(schemaAst, scrubbedOperation));
    const artifacts = relayCompiler.compileRelayArtifacts(context, TRANSFORMS) as any[];

    const requests = artifacts.filter(a => a.kind !== 'Fragment');
    if (requests.length !== 1) {
      throw new Error(`Expected the query document to contain only one operation`);
    }
    const request = relayRuntime.getRequest(requests[0]);
    const operation = relayRuntime.createOperationSelector(request, rawExample.variables);

    return {
      operation,
      response: rawExample.response,
    };
  }
github relay-tools / relay-compiler-language-typescript / src / codegen / RelayFileWriter.ts View on Github external
}
			return cachedDir;
		};

		const transformedTSContext = compilerContext.applyTransforms(
			RelayTSGenerator.TS_TRANSFORMS,
			this._reporter,
		);
		const transformedQueryContext = compilerContext.applyTransforms(
			[
				...this._config.compilerTransforms.commonTransforms,
				...this._config.compilerTransforms.queryTransforms,
			],
			this._reporter,
		);
		const artifacts = compileRelayArtifacts(
			compilerContext,
			this._config.compilerTransforms,
			this._reporter,
		);

		const existingFragmentNames = new Set(
			definitions.map(definition => definition.name),
		);

		// TODO(T22651734): improve this to correctly account for fragments that
		// have generated flow types.
		baseDefinitionNames.forEach(baseDefinitionName => {
			existingFragmentNames.delete(baseDefinitionName);
		});

		const formatModule = this._config.formatModule;
github dotansimha / graphql-code-generator / packages / plugins / other / relay-operation-optimizer / src / index.ts View on Github external
export const plugin: PluginFunction = (
  schema: GraphQLSchema,
  documents: Types.DocumentFile[],
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  config: RelayOptimizerPluginConfig
) => {
  // @TODO way for users to define directives they use, otherwise relay will throw an unknown directive error
  // Maybe we can scan the queries and add them dynamically without users having to do some extra stuff
  // transformASTSchema creates a new schema instance instead of mutating the old one
  const adjustedSchema = RelayCreate.create(
    printSchemaWithDirectives(
      transformASTSchema(schema, [
        /* GraphQL */ `
          directive @connection(key: String!) on FIELD
          directive @client on FIELD
        `,
      ])
    )
  );
  const documentAsts = documents.reduce((prev, v) => {
    return [...prev, ...v.content.definitions];
  }, [] as DefinitionNode[]);

  const relayDocuments = RelayParser.transform(adjustedSchema, documentAsts);

  const fragmentCompilerContext = new GraphQLCompilerContext(adjustedSchema).addAll(relayDocuments);

  const fragmentDocuments = fragmentCompilerContext