GraphQL:查询对象内部的突变

时间:2019-06-17 16:17:15

标签: graphql apollo

假设我有一个具有属性和可变方法的类:

class MyClass {

  constructor(initialValue) {
    this.a = initialValue + 1;
    this.b = initialValue + 2;
  }

  getA() {
    return this.a;
  }

  incA (parent, { inc = 0 }) {
    this.a += inc;
  }

  incB (parent, { inc = 0 }) {
    this.b += inc;
  }

}

我可以将属性无缝映射到对象/查询

const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type MyClass {
    a: Int!
    b: Int!
    getA: Int!
  }

  type Query {
    getMyClass: MyClass
  }
`);

const root = {
  getMyClass() {
    return new MyClass();
  }
}

但是,如果我想以类似方式公开可变函数,该怎么办?可以吗?

const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type MyClass {
    a: Int!
    b: Int!
    getA: Int!
    incA(inc: Int) # Mutations right here
    incB(inc: Int) # Mutations right here
  }

  type Query {
    getMyClass: MyClass
  }
`);

由于必须创建随机函数,因此我可以将它们用作突变,这似乎是为GraphQL编写软件的一种烦人的方式:

const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type MyClass {
    a: Int!
    b: Int!
    getA: Int!
  }

  type Query {
    getMyClass: MyClass
  }

  type Mutation {
    incAForMyClass(inc: Int)
    incBForMyClass(inc: Int)
  }
`);

const myClass = new MyClass();

const root = {
  getMyClass() {
    return myClass;
  }
}

const mutations = {
  incAForMyClass(...args) {
    return myClass.incA(...args);
  },
  incBForMyClass(...args) {
    return myClass.incB(...args);
  }
}

0 个答案:

没有答案