Building a REST API With Feathers.js and SQLite | by Arctype | Apr, 2022

Building a REST API with Feathers.js  and SQLite
Picture by creator

In search of a option to construct an online utility with options like authentication, database setup, and authorization with out writing a ton of code and configurations? Ever wished to create a production-ready app in a matter of days?

Consider it or not, it’s attainable! This tutorial will present you learn how to use Feathers.js to create a REST API in minutes. We’ll study Feathers.js, implement an instance API, and share some ideas and concerns. Let’s start.

Feathers is a light-weight internet framework for creating real-time apps and REST APIs in JavaScript or TypeScript.

Feathers can work together with any backend expertise, helps over a dozen databases, and works with any frontend expertise, equivalent to React, VueJS, Angular, and React Native.

Feathers.js is well-known for its ease of use and rapidity of supply, and in depth documentation. With Feathers, all you’ll want to add a function is to run a easy command.

This tutorial is a hands-on demonstration. To get began, I assume you might have the next:

You’ll create a film rental utility as an example the capabilities of Feathers.js and Arctype database visualization instruments. The administrator will generate motion pictures on this program, and authenticated customers will be capable of hire them. You’ll be taught to make use of Sequelize to correlate tables in Feathers.js, prohibit entry to particular routes, and hyperlink your database to Arctype.

To get began, open your command-line interface and create a folder for this tutorial with the command under:

npm set up @feathersjs/feathers --save

Look forward to the set up to finish and make sure the set up with the command under:

feathers -V

If all the things went nicely with the set up, you’d see the model quantity printed out on the console.

With Feathers put in in your laptop, create a folder for this utility with the command under:

Mkdir RestWithFeathers && RestWithFeathers

Then, generate a brand new API utility with the command under:

feathers generate app

The above command will immediate you to pick out the configuration in your utility. For the demonstration on this tutorial, your choice ought to appear to be the screenshot as proven under:

Building a REST API with Feathers.js  and SQLite

Within the above screenshot, we made the next alternatives:

  • Chosen JavaScript as the popular programming language
  • Specified the title for the applying (movie-rental)
  • Chosen src the placement for the mission boilerplates
  • Chosen npm because the bundle handle
  • Enabled person authentication
  • Chosen Eslint to investigate our code
  • Select a username and password authentication technique.
  • Chosen person because the title for our entity
  • Chosen Sequelize because the ORM for the applying
  • Chosen SQLite as our database
  • Specified movieDB as our database title

As soon as the alternatives are accomplished, the command will generate an express-like mission construction. Now let’s have a look at the folder construction generated by working the above command.

Building a REST API with Feathers.js  and SQLite

For this tutorial, we’ll have a look at as soon as we have a look at the next:

  • config: Comprises the configurations recordsdata for the applying
  • node_modules: A folder to retailer the listing of put in packages required to run the applying.
  • public: Comprises the static recordsdata that may be served to the consumer.
  • src: Comprises the server code for Feathers.js purposes
  • src/hooks: Comprises the applying customized hooks.
  • src/middleware: Comprises Categorical middlewares
  • src/service: Comprises our utility companies
  • src/index.js: The entry file that runs the applying
  • src/app.js: Configures our Feathers utility
  • src/app.hook.js: Comprises hooks that apply to each service
  • src/channels.js: Units Featherjs occasion channels
  • check: Comprises the check for the applying

Now run the server in growth mode with the command under:

npm run dev

Working the server in growth prompts sizzling reload and console error logging. At this level, the server needs to be working on port 3030, and a moviedb.sqlite file needs to be created in your mission’s root listing.

A service is an object or occasion of a category that implements sure strategies. Providers present a constant, protocol-independent interface for interacting with any information. In Feathers, you simply have to run a command, and all the things is ready up so that you can create a service. Create a film service with the command under:

feathers generate service

The above command will immediate you to pick out the configurations in your service. Your choice ought to appear to be the screenshot as proven under:

Building a REST API with Feathers.js  and SQLite

Right here, you chose the ORM in your film desk, the service title, the route URL, and enabled authentication on the film routes. As soon as these alternatives are accomplished, the command will generate a folder construction under within the src/service folder.

┣ 📜film.class.js
┣ 📜film.hooks.js
┗ 📜film.service.js

In your film.hook file, Feathers added the code snippet under, which ensures that earlier than the request passes by means of this path to the film service, it has to verify the person’s person entry token despatched when the person logged in.

earlier than: 
all: [],
discover: [ authenticate('jwt') ],
get: [ authenticate('jwt') ],
create: [ hashPassword('password') ],
replace: [ hashPassword('password'), authenticate('jwt') ],
patch: [ hashPassword('password'), authenticate('jwt') ],
take away: [ authenticate('jwt') ]

Subsequent, create a rental service with the command under:

feathers generate service

The above performs the identical operation with that film service, however this time generates a special folder title and recordsdata as proven under:

📦 leases
┣ 📜leases.class.js
┣ 📜leases.hooks.js
┗ 📜leases.service.js

It can additionally name the jwt authenticate(‘jwt’) perform in all of the routes. Additionally, the command will generate the respective fashions for the companies you simply created with some boilerplates as proven under:

┣ 📜film.mannequin.js
┣ 📜leases.mannequin.js
┗ 📜customers.mannequin.js

With the companies and fashions created, modify the mannequin’s properties to have the required properties for the film and leases desk. For the film mannequin, add the next properties to the properties.

sort: DataTypes.STRING,
allowNull: false,
sort: DataTypes.STRING,
allowNull: false,
sort: DataTypes.STRING,
allowNull: false,
createdAt: sort: DataTypes.DATE, defaultValue: ,
updatedAt: sort: DataTypes.DATE, defaultValue: ,

Then, within the mannequin of the rental, add the next properties.

sort: DataTypes.INTEGER,
allowNull: false,
createdAt: sort: DataTypes.DATE, defaultValue: ,
updatedAt: sort: DataTypes.DATE, defaultValue: ,

We nonetheless have to create an affiliation between the person, film, and rental mannequin, which brings us to the subsequent part.

Database relationships are associations shaped between tables when information is retrieved utilizing be part of statements. Relationships are sometimes deliberate utilizing an ERD diagram.

Our utility has a person, a film, and a rental desk. The film is owned by a rental, and a person owns a rental. Probably the most simple method to sustaining observe of this information in every database is to ascertain a relationship between them, saving the desk IDs as a overseas key within the tables with which they’re associated. So let’s go forward and create a relationship between of three tables. Within the fashions/person.fashions.js, find the feedback:

// Outline associations right here
// See

And add the code snippet under.

const  leases  = fashions;

You created a one-to-many relationship with the leases desk within the code snippet. Which means that one person can have many leases.

We then may also add the code under to the fashions/film.mannequin.js file.

const  leases, film  = fashions;
film.belongsToMany(leases, by means of: 'MovieRendtals' );

Within the above code snippet, we created a many-to-many relationship between the leases desk, which means a film can have a number of leases. In lots of-to-many relationships, a junction desk is created to trace the 2 tables’ IDs, on this case, MovieRentals.

Lastly, add the code snippet under to the fashions/leases.mannequin.js file.

const  customers, film  = fashions;
leases.belongsToMany(film, by means of: 'MovieRentals' );

At this level, the tables now have a relationship with one another. Now you possibly can load the info into the tables whenever you create or fetch the info from any service. That brings us to hooks in Feathers.

Hooks are pluggable middleware capabilities that may be registered earlier than, after, or on errors of a service technique. You possibly can register a single hook perform or create a series of them to create complicated workflows. You’ll create a hook that can load the info related to every desk. In your service/leases folder, create a get-related.js file and the snippet under:

module.exports = perform (choices = ) 
return async (context) =>
const sequelize ='sequelizeClient');
const customers, film = sequelize.fashions;
context.params.sequelize =
embrace: [ model: users , model: movie ],
uncooked: false,
return context;

Within the above code, the snippet tells Feathers to load customers and film fashions each time a film is rented. Now replace your service/leases/rental.hooks.js file with the code snippet under. Modify the code contained in the earlier than object.

all: [authenticate('jwt')],
discover: [getRelated()],
get: [getRelated()],
create: [getRelated()],
replace: [],
patch: [],
take away: []

Now let’s check the applying with Insomnia. We’ll begin with the customers routes.

Create a person

Create a person on the /customers route.

Building a REST API with Feathers.js  and SQLite

Authenticate a person

Authenticate a person on the /authentication route.

Building a REST API with Feathers.js  and SQLite

Create a film

Create a film on the /film route.

Building a REST API with Feathers.js  and SQLite

Hire a film

Hire a film on the /leases route. You’ll specify the userId, movieId, and amount fields on this route.

Building a REST API with Feathers.js  and SQLite

These look good! Now go forward and check different requests technique on every route, like GET, UPDATE, and DELETE.

Join your database to Arctype to view the tables and information created in your utility. You possibly can hook up with Arctype by following these steps:

  1. Run Arctype
  2. Click on on the SQLite tab.
  3. Click on on the Select SQLite File button
  4. Navigate to the mission folder and choose the moviedb.sqlite file
  5. Check the connection and save the modifications

As soon as your database is linked to Arctype, you’d see the customers, motion pictures, leases, and MovieRentals tables as proven within the screenshot under:

Building a REST API with Feathers.js  and SQLite

At this level, your database has efficiently been linked to Arctype. You possibly can click on on every desk to indicate the info saved in them.

All through this tutorial, you’ve explored Feathers.js by constructing a demo utility. You’ve discovered learn how to arrange a Feathers.js utility, create a service, implement authentication/authorization, create customized hooks, and hook up with Arctype.

Now that you just’ve gotten this information, how do you propose to make use of Feathers in your subsequent mission? Maybe you possibly can even add an additional function to this mission by forking or cloning the Github repository.

More Posts