node.js: Rest API (calculator)

Hi people!!

Today, I will teach you how to create the calculator with basic functions.

But before starting, is important to refer to the CRUD definition.

The CRUD defintion are the acronyms for Create, Read, Update and Delete and these are the four basic operations used in relational databases.

In the ISO / SQL standard, this is the mapped abbreviation CRUD:

  • Create — INSERT
  • Read — SELECT
  • Update — UPDATE
  • Delete — DELETE

So, let’s put this into practice!!

mkdir calculator
cd calculator
npm init

Remember that at the end of this step a package.json file will be created.

npm install — save hapi
touch index.js
//Framework hapi.jsconst Hapi = require('hapi');// Machine and logical portconst host = 'localhost';const port = 8000;// Create the serverconst server = Hapi.Server({host: host,port: port});// Start the serverconst init = async () => {await server.start();console.log("Server up no porto: " + port);}// App launchinit();
node index.js

And the result, at this moment, is what is illustrated in this image:

The result, at this moment
server.route ({
method: 'GET',
path: '/ calculator / about',
handler: function (request, h) {

var data = {
msg: 'Calculator API'
};

return data;
}
});

http://localhost:8000/calculator/about

And now, the result is this:

http://localhost:8000/calculator/about

App organization (MVC)

Our application will have this “design”:

  • M : for Model (code for our database model);
  • V : for View (layout);
  • C : for controllers (logical part of the app).
mkdir routes
cd routes
touch routes.js

Before the init () function, the name file must be called. For this, it is necessary to insert the following code:

// Define routersrequire('./routes/routes')(server);
module.exports = function(server) {
//route Somaserver.route({method: 'GET',path: '/calculator/soma/{num1}/{num2}',handler: function (pedido) {const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 + num2};return data;}});//route Subtraçãoserver.route({method: 'GET',path: '/calculator/sub/{num1}/{num2}',handler: function (pedido){const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 - num2};return data;}});
//route Multiplicaçãoserver.route({method: 'GET',path: '/calculator/multi/{num1}/{num2}',handler: function (pedido){const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 * num2};return data;}});//route Divisãoserver.route({method: 'GET',path: '/calculator/div/{num1}/{num2}',handler: function (pedido){const num1 = parseInt(pedido.params.num1);const num2 = parseInt(pedido.params.num2);var data = {resultado: num1 / num2};return data;}});
}

Once the app is created, just test all the basic operations on your browser.

I hope you enjoyed!!

Finalist student in Computer Engineering