Reputation:
I would like to always return a field when certain requests are made so that additional actions can be performed by the client.
For example if user registration has been successful I want to show flash message. But it has to be handled by the backend and not the front end.
I could "require" clients to always request specific field that would hold the needed information but it could be easily overlooked so I'd like to return data whenever needed.
Is this possible?
Upvotes: 0
Views: 735
Reputation: 84867
There is nothing in the GraphQL spec that allows particular fields to be required in the same sense that arguments can be required. This can be handled inside the resolver, however. For example, if you have a query called getFoos
, and you want to require the clients to always request the field foo
when fetching that query, your resolver for getFoos
could look like this:
function (obj, args, ctx, info) {
const fields = info.fieldNodes[0].selectionSet.selections.filter(s => s.name.value)
if (!fields.includes('foo')) return Promise.reject(new Error('Missing field foo!'))
// continue resolving the query as normal
}
Each resolver takes as its fourth parameter an info object that contains detailed information about the request, including what fields were requested. So inside your resolver, just verify that the field was included, and if it's missing, return a rejected Promise instead. This will cause your query to fail anytime that particular field is missing.
Upvotes: 1