Use Dgraph Database with KoaJs and GraphQL

Ashok Vishwakarma
4 min readFeb 6, 2019

--

Dgraph database is touching its popularity as it makes using GraphDB for any project is very simple and easy. I have tried using the same after watching a talk given by its founder Manish Rai Jain at Singapore.

The video is all about the introduction to Dgraph, why they build it, its concept, how it compares with other databases, the schema in Dgraph, GraphQL+- which is a query language for Dgraph and etc.

Do watch the same to get brief information about the same.

What is GraphQL+-?

The default query language for Dgraph is called GraphQL+-, as per their official website:

Dgraph’s GraphQL+- is based on Facebook’s GraphQL. GraphQL wasn’t developed for Graph databases, but its graph-like query syntax, schema validation and subgraph shaped response make it a great language choice. We’ve modified the language to better support graph operations, adding and removing features to get the best fit for graph databases. We’re calling this simplified, feature-rich language, “GraphQL+-”.

Note: GraphQL+- is a work in progress. We’re adding more features and we might further simplify existing ones.

The fundamentals are it finds a node based on the search criteria which matches in the graph and result in a graph which also sports JSON. Each query must have a name specified at the query root which also identifies the result which can be all of the edges of type value.

GraphQL vs GraphQL+-

When asked why Dgraph’s query language is similar to GraphQL not exactly the same, the reply from Manish R Jain was

Yeah, I know that our implementation of GraphQL isn’t exactly as mentioned in the spec. This is because GraphQL is meant as a REST API replacement, and not really a graph query language. So, we’re making modifications to it to ensure it can operate as a full-fledged graph query language.

A good example of this is mutations. GraphQL doesn’t contain all the data or the instructions required to specify how to write data, as that part is generally given away to a Relay JS function. GraphQL just tells you which function to call and the params. That doesn’t work for us, because we’re language agnostic, and implement GraphQL at a systems level. So, we’ve had to modify the mutations to fit our purpose.

At some point, once we’re mature enough and have better understanding and implementation of GraphQL, we can release our mods to the official spec; and see whether they should live separately or be merged into the official GraphQL spec.

What is DgraphKoa?

To make developers life easy to work with Dgraph as Database I have created a simple npm package which does the followings.

  1. Generate a GraphQL-JS schema that maps GraphQL queries to Dgraph queries
  2. Transform Dgraph responses into GraphQL responses (including support for the relay connection specification)
  3. Generate defaults for create/update/delete/query operations (with filtering, ordering and nested create/update mutations)
  4. Configure Dgraph’s schema with types and indexes each property.
  5. Generate and run a Koa application with a koa-graphql middleware.

All you have to do is provide a Dgraph database configuration and a schema.

DgraphKoa Schema

The schema in DgraphKoa is very similar to a GraphQL schema which mentioned in types.

// A simple GraphQL schemaconst schema = `type Person {
id: ID!name: String @filter(types: [EQUALITY])
children: [Person!]! @reverse(name: "parents")
parents: [Person!]! @reverse(name: "children")
}`;

The above schema is a Person type schema in GraphQL with some directives for the filter, reverse and etc.

Given the above schema, DgraphKoa will generate the following Types, Inputs, Queries and Mutations

You can directly use these into your client to query or mutate the Dgraph database directly.

Resolvers

The resolvers for the above schema are also generated and fulfilled using Dgraph database client directly.

Every time a query or mutations hits the endpoint the query or mutation is extracted by the request payload and passed into the corresponding methods for query or mutate.

How to use DgraphKoa

DgraphKoa is published on NPM repository with the name dgraph-koa to get started with you need to install the same into your project as a dependency.

// install dgraph-koanpm install --save dgraph-koa

After a successful install, the package will be available in your node_modules directory and can be used directly like any other package.

// import or require the package in your applicationimport Server from 'dgraph-koa';or const Server = require('dgraph-koa');

The Server is the entry to the DgraphKoa which is used to create your application.

// Creating your DgraphKoa applicationimport Server from 'dgraph-koa';
import grpc from 'grpc';
const app = new Server({
debug: true,
relay: false,
graphiql: true,
graphiqlUrl: '/graphql',
dgraph: {
url: 'localhost:9080',
credentials: grpc.credentials.createInsecure()
}
});

Which can listen to any specified port, host and uses a callback to notify

// Starting the server to listen to port
app.listen(4000, '0.0.0.0', () => {
console.log('Server started at 0.0.0.0:4000');
});

The complete example

import Server from 'dgraph-koa';
import grpc from 'grpc';
const schema = `type Person {
id: ID!name: String @filter(types: [EQUALITY])
children: [Person!]! @reverse(name: "parents")
parents: [Person!]! @reverse(name: "children")
}`;
(async () => {
const app = new Server({
debug: true,
relay: false,
graphiql: true,
graphiqlUrl: '/graphql',
dgraph: {
url: 'localhost:9080',
credentials: grpc.credentials.createInsecure()
}
});
await app.updateSchema(schema); app.listen(4000, '0.0.0.0', () => {
console.log('Server started at 0.0.0.0:4000');
});
})();

As we wanted to Dgraph have the updated schema in the database before starting the application, the app.updateSchema method is called using await and everything is wrapped into a self-invoked async function.

Conclusion

Using GraphDB for your next project was a pain but Dgraph solves that problem and made it simple and easy. With DgraphKoa it is even simpler and easier.

The package is in its early development phase and will keep adding more support and features, any issues/PRs are welcome.

Let me know your thoughts in the comments and don’t forget to clap and share with your friends.

--

--

Ashok Vishwakarma
Ashok Vishwakarma

Written by Ashok Vishwakarma

@GoogleDevExpert — #WebTechnologies & @angular | #Principal #Architect at @Naukri | #Entrepreneur | #TechEnthusiast | #Speaker

No responses yet