This website uses cookies to better the user experience of its visitors. Where applicable, this website uses a cookie control system, allowing users to allow or disallow the use of cookies on their computer/device on their first visit to the website. This complies with recent legislative requirements for websites to obtain explicit consent from users before leaving behind or reading files such as cookies on a user’s computer/device. To learn more click Cookie Policy.

Privacy preference center

Cookies are small files saved to a user’s computer/device hard drive that track, save, and store information about the user’s interactions and website use. They allow a website, through its server, to provide users with a tailored experience within the site. Users are advised to take necessary steps within their web browser security settings to block all cookies from this website and its external serving vendors if they wish to deny the use and saving of cookies from this website to their computer’s/device’s hard drive. To learn more click Cookie Policy.

Manage consent preferences

These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Cookies list
Name _rg_session
Provider rubygarage.org
Retention period 2 days
Type First party
Category Necessary
Description The website session cookie is set by the server to maintain the user's session state across different pages of the website. This cookie is essential for functionalities such as login persistence, ensuring a seamless and consistent user experience. The session cookie does not store personal data and is typically deleted when the browser is closed, enhancing privacy and security.
Name m
Provider m.stripe.com
Retention period 1 year 1 month
Type Third party
Category Necessary
Description The m cookie is set by Stripe and is used to help assess the risk associated with attempted transactions on the website. This cookie plays a critical role in fraud detection by identifying and analyzing patterns of behavior to distinguish between legitimate users and potentially fraudulent activity. It enhances the security of online transactions, ensuring that only authorized payments are processed while minimizing the risk of fraud.
Name __cf_bm
Provider .pipedrive.com
Retention period 1 hour
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to support Cloudflare Bot Management. This cookie helps to identify and filter requests from bots, enhancing the security and performance of the website. By distinguishing between legitimate users and automated traffic, it ensures that the site remains protected from malicious bots and potential attacks. This functionality is crucial for maintaining the integrity and reliability of the site's operations.
Name _GRECAPTCHA
Provider .recaptcha.net
Retention period 6 months
Type Third party
Category Necessary
Description The _GRECAPTCHA cookie is set by Google reCAPTCHA to ensure that interactions with the website are from legitimate human users and not automated bots. This cookie helps protect forms, login pages, and other interactive elements from spam and abuse by analyzing user behavior. It is essential for the proper functioning of reCAPTCHA, providing a critical layer of security to maintain the integrity and reliability of the site's interactive features.
Name __cf_bm
Provider .calendly.com
Retention period 30 minutes
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to distinguish between humans and bots. This cookie is beneficial for the website as it helps in making valid reports on the use of the website. By identifying and managing automated traffic, it ensures that analytics and performance metrics accurately reflect human user interactions, thereby enhancing site security and performance.
Name __cfruid
Provider .calendly.com
Retention period During session
Type Third party
Category Necessary
Description The __cfruid cookie is associated with websites using Cloudflare services. This cookie is used to identify trusted web traffic and enhance security. It helps Cloudflare manage and filter legitimate traffic from potentially harmful requests, thereby protecting the website from malicious activities such as DDoS attacks and ensuring reliable performance for genuine users.
Name OptanonConsent
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonConsent cookie determines whether the visitor has accepted the cookie consent box, ensuring that the consent box will not be presented again upon re-entry to the site. This cookie helps maintain the user's consent preferences and compliance with privacy regulations by storing information about the categories of cookies the user has consented to and preventing unnecessary repetition of consent requests.
Name OptanonAlertBoxClosed
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonAlertBoxClosed cookie is set after visitors have seen a cookie information notice and, in some cases, only when they actively close the notice. It ensures that the cookie consent message is not shown again to the user, enhancing the user experience by preventing repetitive notifications. This cookie helps manage user preferences and ensures compliance with privacy regulations by recording when the notice has been acknowledged.
Name referrer_user_id
Provider .calendly.com
Retention period 14 days
Type Third party
Category Necessary
Description The referrer_user_id cookie is set by Calendly to support the booking functionality on the website. This cookie helps track the source of referrals to the booking page, enabling Calendly to attribute bookings accurately and enhance the user experience by streamlining the scheduling process. It assists in managing user sessions and preferences during the booking workflow, ensuring efficient and reliable operation.
Name _calendly_session
Provider .calendly.com
Retention period 21 days
Type Third party
Category Necessary
Description The _calendly_session cookie is set by Calendly, a meeting scheduling tool, to enable the meeting scheduler to function within the website. This cookie facilitates the scheduling process by maintaining session information, allowing visitors to book meetings and add events to their calendars seamlessly. It ensures that the scheduling workflow operates smoothly, providing a consistent and reliable user experience.
Name _gat_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _gat_UA-* cookie is a pattern type cookie set by Google Analytics, where the pattern element in the name contains the unique identity number of the Google Analytics account or website it relates to. This cookie is a variation of the _gat cookie and is used to throttle the request rate, limiting the amount of data collected by Google Analytics on high traffic websites. It helps manage the volume of data recorded, ensuring efficient performance and accurate analytics reporting.
Name _ga
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga cookie is set by Google Analytics to calculate visitor, session, and campaign data for the site's analytics reports. It helps track how users interact with the website, providing insights into site usage and performance.
Name _ga_*
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga_* cookie is set by Google Analytics to store and count page views on the website. This cookie helps track the number of visits and interactions with the website, providing valuable data for performance and user behavior analysis. It belongs to the analytics category and plays a crucial role in generating detailed usage reports for site optimization.
Name _gid
Provider rubygarage.org
Retention period 1 day
Type First party
Category Analytics
Description The _gid cookie is set by Google Analytics to store information about how visitors use a website and to create an analytics report on the website's performance. This cookie collects data on visitor behavior, including pages visited, duration of the visit, and interactions with the website, helping site owners understand and improve user experience. It is part of the analytics category and typically expires after 24 hours.
Name _dc_gtm_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _dc_gtm_UA-* cookie is set by Google Analytics to help load the Google Analytics script tag via Google Tag Manager. This cookie facilitates the efficient loading of analytics tools, ensuring that data on user behavior and website performance is accurately collected and reported. It is categorized under analytics and assists in the seamless integration and functioning of Google Analytics on the website.

A Detailed Tutorial on How to Build an API App Based on GraphQL and Trailblazer: Part 1

  • 19479 views
  • 10 min
  • Apr 04, 2019
Daria R.

Daria R.

Copywriter

Sviatoslav S.

Sviatoslav S.

Ruby Developer

Share

What’s the quickest way to learn cool new technologies like GraphQL? By following a detailed but simple tutorial and creating your own application. With this idea in mind – and our desire to share knowledge with you – we’ve created a tutorial you can use to build your own app based on GraphQL and Trailblazer. Stay with us if you want to learn how to use these tools in your projects. But first, a little bit of theory.

Main terms

Here are the main terms we’re going to use in this tutorial:

  • GraphQL – A query language for getting data and declaring its structure. This technology is used as an additional layer between a client and a server. One of the main features of GraphQL is that the data structure is determined by the client app.
  • Query – The part of the GraphQL schema responsible for reading data
  • Mutation – The part of the GraphQL schema responsible for modifying data
  • GraphQL schema – The center of any GraphQL server implementation; it describes the functionality available to clients that connect to it
  • Type – The form of all elements that compose a schema
  • Resolver – Instructions for calculating values of a field in a schema
  • Trailblazer – A gem for creating a high-level architecture in an application. The Trailblazer gem stores all business logic in operations. Controllers contain only HTTP-specific logic. Models contain only associations, enums, and scopes.

Why do we need a GraphQL and Trailblazer combination?

We chose these technologies because they work perfectly together. Each of them has a long list of benefits:

GraphQL benefits:

  1. A client can choose what data it needs.
  2. You can use one query to get different data. With REST, you would have to use several queries.
  3. You don’t need to write documentation for APIs, as the schema is a sort of documentation itself.
  4. There’s no need for version control.

Trailblazer benefits:

  1. All business logic is in a separate architectural layer.
  2. Trailblazer provides an API that allows you to structure your business code into steps.
  3. Clean models
  4. Clean controllers

GraphQL and Trailblazer help you organize your API as flexibly as possible in terms of displaying data based on requests from client applications and, at the same time, make it scalable from the business point of view.

Building an API application based on GraphQL

The task

The application we’re going to build is an API with minimal to-do list functionality. We’ll build it with a GraphQL server based on the Trailblazer architecture that will later serve as a template for building more complex applications.

Technology stack

The main technology we’ll be using for our application is Ruby 2.5.1 and Ruby on Rails 5.2.1. We’ll also use Trailblazer 2.1.0.rc1 and GraphQL 1.8.11.

Step-by-step tutorial

1. Project setup

Create a new API application:

Let’s run it with the command rails s and make sure that our app works. To check that it works, follow this link: http://localhost:3000/

The next step is to configure the .gitignore file:

The next step is to set up the test environment. Let’s add the necessary gems to the Gemfile:

And install rspec.

After that, configure rails_helper.rb:

1.1. Configure Trailblazer

Now it’s time to configure Trailblazer and add the necessary gems:

Create trailblazer.rb in config/initializers:

To use such methods as form, present, run, and respond in controllers, we need to amend application controller.rb:

1.2. Configure GraphQL

Now we need to configure GraphQL. First, let’s add the necessary gems to the Gemfile:

The graphql gem is a tool that opens all opportunities of GraphQL. The graphiql-rails gem mounts the GraphQL IDE in Ruby on Rails applications.

Install GraphQL:

After installation, we get the following files:

Rubygarage tutorial

The file structure that the gem offers isn’t very convenient because all GraphQL elements are placed in one folder. We suggest moving the main elements (mutations and queries) to the root GraphQL folder and other elements to the lib subfolder. Let’s use the following structure for the graphql folder:

GraphQL tutorial

During installation of graphql, a controller was generated. This controller is an entry point for GraphQL:

Let’s make this controller RESTful and move the logic to Trailblazer concept

The Graphql::Execute operation looks like this:

We’ll also move the logic for validating the variables parameter to a service object:

At this point, we’ve finished configuring GraphQL.

2. User features

2.1. Signup feature

First, we need to implement the signup feature. For that, we need to create a User model.

2.1.1. Implement an operation

It’s time to create the Users::Create operation. This operation should create a User and validate input data: an input can’t be empty, a password can’t be fewer than six symbols, the password chosen has to match the one in the confirmation field, and the email has to be unique.

Let’s start with tests for this operation:

Now we need to implement the operation itself:

Here’s what’s happening in the concept step by step:

  1. An object of the User class is initialized and saved to the variable ctx[‘model’] with the help of Model macros.
  2. The Users::Contract::Create contract is initialized (creating a form object).
  3. Input parameters are parsed and validated with the contract.
  4. Form data is mapped to the model and saved.

Here’s what the contract looks like:

The contract consists of two parts:

  1. Description of input parameters
  2. Parameter validation with dry-validation

2.1.2. Implement a GraphQL mutation

First, let’s write a test for this mutation:

Here’s what we check in the test. First, we describe the mutation. Then we check two cases: success and fail. Each will follow a specific response schema:

The matcher will look like this:

To pass our tests, we first need to describe the GraphQL object type User:

Every field here has its type. For example, it can be an Object type (like User) or a Scalar type. In the description of this object, we use two built-in Scalar types (ID and String) and one custom Scalar type (Lib::Scalars::DateTime):

Now we’ll proceed directly to describing the mutation that will process the request to create a user.

When we name mutations, we usually use an object + verb construction. The main idea of this approach is that GraphQL sorts mutation fields by name. This way, we’re grouping queries by entities. Also, this approach is used by Shopify.

All mutations will be called from the root mutation. So add the mutation userCreate to the root mutation:

It’s good practice to wrap arguments of mutation queries into an input object. As you can see, in the test for our mutation query we’ve wrapped the arguments in input. There are two ways to wrap arguments:

  1. Inherit a class from GraphQL::Schema::RelayClassicMutation that automatically wraps all arguments in input objects.
  2. Manually create an input object with the necessary arguments (you can find detailed information about how to create an input object in the official documentation for the gem).

We chose the first option and will use it here and in all mutations below. Here’s how this mutation looks:

Our mutation consists of a name, a description, a description of arguments that the mutation takes, a description of fields that the mutation can return, and a method resolve that will return data for the described fields.

In the method resolve, we call our operation. Depending on the result, it returns either the created user or errors. The errors field returns an array of graphql objects of type Objects::Error:

In order to convert the errors that our operation returns to the format appropriate for Objects::Error, we use this service:

2.2. Show user feature

2.2.1. Implement the operation

Let’s start with writing a test for the Users::Show operation:

The operation looks like this:

The operation looks like this:

2.2.2. Implement a GraphQL query

Now let’s write tests for our graphql query:

As in the case of the userCreate mutation, we test two cases: failure (when the user isn’t found) and success (when the user is found). Each case will have its own response schema:

The call to our query will be made from QueryType:

The resolver for the query looks like this:

In the code above, we can see:

  1. The type that the query returns
  2. The argument that the query expects
  3. The resolve method, which starts our operation and returns the found instance of the User class in case of success.

2.2.3. Implement a handler for an ActiveRecord::RecordNotFound exception

If a user isn’t found when the operation Users::Show is run, an ActiveRecord::RecordNotFound exception will be raised. We need to handle this exception. Let’s create a handler and include it in ApplicationSchema:

Now we can handle the ActiveRecord::RecordNotFound exception and our tests will run successfully.

2.3. User authentication feature

We need to add user authentication to prevent user data from overlapping. We’ll use the JWT gem for this.

Add the ruby-jwt gem:

2.3.1. Implement a GraphQL query

Let’s start with tests. We’ll name a query that’s responsible for displaying data on the user identified as “me”:

Schemas for two cases will look as follows:

In our test, we use the sign_in helper, which generates a token and puts it into the request header:

2.3.2. Implement authentication

Authentication will be handled at the controller level. We put authentication logic in the module:

After that, we need to include the module in ApplicationController:

Create an AuthenticationController where the authentication logic will be called:

Our GraphqlsController should be inherited from AuthenticationController:

To use current_user in GraphQL, we need to change our Graphql::Execute operation:

Let’s wrap the call of our operations inside resolvers with method run (similar to the run method in Trailblazer::Rails::Controller). For that, we’ll create Lib::Mutations::Base and Lib::Resolvers::Base:

Now the userCreate mutation and the user query will look like this:

We decided to implement an authentication check in the method ‘ready?’, which is available in mutations and queries and runs before the ‘resolve’ method:

An exception looks like this:

We’ll add a handler for Exceptions::AuthenticationError to our ErrorHandler:

Now it’s time to work with query `me`. We need to declare it in the root query:

The resolver code is simple:

As a result of the query, we receive our instance of the User class that was authenticated.

2.4. Login feature

2.4.1. Implement the operation

Let’s start with tests for the login operation:

Now we’ll describe our operation and contract:

2.4.2. Implement GraphQL mutation

Tests for the mutation will look like this:

As a result of this mutation, we can get three different response schemas:

We’ll declare our mutation in the root mutation:

And describe it:

If the correct username and password are entered, the result of this mutation will be our user and token for authentication. Otherwise, an exception will be raised.

In this part of our tutorial, we’ve learned how to configure Trailblazer and GraphQl. We also implemented such user features as signup, show user, user authentication, and login feature.

Check out the second part of this tutorial to learn how to implement the main features of the ToDo list and authorization feature.

Feel free to start a conversation below if you have any questions and subscribe to our blog to learn with us!

CONTENTS

Authors:

Daria R.

Daria R.

Copywriter

Sviatoslav S.

Sviatoslav S.

Ruby Developer

Rate this article!

Nay
So-so
Not bad
Good
Wow
12 rating, average 4.92 out of 5

Share article with

Comments (0)

There are no comments yet

Leave a comment

Subscribe via email and know it all first!