【问题标题】:graphql mutation work ok, but i can't get recordsgraphql 突变工作正常,但我无法获取记录
【发布时间】:2017-06-26 21:55:13
【问题描述】:

按照本教程: http://graphql.org/graphql-js/mutations-and-input-types/

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  input MessageInput {
    content: String
    author: String
  }

  type Message {
    id: ID!
    content: String
    author: String
  }

  type Query {
    getMessage(id: ID!): Message
  }

  type Mutation {
    createMessage(input: MessageInput): Message
    updateMessage(id: ID!, input: MessageInput): Message
  }
`);

// If Message had any complex fields, we'd put them on this object.
class Message {
    constructor(id, {content, author}) {
        this.id = id;
        this.content = content;
        this.author = author;
    }
}

// Maps username to content
var fakeDatabase = {};

var root = {
    getMessage: function ({id}) {
        if (!fakeDatabase[id]) {
            throw new Error('no message exists with id ' + id);
        }
        return new Message(id, fakeDatabase[id]);
    },
    createMessage: function ({input}) {
        // Create a random id for our "database".
        var id = require('crypto').randomBytes(10).toString('hex');

        fakeDatabase[id] = input;
        return new Message(id, input);
    },
    updateMessage: function ({id, input}) {
        if (!fakeDatabase[id]) {
            throw new Error('no message exists with id ' + id);
        }
        // This replaces all old data, but some apps might want partial update.
        fakeDatabase[id] = input;
        return new Message(id, input);
    },
}

var app = express();
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
}));
app.listen(4000, () => {
    console.log('Running a GraphQL API server at localhost:4000/graphql');
});

我可以创建类似教程教学的项目:

mutation {
  createMessage(input: {
    author: "andy2",
    content: "hope is a good thing2",
  }) {
    id
  }
}

我收到回复:

{
  "data": {
    "createMessage": {
      "id": "d08ae7d739110c04f657"
    }
  }
}

但页面中没有关于如何获取数据的信息,我尝试了这个:

{
  getMessage(id:"d08ae7d739110c04f657") {    
  }
}  

但我得到错误:

TypeError: Failed to fetch

有什么想法吗?

【问题讨论】:

    标签: graphql


    【解决方案1】:

    你用 graph(i)QL 试过了吗?

    在查询中,您缺少要获取的消息参数,应如下所示:

    query {
      getMessage(id: "d08ae7d739110c04f657") {
        content
        author
      }
    }

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 2019-05-02
      • 1970-01-01
      • 2014-10-31
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多