Integrating GraphQL, Apollo Server, Sequelize-Auto with SQL Server.
Tags: Sequelize Auto, Sql Server, GraphQL, Apollo Server

This tutorial demonstrates setting up GraphQL with Apollo Server and connecting your server with SQL Server Database(SSMS) with ORM Sequelize-auto.

You can map any of the tables from your database using Sequelize-auto. You just need to specify proper table names that matches your tables from the database.

If you’ve prior basic knowledge about what exactly GraphQL and Apollo-Server do, then we will start by creating SQL Server DB. We will use a simple Library database with only two tables namely Author and Book.

Database Schema(Library)

Here, above from our database diagram we can easily find that, we have defined two foreign keys (BookID in Authors table as FK_Athors_Books,AuthorID in Books table as FK_Books_Authors)

We will start step by step starting from creating a new project to performing basic operations.

Let’s create a new project.

If you don’t have yarn installed you can make use of npm also.

Creating a new directory and initiating the project.

initiate project with yarn command

add create-nodejs-project dependacy at global level

initiate project with npm command

Above both the commands will generate your package.json files.

2. Adding the required dependencies using yarn

yarn add sequelize-auto sequelize-cli sequelize -g

yarn add apollo-server graphql mssql mssql2 --save

yarn add nodemon -D

3.Adding the required dependancies using npm

npm install sequelize-auto sequelize-cli sequelize -g

npm install apollo-server graphql mssql mssql2 --save

npm install nodemon -D

Above dependancies,

How they will help us?

Sequelize — is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more. Sequelize follows Semantic Versioning. Read more about sequelize.

Sequelize-cli — Before installing this package dependency make sure that you have installed sequelize successfully to your project. Sequelize-cli is command line interface for sequelize.

Sequelize-auto — automatically generate models for SequelizeJS via the command line.

You will need to install sequelize ; it's no longer installed by sequelize-auto .

You will need to install the correct dialect binding before using sequelize-auto. Read more about sequelize-auto

mssql and mssql2 — Microsoft SQL Server client for Node.js (Mandatory to install)

nodemon — nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

nodemon does not require any additional changes to your code or method of development. nodemon is a replacement wrapper for node . To use nodemon , replace the word node on the command line when executing your script.

Creating config and models folder for our project.

Once above dependencies get successfully installed, we will create config file and models using database schema under config and models folder respectively.

For this purpose, run below commands under your project.

sequelize init:config

sequelize init:models

The first command will create a configuration file for connecting to the database, where we’ll be specifying all the connections related details to SQL Server (SSMS).

config.json

3. The second command will create a models folder where we will store our database tables related models i.e. generating models from an existing database tables. For doing this we will make use of Sequelize-Auto.

As we are already in our project directory, we will simply hit the below command, but before hitting the command make sure that you have successfully installed Sequelize-Auto package dependency into your node modules folder[node_modules] in your project directory..

sequelize-auto -h localhost -u <username> -x <password> -p 1433 -d Library -o “./models” -e mssql -c config/config.json

Here,

The following command will automatically generate a models file which will consist of models from the database. Here in the model’s folder, we will have Authors.js, Books.js , index.js and init-models.js (all auto generated) files which consists of database models and their relationships.

Setting up resolvers and typeDefs.

What are resolvers?

Apollo Server needs to know how to populate data for every field in your schema so that it can respond to requests for that data. To accomplish this, it uses resolvers.

A resolver is a function that’s responsible for populating the data for a single field in your schema. It can populate that data in any way you define, such as by fetching data from a back-end database or a third-party API.

If you don’t define a resolver for a particular field, Apollo Server automatically defines a default resolver for it.

What are Typedefs?

GraphQL has its own type language that’s used the write GraphQL schemas: The Schema Definition Language (SDL). In its simplest form, GraphQL SDL can be used to define types looking like this:

type User {

id: ID!

name: String

}

We will start by creating a graphql folder inside our root directory, which will consist of resolvers and typedefs.

We will define typedef by creating a typeDefs.graphql file inside the /graphql folder. First we will define for Author.

Here we’ll start with a type. We’ll have an Author type which looks like AuthorID,Abbrv, FirstName,LastName,DOB,DOD ,BookID.

Once we define our type we need to fetch Authors and this will be done by Query object which will be an array of an Author.

typeDefs.graphql

Here , getAuthorDetails is the name of a Query.

Now let us implement the functionality for what we have defined so far by creating a resolvers.js file inside the graphql folder, which will be a simple JavaScript file.

This file will consist of Query resolvers. Here we’ll have a resolver function for Author which will return an array of the Authtors.

Your file should look like this,

resolvers.js

Similarly, you can do this for Books.

Once we are done with typedefs and resolvers we are good to create our server.js file. In the server.js file, we need to import Apollo Server and gql from the apollo-server package.

Now we can create out typedefs by using the gql function. To import our typeDefs.graphql file we will be using the fs (file system) module. We will use the fs.readFileSync() function to read our schemas and we’ll be passing the encoding option and we’ll be setting it to ‘utf-8’ to make sure it reads the file as a string.

Now we can create a new apollo server instance by passing a configuration object typedefs and revolvers.

server.js

Finally, we can run the server by hitting the below command in command prompt window.

nodemon server

or

nodemon server.js

The reason we have used nodemon is that we can continuously run our server even if we make changes in any of the project file.

Or you can simply run ,

npm start

This will be running on http://localhost:5000, and we will see GraphQL Playground running.

Above is just sample output of the database record.

Till now, we have fetched all record from Authors table. We can also fetch single record from Authors table and What if we want to fetch data for author from multiple tables? Yes, we can do this, as we have already defined the relationship. Now we just need to modify our schema for author as well as we need to add a new type for the book. Our modified schemas should look like this.

modified typeDefs.graphql

In the beginning, we have defined a new queries getAuthor() and getBook(),if we want only single record from Authors and Books table respectively.

Above we have added book field in Author Type with type of book field as Book to get associated data from Book table. And further we have added a new Book Type to get all book records with data associated authors data from Authors table.

To get associated data from multiple tables, we need to specify which fields we want. Here in this case, Suppose we want only BookTitle and TotalPages of associated book. Then we will request on those fields and that’s the power of GraphQL,it will not fetch all details, only requested fields will fetched by Query.