首页 > 解决方案 > 未从 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
    }
  }
}

标签: graphqlapollo-server

解决方案


推荐阅读