官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 克拉玛依市| 保山市| 油尖旺区| 和龙市| 晴隆县| 香格里拉县| 五大连池市| 新丰县| 敖汉旗| 姜堰市| 云安县| 申扎县| 榕江县| 双桥区| 博湖县| 衡南县| 逊克县| 吉木乃县| 多伦县| 华阴市| 通河县| 通江县| 定边县| 姜堰市| 乌鲁木齐市| 瓦房店市| 葫芦岛市| 麦盖提县| 田阳县| 江津市| 丽水市| 穆棱市| 义乌市| 澎湖县| 亚东县| 即墨市| 青川县| 新巴尔虎左旗| 永春县| 襄城县| 龙川县|