<?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 Victoriaigbobi on Medium]]></title>
        <description><![CDATA[Stories by Victoriaigbobi on Medium]]></description>
        <link>https://medium.com/@victoriaigbobi65?source=rss-cc27d3fd5900------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Victoriaigbobi on Medium</title>
            <link>https://medium.com/@victoriaigbobi65?source=rss-cc27d3fd5900------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:22:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@victoriaigbobi65/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[Why Your App Feels Slow (and How to Fix It in 6 Simple Steps)]]></title>
            <link>https://medium.com/@victoriaigbobi65/why-your-app-feels-slow-and-how-to-fix-it-in-6-simple-steps-bb7570bed9bd?source=rss-cc27d3fd5900------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb7570bed9bd</guid>
            <dc:creator><![CDATA[Victoriaigbobi]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 09:08:45 GMT</pubDate>
            <atom:updated>2024-09-24T09:08:45.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcex-OjNY1tGm-CsZlMdlg.png" /></figure><p>Ever notice how a split second feels like forever when you’re waiting on a webpage or app? Users don’t have time to wait — and honestly, they shouldn’t have to. Whether it’s loading a page or delivering real-time data, speed is everything.</p><p>But on the server side, things can slow down in ways users never see. So how do we make sure our apps deliver results instantly, without breaking a sweat?</p><p>1. Index your database for faster lookups<br>Think of indexing like a table of contents for your database. Imagine trying to find a specific chapter in a book without a table of contents. You’d have to flip through every page, right? That’s what your database does without proper indexing — it scans every row to find what it needs. Now imagine you had a detailed index — getting to the right page takes seconds!</p><p>In the same way, adding indexes to your database allows it to jump straight to the data you’re looking for, significantly speeding up queries. For example, if users frequently search for products by price or category, indexing those columns can instantly boost performance. Focus on indexing the most queried fields for a quick win.</p><p>2. Keep frequently accessed data where it’s easiest to grab<br>Picture this: A user logs in, and their full name is displayed on the dashboard, profile, and notifications. If that name is stored in a separate profile entity, your app takes extra steps — fetching it through additional queries. Multiply this by thousands of users, and those extra steps add up fast, slowing down your app.</p><p>Instead, keep essentials in your pocket. By storing frequently accessed data, like fullName, directly in the user object, your app can grab it instantly without running extra errands. This reduces unnecessary database joins, makes things more responsive, and speeds up your app.</p><p>3. Keep the focus on what matters — offload the rest<br>When users interact with your app, they expect things to happen immediately — no delays, no waiting around. But tasks like logging user activity, sending analytics data, or even processing backend calculations can slow the experience down if handled in real-time.</p><p>Prioritize the tasks that impact the user’s immediate experience. Handle essential actions right away and move non-critical tasks to background processes. For example, if a user uploads a file, they care about seeing the success message, not whether analytics were logged that second. This keeps the user happy and your app smooth.</p><p>4. Avoid in-memory data manipulation — let your database do the heavy lifting<br>When I first started out, I thought I had it figured out. Need a count of something from the database? Easy — I’d pull every single record into memory and do the counting in my app. It worked… until the data grew, and my app became slow and resource-hungry.</p><p>I quickly realized my app didn’t need to do all that work — databases are built to handle it. Instead of pulling large datasets into memory, let your database handle filtering, sorting, and counting. This reduces memory usage, speeds up response times, and keeps your app light and responsive.</p><p>5. Minimize database trips — do more with less<br>Picture this: your app needs to fetch a user’s details, their orders, and their preferences. If you make three separate trips to the database — one for each — you’re making your app work harder than it should. These back-and-forth requests add delays, and soon, your app feels sluggish.</p><p>The smarter way? Combine those requests. Grab everything — user details, orders, and preferences — in a single query. This reduces database round trips, speeds up response times, and keeps your app efficient.</p><p>6. Use pagination to handle large data efficiently<br>Ever tried to load a massive list of items all at once? Imagine a user scrolling through thousands of products, and your app pulls in every single one. It not only takes forever but puts a huge strain on your server.</p><p>The solution? Pagination. Break the data into smaller chunks and load only what’s needed — say the first 10, 20, or 50 items at a time. This keeps your app fast, responsive, and user-friendly, without overwhelming your database.</p><p>At the end of the day, speed is everything. In a world where users expect instant results, every millisecond counts. By optimizing database queries, reducing trips, offloading unnecessary tasks, and handling large data with pagination, you’re not just improving performance — you’re crafting a seamless experience.</p><p>Remember, it’s not just about building an app that works — it’s about building one that works fast.</p><p>How do you make sure your app runs fast? What strategies have worked best for you? I’d love to hear your thoughts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb7570bed9bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blog post api]]></title>
            <link>https://medium.com/@victoriaigbobi65/blog-post-api-213f8f13d925?source=rss-cc27d3fd5900------2</link>
            <guid isPermaLink="false">https://medium.com/p/213f8f13d925</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Victoriaigbobi]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 18:33:08 GMT</pubDate>
            <atom:updated>2023-01-08T18:33:08.104Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*U9-IEovQkZV1Do6TsseggA.png" /><figcaption>File structure</figcaption></figure><p>So, today we would be working on a simple CRUD ( Create, Read, Update, Delete ) application.</p><p>We would be working on a basic blog post API.</p><p>I am so excited to be walking you through this process.</p><p>Our API should be able to</p><ol><li>Signup a new user</li><li>Login User</li><li>Create new blog posts ( Created post is automatically in draft state and only logged in users can create a new post )</li><li>update the body of a post ( only owner of a post can update )</li><li>Get all published posts ( this action can be performed by both logged in and not logged in users )</li><li>Delete a post either in draft or published state ( Only the owner of a post )</li><li>Get all posts belonging to a logged in user</li><li>Update the state of a post (from draft to published )</li></ol><h3>PRE-REQUISITE</h3><ol><li>NODEJS — You should have node installed in your system</li><li>MONGODB — You should have mongoDB installed too</li></ol><h3>PROJECT SETUP</h3><ol><li>You can go ahead to create a folder for the project.</li><li>To create a Nodejs project</li></ol><ul><li>You can open the empty folder in the VScode (or any code editor || IDE of choice)</li><li>Press ctrl ` on your keyboard to open up a new terminal ( If you are using VScode)</li><li>You can the enter ``` npm init ``` in the open terminal</li><li>Follow through with the prompt messages in the terminal <br> and voila you have set up a new nodejs project. (You can enter app.js in the prompt for entry point)</li></ul><p>After following through with the steps above, your project should like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*jy6SC2801pA3MxG4w7xG9Q.png" /><figcaption>A package.json file</figcaption></figure><p>3. We can now proceed to install some packages essential to set up our blog App project</p><ul><li>In your terminal, enter the code below to install the package</li></ul><pre>npm i express nodemon mongoose dotenv jsonwebtoken body-parser</pre><p>this packages would do for now but we’d be installing more packages as we progress with the project</p><p>Let me take a minute to explain what the installed packages are useful for</p><ul><li>Express — Amongst everything it does includes helping create robust APIs that are quick and easy</li><li>Nodemon — This package helps us automatically restart our application anytime change in our file is detected.</li><li>Mongoose — This package is used to connect to our database (MongoDB)</li><li>Dotenv — This package automatically loads environment variables from a .env file into our process.env object</li><li>Body-Parser — Express body-parser is <strong>an npm module used to process data sent in an HTTP request body</strong>.</li></ul><h3>SETUP FILES FOR PROJECT</h3><p>After Successfully installing the necessary packages, it’s now time to setup files to get our project running.</p><h4>1. We are going to create a .env file for environmental variables.</h4><pre>MONGODB_URL=mongodb://localhost:27017<br>PORT=5000<br>JWT_SECRET=Write-a-secret-key-for-your-project<br>JWT_EXPIRESIN=1h<br></pre><h4>2. An app.js file (our application entry point)</h4><pre><br>const express = require(&#39;express&#39;) // Requiring the installed express package for use<br>const app = express() // Creating an application with the express package<br><br>app.use(express.json())// It parses incoming JSON requests and puts the parsed data in req<br><br><br>// Exporting the app to be able to create a server from it<br>module.exports=app</pre><h4>3. A server.js file for our server</h4><pre><br>const mongoose = require(&#39;mongoose&#39;) // Requiring the mongoose package to connect to the db<br>require(&#39;dotenv&#39;).config() // configuring our .env file<br>const app = require(&#39;./app&#39;) // importing our app into the server.js file<br>const PORT = process.env.PORT || 3000 // using the .env Port number or 3000<br><br><br>// CONNECTING TO DATABASE<br>const mongo_url = process.env.MONGODB_URL<br>mongoose.connect(mongo_url)<br>mongoose.connection.on(&#39;connected&#39;, ()=&gt;{<br>    console.log(&#39;DB connection successful!&#39;)<br>})<br>mongoose.connection.on(&#39;error&#39;, (err)=&gt;{<br>    console.log(&#39;Something was wrong with DB connection&#39;)<br>})<br><br>// Listening to our server<br>app.listen(PORT, (req, res) =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><h4>4. A models folder</h4><p>This folder houses our database schemas.</p><p>Since we are using MongoDb for this project it is necessary to note that mongoDB stores data in JSON (object) format unlike the regular table in the traditional databases.</p><p>So the schema describes how the fields are stored in the database.</p><p>We are going to be creating some files inside the models folder</p><ul><li>u<strong>ser.js</strong></li></ul><pre>const mongoose = require(&#39;mongoose&#39;)<br><br>const Schema = mongoose.Schema<br>const userSchema = new Schema({<br><br>    first_name: {<br>        type: String,<br>        required: [true, &#39;Please provide your first name!&#39;]<br>    },<br>    last_name: {<br>        type: String,<br>        required: [true, &#39;Please provide last name&#39;]<br>    },<br>    email: {<br>        type: String,<br>        required: [true, &#39;Email address is required!&#39;],<br>        unique: true,<br>        lowercase: true,<br>        validate: [validator.isEmail, &#39;Invalid email!&#39;]<br>    },<br>    password: {<br>        type: String,<br>        required: [true, &#39;Password is required!&#39;],<br>        minlength: [8, &#39;Password must not be less than 8 characters!&#39;],<br>        select: false<br>    }<br>})<br><br>const User = mongoose.model(&#39;users&#39;, userSchema)<br>module.exports=User</pre><ul><li><strong>post.js ( for the blog posts )</strong></li></ul><pre>const mongoose = require(&#39;mongoose&#39;)<br><br><br>const Schema = mongoose.Schema<br>const postSchema = new Schema(<br>  {<br>    title: {<br>      type: String,<br>      required: [true, &quot;Please provide title!&quot;],<br>      unique: [true, &quot;Title must be unique!&quot;],<br>      lowercase: true,<br>    },<br>    description: {<br>      type: String,<br>      required: [true, &quot;Please provide description!&quot;],<br>      lowercase: true,<br>    },<br>    tags: [<br>      {<br>        type: String,<br>        required: [true, &quot;Please provide tag!&quot;],<br>        lowercase: true,<br>      },<br>    ],<br>    author: {<br>      type: mongoose.Schema.Types.ObjectId,<br>      ref: &quot;users&quot;,<br>      required: true,<br>    },<br>    state: {<br>      type: String,<br>      enum: [&quot;draft&quot;, &quot;published&quot;],<br>      lowercase: true,<br>      default: &quot;draft&quot;,<br>    },<br>    read_count: {<br>      type: Number,<br>      default: 0,<br>    },<br>    reading_time: {<br>      type: Number,<br>    },<br>    body: {<br>      type: String,<br>      required: [true, &quot;Please provide body!&quot;],<br>    },<br>  },<br>  { timestamps: true }<br>);<br><br>const Post = mongoose.model(&#39;posts&#39;, postSchema)<br>module.exports=Post</pre><p>So in the post schema, each post is supposed to have,</p><p>1. <strong>title</strong> — title of the post</p><p>2. <strong>description</strong> — description of the post</p><p>3. <strong>tags</strong> — each post should have tags ( t<strong>ags</strong> provide a useful way to group related <strong>posts</strong> together )</p><p>4. <strong>author</strong> — each post have the ID of the author</p><p>5. <strong>state </strong>— each post has a default draft state upon creation( The author can then decide to publish )</p><p>6. <strong>read_count </strong>— each post contains a read_count field that signifies how many times the post has been viewed when published (default is 0)</p><p>7.<strong> reading_time</strong> — each post has a reading_time field that determines how long it takes to read the post</p><p>8. <strong>body </strong>— each post have a body</p><p>9. <strong>timestamps </strong>— each post have timestamps, a time of creation</p><h3>CONTROLLERS, MIDDLEWARE AND ROUTERS</h3><h4>1. CONTROLLER</h4><blockquote>Controllers are responsible for handling incoming request and sending back response or it could also mean a function written to manipulate data.</blockquote><p>Let say a user makes a request to create a new post ( while sending the necessary required data) , controller is the entity that carries out the creating of the new blog post and returns the appropriate response back to the user.</p><p>We are going to be creating a <strong>controllers folder</strong> in our project directory</p><h4>USER CONTROLLER</h4><p>Create a user.js file inside the <strong>controllers</strong> folder.</p><p>Our user.js controller file would handle creating a new user and logging in a user</p><pre><br>const User = require(&quot;../models/user&quot;)// Requiring our user model so as to be able to save data to our db<br>const jwt = require(&quot;jsonwebtoken&quot;) <br><br>require(&quot;dotenv&quot;).config();<br><br><br>//Helper function to sign token<br>const signToken = (id) =&gt; {<br>  return jwt.sign({ id }, process.env.JWT_SECRET, {<br>    expiresIn: process.env.JWT_EXPIRESIN,<br>  });<br>};<br><br>// controller to handle request to signup a newuser<br>exports.createUser = async (req, res, next) =&gt; {<br><br>  try{<br><br>    const { first_name, last_name, email, password } = req.body;<br>  <br>    /*Save new user to DB*/<br>    const newUser = await User.create({<br>      first_name: first_name,<br>      last_name: last_name,<br>      email: email,<br>      password: password,<br>    });<br><br>    /*Success response*/<br>    res.status(201).json({ status: true, newUser: newUser })}<br>  catch(err){<br>    res.status(400).json({ status: false, error: err})}<br><br>  <br>};<br><br>// controller to handle request to log in a user<br>exports.login = async (req, res, next) =&gt; {<br><br>  try{<br>    const { email, password } = req.body;<br><br>    /*Find user and check if user*/<br>    const user = await User.findOne({ email }).select(&quot;+password&quot;);<br>    if (!user || !(await user.correctPassword(password))) {<br>     return res.status(400).json({status: false, message: &quot;Incorrect email or password&quot;})<br>    }<br><br>    /*Generate token for user and send token to user*/<br>    const token = signToken(user._id);<br>    return res.status(200).json({<br>      status: true,<br>      token,<br>    });<br>}<br>  catch(err){<br>    return res.status(400).json({status: false, error: err})}<br>  <br>};<br></pre><p>Let’s update our <strong>models/user.js</strong> file with the code below</p><pre>const userSchema = new Schema // Ignore me<br><br>/*UPDATE FILE WITH THIS LINE OF CODE*/<br><br>//A DOCUMENT MIDDLEWARE THAT HASHES USER&#39;S PASSWORD<br>userSchema.pre(&#39;save&#39;, async function(next){<br>    this.password = await bcrypt.hash(this.password, 10)<br>    next()<br>})<br><br><br>// A MIDDLEWARE TO CHECK PASSWORD<br>userSchema.methods.correctPassword = async function (password) {<br>    const user = this;<br>    const compare = await bcrypt.compare(password, user.password);<br><br>    return compare;<br>};<br><br>const User = mongoose.model(&#39;users&#39;, userSchema) // Ignore me</pre><h4>2. MIDDLEWARE</h4><blockquote>simply put, middleware are functions that are executed or that execute during the processing of HTTP requests.</blockquote><p>That is, lets assume a user makes a request to delete a blog post, we have to first ensure that the said post belongs to the user so that they don’t go around deleting posts that doesn’t belong to them.</p><p>So, the function that ensures or checks if a blog post belongs to a user is a middleware.</p><p>Go ahead to create a<strong> <em>Middleware folder</em></strong> inside your project folder</p><h4>USER MIDDLEWARE</h4><p>create an <strong><em>auth.js file</em></strong> in the <strong><em>middleware folder.</em></strong></p><p>In this we are going to be creating a middleware to authenticate [prove or show they are truly who they say they are] a user</p><p>We are going to be authenticating with <strong><em>passport</em></strong></p><blockquote>Passport is authentication middleware for <a href="https://nodejs.org/">Node.js</a>. Extremely flexible and modular, Passport can be unobtrusively dropped in to any <a href="https://expressjs.com/">Express</a>-based web application.</blockquote><p>Go ahead and run these command in your terminal to install the following packages</p><pre>npm install passport passport-jwt passport-local</pre><p>In your middleware/auth.js file, you can proceed to add this code</p><pre>const passport = require(&quot;passport&quot;);<br>const JwtStrategy = require(&quot;passport-jwt&quot;).Strategy;<br>const ExtractJwt = require(&quot;passport-jwt&quot;).ExtractJwt;<br><br>const User = require(&quot;../models/user&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>var opts = {};<br>opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();<br>opts.secretOrKey = process.env.JWT_SECRET;<br>passport.use(<br>  new JwtStrategy(opts, function (jwt_payload, done) {<br>    User.findById(jwt_payload.id, function (err, user) {<br>      if (err) {<br>        return done(err, false);<br>      }<br>      if (user) {<br>        return done(null, user);<br>      } else {<br>        return done(null, false);<br>        // or you could create a new account<br>      }<br>    });<br>  })<br>);</pre><p>Having concluded working on our users controller and middleware it’s now time to setup our routes and test our endpoint.</p><p>To set up our routes we would create a <strong>routes</strong> <strong>folder</strong>.</p><h4>3. USER ROUTES</h4><ol><li>create a users.js file inside the routes folder</li></ol><blockquote>Let’s mount the users routes to be able to test our signup and sign in code.</blockquote><pre>const express = require(&#39;express&#39;)<br><br>// importing the user controller file<br>const userController = require(&#39;../controllers/user&#39;)<br>const userRouter = express.Router()<br><br>// signup route<br>userRouter<br>    .route(&#39;/signup&#39;)<br>    .post(userController.createUser)<br><br>// login route<br>userRouter<br>    .route(&#39;/login&#39;)<br>    .post(userController.login)<br><br>module.exports=userRouter // Exporting the user route to be able to use it in the app.js file</pre><p>We can now update our app.js file</p><h4>app.js</h4><pre><br>const express = require(&#39;express&#39;) // Requiring the installed express<br>const app = express() // Creating an application with the express package<br>const userRoute = require(&#39;./routes/user&#39;) // requiring our user routes<br><br>app.use(express.json()) // It parses incoming JSON requests and puts the parsed data in req<br>app.use(&#39;/user&#39;, userRoute); // user router<br><br>module.exports=app // Exporting the app to be able to create a server from it</pre><p>After updating our app.js file, let’s now start our server and test our user endpoints.</p><p><strong>Start server</strong></p><ol><li>open a new terminal</li><li>type <strong><em>nodemon server</em></strong> in the terminal</li></ol><p>And you can go ahead to test the endpoints.</p><h3>BLOG CONTROLLER</h3><p>We are going to be building our blog post controller to</p><ol><li>create a new post</li><li>get all posts</li><li>get all posts belonging to a logged in user</li><li>update the post body</li><li>update state of a post</li><li>delete a post only if it’s the owner of the post making the request</li></ol><p>We would create <strong>post.js </strong>file in our controllers folder</p><pre>const Post = require(&#39;../models/post&#39;)<br><br>//Create a new post <br>exports.createPost = async(req, res, next) =&gt; {<br><br>    const { title, description, tags, body } = req.body;<br>    const owner = req.user._id;<br><br>    <br>    const newPost = await Post.create({<br>      title: title,<br>      description: description,<br>      tags: (tags.trim()).split(/[, ]+/),<br>      author: owner,<br>      body: body,<br>    });<br><br>    <br>    return res.status(201).json({<br>        status: true,<br>        newPost,<br>    });<br>    <br>}<br><br>/*Update Post Details*/<br>exports.updatePost = async(req, res, next) =&gt; {<br><br>    const { id } = req.params;<br>    var queryObj = req.body;<br>    const excludedFields = [<br>      &quot;state&quot;,<br>      &quot;author&quot;,<br>      &quot;read_count&quot;,<br>      &quot;reading_time&quot;,<br>      &quot;createdAt&quot;,<br>      &quot;updatedAt&quot;,<br>    ];<br>    excludedFields.forEach((el) =&gt; delete queryObj[el]);<br><br>    const post = await Post.findByIdAndUpdate(<br>      id,<br>      { $set: queryObj },<br>      { new: true, runValidators: true }<br>    ).populate({ path: &quot;author&quot;, select: {first_name: 1, _id: 0}});<br><br><br>    return res.status(200).json({<br>        status: true,<br>        post: post,<br>    });   <br>    <br>}<br><br>/*Update Post state*/<br>exports.updateState = async( req, res, next) =&gt;{<br><br>    const {id} = req.params<br>    const state = req.body.state<br>    var postState = req.state;<br><br>    if (postState !== &quot;published&quot; &amp;&amp; state ) {<br>        const post = await Post.findByIdAndUpdate(id, { $set: {state: state} }, { new: true, runValidators: true })<br>                        .populate({path: &#39;author&#39;, select: {first_name: 1, _id: 0}})<br>    }<br><br>    <br>    <br>    return res.status(200).json({ /*Success response*/<br>        status: true,<br>        post: post<br>    })<br>}<br><br>/*Delete post*/<br>exports.deletePost = catchAsync(async(req, res, next) =&gt; {<br><br>    const { id } = req.params;<br>    const owner = req.user._id;<br><br>    const post = await Post.deleteOne({ id: id, author: owner });<br><br>    return res.status(200).json({<br>      status: true,<br>      msg: null,<br>    });<br>    <br>})<br><br>/*Get all post belonging to a user*/<br>exports.getAllMyPost = catchAsync(async (req, res, next) =&gt; {<br><br>    const visitor = req.user._id;<br>    const queryObj = req.query.state? { author: visitor, state: req.query.state} : {author: visitor}<br><br>    const page = +req.query.page || 1;<br>    const limit = +req.query.limit || 10;<br>    const skip = (page - 1) * limit;<br><br>    const visitorPosts = await Post<br>                            .find(queryObj)<br>                            .skip(skip)<br>                            .limit(limit);<br><br>    return res.status(200).json({<br>      status: true,<br>      numberOfPost: visitorPosts.length,<br>      page: page,<br>      posts: visitorPosts,<br>    });<br>})<br><br>/*Get a single blog post*/<br>exports.getPostById = catchAsync( async (req, res, next) =&gt; {<br>    const {id} = req.params<br><br>    const post = await Post.findById(id)<br>                                .where({state: {$eq: &quot;published&quot;}})<br>                                .populate({path: &quot;author&quot;, select: {__v: 0}})<br>                                .select({__v: 0})<br><br>    if (!post){<br>        return res.status(400).json({<br>msg: `post with ID ${id} doesn&#39;t exist` })<br>    }<br><br>    post.read_count = post.read_count += 1<br>    await post.save()<br><br><br>    return res.status(200).json({<br>        status: true,<br>        post: post<br>    });<br><br>/*Get all blog posts*/<br>exports.getAllPost = catchAsync( async(req, res, next) =&gt; {<br><br>    //FILTERING<br>    let queryObj = { ...req.query};<br>    const excludedFields = [&#39;page&#39;, &#39;sort&#39;, &#39;limit&#39;, &#39;fields&#39;, &quot;author&quot;];<br>    excludedFields.forEach((el) =&gt; delete queryObj[el]);<br><br>    <br>    /*Persist user input to lowercase */<br>    queryObj = Object.fromEntries( Object.entries(queryObj).map(([key, value]) =&gt; [key, value.toLowerCase()]))<br>    const sortBy = req.query.sort? req.query.sort.split(&quot;,&quot;).join(&quot; &quot;): &quot;-createdAt&quot;<br><br>    <br>    /*Query build up*/<br>    if (req.query.author){<br>      queryObj.author = req.query.author;<br>    }<br>    if (req.query.tags) {<br>      queryObj.tags = { $in: [req.query.tags] };<br>    }<br>    queryObj.state = { $eq: &quot;published&quot; };<br>    <br>  <br>    /*Pagination*/<br>    const page = +req.query.page || 1<br>    const limit = +req.query.limit || 20<br>    const skip = (page - 1) * limit<br><br>       const post = await Post<br>        .find(queryObj)<br>        .sort(sortBy)<br>        .skip(skip)<br>        .limit(limit);<br><br>  <br>    return res.status(200).json({<br>        status: true,<br>        page: page,<br>        numberOfPosts: post.length,<br>        posts: post<br>    })<br>})<br></pre><p>In our model folder, we are going to be updating our post.js file with the code below. It helps update the reading time of the blog post before it is saved.</p><h4><strong><em>models/post.js</em></strong></h4><pre>const postSchema.... //Ignore me<br><br>// update file with this line of code<br>postSchema.pre(&#39;save&#39;, async function(next){<br>    /*calculate read time*/<br>    const readTime = Math.round(this.body.split(&#39; &#39;).length / 200)<br>    this.reading_time= readTime &lt; 1? readTime + 1: {readTime}<br>    next()<br>})<br><br>const Post = mongoose.model(&#39;posts&#39;, postSchema) // Ignore me</pre><h4>POST MIDDLEWARE</h4><p>create a <strong><em>protect.js file</em></strong> inside the <strong><em>middleware folder</em></strong></p><p>For this project, we are going to be writing middleware for our blog post to ensure that a post belongs to a user before the user can be allowed to perform certain actions on a blog post. <em>( delete a post, update a post, edit a post status )</em></p><pre>const Post = require(&quot;../models/post&quot;);<br><br><br>exports.protect = async (req, res, next) =&gt; {<br>  const visitor = req.user._id;<br>  const { id } = req.params;<br>  const post = await Post.findById(id);<br><br>  if (!post) {<br>    return res.status(404).json({<br>         msg: `Post with ID ${id} wasn&#39;t found`<br>      });<br>  }<br><br>  /*Check if visitor is owner of post*/<br>  if (post.author.equals(visitor)) {<br>    req.state = post.state;<br>    return next();<br>  }<br><br>  /*Unauthorize message*/<br>  return res.status(401).json({<br>         msg: &#39;Unauthorized action!&#39;<br>      });<br>};</pre><h4>POST ROUTE</h4><p>create a post.js file inside the routes folder</p><blockquote>So we are going to be mounting routes to be able to test our blog post app</blockquote><pre>const express = require(&#39;express&#39;)<br>const passport = require(&#39;passport&#39;)<br><br>const postController = require(&#39;../controllers/post&#39;)<br>const postRouter = express.Router()<br>const auth = require(&#39;../middlewares/protect&#39;)<br>require(&#39;../middlewares/auth&#39;)/*Auth middleware*/<br><br><br>postRouter<br>    .route(&#39;/state/:id&#39;)<br>    .patch(passport.authenticate(&quot;jwt&quot;, { session: false }), auth.protect, postController.updateState)<br><br>postRouter<br>    .route(&#39;/&#39;)<br>    .post(passport.authenticate(&quot;jwt&quot;, { session: false }), postController.createPost)<br>    .get(postController.getAllPost)<br><br><br>postRouter<br>    .route(&quot;/me&quot;)<br>    .get(passport.authenticate(&quot;jwt&quot;, { session: false }), postController.getAllMyPost);<br><br><br>postRouter<br>    .route(&quot;/:id&quot;)<br>    .patch(passport.authenticate(&quot;jwt&quot;, { session: false }), auth.protect, postController.updatePost)<br>    .delete(passport.authenticate(&quot;jwt&quot;, { session: false }),auth.protect, postController.deletePost)<br>    .get(postController.getPostById) <br><br><br>module.exports=postRouter</pre><p>So, lets update our app.js with our post routes and test our endpoint</p><h4>app.js</h4><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br><br>const globalErrorHandler = require(&#39;./src/controllers/error&#39;)<br>const AppError = require(&#39;./utils/appError&#39;)<br>const userRoute = require(&#39;./src/routes/user&#39;)<br>const postRoute = require(&#39;./src/routes/post&#39;) // requiring our post route inour app.js<br><br><br>const app = express()<br><br>app.use(express.json())<br>app.use(bodyParser.urlencoded({ extended: false }));<br>app.use(&#39;/post&#39;, postRoute) // mounting our post route in our app.js<br>app.use(&#39;/user&#39;, userRoute);<br><br><br>app.use(&#39;*&#39;, (req, res, next) =&gt;{<br>    return res.status(404).json({<br>        msg: `This URL ${req.originalUrl} can not be found on this server!`<br>     })<br>})<br><br><br>module.exports=app</pre><p>I hope you found the article useful, you can check out the full project repository on GITHUB</p><p><a href="https://github.com/victoria-igbobi65/semester2exam">GitHub - victoria-igbobi65/semester2exam</a></p><p>Happy coding !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213f8f13d925" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>