【摘要】 使用 apollo-datasource-mongodb 包将 MongoDB 数据映射到 GraphQL 数据层
使用 mongoose 来进行 MongoDB 的驱动,开启连接服务 导入 MongoDB 中的数据 schema
方式一:直接在 resolver 中操作数据库数据
在 GraphQL 的 resolver 中使用导入的数据 Schema …
使用 apollo-datasource-mongodb 包将 MongoDB 数据映射到 GraphQL 数据层
-
使用 mongoose 来进行 MongoDB 的驱动,开启连接服务
-
导入 MongoDB 中的数据 schema
方式一:直接在 resolver 中操作数据库数据
在 GraphQL 的 resolver 中使用导入的数据 Schema 来操作数据库中的数据(增删改查)
方式二:使用 data Sources 来映射数据
方式一的 resolver 与数据库耦合太强,需要进行进一步的拆分解耦导入 apollo-datasource-mongodb 包。
const { MongoDataSource } = require("apollo-datasource-mongodb");
创建数据映射类: 将数据库的数据操作封装在数据映射类中,每一个数据 Schema 都创建一个对应的数据映射类,如 User 数据 Schema 可以创建一个 User 映射类,该类中封装了对 User Schema 数据所需的操作:
// 创建数据映射类,这里创建的是User Schema对应的映射类Users
class Users extends MongoDataSource {
getUser(userID) { return this.findOneById(userID);
}
getUsers() { // 使用this.model来访问对应的数据Schema return this.models.find();
}
} //在创建 server 时,传入 dataSources 选项
const server = new ApolloServer({
typeDefs,
resolver,
dataSources: () => ({ // 使用数据映射类时,构造函数传入数据Schema // users作为dataSources的成员 users: new Users(User);
}),
}); // 在 resolver 中使用 DataSources 映射类提供的方法来操作数据库
const resolver = {
Query: { async users(parent, args, { dataSources }) { // resolver与dataSources交互即可,将数据库的操作与resolver解耦 const users = await dataSources.users.getUsers(); return users; }, async user(parent, { id }, { dataSources }) { const user = await dataSources.user.getUser(id); return user; },
},
};
文章来源: blog.csdn.net,作者:大唐荣华,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/weixin_40599109/article/details/115861587
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END