Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const fieldName = this.getFieldName(field);
const isLastField = nonIdFields.length - 1 === idx ? true : false;
const returnType = isLastField ? 'Build' : nonIdFields[idx + 1].name;
const interfaceName = this.getStepInterfaceName(field.name);
const interfaceDeclaration = new JavaDeclarationBlock()
.asKind('interface')
.withName(interfaceName)
.access('public');
interfaceDeclaration.withBlock(
indent(`${this.getStepInterfaceName(returnType)} ${fieldName}(${this.getNativeType(field)} ${fieldName});`)
);
return interfaceDeclaration;
});
// Builder
const builder = new JavaDeclarationBlock()
.asKind('interface')
.withName(this.getStepInterfaceName('Build'))
.access('public');
const builderBody = [];
builderBody.push(`${this.getModelName(model)} build();`);
nullableFields.forEach((field, idx) => {
const fieldName = this.getFieldName(field);
builderBody.push(`${this.getStepInterfaceName('Build')} ${fieldName}(${this.getNativeType(field)} ${fieldName});`);
});
builder.withBlock(indentMultiline(builderBody.join('\n')));
return [...interfaces, builder];
}
protected generateBuilderClass(model: CodeGenModel, classDeclaration: JavaDeclarationBlock): void {
const nonNullableFields = model.fields.filter(field => !field.isNullable);
const nullableFields = model.fields.filter(field => field.isNullable);
const writeableFields = nullableFields.filter((field: CodeGenField) => !this.READ_ONLY_FIELDS.includes(field.name));
const stepInterfaces = writeableFields.map((field: CodeGenField) => {
return this.getStepInterfaceName(field.name);
});
const builderClassDeclaration = new JavaDeclarationBlock()
.access('public')
.static()
.asKind('class')
.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();
builderClassDeclaration.addClassMethod(
'build',
export const plugin: PluginFunction = async (schema: GraphQLSchema, documents: Types.DocumentFile[], config: JavaResolversPluginRawConfig, { outputFile }): Promise => {
const relevantPath = dirname(normalize(outputFile));
const defaultPackageName = buildPackageNameFromPath(relevantPath);
const visitor = new JavaResolversVisitor(config, schema, defaultPackageName);
const printedSchema = printSchema(schema);
const astNode = parse(printedSchema);
const visitorResult = visit(astNode, { leave: visitor as any });
const mappersImports = visitor.getImports();
const packageName = visitor.getPackageName();
const blockContent = visitorResult.definitions.filter(d => typeof d === 'string').join('\n');
const wrappedContent = visitor.wrapWithClass(blockContent);
return [packageName, mappersImports, wrappedContent].join('\n');
};
ObjectTypeDefinition(node: ObjectTypeDefinitionNode): string {
return new JavaDeclarationBlock()
.access('public')
.asKind('interface')
.withName(this.convertName(node.name))
.withComment(node.description)
.withBlock(node.fields.map(f => indent((f as any)(false))).join('\n')).string;
}
public wrapWithClass(content: string): string {
return new JavaDeclarationBlock()
.access('public')
.asKind('class')
.withName(this.config.className)
.withBlock(indentMultiline(content)).string;
}
const fragmentsClassName = 'Fragments';
childFields.push({
isObject: true,
isList: false,
isFragment: true,
rawType: options.schemaType,
type: options.schemaType,
isNonNull: true,
annotation: 'Nonnull',
className: fragmentsClassName,
fieldName: 'fragments',
});
const fragmentsClass = new JavaDeclarationBlock()
.withName(fragmentsClassName)
.access('public')
.static()
.final()
.asKind('class');
const fragmentMapperClass = new JavaDeclarationBlock()
.withName('Mapper')
.access('public')
.static()
.final()
.implements([`FragmentResponseFieldMapper<${fragmentsClassName}>`])
.asKind('class');
fragmentsClass.addClassMethod(
fragmentsClassName,
private createBuilderClass(parentClassName: string, variables: ReadonlyArray): JavaDeclarationBlock {
const builderClassName = 'Builder';
const cls = new JavaDeclarationBlock()
.static()
.final()
.access('public')
.asKind('class')
.withName(builderClassName)
.addClassMethod(builderClassName, null, '');
variables.forEach(variable => {
const baseTypeNode = getBaseTypeNode(variable.type);
const schemaType = this._schema.getType(baseTypeNode.name.value);
const javaClass = this.getJavaClass(schemaType);
const annotation = isNonNullType(variable.type) ? 'Nonnull' : 'Nullable';
this._imports.add(Imports[annotation]);
cls.addClassMember(variable.variable.name.value, javaClass, null, [annotation], 'private');
cls.addClassMethod(
variable.variable.name.value,
OperationDefinition(node: OperationDefinitionNode): string {
this.visitingFragment = false;
const operationType = toPascalCase(node.operation);
const operationSchemaType = this.getRootType(node.operation);
const className = node.name.value.endsWith(operationType) ? operationType : `${node.name.value}${operationType}`;
this._imports.add(Imports[operationType]);
this._imports.add(Imports.String);
this._imports.add(Imports.Override);
this._imports.add(Imports.Generated);
this._imports.add(Imports.OperationName);
this._imports.add(Imports.Operation);
this._imports.add(Imports.ResponseFieldMapper);
const cls = new JavaDeclarationBlock()
.annotate([`Generated("Apollo GraphQL")`])
.access('public')
.final()
.asKind('class')
.withName(className);
const printed = this.printDocument(node);
cls.implements([`${operationType}<${className}.Data, ${className}.Data, ${node.variableDefinitions.length === 0 ? 'Operation' : className}.Variables>`]);
cls.addClassMember('OPERATION_DEFINITION', 'String', `"${printed}"`, [], 'public', { static: true, final: true });
cls.addClassMember('QUERY_DOCUMENT', 'String', 'OPERATION_DEFINITION', [], 'public', { static: true, final: true });
cls.addClassMember(
'OPERATION_NAME',
'OperationName',
`new OperationName() {
private transformSelectionSet(options: TransformSelectionSetOptions, isRoot = true) {
if (!options.result) {
options.result = {};
}
if (!isObjectType(options.schemaType) && !isInterfaceType(options.schemaType)) {
return options.result;
}
const className = this.createUniqueClassName(Object.keys(options.result), options.className);
const cls = new JavaDeclarationBlock()
.access('public')
.asKind('class')
.withName(className)
.implements(options.implements || []);
if (!options.nonStaticClass) {
cls.static();
}
options.result[className] = cls;
const fields = options.schemaType.getFields();
const childFields: ChildField[] = [...(options.additionalFields || [])];
const childInlineFragments: { onType: string; node: InlineFragmentNode }[] = [];
const childFragmentSpread: LoadedFragment[] = [...(options.additionalFragments || [])];
} else if (isInputObjectType(schemaType)) {
result = {
baseType: `${this.convertName(schemaType.name)}Input`,
typeName: `${this.convertName(schemaType.name)}Input`,
isScalar: false,
isArray,
nullable: nullable,
};
} else if (isEnumType(schemaType)) {
result = { isArray, baseType: this.convertName(schemaType.name), typeName: this.convertName(schemaType.name), isScalar: true, nullable: nullable };
} else {
result = { isArray, baseType: 'Any', typeName: 'Any', isScalar: true, nullable: nullable };
}
if (result) {
result.typeName = wrapTypeWithModifiers(result.typeName, typeNode, this.config.listType);
}
return result;
}