Getting Started with GraphQL and Formidable

Back

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

Installation

To get started with GraphQL, you need to install the following packages:

$ npm i mercurius graphql

Configuration

Once you have installed the required packages, you can go ahead and create a new Service Resolver:

app/Resolvers/GraphQLServiceResolver.ts

import { buildSchema } from 'graphql';
import { GraphQLSchema } from 'graphql';
import { IResolvers } from 'mercurius';
import { ServiceResolver } from '@formidablejs/framework';
import mercurius from 'mercurius';
export class GraphQLServiceResolver extends ServiceResolver {
/**
* Register graphql.
*
* @returns {void}
*/
register() : void {
const schema: GraphQLSchema = buildSchema(`
type Query {
add(x: Int, y: Int): Int
}
`);
const resolvers: IResolvers = {
Query: {
add: async (_, { x, y }) => x + y
}
};
this.app.register(mercurius, {
schema,
resolvers,
});
}
}

The code above is in TypeScript, feel free to use JavaScript or Imba.

You can now enable GraphQL by importing GraphQLServiceResolver in the app.imba config under resolvers:

import { GraphQLServiceResolver } from '../app/Resolvers/GraphQLServiceResolver'
...
export default {
...
resolvers: [
...
GraphQLServiceResolver

And you're done! 🎉🎉🎉

Start the application using npm start then test your GraphQL in the terminal with the following command:

$ curl -H "Content-Type:application/graphql" -XPOST -d "query { add(x: 2, y: 2) }" http://localhost:3000/graphql

For more information, visit the Mercurius documentation

© Donald Pakkies.
github