Compute values from relation data with functions


#1

So I want to compute a value on a type from other data that’s two relations ‘deep’ from it, the reason for why I want to compute this on the back-end side with functions is so I can use the Graphcool API on queries, like orderBy, filter and first since an important part is to find the 5 first filtered values, ordered.

Also so the client code doesn’t have to worry itself with computations, but only provide the needed data to the server.

I have a schema similar to this one:

type Navy implements Node {
  id: ID!
  fleets: [Fleet!] @relation(name: 'a')
}

type Fleet implements Node {
  id: ID!
  navy: Navy!
  shiptypes: [ShipType!] @relation(name: 'b')
}

type ShipType implements Node {
  id: ID!
  fleet: Fleet!
  name: String!
}

What I want is to store the different ShipTypes per Fleet in the Navy type, and have a count of each occurance, so I would be able to use a query similar to this one:

{
  Navy(id: ID!) {
    fleets {
      shiptypes {
        name
      }
    }
    shiptypes(orderBy: count_ASC) {
      name
      count
    }
  }
}

to get this wanted end result:

Navy {
  fleets: [{
    shiptypes: [{
      name: 'cruiser'
    }]
  }, {
    shiptypes: [{
      name: 'destroyer'
    }, {
      name: 'cruiser'
    }]
  }],
  shiptypes: [
    {
      name: 'cruiser',
      count: 2
    },
    {
      name: 'destroyer',
      count: 1
    }
  ]
}

and more importantly that I can get only the shiptypes value for a navy, without needing to get the data its computed from and do the computation on the client side, (I feel like this would require fetching more data than what should be needed, especially when we don’t want any other data from the Fleet or ShipTypes and with the actual app I’m building it could grow exponentially to pretty large arrays. ( Also, in one of the cases I want to get only the first 5 filtered shiptypes; ordered ))

What’s the best course of action here? I guess I could do everything client-side but would prefer if it could be done it an elegant way on the backend with functions,

thanks!