Let's say I have a class that has properties and mutable methods:
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;
}
}
I can map the properties seamlessly to an object / query
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();
}
}
But what if I wanted to expose the mutable functions in a similar manner? Is this ok?
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
}
`);
Because having to create random functions so I can use them as mutations seems like an annoying way to write software for 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);
}
}