Xpertlab – Android Application Development Company in Junagadh
Express.js is a battle-tested framework that is an absolute breeze to use. Even though Express is light, there is often a need for a backend system that is even faster. This allows your app to be snappier and more responsive.
This is where Fastify comes in. It is a framework that is more efficient and speedier than Express due to lower overhead. This means that your server will stay responsive even when dealing with heavy workloads. In fact, according to Sergey Onufrienko, Fastify is around 20% faster than Express.
Other than speed, what does it have to offer? For one, it has a growing library of plugins. Most importantly, it has a schema system. For example, assume that you have the following response from your server:
What if your front end only wants the name
field? By using Fastify’s schema system, you can set a filter and send the name
field as a response:
In this article, you will learn how to build an API using MongoDB and Fastify as your backend framework.
Xpertlab – Android Application Development Company in Junagadh
To initialize a Node.js app, run the following terminal commands:
mkdir fastify-tutorial #create directory
cd fastify-tutorial
cd fastify-tutorial
touch index.js #our main file
npm init -y #initialize the project
Let’s now install the required dependencies. Here, we want the following packages:
dotenv
: To use environment variables.fastify
: To build our backend.fastify-mongodb
: Fastify’s plugin to help us interact with our database.mongodb
: To allow us to parse URL parameters and convert them into ObjectID
fields.To get these modules, run the following command:
npm i dotenv fastify fastify-mongodb mongodb
Next, go to your .env
file and paste your MongoDB connection string like so:
CONNECT_DB = connectionString
In your project’s folder structure, make the following folders:
controllers
: To hold our application logic.routes
: This directory will hold our routes and their respective handlers.In the end, your project’s folder structure should look like this:
In /index.js
, write the following code:
const fastify = require(“fastify”)({ logger: true });
const dotenv = require(“dotenv”);
dotenv.config();
fastify.register(require(“fastify-mongodb”), { forceClose: true, url: process.env.CONNECT_DB, }); fastify.get(“/”, function (req, reply) { reply.send(“Hello, world!”); }); fastify.listen(8080, function (err, address) { if (err) { fastify.log.error(err); process.exit(1); } fastify.log.info(`server listening on ${address}`); });fastify
module. The logger
property tells Fastify to log out the user’s routes and response codes to the terminal.fastify-mongodb
plugin so that we can use our database in our project./
route, display a response.8080
.localhost:8080
.Great! Our code works.
Xpertlab – Android Application Development Company in Junagadh
In your controllers
folder, create a file called users.controller.js
. Here, write the following code:
users
collection from the database.name
and age
fields from the payload and store them in the data
object.We have now written our logic. As the second step, let’s now register it as a handler.
In routes
, create a file called users.js
. Here, write the following code:
/users
route, run the listUser
function./users
route (a POST
request), invoke the addUser
method.We’re almost done! All that’s left is to register the /users
route.
To achieve this, go to /index.js
and write this line:
fastify.register(require(“./routes/users”));
To get all the documents in the users
collection, use a GET
request:
To get all the documents in the users
collection, use a GET
request:
This was really easy!
In the end, /index.js
should look like this:
In controllers/users.controller.js
, add the following code:
id
field. The req.params
the object contains the URL parameters. In this case, we only want the id
parameter.If you are aiming to build an API that favors responsiveness and speed, then Fastify will fulfill your needs. Moreover, its vast ecosystem of plugins allows you to develop complicated features without writing lots of code.