Day 2- 4 of subscription App

Day 2- 4 of subscription App

In the last post, I created the project directory and had the server running.

In this post, I’ll be working on the auth (sign-up route).

The logic to implement in the sign-up route are:

validate email and password
check if email is not already used
hash the password..(not storing the password in plain text incase the DB gets breached)
save the user to the database
send back token

Make sure to:

install express validator lib package (an express middleware for validator)

“npm install –save express-validator”

Download and set up Postman (we’ll be using this to test the API). Check out this article to learn what postman is and how to set it up.

Creating the sign-up route

Create a routes folder inside of the src directory (this will house our routes)

What I did here:

create a auth.ts file ( this will house the auth route)
ln 1 : import express from express
ln 2: get body & validationResult from express-validator (we’ll be using these to validate user’s email and password in the post request)
ln 4 : get router from express and store in a variable
with this router variable we can create multiple routes for this file and export it

-ln 7 – 30: create a post request for signing up
Breakdown:

call the post method on the router, which takes in 2 arguments (path and request handler)
in-between the path and the handler, we add what we want to validate

1. Validate username, email and password

ln 13: catch the validation error with validationResult which returns an array of errors
ln 15: Check if the validation error(array) isn’t empty. If this is true, throw/send back some errors as responses in JSON format.

ln 26 : if there’s no error, send a response that the credentials are valid

Let’s check if this works…

Configure the authRoutes

in the root app (index.ts)
ln 2: import authRoutes from the auth file.
configure the authRoutes in the root application by utilizing app.use()
specify the root path and specify all of the routes
so, to get the signup route, all we need to do is to go to

“localhost:8080/auth/signup”

Testing the API with Postman


Correct credentials

Right here:

create a new collection
create a post request
input the url
http://localhost:8000/auth/sign-up
inside the body , check raw and set to JSON
then put in the username, email and password
click send

What if we put in an invalid email and password? We get this response.


Error response

In the next post, I’ll be checking if email is not already used (in this step, I’ll be creating the database and connecting it to the server).

Leave a Reply

Your email address will not be published. Required fields are marked *