GraphQL突变,在一个请求中接受动态大小和常见标量类型的数组

时间:2016-11-19 20:31:39

标签: javascript graphql apollostack

我需要能够在一个请求中创建一个用户并添加它最喜欢的电影(一组参与电影收藏的对象及其对每部电影的个人评级)。

可能看起来像这样的东西(伪代码)

<Image>

在单个请求中执行此操作的graphql方式是什么?我知道我可以通过多个突变/请求来实现结果,但我想在一个中完成。

5 个答案:

答案 0 :(得分:23)

你可以传递像这样的数组

var MovieSchema = `
  type Movie {
   name: String
  }
  input MovieInput {
   name: String
  }
  mutation {
   addMovies(movies: [MovieInput]): [Movie]
  }
`

然后在你的变异中,你可以传递像

这样的数组
mutation {
  addMovies(movies: [{name: 'name1'}, {name: 'name2'}]) {
    name
  }
}

尚未测试代码,但您明白了

答案 1 :(得分:1)

我想出了一个简单的解决方案-不使用JSON。仅使用一个输入。希望对别人有帮助。

我必须添加此类型:

type Option {
    id: ID!
    status: String!
    products: [Product!]!
}

我们可以添加突变类型并添加输入,如下所示:

type Mutation {
    createOption(data: [createProductInput!]!): Option!
    // other mutation definitions
}

input createProductInput {
    id: ID!
    name: String!
    price: Float!
    producer: ID!
    status: String
}

然后可以使用以下解析器:

const resolvers = {
    Mutation: {
      createOption(parent, args, ctx, info) {

        const status = args.data[0].status;

        // Below code removes 'status' from all array items not to pollute DB.
        // if you query for 'status' after adding option 'null' will be shown. 
        // But 'status': null should not be added to DB. See result of log below.
        args.data.forEach((item) => {
            delete item.status
        });

        console.log('args.data - ', args.data);

        const option = {
            id: uuidv4(),
            status: status,  // or if using babel    status,
            products: args.data
        }

        options.push(option)

        return option
      },
    // other mutation resolvers
    }

现在您可以使用它来添加一个选项(STATUS是从数组的第一项中获取的-它可以为空):

mutation{
  createOption(data:
    [{
            id: "prodB",
            name: "componentB",
            price: 20,
            producer: "e4",
            status: "CANCELLED"
        },
        {
            id: "prodD",
            name: "componentD",
            price: 15,
            producer: "e5"
        }
    ]
  ) {
    id
    status
    products{
      name
      price
    }
  }
}

产生:

{
  "data": {
    "createOption": {
      "id": "d12ef60f-21a8-41f3-825d-5762630acdb4",
      "status": "CANCELLED",
      "products": [
        {
          "name": "componentB",
          "price": 20,
        },
        {
          "name": "componentD",
          "price": 15,
        }
      ]
    }
  }
}

无需多说,要达到上述效果,您需要添加:

type Query {
    products(query: String): [Product!]!
    // others
}

type Product {
    id: ID!
    name: String!
    price: Float!
    producer: Company!
    status: String
}

我知道这不是最好的方法,但是我没有在文档中找到这样做的方法。

答案 2 :(得分:0)

将它们作为JSON字符串传递。这就是我的工作。

答案 3 :(得分:0)

我最终手动解析了正确的架构,因为JavaScript Arrays和JSON.stringify字符串不被接受为graphQL架构格式。

const id = 5;
const title = 'Title test';

let formattedAttachments = '';
attachments.map(attachment => {
  formattedAttachments += `{ id: ${attachment.id}, short_id: "${attachment.shortid}" }`;      
  // { id: 1, short_id: "abcxyz" }{ id: 2, short_id: "bcdqrs" }
});

// Query
const query = `
  mutation {
    addChallengeReply(
      challengeId: ${id}, 
      title: "${title}", 
      attachments: [${formattedAttachments}]
    ) {
      id
      title
      description
    }
  }
`;

答案 4 :(得分:0)

根据您的要求,我理解的是,如果您具有以下代码

const user = {
    name:"Rohit", 
    age:27, 
    marks: [10,15], 
    subjects:[
        {name:"maths"},
        {name:"science"}
    ]
};

const query = `mutation {
        createUser(user:${user}) {
            name
        }
}`

您一定会得到

"mutation {
        createUser(user:[object Object]) {
            name
        }
}"

而不是预期的

"mutation {
        createUser(user:{
            name: "Rohit" ,
            age: 27 ,
            marks: [10 ,15 ] ,
            subjects: [
                {name: "maths" } ,
                {name: "science" } 
                ] 
            }) {
            name
        }
}"

如果这是您想要实现的,那么gqlast是一个不错的标记函数,您可以使用它来获得预期的结果

只需从here获取js文件并将其用作:

const user = {
    name:"Rohit", 
    age:27, 
    marks: [10,15], 
    subjects:[
        {name:"maths"},
        {name:"science"}
    ]
};

const query = gqlast`mutation {
        createUser(user:${user}) {
            name
        }
}`

存储在变量query中的结果将是:

"mutation {
        createUser(user:{
            name: "Rohit" ,
            age: 27 ,
            marks: [10 ,15 ] ,
            subjects: [
                {name: "maths" } ,
                {name: "science" } 
                ] 
            }) {
            name
        }
}"