假设我有一个具有属性和可变方法的类:
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);
}
}