Skip to content

Instantly share code, notes, and snippets.

@hos
Created September 6, 2021 17:30
Show Gist options
  • Save hos/eb2723ac150093eeef54d02d96830a34 to your computer and use it in GitHub Desktop.
Save hos/eb2723ac150093eeef54d02d96830a34 to your computer and use it in GitHub Desktop.
const ReplaceFieldType: Plugin = (builder) => {
// Process the output fields
builder.hook("GraphQLObjectType:fields:field", (field, build, context) => {
const { getTypeByName, graphql } = build;
const { GraphQLList, GraphQLNonNull } = graphql;
const {
scope: { pgFieldIntrospection: attr },
} = context;
if (!attr || attr.kind !== "attribute") {
return field;
}
const overrideType = attr.tags.overrideType;
if (!overrideType || typeof overrideType !== "string") {
return field;
}
const typeName = overrideType.replace("[]", "");
const isArray = overrideType.includes("[]");
const gqlType = getTypeByName(typeName);
if (!gqlType) {
return field;
}
return {
...field,
type: isArray ? new GraphQLList(new GraphQLNonNull(gqlType)) : gqlType,
};
});
// Process the input fields
builder.hook(
"GraphQLInputObjectType:fields:field",
(field, build, context) => {
const { getTypeByName, graphql } = build;
const { GraphQLList, GraphQLNonNull } = graphql;
const {
scope: { pgFieldIntrospection: attr },
} = context;
if (!attr || attr.kind !== "attribute") {
return field;
}
const overrideType = attr.tags.overrideType;
if (!overrideType) {
return field;
}
const typeName = overrideType.replace("[]", "");
const isArray = overrideType.includes("[]");
const gqlType = getTypeByName(typeName + "Input");
if (!gqlType) {
return field;
}
return {
...field,
type: isArray ? new GraphQLList(new GraphQLNonNull(gqlType)) : gqlType,
};
}
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment