adding a field when using delegateToSchema #4312
-
Hello, I've been playing around with using delegateToSchema to forward a query to another schema. I want to add a transform to add fields that the user may not ask for, but are needed to map to other values being queried. I followed this example to create a custom transform and use the const result = await delegateToSchema({
schema: wrapSchema({
schema,
transforms: [new AddFieldToDelegatedRequest(schema, 'Country', 'code')],
executor,
}),
operation: OperationTypeNode.QUERY,
fieldName: 'countries',
args: {},
context,
info,
});
console.log('result:', result[0]); //result: [Object: null prototype] { name: 'Andorra' } * missing 'code' * export class AddFieldToDelegatedRequest implements Transform {
schema;
fieldName;
typeName;
constructor(schema, typeName, fieldName) {
this.schema = schema;
this.fieldName = fieldName;
this.typeName = typeName;
}
transformRequest(originalRequest) {
const typeInfo = new TypeInfo(this.schema);
const doc = visit(
originalRequest.document,
visitWithTypeInfo(typeInfo, {
[Kind.SELECTION_SET]: (node) => {
const parentType = typeInfo.getParentType();
if (parentType && parentType.name === this.typeName) {
const selections = [...node.selections];
// IF the field name is missing for the typename, add it
if (
!selections.find(
(s: FieldNode) => s.name.value === this.fieldName,
)
) {
selections.push({
kind: Kind.FIELD,
name: { kind: Kind.NAME, value: this.fieldName },
});
console.log('added field');
}
return { ...node, selections };
}
return node;
},
}),
);
return { ...originalRequest, document: doc };
}
transformResult(originalResult) {
console.log(
'originalResult',
JSON.stringify(originalResult.data.countries[0], null, 2),
);
return originalResult;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
As i suspected this was user error. After debugging soooooooo much code. I couldn't really figure out what was going on. While looking through docs i realized i could pass transforms as an option to |
Beta Was this translation helpful? Give feedback.
As i suspected this was user error. After debugging soooooooo much code. I couldn't really figure out what was going on. While looking through docs i realized i could pass transforms as an option to
delegateToSchema
so i moved my transform out of thewrapSchema
and added it to thedelegateToSchema
and everything worked. I'll update the repo i included in the original post.