<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Okikiola Osunronbi on Medium]]></title>
        <description><![CDATA[Stories by Okikiola Osunronbi on Medium]]></description>
        <link>https://medium.com/@osunronbiolanlesi?source=rss-b7beb45df750------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EhfAtdid5ZyrK-rN7qscIA.jpeg</url>
            <title>Stories by Okikiola Osunronbi on Medium</title>
            <link>https://medium.com/@osunronbiolanlesi?source=rss-b7beb45df750------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:41:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osunronbiolanlesi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Create a Blog API Using Node, Express and Mongodb]]></title>
            <link>https://medium.com/@osunronbiolanlesi/how-to-create-a-blog-api-using-node-express-and-mongodb-4616609d0b64?source=rss-b7beb45df750------2</link>
            <guid isPermaLink="false">https://medium.com/p/4616609d0b64</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Okikiola Osunronbi]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 07:04:02 GMT</pubDate>
            <atom:updated>2023-01-07T07:07:30.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Express, Nodejs and MongoDB logo" src="https://cdn-images-1.medium.com/max/600/1*NFTgwZ_TUmceZnSHCundBw.jpeg" /></figure><p>In this blog post, we will be going over how to build a REST API for a blog which implements cool features like authentication, CRUD(Create, Read, Update, Delete), global error handling, integration tests etc</p><p>It’s helpful to have experience using <a href="https://nodejs.org/en/">node</a> and <a href="https://www.npmjs.com/package/express">express</a></p><p>Complete source code can be found on <a href="https://github.com/okikiolanlesi/altschool-exam-solution">Github</a></p><h4>Technologies used for this tutorial</h4><ul><li>Node</li><li>Express</li><li>Mongo DB</li><li>Mongoose</li><li>JWT (JSON Web Token)</li><li>Jest</li><li>Supertest</li><li>Github</li></ul><h3>Set Up</h3><p>You’ll need to have a few things ready to start developing this api.</p><p>Some of the requirements are listed below</p><ul><li>node must be installed on your computer</li><li>you need to have a mongo db atlas account or have mongodb set up locally</li><li>you need to have git set up on your system</li><li>you’ll also need to have a github account</li></ul><p>If you don’t know how to do the above, you can find resources for them below</p><ul><li><a href="https://radixweb.com/blog/installing-npm-and-nodejs-on-windows-and-mac">node installation</a></li><li><a href="https://www.mongodb.com/basics/mongodb-atlas-tutorial">mongodb atlas set up</a></li><li><a href="https://zellwk.com/blog/local-mongodb/">mongodb local set up</a></li><li><a href="https://product.hubspot.com/blog/git-and-github-tutorial-for-beginners">git and github setup</a></li></ul><p>After fulfilling the above requirements we can then move on to creating our project folder. Open up your command prompt and navigate to wherever you’ll like to save the folder</p><p>e.g</p><pre>cd desktop</pre><p>Next you need to make a new folder with the below command</p><pre>mkdir blog-api</pre><p>Note that ‘blog-api’ can be any name you deem fit</p><p>Now cd into your newly created directory and auto generate your package.json file using the below command</p><pre>cd blog-api<br>npm init -y</pre><p>the ‘ npm init -y’ command will generate a package.json file with default settings</p><p>Now we have to install some dependencies before we get started building our api. Input the below command into your terminal</p><pre>npm install express mongoose dotenv bcryptjs jsonwebtoken morgan validator jest supertest cors</pre><p>These dependencies will be useful later when we’re developing our app</p><p>Finally, we’re ready to start building the server. Open up your project folder in any IDE of your choice and lets get straight into it</p><h3>Building the API</h3><p>In the project folder create a ‘server.js’ file, you can do this either by using your code editor GUI or in the terminal with the below command</p><pre>touch server.js</pre><p>Next open your server.js file, write the below code and save</p><pre>//server.js<br>console.log(&#39;Hello There&#39;)</pre><p>Then make sure your terminal is still in your project folder before running the below command in your terminal</p><pre>node server</pre><p>You should see ‘Hello There’ printed to your terminal</p><p>Woohoo, were making progress.</p><p>Now before we continue, you should install nodemon as a dev dependency. You can do that with the below command</p><pre>npm install nodemon --save-dev</pre><p>You can also install nodemon globally by running the below command in your terminal</p><pre>npm install -g nodemon</pre><p>Nodemon will help us restart our app everytime changes are made and saved. The below command can be used instead of ‘node server’</p><pre>nodemon server</pre><p>A more convenient way of doing this is saving the command as a script in your package.json</p><p>Navigate to your package.json and add the below script there</p><pre>    &quot;start:dev&quot;: &quot;nodemon server.js&quot;</pre><p>The scripts section in you package.json file should look like this now</p><figure><img alt="scripts section in package.json file snapshot" src="https://cdn-images-1.medium.com/max/671/1*uSIdQBHrlTP70wprZJ-alA.png" /></figure><p>Now we can run ‘npm run start:dev’ in the terminal and it will automatically run the server.js file</p><pre>npm run start:dev</pre><p>This is more convenient and also useful incase other people want to test or contribute to your code, they can easily start up your app.</p><p>Now that we are done with that, we can start writing our application code in the server.js file but before we continue don’t forget to remove the console.log we previously put there.</p><p>Your server.js file should look like this.</p><figure><img alt="server.js file screenshot" src="https://cdn-images-1.medium.com/max/1024/1*aI0BFH-Vscgt3BdNjby3Tw.png" /></figure><h4>Requiring some modules</h4><p>We installed some dependencies during the setup phase and we will be needing some of them in the server.js file.</p><p>Write the below code to require the dependencies.</p><pre>//server.js<br>const mongoose = require(&quot;mongoose&quot;);<br>const dotenv = require(&quot;dotenv&quot;);</pre><ul><li>Mongoose is an object document mapper for mongo db, its useful for connecting to your database, creating models, executing queries etc.</li><li>dotenv is a library that allows us have access to our environment variables which are set in our ‘.env’ file.</li></ul><p>Speaking about environment variables we’ll need to create a .env file in our project folder.</p><pre>touch .env</pre><p>Open the .env file and paste the following inside.</p><pre>MONGO_URL=&lt;YOUR_MONGO_DATABASE_URI&gt;<br>PORT=8080 or what ever port you like<br>TEST_MONGO_URL=&lt;YOUR_MONGODB_TEST_DATABASE_URI&gt;<br>NODE_ENV=development<br>JWT_SECRET=&lt;A STRING THAT HAS AT LEAST 32 CHARACTERS&gt;<br>JWT_EXPIRES_IN=1d<br>JWT_COOKIE_EXPIRES_IN=1 </pre><p>Remember to replace each value with your preferred values.</p><p>You should also create a ‘.env.example’ file which has all the variables needed but with dummy data. The reason for this is to let developers who want to contribute to your codebase know the required variables for your app to work since we’re not going to upload our .env file to github.</p><p>Here’s an example of how your .env.example file should look like.</p><pre>MONGO_URL=xxxxxx<br>PORT=xxxxxx<br>TEST_MONGO_URL=xxxxxx<br>NODE_ENV=xxxxxx<br>JWT_SECRET=xxxxxx<br>JWT_EXPIRES_IN=xxxxxx<br>JWT_COOKIE_EXPIRES_IN=xxxxxx</pre><p>Good, now back to our server.js file.</p><p>Add the below code after your require statements.</p><pre>dotenv.config()<br>console.log(process.env.PORT)</pre><p>Save the file and nodemon should automatically rerun the application.</p><p>Printed to the console should be the port assigned in your .env file</p><p>Dotenv makes all environment variables available on the process.env object.</p><p>You can now remove the console.log from your server.js file</p><p>Your server.js file should look like this now</p><pre>//server.js<br>const mongoose = require(&#39;mongoose&#39;)<br>const dotenv = require(&#39;dotenv&#39;)<br><br>dotenv.config()</pre><p>Next we should import our express app into the server.js file.</p><p>Our express server is going to be created in a seperate file called app.js, so let’s create that first.</p><pre>touch app.js</pre><p>In our app.js file we will also need some dependencies so let’s require them first.</p><pre>const express = require(&quot;express&quot;);<br>const cookieParser = require(&quot;cookie-parser&quot;); // Used to parse cookies<br>const morgan = require(&quot;morgan&quot;); // useful for logging server request during development</pre><p>Then we need to call the express function and save it in a variable.</p><pre>const app = express()</pre><p>Next we need to set up some middlewares using the app variable.</p><pre><br>if (process.env.NODE_ENV === &quot;development&quot;) {<br>  // only logs request in development<br>  app.use(morgan(&quot;dev&quot;));<br>}<br>app.use(cors({origin: &#39;*&#39;, credentialse: true})) //Sets the cross origin resource sharing headers<br>app.use(cookieParser()); // parses cookies from our requests<br>app.use(express.json({ limit: &quot;10kb&quot; })); // parses json data from our requests</pre><p>Next we will set up our routes.</p><pre>// User routes<br>app.use(&quot;/api/v1/users&quot;, (req, res, next)=&gt;{<br>  res.status(200).json({<br>      status: &quot;success&quot;<br>      message:&quot;User route is working&quot;<br>  })<br>});<br><br>// Blog routes<br>app.use(&quot;/api/v1/blogs&quot;, (req, res, next)=&gt;{<br>  res.status(200).json({<br>      status: &quot;success&quot;<br>      message:&quot;Blog route is working&quot;<br>  })<br>});<br><br>// A 404 route for undeclared routes<br>app.all(&#39;*&#39;, (req, res, next)=&gt;{<br>  res.status(404).json({<br>      status: &quot;error&quot;<br>      message:&quot;Route not found&quot;<br>  })<br>} )</pre><p>The above routes are still going to be modified since we are going to have seperate files that handle the routing logic and corresponding controllers. But for now lets work with the above snippet.</p><p>Next we have to export the app.</p><p>Add the below code to your app.js file.</p><pre>module.exports = app</pre><p>Your app.js file should look like this.</p><pre>// app.js<br>const express = require(&quot;express&quot;);<br>const cookieParser = require(&quot;cookie-parser&quot;); // Used to parse cookies<br>const morgan = require(&quot;morgan&quot;); // useful for logging server request during development<br><br>if (process.env.NODE_ENV === &quot;development&quot;) {<br>  // only logs requests in development<br>  app.use(morgan(&quot;dev&quot;));<br>}<br>app.use(cors({origin: &#39;*&#39;, credentialse: true})) //Sets the cross origin resource sharing headers<br>app.use(cookieParser()); // parses cookies from our requests<br>app.use(express.json({ limit: &quot;10kb&quot; })); // parses json data from our requests<br><br>// User routes<br>app.use(&quot;/api/v1/users&quot;, (req, res, next)=&gt;{<br>  res.status(200).json({<br>      status: &quot;success&quot;<br>      message:&quot;User route is working&quot;<br>  })<br>});<br><br>// Blog routes<br>app.use(&quot;/api/v1/blogs&quot;, (req, res, next)=&gt;{<br>  res.status(200).json({<br>      status: &quot;success&quot;<br>      message:&quot;Blog route is working&quot;<br>  })<br>});<br><br>// A 404 route for undeclared routes<br>app.all(&#39;*&#39;, (req, res, next)=&gt;{<br>  res.status(404).json({<br>      status: &quot;error&quot;<br>      message:&quot;Route not found&quot;<br>  })<br>} )<br><br>module.exports = app</pre><p>Now that we have created and exported our express server in our app.js file we can then import/require it in our server.js file.</p><p>So back in our server.js file, add the following code.</p><pre>const app = require(&#39;./app&#39;)</pre><p>After adding the above snippet, we will then connect to our database using mongoose.</p><p>Add the following to the server.js file.</p><pre>mongoose.connect(process.env.MONGO_URL)<br>.then(() =&gt; {<br>    console.log(&quot;DB connection successful!&quot;);<br>})<br>.catch((err)=&gt; {<br>    console.log(&#39;Could not connect to mongodb&#39;)<br>    console.log(err)    <br>})</pre><p>Then finally we can listen for requests using the below code snippet.</p><pre>app.listen(process.env.PORT, (err) =&gt; {<br>    if(err){<br>      console.log(&#39;An error occured while trying to start server&#39;)<br>      console.log(err)<br>    }<br>    console.log(`Server listening on port ${process.env.PORT}`)<br>}</pre><p>Your server.js file should look like this now.</p><pre>const mongoose = require(&quot;mongoose&quot;);<br>const dotenv = require(&quot;dotenv&quot;);<br><br>dotenv.config();<br><br>const app = require(&quot;./app&quot;);<br><br>const mongoUrl = process.env.MONGO_URL;<br><br>mongoose<br>  .connect(mongoUrl)<br>  .then(() =&gt; {<br>    console.log(&quot;DB connection successful!&quot;);<br>  })<br>  .catch((err) =&gt; {<br>    console.log(&quot;could not connect to MongoDB&quot;);<br>    console.log(err);<br>  });<br><br>app.listen(process.env.PORT, (err) =&gt; {<br>  if (err) {<br>    console.log(err);<br>  }<br>  console.log(`App running on port ${process.env.PORT}`);<br>});</pre><p>That should be all for our server.js file</p><p>To test if everything works, send a request to</p><p>‘http://localhost:&lt;YOUR PORT NUMBER&gt;/api/v1/users’</p><p>You should get a response that looks like this.</p><pre>{<br>  &quot;status&quot;: &quot;success&quot;,<br>  &quot;message&quot;: &quot;User route is working&quot;<br>}</pre><p>If you get the above response, then you’re good to go and we can move on to other parts of our application</p><h4>Helper Modules</h4><p>Before we start working on the core logic of our application, we will create some utitlity modules that will ease our development process.</p><p>In your project folder create a new folder named ‘utils’.</p><pre>mkdir utils</pre><p>We will create three files in this folder</p><ul><li>AppError.js</li><li>ApiFeatures.js</li><li>CatchAsync.js</li></ul><p>In the AppError.js file, paste the following.</p><pre>class AppError extends Error {<br>  constructor(message, statusCode){<br>      super(message);<br>      this.statusCode= statusCode;<br>      this.status = `${statusCode}`.startsWith(4) ? &#39;fail&#39; : &#39;error&#39;;<br>      isOperational=true;<br>      Error.captureStackTrace(this, this.constructor);<br>  }<br>}<br>module.exports = AppError</pre><p>The AppError.js file is useful for creating customized error objects which will be used for proper error handling.</p><p>In the ApiFeatures.js file paste the following.</p><pre>class APIFeatures {<br>  constructor(query, queryString) {<br>    this.query = query;<br>    this.queryString = queryString;<br>  }<br><br>  filter() {<br>    const queryObj = { ...this.queryString };<br>    const excludedFields = [&quot;page&quot;, &quot;sort&quot;, &quot;limit&quot;, &quot;fields&quot;];<br>    excludedFields.forEach((el) =&gt; delete queryObj[el]);<br><br>    // 1B) Advanced filtering<br>    let queryStr = JSON.stringify(queryObj);<br>    queryStr = queryStr.replace(<br>      /\b(gte|gt|lte|lt|in)\b/g,<br>      (match) =&gt; `$${match}`<br>    );<br><br>    let parsedQuery = JSON.parse(queryStr);<br><br>    if (parsedQuery.tags) {<br>      let arrayOfTags = parsedQuery.tags.split(&quot;,&quot;);<br>      parsedQuery.tags = { $in: arrayOfTags };<br>      console.log(parsedQuery);<br>    }<br>    // Modified query so that it can use $text operator<br>    if (parsedQuery.title) {<br>      let formerTitle = parsedQuery.title;<br><br>      parsedQuery.$text = {<br>        $search: formerTitle,<br>        $caseSensitive: false,<br>      };<br><br>      delete parsedQuery.title;<br>    }<br><br>    this.query = this.query.find(parsedQuery);<br><br>    return this;<br>  }<br><br>  sort() {<br>    if (this.queryString.sort) {<br>      const sortBy = this.queryString.sort.split(&quot;,&quot;).join(&quot; &quot;);<br>      this.query = this.query.sort(sortBy);<br>    } else {<br>      this.query = this.query.sort(&quot;-createdAt&quot;);<br>    }<br><br>    return this;<br>  }<br><br>  limitFields() {<br>    if (this.queryString.fields) {<br>      const fields = this.queryString.fields.split(&quot;,&quot;).join(&quot; &quot;);<br>      this.query = this.query.select(fields);<br>    } else {<br>      this.query = this.query.select(&quot;-__v&quot;);<br>    }<br><br>    return this;<br>  }<br><br>  paginate() {<br>    const page = this.queryString.page * 1 || 1;<br>    const limit = this.queryString.limit * 1 || 20;<br>    const skip = (page - 1) * limit;<br><br>    this.query = this.query.skip(skip).limit(limit);<br><br>    return this;<br>  }<br>}<br>module.exports = APIFeatures;</pre><p>The ApiFeatures Class will be used when writing our controllers.</p><p>In the CatchAsync file, paste the following.</p><pre>module.exports = (fn) =&gt; (req, res, next) =&gt; {<br>  fn(req, res, next).catch(next);<br>};</pre><p>This function returns the function argument with the catch block already attached. This will help us write DRY(don’t repeat yourself) code in our controllers.</p><p>And that’s it for our utils folder, now lets work on global error handling.</p><h4>Error handling</h4><p>In your project folder, create a new directory named ‘controllers’.</p><pre>mkdir controllers</pre><p>Then cd into the controllers folder and create an errorController.js file.</p><pre>cd controllers<br>touch errorController.js</pre><p>In your errorController.js file add the following code.</p><pre>const AppError = require(&quot;../utils/AppError&quot;);<br><br>const handleCastErrorDB = (err, res) =&gt; {<br>  const message = `Invalid ${err.path}: ${err.value}`;<br>  return new AppError(message, 404);<br>};<br>const handleDuplicateFieldsError = (err) =&gt; {<br>  const message = `${err.keyValue.name} already exists in database, please use another value`;<br>  return new AppError(message, 400);<br>};<br>const handleValidationError = (err) =&gt; {<br>  const errors = Object.values(err.errors).map((val) =&gt; val.message);<br>  const message = `Invalid input data: ${errors.join(&quot;; &quot;)}`;<br>  return new AppError(message, 401);<br>};<br>const handleJsonWebTokenError = (err) =&gt; {<br>  const message = `${err.name}; ${err.message}`;<br>  return new AppError(message, 401);<br>};<br>const handleExpiredJWTError = (err) =&gt; {<br>  const message = `${err.message}! Please login again`;<br>  return new AppError(message, 401);<br>};<br><br>const sendErrorDev = (err, res) =&gt; {<br>  res.status(err.statusCode).json({<br>    status: err.status,<br>    error: err,<br>    message: err.message,<br>    stack: err.stack,<br>  });<br>};<br><br>const sendErrorProd = (err, res) =&gt; {<br>  // OPERATIONAL ERROR, trusted so send appropriate message to the client<br>  if (err.isOperational) {<br>    res.status(err.statusCode).json({<br>      status: err.status,<br>      message: err.message,<br>    });<br>    // PROGRAMMING OR UNKNOWN ERROR, so don&#39;t leak error details to the client<br>  } else {<br>    //   1) log error to the console<br>    console.error(&quot;ERROR&quot;, err);<br><br>    //   2) send a generic message<br>    res.status(500).json({<br>      status: &quot;error&quot;,<br>      message: &quot;Something went very wrong&quot;,<br>    });<br>  }<br>};<br>module.exports = (err, req, res, next) =&gt; {<br>  err.statusCode = err.statusCode || 500;<br>  err.status = err.status || &quot;error&quot;;<br>  if (process.env.NODE_ENV === &quot;development&quot;) {<br>    sendErrorDev(err, res);<br>  } else if (process.env.NODE_ENV === &quot;production&quot;) {<br>    let error = { ...err };<br>    error.message = err.message;<br>    if (err.name === &quot;CastError&quot;) error = handleCastErrorDB(err);<br>    if (err.code === 11000) error = handleDuplicateFieldsError(err);<br>    if (err.name === &quot;ValidationError&quot;) {<br>      error = handleValidationError(err);<br>    }<br>    if (err.name === &quot;JsonWebTokenError&quot;) {<br>      error = handleJsonWebTokenError(err);<br>    }<br>    if (err.name === &quot;TokenExpiredError&quot;) {<br>      error = handleExpiredJWTError(err);<br>    }<br>    sendErrorProd(error, res);<br>  }<br>};</pre><p>Then we can import this file in our app.js file and use it as our global error handler.</p><p>Open the app.js file and require the errorController module at the top.</p><pre>// app.js<br>const globalErrorHandler = require(&#39;./contollers/errorController&#39;)</pre><p>After importig the module then paste this code immediately above the module.exports line.</p><pre>app.use(globalErrorHandler); // Error handling middleware;</pre><p>Also replace the 404 route with the below snippet since our error handler is working now.</p><pre>app.all(&quot;*&quot;, (req, res, next) =&gt; {<br>  next(new AppError(`Can&#39;t find ${req.originalUrl} on this server!`, 404));<br>});</pre><p>Your app.js file should look like this now.</p><pre>// app.js<br>const express = require(&quot;express&quot;);<br>const cookieParser = require(&quot;cookie-parser&quot;); // Used to parse cookies<br>const morgan = require(&quot;morgan&quot;); // useful for logging server request during development<br>const globalErrorHandler = require(&#39;./controllers/errorController&#39;)<br><br><br>if (process.env.NODE_ENV === &quot;development&quot;) {<br>  // only logs requests in development<br>  app.use(morgan(&quot;dev&quot;));<br>}<br>app.use(cors({origin: &#39;*&#39;, credentialse: true})) //Sets the cross origin resource sharing headers<br>app.use(cookieParser()); // parses cookies from our requests<br>app.use(express.json({ limit: &quot;10kb&quot; })); // parses json data from our requests<br><br>// User routes<br>app.use(&quot;/api/v1/users&quot;, (req, res, next)=&gt;{<br>  res.status(200).json({<br>      status: &quot;success&quot;<br>      message:&quot;User route is working&quot;<br>  })<br>});<br><br>// Blog routes<br>app.use(&quot;/api/v1/blogs&quot;, (req, res, next)=&gt;{<br>  res.status(200).json({<br>      status: &quot;success&quot;<br>      message:&quot;Blog route is working&quot;<br>  })<br>});<br><br>// A 404 route for undeclared routes<br>app.all(&quot;*&quot;, (req, res, next) =&gt; {<br>  next(new AppError(`Can&#39;t find ${req.originalUrl} on this server!`, 404));<br>});<br><br>app.use(globalErrorHandler) // Error handling middleware<br><br>module.exports = app</pre><p>Express automatically looks for a middleware that has four paramaters as arguments(commonly named err, req, res, next) and routes all errors to that middleware. In our case that middleware was created in our errorController.js file and exported to be used in our app.js file.</p><p>The global error handler then recieves the error and sends a response back to the client with an appropriate message and other helpful info such as status code, stack trace e.t.c.</p><p>Now that we are done with our global error handler we are going to start working on our models.</p><h4>Models</h4><p>Inside the project folder, create a new folder named ‘models’.</p><pre>mkdir models</pre><p>Inside the models folder we’re going to create two files.</p><ul><li>userModel.js</li><li>blogModel.js</li></ul><p>In the userModel.js file, type the following.</p><pre>const mongoose = require(&quot;mongoose&quot;);<br>const validator = require(&quot;validator&quot;);<br>const bcrypt = require(&quot;bcryptjs&quot;);<br>const userSchema = new mongoose.Schema(<br>  {<br>    first_name: {<br>      type: String,<br>      required: [true, &quot;User must have a first name&quot;],<br>      maxlength: [20, &quot;A user name must have less or equal to 20 characters&quot;],<br>    },<br>    last_name: {<br>      type: String,<br>      required: [true, &quot;User must have a last name&quot;],<br>      maxlength: [20, &quot;A user name must have less or equal to 20 characters&quot;],<br>    },<br>    email: {<br>      type: String,<br>      required: [true, &quot;User must have an email&quot;],<br>      unique: true,<br>      lowercase: true,<br>      validate: [validator.isEmail, &quot;Please provide a valid email&quot;],<br>    },<br>    password: {<br>      type: String,<br>      required: [true, &quot;User must have a password&quot;],<br>      minlength: [<br>        8,<br>        &quot;A user password must have more or equal then 8 characters&quot;,<br>      ],<br>      select: false,<br>    },<br>    passwordConfirm: {<br>      type: String,<br>      required: [true, &quot;User must have a passwordConfirm&quot;],<br>      validate: {<br>        validator: function (el) {<br>          return el === this.password;<br>        },<br>        message: &quot;Passwords are not the same!&quot;,<br>      },<br>    },<br>  },<br>  {<br>    toJSON: { virtuals: true },<br>    toObject: { virtuals: true },<br>  }<br>);<br>userSchema.virtual(&quot;blogs&quot;, {<br>  ref: &quot;Blog&quot;,<br>  foreignField: &quot;author&quot;,<br>  localField: &quot;_id&quot;,<br>});<br>userSchema.pre(&quot;save&quot;, async function (next) {<br>  if (!this.isModified(&quot;password&quot;)) return next();<br>  this.password = await bcrypt.hash(this.password, 12);<br>  this.passwordConfirm = undefined;<br>  next();<br>});<br>userSchema.methods.correctPassword = async function (<br>  candidatePassword,<br>  userPassword<br>) {<br>  return await bcrypt.compare(candidatePassword, userPassword);<br>};<br>const User = mongoose.model(&quot;User&quot;, userSchema);<br><br>module.exports = User;</pre><p>In the blogModel.js file, paste the following.</p><pre>const mongoose = require(&quot;mongoose&quot;);<br>const { Schema } = mongoose;<br>const blogSchema = new mongoose.Schema(<br>  {<br>    title: {<br>      type: String,<br>      required: [true, &quot;Blog must have a title&quot;],<br>      unique: true,<br>    },<br>    description: {<br>      type: String,<br>      required: [true, &quot;Blog must have a description&quot;],<br>      maxlength: [<br>        100,<br>        &quot;A blog description must have less or equal to 100 characters&quot;,<br>      ],<br>    },<br>    author: {<br>      type: Schema.Types.ObjectId,<br>      ref: &quot;User&quot;,<br>      required: [true, &quot;Blog must have an author&quot;],<br>    },<br>    state: {<br>      type: String,<br>      enum: [&quot;draft&quot;, &quot;published&quot;],<br>      default: &quot;draft&quot;,<br>    },<br>    read_count: {<br>      type: Number,<br>      default: 0,<br>    },<br>    reading_time: {<br>      type: Number,<br>      default: 0,<br>    },<br>    tags: {<br>      type: [String],<br>      default: [],<br>    },<br>    body: {<br>      type: String,<br>      required: [true, &quot;Blog must have a body&quot;],<br>    },<br>  },<br>  {<br>    timestamps: true,<br>    toJSON: { virtuals: true },<br>    toObject: { virtuals: true },<br>  }<br>);<br><br>blogSchema.index({ title: &quot;text&quot; });<br><br>blogSchema.pre(/^find/, function (next) {<br>  this.populate({<br>    path: &quot;author&quot;,<br>    select: &quot;first_name last_name email&quot;,<br>  });<br>  next();<br>});<br>blogSchema.pre(&quot;save&quot;, function (next) {<br>  this.reading_time = Math.ceil(this.body.split(&quot; &quot;).length / 200);<br>  next();<br>});<br>const Blog = mongoose.model(&quot;Blog&quot;, blogSchema);<br>module.exports = Blog;</pre><p>Now that we have our models set up, lets create our controllers.</p><h4>Controllers</h4><p>We’re going to create three new files in the controllers folder</p><ul><li>blogController.js (All blog related logic will be stored here)</li><li>userController.js (All user related logic will be stored here)</li><li>authController.js (All authentication/authorization related logic will be stored here)</li></ul><p>In the blogController.js file, type the following.</p><pre>const AppError = require(&quot;../utils/AppError&quot;);<br>const catchAsync = require(&quot;../utils/catchAsync&quot;);<br>const Blog = require(&quot;../models/blogModel&quot;);<br>const APIFeatures = require(&quot;../utils/APIFeatures&quot;);<br><br>exports.getAllBlogs = catchAsync(async (req, res, next) =&gt; {<br>  const features = new APIFeatures(Blog.find({ state: &quot;published&quot; }), req.query)<br>    .filter()<br>    .sort()<br>    .limitFields()<br>    .paginate();<br>  const blogs = await features.query;<br>  res.status(200).json({<br>    status: &quot;success&quot;,<br>    results: blogs.length,<br>    data: {<br>      blogs,<br>    },<br>  });<br>});<br><br>exports.setAuthorId = catchAsync(async (req, res, next) =&gt; {<br>  req.body.author = req.user.id;<br>  next();<br>});<br><br>exports.createBlog = catchAsync(async (req, res, next) =&gt; {<br>  const newBlogToCreate = {<br>    title: req.body.title,<br>    description: req.body.description,<br>    author: req.body.author,<br>    state: req.body.state,<br>    tags: req.body.tags,<br>    body: req.body.body,<br>  };<br>  const newBlog = await Blog.create(newBlogToCreate);<br>  if (!newBlog) {<br>    return next(new AppError(&quot;Blog could not be created&quot;, 400));<br>  }<br>  res.status(201).json({<br>    status: &quot;success&quot;,<br>    data: {<br>      blog: newBlog,<br>    },<br>  });<br>});<br><br>exports.getBlog = catchAsync(async (req, res, next) =&gt; {<br>  const blog = await Blog.findOneAndUpdate(<br>    { $and: [{ _id: req.params.id }, { state: &quot;published&quot; }] },<br>    { $inc: { read_count: +1 } },<br>    {<br>      runValidators: true,<br>      new: true,<br>    }<br>  );<br><br>  if (!blog) return next(new AppError(&quot;Blog not found&quot;, 404));<br><br>  res.status(200).json({<br>    status: &quot;success&quot;,<br>    data: {<br>      blog,<br>    },<br>  });<br>});<br><br>exports.updateBlog = catchAsync(async (req, res, next) =&gt; {<br>  let blog = await Blog.findOne({ _id: req.params.id });<br><br>  if (!blog) return next(new AppError(&quot;Blog not found&quot;, 404));<br><br>  if (req.user.id !== blog.author.id) {<br>    return next(<br>      new AppError(&quot;You are not authorized to update this blog&quot;, 401)<br>    );<br>  }<br><br>  if (req.body.title) {<br>    blog.title = req.body.title;<br>  }<br>  if (req.body.description) {<br>    blog.description = req.body.description;<br>  }<br>  if (req.body.state) {<br>    blog.state = req.body.state;<br>  }<br>  if (req.body.tags) {<br>    blog.tags = req.body.tags;<br>  }<br>  if (req.body.body) {<br>    blog.body = req.body.body;<br>  }<br><br>  const updatedBlog = await blog.save();<br><br>  if (!updatedBlog) return next(new AppError(&quot;Blog not updated&quot;, 401));<br>  res.status(200).json({<br>    status: &quot;success&quot;,<br>    data: {<br>      updatedBlog,<br>    },<br>  });<br>});<br><br>exports.deleteBlog = catchAsync(async (req, res, next) =&gt; {<br>  const blog = await Blog.findById(req.params.id);<br>  if (!blog) return next(new AppError(&quot;Blog not found&quot;, 404));<br>  if (req.user.id !== blog.author.id)<br>    return next(<br>      new AppError(&quot;You are not authorized to delete this blog&quot;, 401)<br>    );<br>  const deletedBlog = await Blog.findByIdAndDelete(req.params.id);<br>  if (!deletedBlog) return next(new AppError(&quot;Blog not found&quot;, 400));<br>  res.status(204).json({<br>    status: &quot;success&quot;,<br>    data: null,<br>  });<br>});<br><br>exports.getMyBlogs = catchAsync(async (req, res, next) =&gt; {<br>  const features = new APIFeatures(<br>    Blog.find({ author: req.user._id }).select(&quot;-__v -author&quot;),<br>    req.query<br>  )<br>    .filter()<br>    .limitFields()<br>    .sort()<br>    .paginate();<br><br>  const blogs = await features.query;<br>  if (!blogs) return next(new AppError(&quot;No blogs found&quot;, 404));<br>  res.status(200).json({<br>    status: &quot;success&quot;,<br>    results: blogs.length,<br>    data: {<br>      blogs,<br>    },<br>  });<br>});</pre><p>In the userController.js file, type the following.</p><pre>const AppError = require(&quot;../utils/AppError&quot;);<br>const catchAsync = require(&quot;../utils/catchAsync&quot;);<br>const User = require(&quot;../models/userModel&quot;);<br>const APIFeatures = require(&quot;../utils/APIFeatures&quot;);<br><br>exports.getAllUsers = catchAsync(async (req, res, next) =&gt; {<br>  const features = new APIFeatures(User.find(), req.query)<br>    .filter()<br>    .sort()<br>    .limitFields()<br>    .paginate();<br>  const users = await features.query;<br>  res.status(200).json({<br>    status: &quot;success&quot;,<br>    results: users.length,<br>    data: {<br>      users,<br>    },<br>  });<br>});<br><br>exports.getUser = catchAsync(async (req, res, next) =&gt; {<br>  const user = await User.findById(req.params.id).populate(&quot;blogs&quot;);<br>  if (!user) return next(new AppError(&quot;User not found&quot;, 404));<br>  res.status(200).json({<br>    status: &quot;success&quot;,<br>    data: {<br>      user,<br>    },<br>  });<br>});</pre><p>In the authController.js file, type the following.</p><pre>const AppError = require(&quot;../utils/AppError&quot;);<br>const catchAsync = require(&quot;../utils/catchAsync&quot;);<br>const User = require(&quot;../models/userModel&quot;);<br>const JWT = require(&quot;jsonwebtoken&quot;);<br>const { promisify } = require(&quot;util&quot;);<br><br>const signToken = (id) =&gt; {<br>  return JWT.sign({ id }, process.env.JWT_SECRET, {<br>    expiresIn: process.env.JWT_EXPIRES_IN,<br>  });<br>};<br>const createSendToken = (user, statusCode, res) =&gt; {<br>  const token = signToken(user._id);<br>  const cookieOptions = {<br>    expires: new Date(<br>      Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 60 * 60 * 1000<br>    ),<br>    httpOnly: true,<br>    sameSite: &quot;none&quot;,<br>    secure: true,<br>  };<br>  res.cookie(&quot;jwt&quot;, token, cookieOptions);<br>  user.password = undefined;<br>  res.status(statusCode).json({<br>    status: &quot;success&quot;,<br>    token,<br>    data: {<br>      user,<br>    },<br>  });<br>};<br><br>exports.signup = catchAsync(async (req, res, next) =&gt; {<br>  const newUser = await User.create(req.body);<br>  if (!newUser) return next(new AppError(&quot;User not created&quot;, 401));<br>  createSendToken(newUser, 201, res);<br>});<br><br>exports.login = catchAsync(async (req, res, next) =&gt; {<br>  const { email, password } = req.body;<br>  if (!email || !password) {<br>    return next(new AppError(&quot;Please provide email and password&quot;, 400));<br>  }<br>  const user = await User.findOne({ email }).select(&quot;+password&quot;);<br>  if (!user || !(await user.correctPassword(password, user.password))) {<br>    return next(new AppError(&quot;Incorrect email or password&quot;, 401));<br>  }<br>  createSendToken(user, 200, res);<br>});<br><br>exports.protect = catchAsync(async (req, res, next) =&gt; {<br>  // Get token and check if its there<br>  let token;<br>  if (<br>    req.headers.authorization &amp;&amp;<br>    req.headers.authorization.startsWith(&quot;Bearer&quot;)<br>  ) {<br>    token = req.headers.authorization.split(&quot; &quot;)[1];<br>  } else if (req.cookies.jwt) {<br>    token = req.cookies.jwt;<br>  }<br><br>  if (!token) {<br>    return next(<br>      new AppError(&quot;You are not logged in! Please log in to get access&quot;, 401)<br>    );<br>  }<br>  const decoded = await promisify(JWT.verify)(token, process.env.JWT_SECRET);<br>  if (!decoded) return next(new AppError(&quot;Token is invalid&quot;, 401));<br>  const user = await User.findById(decoded.id);<br>  if (!user) {<br>    return next(new AppError(&quot;user does not exist&quot;, 401));<br>  }<br>  req.user = user;<br>  next();<br>});<br>// ignore</pre><p>Now that both our models and controllers are ready, we can finally start working on our routes.</p><h4>Routes</h4><p>In our project folder, create a new folder named ‘routes’.</p><pre>mkdir routes</pre><p>Then we will create two files</p><ul><li>userRoutes.js (handles all the routes for users)</li><li>blogRoutes.js (handles all the routes for blogs)</li></ul><p>In the userRoutes.js file, write the following.</p><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const authController = require(&quot;../controllers/authController&quot;);<br>const userController = require(&quot;../controllers/userController&quot;);<br><br>router.route(&quot;/signup&quot;).post(authController.signup);<br>router.route(&quot;/login&quot;).post(authController.login);<br><br>router.route(&quot;/&quot;).get(userController.getAllUsers);<br>router.route(&quot;/:id&quot;).get(userController.getUser);<br>module.exports = router;</pre><p>In the blogRoutes.js file, write the following.</p><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const blogController = require(&quot;../controllers/blogController&quot;);<br>const authController = require(&quot;../controllers/authController&quot;);<br>router<br>  .route(&quot;/&quot;)<br>  .get(blogController.getAllBlogs)<br>  .post(<br>    authController.protect,<br>    blogController.setAuthorId,<br>    blogController.createBlog<br>  );<br>router<br>  .route(&quot;/getMyBlogs&quot;)<br>  .get(authController.protect, blogController.getMyBlogs);<br>router<br>  .route(&quot;/:id&quot;)<br>  .get(blogController.getBlog)<br>  .patch(authController.protect, blogController.updateBlog)<br>  .delete(authController.protect, blogController.deleteBlog);<br><br>module.exports = router;</pre><p>Now that we’ve created the routes we can replace the faux controller we put in the app.js file .</p><p>First import the routers in your app.js file.</p><pre>const userRouter = require(&quot;./routes/userRoutes&quot;);<br>const blogRouter = require(&quot;./routes/blogRoutes&quot;);</pre><p>Then replace the faux controllers with appropriate routers.</p><pre>app.use(&quot;/api/v1/users&quot;, userRouter);<br>app.use(&quot;/api/v1/blogs&quot;, blogRouter);</pre><p>The app.js file should look like this now.</p><pre>// app.js<br>const express = require(&quot;express&quot;);<br>const cookieParser = require(&quot;cookie-parser&quot;); // Used to parse cookies<br>const morgan = require(&quot;morgan&quot;); // useful for logging server request during development<br>const globalErrorHandler = require(&#39;./controllers/errorController&#39;)<br>const userRouter = require(&quot;./routes/userRoutes&quot;);<br>const blogRouter = require(&quot;./routes/blogRoutes&quot;);<br><br>if (process.env.NODE_ENV === &quot;development&quot;) {<br>  // only logs requests in development<br>  app.use(morgan(&quot;dev&quot;));<br>}<br>app.use(cors({origin: &#39;*&#39;, credentialse: true})) //Sets the cross origin resource sharing headers<br>app.use(cookieParser()); // parses cookies from our requests<br>app.use(express.json({ limit: &quot;10kb&quot; })); // parses json data from our requests<br><br>// User routes<br>app.use(&quot;/api/v1/users&quot;, userRouter);<br><br>// Blog routes<br>app.use(&quot;/api/v1/blogs&quot;, blogRouter);<br><br>// A 404 route for undeclared routes<br>app.all(&quot;*&quot;, (req, res, next) =&gt; {<br>  next(new AppError(`Can&#39;t find ${req.originalUrl} on this server!`, 404));<br>});<br><br>app.use(globalErrorHandler) // Error handling middleware<br><br>module.exports = app</pre><p>Excellent, now your app should be fully functional.</p><p>To test all our routes we will write tests for each resource.</p><h4>Tests</h4><p>We will use jest and supertest to run our test.</p><p>In our project folder, create a new folder named ‘tests’.</p><p>we will create three files</p><ul><li>auth.test.js</li><li>blog.test.js</li><li>user.test.js</li></ul><p>In the auth.test.js file, add the following.</p><pre>const User = require(&quot;../models/userModel&quot;);<br>const supertest = require(&quot;supertest&quot;);<br>const app = require(&quot;../app&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>const { JsonWebTokenError } = require(&quot;jsonwebtoken&quot;);<br><br>require(&quot;dotenv&quot;).config({ path: &quot;./config.env&quot; });<br>jest.setTimeout(20000);<br>describe(&quot;Auth routes&quot;, () =&gt; {<br>  beforeAll(async () =&gt; {<br>    mongoose<br>      .connect(process.env.TEST_MONGO_URL, {<br>        useUnifiedTopology: true,<br>        useNewUrlParser: true,<br>      })<br>      .then(() =&gt; {<br>        console.log(&quot;DB connection successful!&quot;);<br>      })<br>      .catch((err) =&gt; {<br>        console.log(&quot;could not connect to MongoDB&quot;);<br>        console.log(err);<br>      });<br>  });<br>  beforeEach(async () =&gt; {<br>    await User.create({<br>      first_name: &quot;test&quot;,<br>      last_name: &quot;test&quot;,<br>      email: &quot;test4@gmail.com&quot;,<br>      password: &quot;testtesttest&quot;,<br>      passwordConfirm: &quot;testtesttest&quot;,<br>    });<br>  });<br>  afterEach(async () =&gt; {<br>    await User.deleteMany();<br>  });<br>  afterAll(async () =&gt; {<br>    await User.deleteMany();<br>    await mongoose.connection.close();<br>  });<br>  it(&quot;should signup a new user&quot;, async () =&gt; {<br>    const response = await supertest(app)<br>      .post(&quot;/api/v1/users/signup&quot;)<br>      .set(&quot;Content-type&quot;, &quot;application/json&quot;)<br>      .send({<br>        first_name: &quot;test&quot;,<br>        last_name: &quot;test&quot;,<br>        email: &quot;test5@gmail.com&quot;,<br>        password: &quot;testtesttest&quot;,<br>        passwordConfirm: &quot;testtesttest&quot;,<br>      });<br>    expect(response.statusCode).toBe(201);<br>    expect(response.body).toHaveProperty(&quot;status&quot;, &quot;success&quot;);<br>    expect(response.body).toHaveProperty(&quot;data&quot;);<br>    expect(response.body.data).toHaveProperty(&quot;user&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;first_name&quot;, &quot;test&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;last_name&quot;, &quot;test&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;email&quot;, &quot;test5@gmail.com&quot;);<br>    expect(response.body.token).toBeTruthy();<br>    expect(response.body.data.user.password).toBeUndefined();<br>  });<br>  it(&quot;should login a user&quot;, async () =&gt; {<br>    const response = await supertest(app)<br>      .post(&quot;/api/v1/users/login&quot;)<br>      .set(&quot;Content-type&quot;, &quot;application/json&quot;)<br>      .send({<br>        email: &quot;test4@gmail.com&quot;,<br>        password: &quot;testtesttest&quot;,<br>      });<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body).toHaveProperty(&quot;status&quot;, &quot;success&quot;);<br>    expect(response.body).toHaveProperty(&quot;data&quot;);<br>    expect(response.body.data).toHaveProperty(&quot;user&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;first_name&quot;, &quot;test&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;last_name&quot;, &quot;test&quot;);<br>    expect(response.body).toHaveProperty(&quot;token&quot;);<br>  });<br>});</pre><p>In the above code, we first import all dependencies/modules required to run our tests, then we configure our dotenv package and set our test timeout duration.</p><p>Moving on to the core parts of the tests, the describe function acts as a description for the current test suite. It wraps all test cases for this file in its call back function.</p><p>In the describe callback function, we have a couple functions being called. The beforeAll, beforeEach, afterEach and afterAll functions are mainly used for setup and cleanup for test cases while the it() function represents each individual test case.</p><p>In our case, we use supertest to send a request to our server and we check to see if we get the expected result, if the response matches the expected output then the test case will pass and if not, it will fail.</p><p>Now that we understand how to write tests, let’s write tests for the remaining test suites.</p><p>In the blog.test.js file, write the following</p><pre>const supertest = require(&quot;supertest&quot;);<br>const User = require(&quot;../models/userModel&quot;);<br>const Blog = require(&quot;../models/blogModel&quot;);<br>const app = require(&quot;../app&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>require(&quot;dotenv&quot;).config({ path: &quot;./config.env&quot; });<br><br>jest.setTimeout(20000);<br><br>describe(&quot;Auth routes&quot;, () =&gt; {<br>  // let conn;<br>  let author;<br>  let token;<br>  let oneBlog;<br>  beforeAll(async () =&gt; {<br>    await mongoose<br>      .connect(process.env.TEST_MONGO_URL, {<br>        useUnifiedTopology: true,<br>        useNewUrlParser: true,<br>      })<br>      .then(() =&gt; {<br>        console.log(&quot;DB connection successful!&quot;);<br>      })<br>      .catch((err) =&gt; {<br>        console.log(&quot;could not connect to MongoDB&quot;);<br>        console.log(err);<br>      });<br>    const user = await User.create({<br>      first_name: &quot;test&quot;,<br>      last_name: &quot;test&quot;,<br>      email: &quot;test2@gmail.com&quot;,<br>      password: &quot;testtesttest&quot;,<br>      passwordConfirm: &quot;testtesttest&quot;,<br>    });<br>    author = user;<br>    const loginResponse = await supertest(app)<br>      .post(&quot;/api/v1/users/login&quot;)<br>      .set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>      .send({ email: &quot;test2@gmail.com&quot;, password: &quot;testtesttest&quot; });<br>    token = loginResponse._body.token;<br>  });<br>  beforeEach(async () =&gt; {<br>    const blog = await Blog.create({<br>      title: &quot;test&quot;,<br>      description: &quot;test&quot;,<br>      author: author.id,<br>      state: &quot;published&quot;,<br>      tags: [&quot;test&quot;],<br>      body: &quot;test&quot;,<br>    });<br>    oneBlog = blog;<br>  });<br><br>  afterEach(async () =&gt; {<br>    await Blog.deleteMany();<br>  });<br>  afterAll(async () =&gt; {<br>    await User.deleteMany();<br>    await Blog.deleteMany();<br><br>    await mongoose.connection.close();<br>  });<br>  it(&quot;Should get all blogs from the database&quot;, async () =&gt; {<br>    const response = await supertest(app).get(&quot;/api/v1/blogs&quot;);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>  });<br>  it(&quot;Should get all blogs from the database and filter by author&quot;, async () =&gt; {<br>    const response = await supertest(app).get(<br>      `/api/v1/blogs?author=${author.id}`<br>    );<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.blogs).toBeTruthy();<br>  });<br>  it(&quot;Should get all blogs from the database and filter by tags&quot;, async () =&gt; {<br>    const response = await supertest(app).get(`/api/v1/blogs?tags=test`);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.blogs).toBeTruthy();<br>  });<br>  it(&quot;Should get all blogs from the database and filter by state&quot;, async () =&gt; {<br>    const response = await supertest(app).get(`/api/v1/blogs?state=published`);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.blogs).toBeTruthy();<br>  });<br>  it(&quot;Should get one blogs by id from the database&quot;, async () =&gt; {<br>    const response = await supertest(app).get(`/api/v1/blogs/${oneBlog.id}`);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.blog).toBeTruthy();<br>    expect(response.body.data.blog.author.first_name).toBe(&quot;test&quot;);<br>    expect(response.body.data.blog.author).toBeTruthy();<br>  });<br>  it(&quot;Should only update blog if its the owner requesting&quot;, async () =&gt; {<br>    const response = await supertest(app)<br>      .patch(`/api/v1/blogs/${oneBlog.id}`)<br>      .set(&quot;Authorization&quot;, `Bearer ${token}`)<br>      .set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>      .send({ state: &quot;draft&quot; });<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.updatedBlog).toBeTruthy();<br>    expect(response.body.data.updatedBlog.state).toBe(&quot;draft&quot;);<br>    expect(response.body.data.updatedBlog.author).toBeTruthy();<br>  });<br><br>  it(&quot;Should only create blog if user is logged in&quot;, async () =&gt; {<br>    const response = await supertest(app)<br>      .post(`/api/v1/blogs/`)<br>      .set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>      .set(&quot;authorization&quot;, `Bearer ${token}`)<br>      .send({<br>        title: &quot;test2&quot;,<br>        description: &quot;test&quot;,<br>        state: &quot;draft&quot;,<br>        tags: [&quot;test&quot;],<br>        body: &quot;test&quot;,<br>      });<br>    expect(response.statusCode).toBe(201);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.blog).toBeTruthy();<br>    expect(response.body.data.blog.title).toBe(&quot;test2&quot;);<br>    expect(response.body.data.blog.author).toBeTruthy();<br>    expect(response.body.data.blog.author).toBe(author.id);<br>  });<br><br>  it(&quot;Should only delete blog if its the owner requesting&quot;, async () =&gt; {<br>    const response = await supertest(app)<br>      .delete(`/api/v1/blogs/${oneBlog.id}`)<br>      .set(&quot;Authorization&quot;, `Bearer ${token}`)<br>      .set(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    expect(response.statusCode).toBe(204);<br>  });<br>  it(&quot;Should get user blogs&quot;, async () =&gt; {<br>    const response = await supertest(app)<br>      .get(`/api/v1/blogs/getMyBlogs`)<br>      .set(&quot;Authorization&quot;, `Bearer ${token}`)<br>      .set(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body.status).toStrictEqual(&quot;success&quot;);<br>    expect(response.body.data.blogs).toBeTruthy();<br>  });<br>});</pre><p>In the user.test.js file , add the following</p><pre>const supertest = require(&quot;supertest&quot;);<br>const app = require(&quot;../app&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>const User = require(&quot;../models/userModel&quot;);<br>require(&quot;dotenv&quot;).config({ path: &quot;./config.env&quot; });<br>jest.setTimeout(20000);<br><br>describe(&quot;User routes&quot;, () =&gt; {<br>  let user;<br>  beforeAll(async () =&gt; {<br>    mongoose<br>      .connect(process.env.TEST_MONGO_URL, {<br>        useUnifiedTopology: true,<br>        useNewUrlParser: true,<br>      })<br>      .then(() =&gt; {<br>        console.log(&quot;DB connection successful!&quot;);<br>      })<br>      .catch((err) =&gt; {<br>        console.log(&quot;could not connect to MongoDB&quot;);<br>        console.log(err);<br>      });<br>    user = await User.create({<br>      first_name: &quot;test&quot;,<br>      last_name: &quot;test&quot;,<br>      email: &quot;test6@gmail.com&quot;,<br>      password: &quot;testtesttest&quot;,<br>      passwordConfirm: &quot;testtesttest&quot;,<br>    });<br>  });<br><br>  afterAll(async () =&gt; {<br>    await User.deleteMany();<br>    await mongoose.connection.close();<br>  });<br>  it(&quot;should get all users&quot;, async () =&gt; {<br>    const response = await supertest(app).get(&quot;/api/v1/users&quot;);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body).toHaveProperty(&quot;status&quot;, &quot;success&quot;);<br>    expect(response.body).toHaveProperty(&quot;data&quot;);<br>    expect(response.body.data).toHaveProperty(&quot;users&quot;);<br>    expect(response.body.data.users.length).toBeGreaterThan(0);<br>  });<br>  it(&quot;should get a user&quot;, async () =&gt; {<br>    const response = await supertest(app).get(`/api/v1/users/${user.id}`);<br>    expect(response.statusCode).toBe(200);<br>    expect(response.body).toHaveProperty(&quot;status&quot;, &quot;success&quot;);<br>    expect(response.body).toHaveProperty(&quot;data&quot;);<br>    expect(response.body.data).toHaveProperty(&quot;user&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;first_name&quot;, &quot;test&quot;);<br>    expect(response.body.data.user).toHaveProperty(&quot;last_name&quot;, &quot;test&quot;);<br>  });<br>});</pre><p>Great, we now have test suites for all our resources.</p><p>To run our tests we will add another script to the package.json file.</p><pre>    &quot;test&quot;: &quot;jest --coverage --runInBand --detectOpenHandles&quot;</pre><p>Your script section in the package.json file should look like this now.</p><figure><img alt="script section in the package.json file snapshot" src="https://cdn-images-1.medium.com/max/627/1*MHNnQhRoAVk360IeT6k--w.png" /></figure><p>Now all we need to do is run the below command in the terminal.</p><pre>npm run test</pre><p>If all files were set up properly you should see an output similar to the one below.</p><figure><img alt="Test output snapshot" src="https://cdn-images-1.medium.com/max/848/1*iaJ3WzsR4NqOnbD7OQunJg.png" /></figure><p>Before we round up and push our code to github, theres one last script I want to add to our package.json file.</p><pre>    &quot;start&quot;: &quot;NODE_ENV=production node server.js&quot;</pre><p>The scripts section in the package.json file should look like this now</p><figure><img alt="script section in the package.json file snapshot" src="https://cdn-images-1.medium.com/max/546/1*pqZhsiZ6DagzHNrd-KEMMw.png" /></figure><p>The above script is useful in case you want to host your api in the future.</p><p>Now our api is ready and should be shipped off to github for safe keeping and maybe even contributions.</p><h4>Github</h4><p>Firstly, we need to create a new repo on github. While creating a new repo do not add a README.md file, you can add that later when were done pushing</p><p>After creating an empty repo, create a new file called .gitignore in your project folder</p><pre>touch .gitignore</pre><p>And add the following to the .gitignore file</p><pre>node_modules<br>.env<br>coverage</pre><p>This tells git not to track these file, so these files will not be uploaded to github</p><p>Next step is to run the following commands in your terminal one after the other</p><pre>git init<br>git add .<br>git commit -m &quot;first commit&quot;<br>git remote add origin https://github.com/&lt;YOUR_GITHUB_NAME&gt;/&lt;YOUR_GITHUB_REPO_NAME&gt;.git<br>git push -u origin main</pre><p>After running all the commands above, you should be able to see your codebase in your github repository.</p><p>And thats a wrap!</p><h4>Wrap up</h4><p>Congratulations on making it to the end of this blogpost. If you would like for me to write on other topics or would like to point out some corrections, please let me know in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4616609d0b64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>