Hands-On Full-Stack Web Development with GraphQL and React
上QQ阅读APP看书,第一时间看更新

Implementing GraphQL resolvers

Now that the schema is ready, we need the matching resolver functions.

Create a resolvers.js file in the graphql folder as follows:

const resolvers = {
RootQuery: {
posts(root, args, context) {
return [];
},
},
};

export default resolvers;

The resolvers object holds all types as a property. We set up RootQuery, holding the posts query in the same way as we did in our schema. The resolvers object must equal the schema but recursively merged. If you want to query a subfield, such as the user of a post, you have to extend the resolvers object with a Post object containing a user function next to RootQuery.

If we send a query for all posts, the posts function is executed. There, you can do whatever you want, but you need to return something that matches the schema. So, if you have an array of posts as the response type of RootQuery, you cannot return something different, such as just one post object instead of an array. In that case, you would receive an error.

Furthermore, GraphQL checks the data type of every property. If id is defined as Int, you cannot return a regular MongoDB id since these ids are of type String. GraphQL would throw an error too.

GraphQL will parse or cast specific data types for you if the value type is matching. For example, a  string with the value of 2.1 is parsed to  Float without any problems.  On the other hand, an empty string cannot be converted to Float, and an error would be thrown. It is better to directly have the correct data types, because this saves you casting and also prevents unwanted problems.

Our posts query will return an empty array, which would be a correct response for GraphQL. We will come back to the resolver functions later, but it is okay for the moment. You should be able to start the server again.