Selecting database as data source for GraphQL server

GraphQL — How to adopt it?

Developers can adopt GraphQL API in many different ways:

Apollo Server as gateway for your all client/server interactions. Source:https://blog.apollographql.com/announcing-apollo-server-2-2b69fb4702ce

Resolvers for your datasource

No matter if you use ORM, SQL builder like Knex.js or having some complex business logic, GraphQL will always have at least two layers of resolvers:

  • Type resolvers that are used to fetch the type
  • Field resolvers that resolve actual field and can trigger another type resolver in case of relationships
Source: https://www.prisma.io/blog/graphql-server-basics-the-schema-ac5e2950214e/

Finding perfect database for GraphQL storage

Could NoSQL database like MongoDB has any advantages over relational databases as datasource for GraphQL? Schemaless databases are tempting to use because we do not need to deal with DDL statements under the hood, however NoSQL database may still require some changes in resolvers (all depends how resolvers are written.

  • No schema — no need to alter tables when adding new field.
  • Simplified relationships management (no constraints etc.)
  • Ability to generalize schema (Passing generic JSON Scalar as part of the field.
  • Mapping between database and schema can be done using ORM
  • Lack of enforcement for types and database structure can lead to GraphQL errors when listing data
  • When adding new required fields developers will need to provide way to return new value or execute command that will insert default values.
  • If there is external source of the data resolvers needs to check if it is going to comply with the provided schema. Inserts from external API can break GraphQL API easily.
  • Enforcement for types and database structure
  • Direct mapping between Database schema and GraphQL schema without ORM
  • Changing schema requires user to executes changes in the table — however this could be automated by underlying framework.
  • Unclear path for field deletions — it’s not recommended to drop column in existing database etc.

Summary

If we are making many changes in your schema and want to avoid dealing with database modifications NoSQL storage solution can be the more suitable aproach for data storage. However when using NoSQL solution developers will need to make sure that new required fields are fetched from the database which can be resolved by inserting data to database or providing default value in resolvers.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store