Book Image

Getting Started with hapi.js

Book Image

Getting Started with hapi.js

Overview of this book

This book will introduce hapi.js and walk you through the creation of your first working application using the out-of-the-box features hapi.js provides. Packed with real-world problems and examples, this book introduces some of the basic concepts of hapi.js and Node.js and takes you through the typical journey you'll face when developing an application. Starting with easier concepts such as routing requests, building APIs serving JSON, using templates to build websites and applications, and connecting databases, we then move on to more complex problems such as authentication, model validation, caching, and techniques for structuring your codebase to scale gracefully. You will also develop skills to ensure your application's reliability through testing, code coverage, and logging. By the end of this book, you'll be equipped with all the skills you need to build your first fully featured application. This book will be invaluable if you are investigating Node.js frameworks or planning on using hapi.js in your next project.
Table of Contents (15 chapters)
Getting Started with hapi.js
Credits
Foreword
About the Author
About the Reviewer
www.PacktPub.com
Preface
5
Securing Applications with Authentication and Authorization
Index

An introduction to validation


In pretty much any type of application, we are going to work with data, and of course, we need to ensure that this data is of a certain type or structure before we can act on it. This poses a number of problems. First, how do we easily define the way we want our data to be structured (often referred to as a schema), and second, how can we provide feedback in a consistent manner if the data provided isn't structured the way we want.

As with testing, if it's not easy to write or understand a schema, often, as developers, we won't do it, and instead, resort to very primitive attempts such as:

…
if (typeof username !== 'string') {
  // throw or return error
}
// perform action
…

First of all, please note that if you find yourself doing this, you're going to have huge problems as your application logic grows. You might have already seen examples of this—massive validation functions for performing actions with different combinations of properties.

This is hugely counterproductive...