Welcome again! If you reached this post from nowhere and don’t understand what all this is about, you can check out the previous posts:
- 1. Intro and Initial Setup
- 2. Setting up the Web Server
- 3. The Database: Setup
- 4. The Database: Connect and Config
- 5. The Endpoints
- 6. Security with JWT
You can find the code for this tutorial in GitHub.
If you followed the steps from the previous posts your project directory structure should look like this:
├── config │ ├── env │ │ ├── development.js │ │ └── index.js │ ├── express.js │ └── jwt.js ├── gulpfile.babel.js ├── index.js ├── package.json └── server ├── controllers │ ├── auth.js │ ├── tasks.js │ └── users.js ├── models │ ├── task.js │ └── user.js └── routes ├── auth.js ├── index.js ├── tasks.js └── users.js
If it doesn’t, please go back and check if you missed something from the previous posts.
Request Payload Validation
We have now a set of endpoints to manage users and tasks, and secured with JWT to avoid unknown clients to access our API. Now we’ll have a look at how can we add some validation to the request payload sent by clients. Since we want to keep our database consistent, it’s good to check what the user is sending us. You can do validations in different levels. In the top level, you can validate data types and format of parameters, and in the next level you can validate that a resource ID sent by the user exists in the database.
During this post we’ll focus on the first level, which is validating the data types and the format of the data sent by the user. The second level explained before can be easily done with a database query at the beginning of your endpoint controller.
We’ll be using a few handy modules for the validation purpose:
npm install --save express-validation@^0.4.5 joi@^7.2.3
- express-validation provides a middleware function that can validate the request payload data given a set of rules provided by us.
- joi it’s the module we’ll use to define those rules