Tuesday 6 June 2017

Why not to use GraphQL as a business logic layer?

I was wondering how to separate transport layer (REST API / GraphQL) from business logic layer when writing application. When implementing business logic function/method, for example postCreate, it might look like this:

async function postCreate (viewer, params) {
  // validate params (don't allow additional params!)
  // authorize viewer
  // filter/modify/authorize params according to viewer role
  // perform some logic
  // filter output according to viewer role
  // return result
}

If I would like to keep GraphQL away from business logic I would have to implement all actions performed in postCreate function by myself (or use third party libs). Also if postCreate function would return nested data like for example post.author.firends then I would have to deal with a complicated graph-like structure in postCreate function params.

On the other hand, with GraphQL writing such function is easy, because there is input/output validation/filtering out of the box, dealing with nested data is also easy, authorization can be done using GraphQL resolver context argument, and so on.

The longer I think of it, the longer I am convinced that GraphQL is ideal for writing business logic. The fact that it is possible to expose GrpahQL api through HTTP is just a nice feature. And event I would want to make a standard REST API I could just call GraphQL from http routes, for example like this:

app.post('/posts', async function (req, res, next) {
  const query = `mutation ($input: PostCreateData!) { postCreate (input: $input) { id, title } }`;
  const variables = { input: req.body };
  await graphql({ query, variables }); 
})

Of course it's the very simple example - in real world we would have to implement some extra params that would represent fields (possibly nested) that user would like to receive in response, handle errors properly and so on.

Anyway my question is not about REST API because right now in 99% I write only GraphQL. The question is - why not to use GraphQL in business logic layer? The only drawback that comes to my mind is that if I would like to call some business logic method from "inside" of my app I would have to call it with GraphQL query which feels little bit awkward - but I guess this could be solved by writing GraphQL queries as plain objects (json) and translated to GraphQL...

What do you guys think? Do you use GraphQL for business logic?



via user606521

No comments:

Post a Comment