import app from'./app';constPORT=process.env.PORT||3000;app.listen(PORT, () => {console.log(`Servidor rodando na porta ${PORT}`);console.log(`Documentação disponível em http://localhost:${PORT}/api/docs`);});
src\app.ts
import express from'express';import userRoutes from'./routes/userRoutes';import sequelize from'./config/database';constapp=express();app.use(express.json());app.use('/api', userRoutes);sequelize.sync().then(() => {console.log('DB Connected'); }).catch((error:any) => {console.error('Erro ao conectar ao banco de dados:', error); });exportdefault app;
Giống với Laravel cũng có những thuật ngữ phải nhớ
The A.hasOne(B) association means that a One - To - One relationship exists between A and B, with the foreign key being defined in the target model(B).
The A.belongsTo(B) association means that a One - To - One relationship exists between A and B, with the foreign key being defined in the source model(A).
The A.hasMany(B) association means that a One - To - Many relationship exists between A and B, with the foreign key being defined in the target model(B).
These three calls will cause Sequelize to automatically add foreign keys to the appropriate models(unless they are already present).
The A.belongsToMany(B, { through: 'C' }) association means that a Many - To - Many relationship exists between A and B, using table C as junction table, which will have the foreign keys(aId and bId, for example).Sequelize will automatically create this model C(unless it already exists) and define the appropriate foreign keys on it.
package.json
{"name":"graphql-example","version":"1.0.0","description":"GraphQL Example project for Toptal blog article","main":"index.js","repository":"ssh://git@github.com/amaurymartiny/graphql-example","author":"Amaury Martiny <amaury.martiny@gmail.com>","license":"MIT","semistandard": {"env":"node" },"scripts": {"start":"babel-node index.js","dev":"nodemon --exec babel-node index.js","lint":"semistandard --fix" },"dependencies": {"@apollo/server":"^4.11.3","@graphql-tools/schema":"^10.0.16","apollo-server-express":"^3.13.0","babel-cli":"^6.26.0","babel-preset-es2015":"^6.24.1","body-parser":"^1.20.3","cors":"^2.8.5","express":"^4.21.2","graphql":"^16.10.0","graphql-server-express":"^1.4.1","graphql-tools":"^9.0.11","http":"^0.0.1-security","nodemon":"^3.1.9","path":"^0.12.7","semistandard":"^17.0.0","sequelize":"^6.37.5","sqlite3":"^5.1.7" }}
import express from'express';import { ApolloServer } from'@apollo/server';import bodyParser from'body-parser';import cors from'cors';// import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';// import { makeExecutableSchema } from 'graphql-tools';import { makeExecutableSchema } from'@graphql-tools/schema';import { expressMiddleware } from'@apollo/server/express4';import routes from'./rest/routes';import typeDefs from'./graphql/typeDefs';import resolvers from'./graphql/resolvers';import http from'http';constapp=express();consthttpServer=http.createServer(app);// Middlewaresapp.use(bodyParser.json());// Mount REST on /apiapp.use('/api', routes);// Mount GraphQL on /graphql// const schema = makeExecutableSchema({// typeDefs,// resolvers: resolvers()// });constserver=newApolloServer({ typeDefs, resolvers:resolvers()});asyncfunctiontest() {awaitserver.start();// app.use('/graphql', graphqlExpress({ schema }));// app.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql' }));// app.listen(3000, () => console.log('Express app listening on localhost:3000'));app.use(cors(),bodyParser.json(),expressMiddleware(server), );awaitnewPromise((resolve) =>httpServer.listen({ port:3000 }, resolve));console.log(`🚀 Server ready at http://localhost:3000`);}test();
rest\routes\user.routes.js
import express from'express';import userController from'../controllers/user.controller';constrouter=express.Router(); // eslint-disable-line new-caprouter.route('/')/** GET /api/users - Get list of users */.get(userController.list);router.route('/:userId')/** GET /api/users/:userId - Get user */.get(userController.get);router.route('/:userId/projects')/** GET /api/users/:userId/projects - List projects of user */.get(userController.listProjects);/** Load user when API with userId route parameter is hit */router.param('userId',userController.load);exportdefault router;
rest\routes\task.routes.js
import express from'express';import taskController from'../controllers/task.controller';constrouter=express.Router(); // eslint-disable-line new-caprouter.route('/')/** GET /api/tasks - Get list of tasks */.get(taskController.list);router.route('/:taskId')/** GET /api/tasks/:taskId - Get task */.get(taskController.get);/** Load task when API with taskId route parameter is hit */router.param('taskId',taskController.load);exportdefault router;
rest\routes\project.routes.js
import express from'express';import projectController from'../controllers/project.controller';constrouter=express.Router(); // eslint-disable-line new-caprouter.route('/')/** GET /api/projects - Get list of projects */.get(projectController.list);router.route('/:projectId')/** GET /api/projects/:projectId - Get project */.get(projectController.get);/** Load project when API with projectId route parameter is hit */router.param('projectId',projectController.load);exportdefault router;
import sequelize from'../../models';constProject=sequelize.models.Project;/** * Load Project and append to req. */functionload (req, res, next, id) {Project.findOne({ id }).then((Project) => {req.Project = Project; // eslint-disable-line no-param-reassignreturnnext(); }).catch(e =>next(e));}/** * Get Project list. * @property{number} req.query.skip - Number of Projects to be skipped. * @property{number} req.query.limit - Limit number of Projects to be returned. * @returns{Project[]} */functionlist (req, res, next) {Project.findAll().then(Projects =>res.json(Projects)).catch(e =>next(e));}/** * Get Project * @returns{Project} */functionget (req, res) {returnres.json(req.Project);}exportdefault { load, get, list };
rest\controllers\task.controller.js
import sequelize from'../../models';constTask=sequelize.models.Task;/** * Load Task and append to req. */functionload (req, res, next, id) {Task.findOne({ id }).then((Task) => {req.Task = Task; // eslint-disable-line no-param-reassignreturnnext(); }).catch(e =>next(e));}/** * Get Task list. * @property{number} req.query.skip - Number of Tasks to be skipped. * @property{number} req.query.limit - Limit number of Tasks to be returned. * @returns{Task[]} */functionlist (req, res, next) {Task.findAll().then(Tasks =>res.json(Tasks)).catch(e =>next(e));}/** * Get Task * @returns{Task} */functionget (req, res) {returnres.json(req.Task);}exportdefault { load, get, list };
rest\controllers\user.controller.js
import sequelize from'../../models';constUser=sequelize.models.User;/** * Load user and append to req. */functionload(req, res, next, id) {User.findByPk(id).then((user) => {req.user = user;returnnext(); }).catch(e =>next(e));}/** * Get user list. * @property{number} req.query.skip - Number of users to be skipped. * @property{number} req.query.limit - Limit number of users to be returned. * @returns{User[]} */functionlist(req, res, next) {User.findAll().then(users =>res.json(users)).catch(e =>next(e));}/** * Get user * @returns{User} */functionget(req, res) {returnres.json(req.user);}/** * List projects of user * @returns{Projects[]} */functionlistProjects(req, res, next) {req.user.getProjects().then(projects =>res.json(projects)).catch(e =>next(e));}exportdefault { load, get, list, listProjects };
import { Sequelize } from'sequelize';import User from'./user.model';import Project from'./project.model';import Task from'./task.model';import seed from'./seed'; // eslint-disable-lineimport path from'path';constsequelize=newSequelize("db",process.env.USER,process.env.PASSWORD, { host:"0.0.0.0", dialect:'sqlite', pool: { max:5, min:0, idle:10000 }, storage:path.resolve('db','db.sqlite'), logging:false });sequelize.authenticate().then(() => {console.log('Connection has been established successfully.');}).catch(err => {console.error('Unable to connect to the database:', err);});User(sequelize);Project(sequelize);Task(sequelize);// Set up data relationshipsconstmodels=sequelize.models;Object.keys(models).forEach(name => {if ('associate'in models[name]) { models[name].associate(models); }});sequelize.sync();// Uncomment the line if you want to rerun DB seed// sequelize.sync({ force: true }).then(() => seed(sequelize));exportdefault sequelize;
graphql\typeDefs.js
consttypeDefinitions=`type User { id: ID! firstname: String lastname: String email: String projects: [Project]}input UserInput { firstname: String lastname: String email: String}type Project { id: ID! name: String tasks: [Task]}input ProjectInput { name: String UserId: ID!}type Task { id: ID! description: String ProjectId: ID!}input TaskInput { description: String ProjectId: ID!}# The schema allows the following queries:type RootQuery { user(id: ID): User users: [User] project(id: ID!): Project projects: [Project] task(id: ID!): Task tasks: [Task]}# The schema allows the following mutations:type RootMutation { createUser(input: UserInput!): User updateUser(id: ID!, input: UserInput!): User removeUser(id: ID!): User createProject(input: ProjectInput!): Project updateProject(id: ID!, input: ProjectInput!): Project removeProject(id: ID!): Project createTask(input: TaskInput!): Task updateTask(id: ID!, input: TaskInput!): Task removeTask(id: ID!): Task}# We need to tell the server which types represent the root query.# We call them RootQuery and RootMutation by convention.schema { query: RootQuery mutation: RootMutation}`;exportdefault typeDefinitions;
You might have heard about the new kid around the block: GraphQL. If not, GraphQL is, in a word, a new way to fetch APIs, an alternative to REST. It started as an internal project at Facebook, and since it was open sourced, it has gained a lot of traction.
The aim of this article is to help you make an easy transition from REST to GraphQL, whether you’ve already made your mind for GraphQL or you’re just willing to give it a try. No prior knowledge of GraphQL is needed, but some familiarity with REST APIs is required to understand the article.
The first part of the article will start by giving three reasons why I personally think GraphQL is superior to REST. The second part is a tutorial on how to add a GraphQL endpoint on your back-end.
GraphQL vs. REST: Why Drop REST?
If you are still hesitating on whether or not GraphQL is suited for your needs, a quite extensive and objective overview of “REST vs. GraphQL” is given here. However, for my top three reasons to use GraphQL, read on.
Reason 1: Network Performance
Say you have a user resource on the back-end with first name, last name, email, and 10 other fields. On the client, you generally only need a couple of those.
Making a REST call on the /users endpoint gives you back all the fields of the user, and the client only uses the ones it needs. There is clearly some data transfer waste, which might be a consideration on mobile clients.
GraphQL by default fetches the smallest data possible. If you only need first and last names of your users, you specify that in your query.
The interface below is called GraphiQL, which is like an API explorer for GraphQL. I created a small project for the purpose of this article. The code is hosted on GitHub, and we’ll dive into it in the second part.
On the left pane of the interface is the query. Here, we are fetching all the users—we would do GET /users with REST—and only getting their first and last names.
If we wanted to get the emails as well, adding an “email” line below “lastname” would do the trick.
Some REST back-ends do offer options like /users?fields=firstname,lastname to return partial resources. For what it’s worth, Google recommends it. However, it is not implemented by default, and it makes the request barely readable, especially when you toss in other query parameters:
&status=active to filter active users
&sort=createdAat to sort the users by their creation date
&sortDirection=desc because you obviously need it
&include=projects to include the users’ projects
These query parameters are patches added to the REST API to imitate a query language. GraphQL is above all a query language, which makes requests concise and precise from the beginning.
Reason 2: The “Include vs. Endpoint” Design Choice
Let’s imagine we want to build a simple project management tool. We have three resources: users, projects, and tasks. We also define the following relationships between the resources:
Here are some of the endpoints we expose to the world:
Endpoint
Description
GET /users
List all users
GET /users/:id
Get the single user with id :id
GET /users/:id/projects
Get all projects of one user
The endpoints are simple, easily readable, and well-organized.
Things get trickier when our requests get more complex. Let’s take the GET /users/:id/projects endpoint: Say I want to show only the projects’ titles on the home page, but projects+tasks on the dashboard, without making multiple REST calls. I would call:
GET /users/:id/projects for the home page.
GET /users/:id/projects?include=tasks (for example) on the dashboard page so that the back-end appends all related tasks.
It’s common practice to add query parameters ?include=... to make this work, and is even recommended by the JSON API specification. Query parameters like ?include=tasks are still readable, but before long, we will end up with ?include=tasks,tasks.owner,tasks.comments,tasks.comments.author.
In this case, would be it wiser to create a /projects endpoint to do this? Something like /projects?userId=:id&include=tasks, as we would have one level of relationship less to include? Or, actually, a /tasks?userId=:id endpoint might work too. This can be a difficult design choice, even more complicated if we have a many-to-many relationship.
GraphQL uses the include approach everywhere. This makes the syntax to fetch relationships powerful and consistent.
Here’s an example of fetching all projects and tasks from the user with id 1.
Query
{ user(id:1){ projects { name tasks { description}}}}
Result
{ "data": { "user": { "projects": [ { "name": "Migrate from REST to GraphQL", "tasks": [ { "description": "Read tutorial" }, { "description": "Start coding" } ] }, { "name": "Create a blog", "tasks": [ { "description": "Write draft of article" }, { "description": "Set up blog platform" } ] } ] } }}
As you can see, the query syntax is easily readable. If we wanted to go deeper and include tasks, comments, pictures, and authors, we wouldn’t think twice about how to organize our API. GraphQL makes it easy to fetch complex objects.
Reason 3: Managing Different Types of Clients
When building a back-end, we always start by trying to make the API as widely usable by all clients as possible. Yet clients always want to call less and fetch more. With deep includes, partial resources, and filtering, requests made by web and mobile clients may differ a lot one from another.
With REST, there are a couple of solutions. We can create a custom endpoint (i.e., an alias endpoint, e.g., /mobile_user), a custom representation (Content-Type: application/vnd.rest-app-example.com+v1+mobile+json), or even a client-specific API (like Netflix once did). All three of them require extra effort from the back-end development team.
GraphQL gives more power to the client. If the client needs complex requests, it will build the corresponding queries itself. Each client can consume the same API differently.
How to Start with GraphQL
In most debates about “GraphQL vs. REST” today, people think that they must choose either one of the two. This is simply not true.
Modern applications generally use several different services, which expose several APIs. We could actually think of GraphQL as a gateway or a wrapper to all these services. All clients would hit the GraphQL endpoint, and this endpoint would hit the database layer, an external service like ElasticSearch or Sendgrid, or other REST endpoints.
A second way of using both is to have a separate /graphql endpoint on your REST API. This is especially useful if you already have numerous clients hitting your REST API, but you want to try GraphQL without compromising the existing infrastructure. And this is the solution we are exploring today.
As said earlier, I will illustrate this tutorial with a small example project, available on GitHub. It is a simplified project management tool, with users, projects, and tasks.
The technologies used for this project are Node.js and Express for the web server, SQLite as the relational database, and Sequelize as an ORM. The three models—user, project, and task—are defined in the models folder. The REST endpoints /api/users*, /api/projects* and /api/tasks* are exposed to the world, and are defined in the rest folder.
* Note: After publication, Heroku stopped offering free hosting, and the demos are no longer available.
Do note that GraphQL can be installed on any type of back-end and database, using any programming language. The technologies used here are chosen for the sake of simplicity and readability.
Our goal is to create a /graphql endpoint without removing the REST endpoints. The GraphQL endpoint will hit the database ORM directly to fetch data, so that it is totally independant from the REST logic.
Types
The data model is represented in GraphQL by types, which are strongly typed. There should be a 1-to-1 mapping between your models and GraphQL types. Our User type would be:
type User { id: ID! # The "!" means required firstname: String lastname: String email: String projects: [Project] # Project is another GraphQL type}
Queries
Queries define what queries you can run on your GraphQL API. By convention, there should be a RootQuery, which contains all the existing queries. I also pointed out the REST equivalent of each query:
type RootQuery { user(id: ID): User # Corresponds to GET /api/users/:id users: [User] # Corresponds to GET /api/users project(id: ID!): Project # Corresponds to GET /api/projects/:id projects: [Project] # Corresponds to GET /api/projects task(id: ID!): Task # Corresponds to GET /api/tasks/:id tasks: [Task] # Corresponds to GET /api/tasks}
Mutations
If queries are GET requests, mutations can be seen as POST/PATCH/PUT/DELETE requests (although really they are synchronized versions of queries).
By convention, we put all our mutations in a RootMutation:
type RootMutation { createUser(input: UserInput!): User # Corresponds to POST /api/users updateUser(id: ID!, input: UserInput!): User # Corresponds to PATCH /api/users removeUser(id: ID!): User # Corresponds to DELETE /api/users createProject(input: ProjectInput!): Project updateProject(id: ID!, input: ProjectInput!): Project removeProject(id: ID!): Project createTask(input: TaskInput!): Task updateTask(id: ID!, input: TaskInput!): Task removeTask(id: ID!): Task}
Note that we introduced new types here, called UserInput, ProjectInput, and TaskInput. This is a common practice with REST too, to create an input data model for creating and updating resources. Here, our UserInput type is our User type without the id and projects fields, and notice the keyword input instead of type:
This schema is strongly typed and is what allowed us to have those handy autocompletes in GraphiQL*.
* Note: After publication, Heroku stopped offering free hosting, and the demos for this article are no longer available.
Resolvers
Now that we have the public schema, it is time to tell GraphQL what to do when each of these queries/mutations is requested. Resolvers do the hard work; they can, for example:
Hit an internal REST endpoint
Call a microservice
Hit the database layer to do CRUD operations
We are choosing the third option in our example app. Let’s have a look at our resolvers file:
constmodels=sequelize.models;RootQuery: {user (root, { id }, context) {returnmodels.User.findById(id, context); },users (root, args, context) {returnmodels.User.findAll({}, context); },// Resolvers for Project and Task go here},/* For reminder, our RootQuery type was:type RootQuery { user(id: ID): User users: [User] # Other queries}
This means, if the user(id: ID!) query is requested on GraphQL, then we return User.findById(), which is a Sequelize ORM function, from the database.
What about joining other models in the request? Well, we need to define more resolvers:
User: {projects (user) {returnuser.getProjects(); // getProjects is a function managed by Sequelize ORM }},/* For reminder, our User type was:type User { projects: [Project] # We defined a resolver above for this field # ...other fields}*/
So when we request the projects field in a User type in GraphQL, this join will be appended to the database query.
And finally, resolvers for mutations:
RootMutation: {createUser (root, { input }, context) {returnmodels.User.create(input, context); },updateUser (root, { id, input }, context) {returnmodels.User.update(input, { ...context, where: { id } }); },removeUser (root, { id }, context) {returnmodels.User.destroy(input, { ...context, where: { id } }); },// ... Resolvers for Project and Task go here}
You can play around with this here. For the sake of keeping the data on the server clean, I disabled the resolvers for mutations, which means that the mutations will not do any create, update or delete operations in the database (and thus return null on the interface).
Query
query getUserWithProjects { user(id:2){ firstname lastname projects { name tasks { description}}}}mutation createProject { createProject(input:{name:"New Project", UserId: 2}){ id name}}
It may take some time to rewrite all types, queries, and resolvers for your existing app. However, a lot of tools exist to help you. For instance, there are tools that translate a SQL schema to a GraphQL schema, including resolvers!
Putting Everything Together
With a well-defined schema and resolvers on what to do on each query of the schema, we can mount a /graphql endpoint on our back-end:
// Mount GraphQL on /graphqlconstschema=makeExecutableSchema({ typeDefs,// Our RootQuery and RootMutation schema resolvers:resolvers() // Our resolvers});app.use('/graphql',graphqlExpress({ schema }));
And we can have a nice-looking GraphiQL interface* on our back-end. To make a request without GraphiQL, simply copy the URL of the request (i.e., https://host/graphql?query=query%20%7B%0A%20%20user(id%3A%202)%20%7B%0A%20%20%20%20firstname%0A%20%20%20%20lastname%0A%20%20%20%20projects%20%7B%0A%20%20%20%20%20%20name%0A%20%20%20%20%20%20tasks%20%7B%0A%20%20%20%20%20%20%20%20description%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D*), and run it with cURL, AJAX, or directly in the browser. Of course, there are some GraphQL clients to help you build these queries. See below for some examples.
* Note: After publication, Heroku stopped offering free hosting, and the demos are no longer available.
What’s Next?
This article’s aim is to give you a taste of what GraphQL looks like and show you that it’s definitely possible to try GraphQL without throwing away your REST infrastructure. The best way to know if GraphQL suits your needs is to try it yourself. I hope that this article will make you take the dive.
There are a lot of features we haven’t discussed about in this article, such as real-time updates, server-side batching, authentication, authorization, client-side caching, file uploading, etc. An excellent resource to learn about these features is How to GraphQL.
In conclusion, I believe that GraphQL is more than hype. It won’t replace REST tomorrow just yet, but it does offer a performant solution to a genuine problem. It is relatively new, and best practices are still developing, but it is definitely a technology that we will hear about in the next couple of years.