How To: Extend GraphQL to add a field
Sometimes you only need to extend GraphQL to add a field to an existing type. Here's how to do it.
Extend the schema
If it doesn't already exist, create
schemas
folder in the plugin, and add anindex.js
file there.If it doesn't already exist, create
schema.graphql
inschemas
in the plugin.Import the GraphQL file into
index.js
and default export it in an array:import schema from "./schema.graphql"; export default [schema];
NOTE: For large plugins, you can split to multiple
.graphql
files and export a multi-item array.In the
.graphql
file, use GraphQL language to extend the type with your custom field.extend type SomeType { "Custom data for some purpose documented here" myCustomField: String }
Document all fields you add using string literals. See Documenting a GraphQL Schema.
If not already done, register your schemas in the plugin's
register.js
file:import schemas from "./schemas"; export default async function register(app) { await app.registerPlugin({ graphQL: { schemas }, // other props }); }
Create a field resolver if necessary
If your field is not stored in the database in the same schema, such as if it is derived from other properties or collections or is stored in another system, then you'll also need to create a field resolver.
Create the resolver
- If it doesn't already exist, create
resolvers
folder in the plugin, and add anindex.js
file there. - In
resolvers
, create a file for the field resolver with the same name as the type the field is for, e.g.Tag.js
if you extended theTag
type. The file should look something like this initially:
export default {
myCustomField(tag, args, context) {
return null;
}
};
Replace return null
with whatever logic you need to derive the custom field value and return it. You may make the resolver function async
if necessary.
You have some freedom here to structure the
resolvers
folder in whatever way works best for your plugin. For an explanation and recommendations, refer to Understanding the Resolvers File Structure
Register the resolver
In resolvers/index.js
in the plugin, import your new file and add it to the default export object. Example:
import Tag from "./Tag"
export default {
Tag
};
If this is the first resolver for the plugin, pass the full resolvers
object to registerPlugin
in the plugin's register.js
file:
import resolvers from "./resolvers";
import schemas from "./schemas";
export default async function register(app) {
await app.registerPlugin({
graphQL: {
resolvers,
schemas
},
// other props
});
}
You should now be able to query for your custom field using GraphQL.