How to interpret Query, Mutation and Subscription operations in a Ballerina GraphQL service?

How to interpret Query, Mutation and Subscription operations in a Ballerina GraphQL service?


0

Most GraphQL libraries use the schema definition language(SDL) to define the types of a GraphQL service, like this:

type Query {
  greeting: String!
}

type Mutation {
  setName(name: String!): String!
}

type Subscription {
  greetings: String!
}

In Ballerina, how do we define the schema, and where should we add these types?

1 Answer
1


0

The Ballerina GraphQL package uses the code-first approach to write GraphQL services. This means no GraphQL schema is required to create a GraphQL service. The Ballerina GraphQL package will walk through the service and the types related to the service to generate the complete GraphQL schema.

You can write the GraphQL service for above schema as follows:

The resource method with the get accessor inside a GraphQL service is mapped to a field in the root Query type. The greeting field can be defined like this.

resource function get greeting() returns string {
    return "Hello, World!";
}

In Ballerina, each remote method inside the GraphQL service is mapped to a field in the root Mutation type. You can add any logic inside the function.

remote function setName(string name) returns string {
    self.name = name;
    return self.name;
}

The Subscription type in a GraphQL schema is used to continuously fetch data from a GraphQL service. In Ballerina, each resource method with the subscribe accessor inside a GraphQL service is mapped to a field in the root Subscription type.

resource function subscribe greetings() returns stream<string> {
    return ["Hello", "Hi", "Hello World!"].toStream();
}

You can define the complete GraphQL service for the above schema as follows:

import ballerina/graphql;

service /graphql on new graphql:Listener(9090) {

    private string name = "Ballerina";

    resource function get greeting() returns string {
        return "Hello, World!";
    }

    remote function setName(string name) returns string {
        self.name = name;
        return self.name;
    }

    resource function subscribe greetings() returns stream<string> {
        return ["Hello", "Hi", "Hello World!"].toStream();
    }
}

More details can be found in the Ballerina GraphQL spec.



Leave a Reply

Your email address will not be published. Required fields are marked *