0

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);
  }
}
Lukas
  • 9,752
  • 15
  • 76
  • 120
  • You certainly *can* design a schema this way, although you should bear in mind that not all operations you need to perform will necessarily neatly map to a single method of some model. Moreover, operations often provide an additional level of abstraction over existing data models. Having to modify a data model just to expose a field in the schema may not be desirable. See the linked post for additional discussion of pros and cons. – Daniel Rearden Jun 17 '19 at 18:07
  • As a side note, you probably [don't want to use buildSchema](https://stackoverflow.com/questions/53984094/notable-differences-between-buildschema-and-graphqlschema/53987189#53987189). – Daniel Rearden Jun 17 '19 at 18:08

0 Answers0