Apollo Client 2 + React的Hello world示例?

时间:2018-01-23 13:00:29

标签: graphql apollo-client

我试图用React和GraphQL返回一个字符串但是我在第一阶段陷入困境。这是我的尝试:

import { makeExecutableSchema } from 'graphql-tools';

const typeDefs = `
  type Query {
    author: Person
  }
  type Person {
    name: String
  }
`;

const resolvers = {
    Query: {
        author: { name: 'billy' },
    },
};

const schema = makeExecutableSchema({
    typeDefs,
    resolvers,
});

createApolloServer({ schema });

这是我对该代码的理解:

在我的架构中,我定义了一个名为Query的{​​{1}},它应返回author

Person的名称字段是字符串。

我的解析程序有一个名为Person的{​​{1}},它应该返回一个名称字段为' billy'

的对象

然而,在我的Graphicool浏览器工具中,这个查询:

Query

返回:

author

2 个答案:

答案 0 :(得分:0)

import { createApolloServer } from 'meteor/apollo';
import { makeExecutableSchema } from 'graphql-tools';
import merge from 'lodash/merge'; // will be useful later when their are more schemas 

import GroupsSchema from './Groups.graphql';
import GroupsResolvers from './resolvers';

const typeDefs = [GroupsSchema];
const resolvers = merge(GroupsResolvers);

const schema = makeExecutableSchema({
    typeDefs,
    resolvers,
});

createApolloServer({ schema });

在./Groups.graphql中:

type Query {
    hi: String
    groups: [Group]
    group: Group
}

type Group {
    name: String
}

在'./resolvers'中:

export default {
    Query: {
        hi() {
            return 'howdy';
        },
        groups() {
            return [{ name: 'one', _id: '123' }, { name: 'two', _id: '456' }];
            // return Groups.find().fetch();
        },
        group() {
            return { name: 'found me' };
        },
    },
};

在React组件中:

const mainQuery = gql`
    {
        groups {
            name
        }
    }
`;

export default graphql(mainQuery)(ComponentName);

答案 1 :(得分:0)

解析器是GraphQL在解析特定字段时将调用的函数。这意味着您的resolvers对象应该更像这样:

const resolvers = {
  Query: {
    author: () => ({ name: 'billy' }),
  },
}

或者,或者,

const resolvers = {
  Query: {
    author() {
      return { name: 'billy' }
    },
  },
}

您可以check out the docs获取更多信息。