Karim Aya

Karim Aya

1564366619

Joi — awesome code validation for Node.js and Express

Originally published by Chris Noring at dev.to

There are different situations when we need to perform these checks like validating a response from a backend endpoint or maybe verifying what goes into our REST API won’t break our code. We will focus on the latter, how to validate our API.

Consider the below code that we might need to write when we don't have a validation library:

if (!data.parameterX) { 
  throw new Exception('parameterX missing') 
} 
try { 
  let value = parseInt(data.parameterX); 
} catch (err) { 
  throw new Exception('parameterX should be number'); 
} 
if(!/[a-z]/.test(data.parameterY)) { 
  throw new Exception('parameterY should be lower caps text') 
}

I think you get the idea from the above cringe-worthy code. We tend to perform a lot of tests on our parameters to ensure they are the right and/or their values contains the allowed values.

As developers we tend to feel really bad about code like this, so we either start writing a lib for this or we turn to our old friend NPM and hope that some other developer have felt this pain and had too much time on their hands and made a lib that you could use.

There are many libs that will do this for you. I aim to describe a specific one called Joi.

https://github.com/hapijs/joi

Throughout this article we will take the following journey together:

  • Have a look at Joi’s features
  • See how we can use Joi in the backend in a Request pipeline
  • Improve even further by building a middleware for Express in Node.js

Introducing Joi

Installing Joi is quite easy. We just need to type:

npm install joi

After that, we are ready to use it. Let’s have a quick look at how we use it. The first thing we do is import it and then we set up some rules, like so:

const Joi = require('joi'); 
const schema = Joi.object().keys({ 
  name: Joi.string().alphanum().min(3).max(30).required(),
  birthyear: Joi.number().integer().min(1970).max(2013), 
}); 
const dataToValidate = { 
  name 'chris', 
  birthyear: 1971 
} 
const result = Joi.validate(dataToValidate, schema); 
// result.error == null means valid

What we are looking at above is us doing the following:

  • constructing a schema, our call to Joi.object(),
  • validating our data, our call to Joi.validate() with dataToValidateand schema as input parameters

Ok, now we understand the basic motions. What else can we do?

Well, Joi supports all sorts of primitives as well as Regex and can be nested to any depth. Let’s list some different constructs it supports:

  • string, this says it needs to be of type string, and we use it like so Joi.string()
  • number, Joi.number() and also supporting helper operations such as min() and max(), like so Joi.number().min(1).max(10)
  • required, we can say whether a property is required with the help of the method required, like so Joi.string().required()
  • any, this means it could be any type, usually, we tend to use it with the helper allow() that specifies what it can contain, like so, Joi.any().allow('a')
  • optional, this is strictly speaking not a type but has an interesting effect. If you specify for example prop : Joi.string().optional. If we don't provide prop then everybody's happy. However, if we do provide it and make it an integer the validation will fail
  • array, we can check whether the property is an array of say strings, then it would look like this Joi.array().items(Joi.string().valid('a', 'b')
  • regex, it supports pattern matching with RegEx as well like so Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/)

The whole API for Joi is enormous. I suggest to have a look and see if there is a helper function that can solve whatever case you have that I’m not showing above

Joi API

https://github.com/hapijs/joi/blob/v14.3.1/API.md

 Nested types

Ok, so we have only shown how to declare a schema so far that is one level deep. We did so by calling the following:

Joi.object().keys({ });

This stated that our data is an object. Then we added some properties to our object like so:

Joi.object().keys({ 
  name: Joi.string().alphanum().min(3).max(30).required(),
  birthyear: Joi.number().integer().min(1970).max(2013) 
});

Now, nested structures are really more of the same. Let’s create an entirely new schema, a schema for a blog post, looking like this:

const blogPostSchema = Joi.object().keys({ 
  title: Joi.string().alphanum().min(3).max(30).required(),
  description: Joi.string(), 
  comments: Joi.array().items(Joi.object.keys({ 
    description: Joi.string(), 
    author: Joi.string().required(), 
    grade: Joi.number().min(1).max(5) 
  })) 
});

Note especially the comments property, that thing looks exactly like the outer call we first make and it is the same. Nesting is as easy as that.

Node.js Express and Joi

Libraries like these are great but wouldn’t it be even better if we could use them in a more seamless way, like in a Request pipeline? Let’s have a look firstly how we would use Joi in an Express app in Node.js:

const Joi = require('joi'); 
app.post('/blog', async (req, res, next) => { 
  const { body } = req; const 
  blogSchema = Joi.object().keys({ 
    title: Joi.string().required 
    description: Joi.string().required(), 
    authorId: Joi.number().required() 
  }); 
  const result = Joi.validate(body, blogShema); 
  const { value, error } = result; 
  const valid = error == null; 
  if (!valid) { 
    res.status(422).json({ 
      message: 'Invalid request', 
      data: body 
    }) 
  } else { 
    const createdPost = await api.createPost(data); 
    res.json({ message: 'Resource created', data: createdPost }) 
  } 
});

The above works. But we have to, for each route:

  1. create a schema
  2. call validate()

It’s, for lack of a better word, lacking in elegance. We want something slick looking.

Building a middleware

Let’s see if we can’t rebuild it a bit to a middleware. Middlewares in Express is simply something we can stick into the request pipeline whenever we need it. In our case, we would want to try and verify our request and early on determine whether it is worth proceeding with it or abort it.

So let’s look at a middleware. It’s just a function right:

const handler = (req, res, next) = { // handle our request } 
const middleware = (req, res, next) => { // to be defined } 
app.post( '/blog', middleware, handler )

It would be neat if we could provide a schema to our middleware so all we had to do in the middleware function was something like this:

(req, res, next) => { 
  const result = Joi.validate(schema, data) 
}

We could create a module with a factory function and module for all our schemas. Let’s have a look at our factory function module first:

const Joi = require('joi'); 
const middleware = (schema, property) => { 
  return (req, res, next) => { 
  const { error } = Joi.validate(req.body, schema); 
  const valid = error == null; 

if (valid) {
next();
} else {
const { details } = error;
const message = details.map(i => i.message).join(‘,’);

console.log("error", message); 

res.status(422).json({ error: message }) }
}
}
module.exports = middleware;

Let’s thereafter create a module for all our schemas, like so:

// schemas.js
const Joi = require(‘joi’)
const schemas = {
blogPOST: Joi.object().keys({
title: Joi.string().required
description: Joi.string().required()
})
// define all the other schemas below
};
module.exports = schemas;

Ok then, let’s head back to our application file:

// app.js
const express = require(‘express’)
const cors = require(‘cors’);
const app = express()
const port = 3000
const schemas = require(‘./schemas’);
const middleware = require(‘./middleware’);
var bodyParser = require(“body-parser”);

app.use(cors());
app.use(bodyParser.json());
app.get(‘/’, (req, res) => res.send(‘Hello World!’))
app.post(‘/blog’, middleware(schemas.blogPOST) , (req, res) => {
console.log(‘/update’);
res.json(req.body);
});
app.listen(port, () => console.log(Example app listening on port ${port}!))

Testing it out

There are many ways to test this out. We could do a fetch() call from a browser console or use cURL and so on. We opt for using a chrome plugin called Advanced REST Client.

Let’s try to make a POST request to /blog. Remember our schema for this route said that title and description were mandatory so let’s try to crash it, let’s omit title and see what happens:

Aha, we get a 422 status code and the message title is required, so Joi does what it is supposed to. Just for safety sake lets re-add title:

Ok, happy days, it works again.

Support Router and Query parameters

Ok, great we can deal with BODY in POST request what about router parameters and query parameters and what would we like to validate with them:

  • query parameters, here it makes sense to check that for example parameters like page and pageSize exist and is of type number. Imagine us doing a crazy request and our database contains a few million products, AOUCH :)
  • router parameters, here it would make sense to first off check that we are getting a number if we should get a number that is ( we could be sending GUIDs for example ) and maybe check that we are not sending something that is obviously wrong like a 0 or something

 Adding query parameters support

Ok, we know of query parameters in Express, that they reside under the request.query. So the simplest thing we could do here is to ensure our middleware.js takes another parameter, like so:

const middleware = (schema, property) => { }

and our full code for middleware.js would, therefore, look like this:

const Joi = require(‘joi’);
const middleware = (schema, property) => {
return (req, res, next) => {
const { error } = Joi.validate(req[property], schema);
const valid = error == null;
if (valid) { next(); }
else {
const { details } = error;
const message = details.map(i => i.message).join(‘,’)
console.log(“error”, message);
res.status(422).json({ error: message })
}
}
}
module.exports = middleware;

This would mean we would have to have a look at app.js and change how we invoke our middleware() function. First off our POST request would now have to look like this:

app.post(
‘/blog’,
middleware(schemas.blogPOST, ‘body’) ,
(req, res) => {
console.log(‘/update’);
res.json(req.body);
});

As you can see we add another argument body to our middleware() call.

Let’s now add the request who’s query parameters we are interested in:

app.get(
‘/products’,
middleware(schemas.blogLIST, ‘query’),
(req, res) => { console.log(‘/products’);
const { page, pageSize } = req.query;
res.json(req.query);
});

As you can see all we have to do above is add the argument query. Lastly, let’s have a look at our schemas.js:

// schemas.js
const Joi = require(‘joi’);
const schemas = {
blogPOST: Joi.object().keys({
title: Joi.string().required(),
description: Joi.string().required(),
year: Joi.number() }),
blogLIST: {
page: Joi.number().required(),
pageSize: Joi.number().required()
}
};
module.exports = schemas;

As you can see above we have added the blogLIST entry.

Testing it out

Let’s head back to Advanced REST client and see what happens if we try to navigate to /products without adding the query parameters:

As you can see Joi kicks in and tells us that page is missing.

Let’s ensure page and pageSize is added to our URL and try it again:

Ok, everybody is happy again. :)

Adding router parameters support

Just like with query parameters we just need to point out where we find our parameters, in Express those reside under req.params. Thanks to the works we already did with middleware.js we just need to update our app.js with our new route entry like so:

// app.js
app.get(
‘/products/:id’,
middleware(schemas.blogDETAIL, ‘params’),
(req, res) => {
console.log(“/products/:id”);
const { id } = req.params;
res.json(req.params);
}
)

At this point we need to go into schemas.js and add the blogDetail entry so schemas.js should now look like the following:

// schemas.js

const Joi = require(‘joi’);

const schemas = {
blogPOST: Joi.object().keys({
title: Joi.string().required(),
description: Joi.string().required(),
year: Joi.number() }),
blogLIST: {
page: Joi.number().required(),
pageSize: Joi.number().required()
},
blogDETAIL: {
id: Joi.number().min(1).required()
}
};
module.exports = schemas;

Try it out

The last step is trying it out so let’s first test to navigate to /products/abc. That should throw an error, we are only OK with numbers over 0:

Ok, now for a URL stating /products/0, our other requirement:

Also, that fails, as expected.

Summary

We have introduced the validation library Joi and presented some basic features and how to use it. Lastly, we have looked at how to create a middleware for Express and use Joi in a smart way.

Originally published by Chris Noring at dev.to

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Docker for Node.js Projects From a Docker Captain

☞ Intro To MySQL With Node.js - Learn To Use MySQL with Node!

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

☞ React Node FullStack - Social Network from Scratch to Deploy

☞ Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

☞ Complete Next.js with React & Node - Beautiful Portfolio App

☞ Build a Blockchain & Cryptocurrency | Full-Stack Edition

#node-js #web-development #express

What is GEEK

Buddha Community

Joi — awesome code validation for Node.js and Express

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

Node JS Server Side Form Validation using Express-Validator, Body-Parser and EJS

Today we are going to do some server-side form validation using the Express-validator, Body-parser and for the view engine, I will be using EJS.

This is an introduction video, but it should give you enough knowledge to get you started with form validation.

As you might already know it’s usually good practice to validate user input on Server Side because you can protect against malicious users, who can easily bypass your client-side scripting language and submit dangerous input to the server.

BLOG POST & SOURCE FILES
https://raddy.co.uk/blog/node-js-form-validation-using-express-validator-and-ejs/

Introduction: (0:00)
Project Overview: (1:00)
Views & Form: (3:20)
Form Validation: (9:34)
Outro: (20:37)

CONNECT with RaddyTheBrand
Website: https://www.raddy.co.uk
GitHub: https://www.github.com/RaddyTheBrand
Instagram: https://www.instagram.com/RaddyTheBrand
Twitter: https://www.twitter.com/RaddyTheBrand
Newsletter: https://www.raddy.co.uk/newsletter

DONATE to RaddyTheBrand
BuyMeACoffee: https://www.buymeacoffee.com/RaddyTheBrand
PayPal: https://bit.ly/3tAuElv

#ejs #node js #node #express-validator #body-parser #node js server side

Deploy a Node.js App to Heroku's Free Tier + Keeping the App Alive | Node.js + Express.js

In this video, we’ll be going over how to quickly deploy your Node.js app to Heroku for FREE and how we can keep this app alive/online despite Heroku’s free tier’s limitations.

Building the Mars Rover Pictures of the Day App: https://www.youtube.com/watch?v=s5sygFQ_vLE

Kaffeine: https://kaffeine.herokuapp.com/
Other alternatives to keep Heroku apps alive:

Sections:
0:00 - Intro
0:22 - Discussing how to keep Heroku’s free apps alive
1:20 - Linking your Heroku app to your GitHub repo
2:47 - Setting up the server and GET endpoint to ping
7:09 - Setting up the config to start the app
8:46 - Verifying the deployment
9:36 - Keeping the app alive/online
10:23 - Conclusion

Found this video helpful? Feel free to support this channel here: https://ko-fi.com/jacksonyuan

#express.js #express #node.js #node #heroku's