How to run GraphQL Nodejs server on PostgreSQL under 30 minutes
We will setup an Apollo Server for GraphQL with Sequelize ORM for PostgreSQL
At the end of these steps you would be able to run some GraphQL queries and get data from the PostgreSQL.
Lets get started with installing required package.
npm install apollo-server-koa graphql graphql-relay graphql-sequelize koa pg sequelize dotenvnpm install --save-dev nodemon
Create a new file called server.js and then paste the following code to check if apollo-server is started normally.
// path: ./server.jsconst Koa = require('koa');
const { ApolloServer, gql } = require('apollo-server-koa');
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = new Koa();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`),
);
Then run nodemon server.js and navigate to http://localhost:4000/graphql fills in following query:
{
hello
}
And you should get a response:
{
"data": {
"hello": "Hello world!"
}
}
Next we have to define model in sequelize base on database we will use https://github.com/pthom/northwind_psql.
We need to initialize connection to PostgreSQL database name northwind.
Create a .env file to store db username and password.
DB_USER=user
DB_PASSWORD=password
Create a new file called initializeDb.js and fills in the configuration and credentials.
// path ./initializeDb.jsconst path = require('path');
// this will load .env parameters to process.env
const env = require('dotenv').config({path: path.join(__dirname, '.env')});const username = process.env.DB_USER
const password = process.env.DB_PASSWORDconst Sequelize = require('sequelize');
const sequelize = new Sequelize(`postgres://${username}:${password}@127.0.0.1:5432/northwind`);module.exports = sequelize;
Next create a folder name models to store all the Sequelize models. Create a model call order.js for the order model.
// path ./models/order.jsconst Sequelize = require('Sequelize');
const sequelize = require('../initializeDb');const order = sequelize.define('Order', {
order_id: {
type: Sequelize.STRING,
primaryKey: true,
},
customer_id: Sequelize.STRING,
employee_id: Sequelize.INTEGER,
order_date: Sequelize.DATE,
required_date: Sequelize.DATE,
shipped_date: Sequelize.DATE,
ship_via: Sequelize.INTEGER,
freight: Sequelize.REAL,
ship_name: Sequelize.STRING,
ship_address: Sequelize.STRING,
ship_city: Sequelize.STRING,
ship_region: Sequelize.STRING,
ship_postal_code: Sequelize.STRING,
ship_country: Sequelize.STRING,
}, {
schema: 'public',
tableName: 'orders',
timestamps: false,
});module.exports = order;
After that we will going to change server.js to allow query for order. Lets define the attributes of order in typeDefs
// path ./server.js// define the new typeDefs
const typeDefs = gql`
type Query {
order(order_id: ID!): Order
orders: [Order]
}type Order {
order_id: ID
customer_id: String,
employee_id: Int,
order_date: String,
required_date: String,
shipped_date: String,
ship_via: Int,
freight: Float,
ship_name: String,
ship_address: String,
ship_city: String,
ship_region: String,
ship_postal_code: String,
ship_country: String,
}
`;
Then we will need to change our resolvers and imports some useful function from graphql-sequelize:
// path ./server.js// at top of files add these import
const order = require('./models/order');
const {resolver} = require('graphql-sequelize');// define the new resolvers
const resolvers = {
Query: {
order: resolver(order),
orders: resolver(order,{list: true})
},
};
Now go to http://localhost:4000/graphql and try following single order query.
{
order(order_id: 10250) {
order_id
customer_id
employee_id
order_date
required_date
shipped_date
ship_via
freight
ship_name
ship_address
ship_city
ship_region
ship_postal_code
ship_country
}
}
You should see a item returned as response. Try this query to get a list of order:
{
orders {
order_id
customer_id
employee_id
order_date
required_date
shipped_date
ship_via
freight
ship_name
ship_address
ship_city
ship_region
ship_postal_code
ship_country
}
}
Again you will see a list of orders being returned.
Now you have a server accepting GraphQL query and serving PostgreSQL data.
Next up: How to make GraphQL schema and Sequelize fields works together — Don’t Repeat Yourself (DRY)