GraphQL to SQL service example
Simple example of a GraphQL server that connects to a SQL backend. To demonstrate this, we're using Apollo and Prisma respectively.
It's also accessing data from elsewhere, to demonstrate how GraphQL combines multiple sources.
Also a few development convenience things, like Nodemon and the prisma cli.
The architecture is structured in a way that the different stages of a GraphQL request are clearly separated:
When a request with a GraphQL query comes in, the following happens:
You are free to organise your code in whatever way you like, but the structure we chose here makes a lot of sense for what we need.
src
folder (apart from project config files)src
we have a schema
and a providers
folder, clearly separating these responsibilities.providers
and the schema
folder, we distinguish between the two different data domains we support: books
and poetry
. It's nice and clean, and allows you to easily find what you're looking for.There is also an images
folder in this repo, which just holds the assets for this README.
For the GraphQL Server, we use the most popular library around: Apollo-Server.
It gives us everything we need to handle GraphQL stuff:
gql
string template to parse the GraphQL schema notations.It's a pretty traditional need to access a SQL database from our GraphQL server. Lots of so-called ORMs exist to do this, most notable Sequelize and Knex. But recently Prisma has made waves and so we're using it for our example here.
Check the src/providers/booksDB
folder for how we handle our SQL database using Prisma:
dbClient.js
we initialize our Prisma client, which we will use to execute all our SQL requests.dbProvider.js
, we execute the actual queries against the DB, using the prisma client.ensureSeedData()
function in seed.js
, in case the database is empty. This way we have some data to query, no matter what.npm install
npm start
launches nodemon for easy developmentNOTE: You can reset the SQLite DB anytime by running npm run resetDB
.
Apollo Server comes with a querying UI out of the box.
Simply visit http://localhost:3000 and execute a GraphQL query, e.g.: