I'm conceptually stuck with graphsql (using graphql-js).
Lets's say the API user sends a query and the database-server is down and I'd like to return this information as an error in the in the
data { errors }
list.
How can i access the errors object in data and push my own error messages (e.g. about the database-server outage) there?
Next thing I am wondering about is how to add an addition messages object to the data object.
Let's say The user has requested a database item by id (e.g. a particular account) and that item does not exist. Now, I'd like to return something like this:
{
data: {
messages: [{status: "failure", message: "This account does not exist"}]
}
}
How would I do that and would I have to define the messages also as a type?
One way of having
errors
andmessages
as part of query result is to include them as fields to your GraphQL object type(s).For example, you have a GraphQL object type
Item
with fields id, name, errors and messages. When the database server is down, onlyerrors
field of item instance is populated. When an item with the given ID is unavailable,messages
field is populated. When the item is available, name field is set.The only way to get
errors
andmessages
fields to appear inside of thedata
property of the GraphQL response is to include them in the type system of your GraphQL schema and to explicitly ask for them from the client. However, if you want to have a customerrors
andmessages
field that is returned on every request regardless of whether the client asked for them or not you can include them outside thedata
property.For example, if you are using
express-graphql
, it provides an extensions option that allows you attach any excess information to every response payload (https://github.com/graphql/express-graphql/blob/c92cfad64f4b18abce3cdeca36bb8553dd020773/src/index.js#L95)If you are not using
express-graphql
, you can look at it as an example of how you can include your own metadata in each response.express-graphql
is a pretty simple wrapper and you can always just write your own data into the response. For example, this is the line whereexpress-graphql
attacheserrors
(https://github.com/graphql/express-graphql/blob/c92cfad64f4b18abce3cdeca36bb8553dd020773/src/index.js#L309). You could do the same but under a different key.Best of luck!