How to use @graphql-codegen/visitor-plugin-common - 10 common examples

To help you get started, we’ve selected a few @graphql-codegen/visitor-plugin-common 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 aws-amplify / amplify-cli / packages / amplify-codegen-appsync-model-plugin / src / languages / swift-declaration-block.ts View on Github external
.map((line, index) => {
      const isLast = lines.length === index + 1;
      const isFirst = index === 0;

      if (isFirst && isLast) {
        return indent(`// ${comment} \n`, indentLevel);
      }
      line = line.split('*/').join('*\\/');
      return indent(`${isFirst ? '/*' : ''} * ${line}${isLast ? '\n */\n' : ''}`, indentLevel);
    })
    .join('\n');
github aws-amplify / amplify-cli / packages / amplify-codegen-appsync-model-plugin / src / visitors / appsync-java-visitor.ts View on Github external
.withName('Builder')
      .implements([...stepInterfaces, this.getStepInterfaceName('Build')]);

    // Add private instance fields
    [...nonNullableFields, ...nullableFields].forEach((field: CodeGenField) => {
      const fieldName = this.getFieldName(field);
      builderClassDeclaration.addClassMember(fieldName, this.getNativeType(field), '', undefined, 'private');
    });

    // methods
    // build();
    const buildImplementation = [`String id = this.id != null ? this.id : UUID.randomUUID().toString();`, ''];
    const buildParams = this.getNonConnectedField(model)
      .map(field => this.getFieldName(field))
      .join(',\n');
    buildImplementation.push(`return new ${this.getModelName(model)}(\n${indentMultiline(buildParams)});`);
    builderClassDeclaration.addClassMethod(
      'build',
      this.getModelName(model),
      indentMultiline(buildImplementation.join('\n')),
      undefined,
      [],
      'public',
      {},
      ['Override']
    );

    // non-nullable fields
    stepFields.forEach((field: CodeGenField, idx: number, fields) => {
      const isLastStep = idx === fields.length - 1;
      const fieldName = this.getFieldName(field);
      const methodName = this.getStepFunctionName(field);
github aws-amplify / amplify-cli / packages / amplify-codegen-model-plugin / src / languages / typescript-declaration-block.ts View on Github external
.map((line, index) => {
      const isLast = lines.length === index + 1;
      const isFirst = index === 0;

      if (isFirst && isLast) {
        return indent(`// ${comment} */\n`, indentLevel);
      }

      return indent(`${isFirst ? '/*' : ''} * ${line}${isLast ? '\n */\n' : ''}`, indentLevel);
    })
    .join('\n');
github aws-amplify / amplify-cli / packages / amplify-codegen-appsync-model-plugin / src / visitors / appsync-java-visitor.ts View on Github external
generateClassLoader(): string {
    const AMPLIFY_MODEL_VERSION = 'AMPLIFY_MODEL_VERSION';
    const result: string[] = [this.generatePackageName(), '', this.generateImportStatements(LOADER_IMPORT_PACKAGES)];
    result.push(
      transformComment(dedent` Contains the set of model classes that implement {@link Model}
    interface.`)
    );

    const loaderClassDeclaration = new JavaDeclarationBlock()
      .withName(LOADER_CLASS_NAME)
      .access('public')
      .final()
      .asKind('class')
      .implements(['ModelProvider']);

    // Schema version
    // private static final String AMPLIFY_MODELS_VERSION = "hash-code";
    loaderClassDeclaration.addClassMember(AMPLIFY_MODEL_VERSION, 'String', `"${this.computeVersion()}"`, [], 'private', {
      final: true,
      static: true,
    });
github dotansimha / graphql-code-generator / packages / plugins / typescript / typescript / src / visitor.ts View on Github external
EnumTypeDefinition(node: EnumTypeDefinitionNode): string {
    const enumName = (node.name as any) as string;

    // In case of mapped external enum string
    if (this.config.enumValues[enumName] && this.config.enumValues[enumName].sourceFile) {
      return `export { ${this.config.enumValues[enumName].typeIdentifier} };\n`;
    }

    const enumTypeName = this.convertName(node, { useTypesPrefix: this.config.enumPrefix });

    if (this.config.enumsAsTypes) {
      return new DeclarationBlock(this._declarationBlockConfig)
        .export()
        .asKind('type')
        .withComment((node.description as any) as string)
        .withName(enumTypeName)
        .withContent(
          '\n' +
            node.values
              .map(enumOption => {
                let enumValue: string = (enumOption.name as any) as string;
                const comment = transformComment((enumOption.description as any) as string, 1);

                if (this.config.enumValues[enumName] && this.config.enumValues[enumName].mappedValues && this.config.enumValues[enumName].mappedValues[enumValue]) {
                  enumValue = this.config.enumValues[enumName].mappedValues[enumValue];
                }

                return comment + indent(wrapWithSingleQuotes(enumValue));
github dotansimha / graphql-code-generator / packages / plugins / flow / operations / src / index.ts View on Github external
export const plugin: PluginFunction = (schema: GraphQLSchema, rawDocuments: Types.DocumentFile[], config: FlowDocumentsPluginConfig) => {
  const documents = config.flattenGeneratedTypes ? optimizeOperations(schema, rawDocuments) : rawDocuments;
  let prefix = `type $Pick = $ObjMapi(k: Key) => $ElementType>;\n`;

  const allAst = concatAST(
    documents.reduce((prev, v) => {
      return [...prev, v.content];
    }, [])
  );

  const allFragments: LoadedFragment[] = [
    ...(allAst.definitions.filter(d => d.kind === Kind.FRAGMENT_DEFINITION) as FragmentDefinitionNode[]).map(fragmentDef => ({ node: fragmentDef, name: fragmentDef.name.value, onType: fragmentDef.typeCondition.name.value, isExternal: false })),
    ...(config.externalFragments || []),
  ];

  const visitorResult = visit(allAst, {
    leave: new FlowDocumentsVisitor(schema, config, allFragments),
  });
github dotansimha / graphql-code-generator / packages / plugins / typescript / operations / src / index.ts View on Github external
export const plugin: PluginFunction = (schema: GraphQLSchema, rawDocuments: Types.DocumentFile[], config: TypeScriptDocumentsPluginConfig) => {
  const documents = config.flattenGeneratedTypes ? optimizeOperations(schema, rawDocuments) : rawDocuments;
  const allAst = concatAST(
    documents.reduce((prev, v) => {
      return [...prev, v.content];
    }, [])
  );

  const allFragments: LoadedFragment[] = [
    ...(allAst.definitions.filter(d => d.kind === Kind.FRAGMENT_DEFINITION) as FragmentDefinitionNode[]).map(fragmentDef => ({ node: fragmentDef, name: fragmentDef.name.value, onType: fragmentDef.typeCondition.name.value, isExternal: false })),
    ...(config.externalFragments || []),
  ];

  const visitorResult = visit(allAst, {
    leave: new TypeScriptDocumentsVisitor(schema, config, allFragments),
  });

  const result = visitorResult.definitions.join('\n');
github aws-amplify / amplify-cli / packages / amplify-codegen-appsync-model-plugin / src / languages / java-declaration-block.ts View on Github external
method.flags.final ? 'final' : null,
      method.flags.transient ? 'transient' : null,
      method.flags.volatile ? 'volatile' : null,
      ...(method.returnTypeAnnotations || []).map(annotation => `@${annotation}`),
      method.returnType,
      method.name,
    ].filter(f => f);

    const args = method.args.map(arg => this.printMember(arg)).join(', ');
    const comment = method.comment ? transformComment(method.comment) : '';
    const possibleException = method.exception && method.exception.length ? ` throws ${method.exception.join(', ')}` : '';
    return [
      comment,
      [pieces.join(' '), '(', args, ')', possibleException, ' ', '{'].filter(p => p).join(''),
      '\n',
      indentMultiline(method.implementation),
      '\n',
      '}',
    ]
      .filter(p => p)
      .join('');
  }
github aws-amplify / amplify-cli / packages / amplify-codegen-appsync-model-plugin / src / visitors / appsync-java-visitor.ts View on Github external
Object.entries(this.getSelectedEnums()).forEach(([name, enumValue]) => {
      const enumDeclaration = new JavaDeclarationBlock()
        .asKind('enum')
        .access('public')
        .withName(this.getEnumName(enumValue))
        .annotate(['SuppressWarnings("all")'])
        .withComment('Auto generated enum from GraphQL schema.');
      const body = Object.values(enumValue.values);
      enumDeclaration.withBlock(indentMultiline(body.join(',\n')));
      result.push(enumDeclaration.string);
    });
    return result.join('\n');
github aws-amplify / amplify-cli / packages / amplify-codegen-model-plugin / src / languages / typescript-declaration-block.ts View on Github external
}
      methodAccessAndName.push(method.name);

      const args = method.args
        .map(arg => {
          return `${arg.name}${arg.type ? `: ${arg.type}` : ''}`;
        })
        .join(', ');

      const returnType = method.returnType ? `: ${method.returnType}` : '';
      const methodHeaderStr = `${methodAccessAndName.join(' ')}(${args})${returnType}`;

      if (this._flags.isDeclaration) {
        return `${methodHeaderStr};`;
      }
      return [`${methodHeaderStr}`, '{', method.implmentation ? indentMultiline(method.implmentation) : '', '}'].join('\n');
    });
    return methods.join('\n');