Данные не возвращены из источника данных REST на сервере Apollo для graphQL - PullRequest
0 голосов
/ 24 сентября 2018

Я пробую базовую реализацию для сервера Apollo для GraphQL с моими вызовами API REST в качестве источников данных.Я не вижу никаких данных, возвращенных из того же самого, хотя есть данные, возвращаемые, когда я вызываю 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
    }
  }
}
...