graphql - 未从 Apollo 服务器中用于 graphQL 的 REST 数据源返回的数据
问题描述
我正在尝试使用我的 REST API 调用作为数据源的 GraphQL 的 Apollo 服务器的基本实现。即使在我单独调用 API 时返回了数据,我也没有看到从相同返回的任何数据。任何人都可以帮助弄清楚可能出了什么问题吗?
PS:我的 API 上启用了 CORS,所以不确定我是否正确传递了它。我不知道如何弄清楚这调用的是什么 URL。
我的示例代码如下:
const { ApolloServer, gql } = require('apollo-server');
const { RESTDataSource } = require('apollo-datasource-rest');
class Contact extends RESTDataSource {
constructor() {
super();
this.baseURL = 'http://localhost:8080/objects/';
}
async getContactById(id) {
return this.get(`contact/${id}`);
}
async getAllContacts() {
const data = await this.get(`contact`);
return data.results;
}
// an example making an HTTP PUT request
async newContact(contact) {
return this.put(
'contact', // path
contact, // request body
);
}
};
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
type Query {
allContacts: [Contact]
contactById(id: ID): Contact
}
type Contact {
id: ID
contact_name: String
}
`;
// Resolvers define the technique for fetching the types in the
// schema.
const resolvers = {
Query: {
contactById: async (_source, { id }, { dataSources }) => {
return dataSources.contact.getContactById(id);
},
allContacts: async (_source, _args, { dataSources }) => {
return dataSources.contact.getAllContacts();
},
},
};
// In the most basic sense, the ApolloServer can be started
// by passing type definitions (typeDefs) and the resolvers
// responsible for fetching the data for those types.
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => {
return {
contact : new Contact(),
};
},
cors : true,
});
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`);
});
以下是来自 GraphQL 游乐场的请求和响应:
query {
contactById (id : 5) {
id
contact_name
}
}
回复:
{
"data": {
"contactById": {
"id": null,
"contact_name": null
}
}
}
解决方案
推荐阅读
- ios - 以 RTL 语言翻转的 SwiftUI 菜单内容
- migration - Bigcommerce 订单是否有其他详细信息和订单项属性
- android - android - 如何更改底部导航文本
- javascript - 从 discord.js 中的传入消息中获取命令
- javascript - Google 表格 - 脚本编辑器 数据验证生成器 - 格式化过滤日期列表
- php - 如何选择在 table1 中有值但在 table2 中为 NULL 的字段表?
- python - 模拟 NamedTemporaryFile 写入和关闭文件
- php - Hypens 打破 Laravel 动态路由
- powerbi - 在 Power Query 中应用条件(根据每个 Consol ID 筛选最早日期) - PowerBI
- tkinter - Tkinter 通过循环将条目值添加到列表中