Table of Contents for
Server Side development with Node.js and Koa.js Quick Start Guide

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Server Side development with Node.js and Koa.js Quick Start Guide by Olayinka Omole Published by Packt Publishing, 2018
  1. Server Side Development with Node.js and Koa.js Quick Start Guide
  2. Title Page
  3. Copyright and Credits
  4. Server Side Development with Node.js and Koa.js Quick Start Guide
  5. About Packt
  6. Why subscribe?
  7. Packt.com
  8. Contributors
  9. About the author
  10. About the reviewer
  11. Packt is searching for authors like you
  12. Table of Contents
  13. Preface
  14. Who this book is for
  15. What this book covers
  16. To get the most out of this book
  17. Download the example code files
  18. Download the color images
  19. Code in action
  20. Conventions used
  21. Get in touch
  22. Reviews
  23. Introducing Koa
  24. Technical requirements
  25. What is Koa?
  26. What can you do with Koa?
  27. Why choose Koa?
  28. When you should not use Koa
  29. Koa versus Express
  30. How can this book help you understand Koa better?
  31. Summary
  32. Getting Started with Koa
  33. Technical requirements
  34. Modern JavaScript
  35. A primer on Node
  36. What is async… await?
  37. The promise class
  38. Introducing async
  39. Introducing await
  40. Installing Koa
  41. Using Babel
  42. Starting a server in Koa
  43. Summary
  44. Koa Core Concepts
  45. Technical requirements
  46. The application object
  47. Useful application methods
  48. Settings
  49. The context object
  50. Context object API
  51. Aliases
  52. The request object
  53. Content negotiation
  54. The response object
  55. Middleware
  56. Cascading in Koa
  57. Defining middleware
  58. Registering middleware
  59. Common middleware
  60. Summary
  61. Handling Errors in Koa
  62. Technical requirements
  63. Catching errors in Koa
  64. Koa's default error handler
  65. Emitting errors
  66. Error event listener
  67. Throwing HTTP errors
  68. Writing error handlers
  69. Summary
  70. Building an API in Koa
  71. Technical requirements
  72. Project setup
  73. Initialization
  74. Installing dependencies
  75. Structure
  76. Building the application
  77. Starting the server
  78. Using Nodemon
  79. Connecting to a database
  80. Creating data models
  81. Setting up the router
  82. Setting up a logger
  83. Creating contact endpoints and controller actions
  84. Retrieving all contacts
  85. Storing new contacts
  86. Retrieving a single contact
  87. Updating a contact
  88. Deleting a contact
  89. Validating requests
  90. Useful notes
  91. Summary
  92. Building an Application in Koa
  93. Technical requirements
  94. About the application
  95. Setting up a project
  96. Installing dependencies
  97. Project structure
  98. Building the application
  99. Starting the server
  100. Connecting to the database
  101. Creating data models
  102. The user model
  103. The post model
  104. Setting up the router
  105. Setting up the views
  106. Using partials
  107. Setting up sessions
  108. Handling authentication
  109. User registration and login
  110. Authentication middleware
  111. Creating controller functions
  112. Summary
  113. Other Books You May Enjoy
  114. Leave a review - let other readers know what you think

Validating requests

A great way to ensure that we always get the data that we need is to validate requests before persisting them to the database. Mongoose already does schema validation, but we can also implement an extra layer of validation, to ensure that we are in full control of our data.

A popular JSON schema validation library that we can make use of in Node.js is Joi. Joi is an object schema validator, and it will work well for ensuring that we have the proper data coming through from our requests.

We will create a custom middleware for validating requests on selected routes, and register it in our app.

First, let's create the middleware function. Creating a validator.js file in the middleware folder can be done by using the following command:

touch middleware/validator.js

Now, we can insert the following content into the file:

// ./middleware/validator.js

const Joi = require('joi');

const schema = Joi.object({
name: Joi.string().required(),
address: Joi.string(),
company: Joi.string(),
position: Joi.string(),
phoneNumber: Joi.number().required()
});

const ALLOWED_METHODS = ['PUT', 'POST'];

module.exports = () => {
return async (ctx, next) => {
const { method } = ctx;
const { body } = ctx.request;

if (ALLOWED_METHODS.includes(method)) {
const { error } = Joi.validate(body, schema);
if (error) {
ctx.status = 422;
ctx.body = {
status: 'error',
message: 'validation error',
errors: error.details.map(e => e.message)
};
} else {
await next();
}
} else {
await next();
}
};
};

In the preceding code block, we specify the methods that we would like to validate against in the ALLOWED_METHODS variable. This ensures that we only validate against POST and PUT requests that contain request body data, and not GET requests, which do not. If a request matches any of these methods, we then validate the request body against a defined schema.

Joi possesses various methods for schema validation. Notably, we make use of the .required() method, to ensure that the name and phoneNumber properties are always present.

Note that we only specify one validation schema in our application, as we only have one data model. In more complex applications, which possess multiple data models, multiple schemas need to be implemented, where the correct schema to use for validation can be decided based on the route.

If an error occurs from Joi during validation, we set the response status code to 422 (Unprocessable Entity) and send back the error messages from Joi.

To register the middleware, let's update the index.js file, as follows:

// ./index.js
// ...

const validator = require('./middleware/validator');

app.use(validator());

// ...

At this point, the complete index.js file looks as follows:

const Koa = require('koa');
const logger = require('koa-logger');
const bodyParser = require('koa-body');
const router = require('./middleware/router');
const validator = require('./middleware/validator');
const app = new Koa();

const mongoose = require('mongoose');
mongoose.connect(
'mongodb://localhost:27017/koa-contact',
{ useNewUrlParser: true }
);

const db = mongoose.connection;
db.on('error', error => {
throw new Error(`error connecting to db: ${error}`);
});
db.once('open', () => console.log('database connected'));

app.use(logger());

app.use(bodyParser());

app.use(validator());

app.use(router.routes());
app.use(router.allowedMethods());

const port = process.env.PORT || 3000;
app.listen(port, () =>
console.log(`Server running on http://localhost:${port}`)
);

If we try to save a contact without specifying a name, the following is an example response that we might receive:

{
"status": "error",
"message": "validation error",
"errors": [
"\"name\" is required"
]
}