Empowering your GraphQL API
Dynamic Schema Changes with Apollo Prisma
In this article, we’ll dive into the process of building a powerful GraphQL API using Apollo and Prisma. GraphQL has good flexibility over traditional REST API for retrieving, updating, and querying data. We’ll leverage Apollo to create a GraphQL server and Prisma for managing the database layer. This combination empowers developers to create efficient and structured APIs with ease.
Why Apollo Prisma will be the correct choice over Spring Boot on Dynamic Schema changes
GraphQL schemas are more flexible to support dynamic schema changes like Tables additions or removal, columns addition, and datatype changes. Soon you will learn how simple it is to retrieve dynamic schema changes.
Spring boot is not flexible to support dynamic schema changes. You will end up with a tightly coupled system where you would need to change the design structure of an application. Accommodating new columns or tables could require modifying GraphQL schema and resolvers. The tightly coupled architecture will lead to increased development efforts, release cycles, and the introduction of bugs.
Prerequisites
To work with this article, you need:
- Node.js installed
- Basic understanding of TypeScript/ JavaScript and GraphQL APIs.
- TypeGraphQL: It is a Framework that follows a code-first and object-oriented approach toward building GraphQL API. It allows developers to define GraphQL schema and resolvers using TypeScript classes and decorators, which makes the process type-safe.
- Prisma: It is an ORM framework that is an open-source database toolkit. It helps integration with GraphQL. It simplifies database management and allows developers to focus more on building features and less on low-level database interactions.
- Apollo Server is an open-source GraphQL server implementation developed by the Apollo team. It is designed to simplify the process of building GraphQL APIs in various programming languages, including JavaScript(Node.js), Python, and more.
Implementation
Let’s take a deep dive into the practical implementation. Imagine you’re working on an employee management application, and your UI needs to fetch employee data. In just a few simple steps that will take you around 5 to 10 minutes, you’ll be fully equipped to retrieve the entire employee schema with a single Prisma command. Let’s walk through the process together. If your data schema gets updated, then you will just need to follow the second and third steps from below Note.
A complete example of this implementation can be found on GitHub.
Note: If you directly check out the code from GitHub, then just follow four steps. 1. npm install, 2. npx prisma db pull,3. npx prisma generate, and npm run dev or node /dist/index.js
Step 1: Create a project working directory, and npm init will help to create package.json
mkdir apollo-with-prisma
cd apollo-with-prisma
npm init -y
Step 2: Set up dependencies (refer to given GitHub project package.json) and run npm install, which will install all required packages.
npm install
Step 3: Create tsconfig.json, which is used to transpile your typescript code to java script.
Step 4: Create the below-required packages and the following code to set up your GraphQL server.
The below piece of code will help during deploying your project for a health check. (file: metrics.ts)
import {Express, Request, Response} from "express";
tconst metrics = (app: Express) => {
app.get('/apollo-with-prisma/actuator/health', (req: Request, res: Response) => {
res.status(200).send('Okay!');
});
}
module.exports = metrics;
The below piece of code will help to allow you to use the Express.js framework to create an HTTP server. (file: express-app.ts)
import express, {Express} from "express";
import bodyParser from "body-parser";
const metrics = require("./metrics");
const app: Express = express();
app.disable("x-powered-by");
app.use(bodyParser.json());
metrics(app);
module.exports = app;
The below piece of code is the main file to import express-app and Prisma service and start the server at port 4000. It checks the env file to check if the port number is defined, and if not found, it will use a hardcoded 3000 port. (file: index.ts)
import * as dotenv from 'dotenv';
import {Express} from "express";
import 'reflect-metadata';
const app: Express = require("./app/express-app");
const prismaService = require("./service/prisma-service");
dotenv.config();
prismaService(app);
const port: string = process.env.PORT_NUMBER || '3000';
const index = app.listen(port, () => {
console.log('🚀 Server ready at: <' + `${process.env.HOST_URL}` + '>');
});
module.exports = index;
Step 5: Set up Prisma to start interesting data modeling.
This command will create a .env file where we can configure database properties.
npx prisma init
Configure DB properties and run the below command to fetch the whole DB schema.
npx prisma db pull
Run the below command to generate a type graph (resolver).
npx prisma generate
Build the project and run transpired index.js
npm run build
node ./dist/index.js #It start Apollo server at localhost:4000
Above implementation will fit any application schema. You would need to pay attention to Prisma commands to directly fetch your database schema.
After running the above project, Apollo Server with Prisma will be hosted on the below URL to run Graph queries.
http://localhost:4000/apollo-with-prisma/graphql
Once we start the server, we can easily fetch or modify data on a given database via GraphQL.
Below Sandbox provides an inbuilt feature to create graph Queries and Mutations. The below image is Apollo Server Sandbox to prepare graph query by selecting fields and arguments to fetch First Employee along with only required fields from the database.
Below images are Apollo Server Sandbox documentation for Query and Mutation which are graphQL root types. Queries are used to fetch data and Mutations are used to update the data on a given database.
Below image is for the Query documentation to fetch data via GraphQL.
Below image is for the Mutation documentation to modify data via GraphQL.
Conclusion
In the ever-changing landscape of software development, adaptability is paramount. Apollo Prisma’s schema flexibility offers a distinct advantage over the tightly coupled approach of Spring Boot. By decoupling your GraphQL schema from your database schema, Prisma empowers your application to gracefully handle evolving data sources. This approach leads to quicker development cycles, smoother schema changes, and ultimately, a more resilient and agile application.
When faced with the choice between Apollo Prisma and Spring Boot for your GraphQL implementation, consider the long-term benefits of flexibility and ease of adapting to change. Opting for Prisma can be a strategic decision that paves the way for a more adaptable and robust application architecture.
In this article, we’ve highlighted the challenges posed by dynamic database schema changes and how Apollo Prisma’s schema flexibility offers a solution that outshines the traditional tightly coupled approach of Spring Boot. By selecting the right GraphQL solution, you set your development journey on a path to resilience and success in a rapidly evolving technological landscape.