How to Structure GraphQL/Serverless App Using Typescript.
In this article, I will share a scalable and modular solution to structure a GraphQL application.
When you create a new project structuring your code is probably the first task. Of course, if you’re using a framework, you will probably have it out of the box. However, when writing microservices, I find frameworks too bloated because they come with many things that you probably don’t need.
What is GraphQL?
GraphQL is a syntax that describes how to ask for data and is generally used to load data from a server to a client.
In short, it lets you:
- Reduce network costs and get better query efficiency.
- Ensure you’re never sending more or less than the client needs.
- Describe your API with types that map your schema to existing backends.
In this article, I am going to use ApolloServer to build the GraphQL server.
What is Serverless?
With Serverless comes the following:
- No server management (no need to manage any form of machine)
- Pay-per-execution (never pay for idle)
- Auto-scale (scale based on demand)
- Function as a unit of application logic
Step 1: Configure the Serverless template
Create a new folder to store your application and create a serverless.yml
file.
Step 2: Create config files and install dependencies
Create the tsconfig.json
, package.json
and webpack.config.js
run npm install
Step 3: Create handler function
Create a src
folder and inside create a functions
folder.
GraphQL shrink your APIs down into a single HTTP, so we only need to create a single handler inside the functions
folder to handle all the requests, for convention we call it graphql.ts
Step 4: Create GraphQL service
Create a new folder services
and inside create a graphql
folder, as the project grows we might need to add more folders like (middleware, utils) so to keep everything clean and tidy we create a subfolder inside graphql
called modules
At this point your project structure should look like this:
Inside graphql
folder create an index file:
Step 5: Create your first module
We are going to use a collection of albums as an example, inside modules
we need to create a folder called album
which is going to be our first module and inside we create the following files:
At this point, we only need to export our module.
Create a file inside modules
called index.ts
Step 6: Final step run the application
Run npm start
from the root of your application and head over to localhost:3000/local/graphql
🚀
Every example comes from the https://github.com/Mircoguidetti/graphql-serverless-scaffold Github repository
Thanks for reading and good luck with your next project! Leave a comment or message me if you have any questions. Happy Hacking!