<?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 Toye Adedamola on Medium]]></title>
        <description><![CDATA[Stories by Toye Adedamola on Medium]]></description>
        <link>https://medium.com/@toye.adedamola?source=rss-d7bb4ead0f86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2Yu7ZUUWo35g9Yx1</url>
            <title>Stories by Toye Adedamola on Medium</title>
            <link>https://medium.com/@toye.adedamola?source=rss-d7bb4ead0f86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:22:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@toye.adedamola/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 Build a Mentorship API Without a Database Using ExpressJS]]></title>
            <link>https://medium.com/@toye.adedamola/how-to-build-a-mentorship-api-without-a-database-using-expressjs-4aff4de85373?source=rss-d7bb4ead0f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aff4de85373</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Toye Adedamola]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 22:04:47 GMT</pubDate>
            <atom:updated>2025-05-06T19:17:39.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9TiqCnBNfOZAjlHT" /><figcaption>Photo by <a href="https://unsplash.com/@douglasamarelo?utm_source=medium&amp;utm_medium=referral">Douglas Lopes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, you will learn how to create a mentorship API with the following features:</p><ol><li>Users can sign up and sign in.</li><li>Admin can promote users to mentors.</li><li>Users can view mentors and also see details of a specific mentor.</li><li>Users can create mentorship session requests with mentors and leave reviews after sessions.</li><li>Mentors can accept or reject mentorship session requests.</li><li>Users can view all their mentorship sessions.</li></ol><p>This may seem like just a regular API, but here’s the twist: we won’t use a database to store our data. Curious to see how it will turn out? Let’s dive in!</p><h4>What You’ll Learn</h4><ol><li><strong>Setting up the project environment (Node.js and Express)</strong></li><li><strong>Implementing In-Memory Data Storage</strong></li><li><strong>Building controller functions for authentication, managing mentors, admins, and sessions</strong></li><li><strong>Adding authentication and authorization Middleware</strong></li><li><strong>Creating the API endpoints.</strong></li><li><strong>Populating app.js with the endpoints</strong></li></ol><h3>Setting Up the Project Environment</h3><p>Before you start building the Mentorship API, you need to set up your project environment. Here’s how you can do it:</p><ol><li>First, create a folder for your project. You can name it anything (e.g, mentorship-api). To do this, open your terminal and run:</li></ol><pre>mkdir mentorship-api<br>cd mentorship-api<br>npm init -y</pre><p>This will create a <strong><em>package.json</em></strong> file for your project, which will contain the dependencies and other important information about your project.</p><p>2. Install the required dependencies. For this project, install <strong><em>express</em></strong>, <strong><em>bcryptjs</em></strong>, <strong><em>jswebtoken</em></strong>, and <strong><em>dotenv</em></strong>. <strong><em>express</em></strong> is the framework you will use to build this API. <strong><em>dotenv</em></strong> helps to load environmental variables from the <strong><em>.env</em></strong> file (where you store protected information like jsonwebtoken secret key). <strong><em>bcryptjs</em></strong> is for hashing passwords securely.<strong><em> jsonwebtoken</em></strong> is for creating and verifying authentication tokens. Don’t worry if you do not understand their usefulness yet; as we progress, it will become clearer.</p><pre>npm install express dotenv bcryptjs jsonwebtoken</pre><p>3. Next thing you need to do is to set upthe<strong><em> app.js</em></strong> file. Create an <strong><em>app.j</em></strong>s file (if it doesn’t exist already) in the root directory. In this file, import express and dotenv. Your <strong><em>app.js</em></strong> file should look like this:</p><pre>// app.js<br>import express from &#39;express&#39;;<br>import dotenv from &#39;dotenv&#39;;<br><br>dotenv.config(); //load environmental variables from a .env file into process.env<br><br>const app = express();<br>app.use(express.json());<br><br>app.get(&#39;/&#39;,(req,res) =&gt; {<br>  res.send(&#39;Welcome&#39;)<br>})<br>export default app;</pre><p>Later on, you will populate the <strong><em>app.js</em></strong> file with your routes. But this is what we need for now.</p><p>4. Create a <strong><em>server.js</em></strong> file in the root directory where you’ll start the server.</p><pre>// server.js<br>import app from &#39;./app.js&#39;<br><br>const PORT = process.env.PORT || 5001;<br><br>app.listen(PORT, ()=&gt;{<br>    console.log(`Server running on port ${PORT}`)<br>});</pre><p>You can create a <strong><em>.env</em></strong> file in the root directory where you can add the port number and your jsonwebtoken secret key:</p><pre>// .env file<br>PORT=3000<br>JWT_SECRET=your_jwt_secret_key_here</pre><h3>Implementing In-Memory Data Storage</h3><p>You might be wondering how we can store the data without an actual database. First, we need to identify what exactly we want to store. This API revolves around authenticated users requesting sessions with mentors (who are also users of the platform). This means we need somewhere to store both the <strong>users</strong> and the <strong>sessions</strong>.</p><p>To make things simple, you could store both users and sessions in an array. But what happens if you close down the server? Will the data persist? Normally, a database keeps your data safe even when the server restarts. Since we’re not using a database, we’ll mimic this behaviour by saving the data to a file using Node’s built-in <strong>fs</strong> module. We can persist data so that even after the server restarts, the users’ and sessions’ data doesn’t disappear. To do this, we can use the <strong>fs</strong> library to write and read data to and from a JSON file.</p><p>Now, let’s start by creating simple functions to save users to a JSON file and retrieve them when needed.</p><h4>Storing Users in JSON</h4><p>Let’s start by storing user data. Create a <strong>data<em> </em></strong>folder. Then, create a <strong>user.js<em> </em></strong>file that includes all the logic for saving and reading user data.</p><p>Before moving forward, you want to take note of the fields each user must have. Each user must have a first name, a last name, an email, a password, an address, a bio, an occupation, and a role. If you were using an actual database, this information would be stored in the user model. But since we aren’t using an actual database, you can document the required fields in a simple <strong>.txt </strong>file for easy reference.</p><p>Now that we’ve sorted that out, you can move on to the users.js file. I’ll walk you through the steps first without full code snippets, so you can understand each part. At the end, I’ll show you a full snippet you can compare with.</p><ol><li>Import the file system module to manage reading and writing user data</li><li>Declare a file path where the data will be stored, such as <strong>./data/users.json</strong>.</li><li>You want to make sure the file in the file path declared above exists (you can use the <strong><em>existsSync</em></strong> method for this). If it doesn’t exist, you need to write an empty array to that file (you can use the <strong><em>writeFileSync</em></strong> method for this)</li><li>You need to create a function for loading users from the JSON file (<strong><em>loadUsersFromFile</em></strong> function). This is important to ensure you always get the latest version of the users&#39; data before saving new data.</li><li>In this <strong><em>loadUsersFromFile</em></strong> function, read the data in the <strong><em>filePath </em></strong>defined earlier and store it in the <strong><em>fileData</em></strong> variable (you can use the <strong><em>readFileSync</em></strong> method for this). Then, return the <strong><em>fileData</em></strong> as an object (use <strong><em>JSON.parse </em></strong>for this). If there’s no <strong><em>fileData, </em></strong>return an empty array.</li><li>We also need a function to save users to the JSON file (<strong><em>saveUsersToFile</em></strong> function). This function takes in the users array as an argument. It then writes the users array to the <strong><em>filePath </em></strong>defined earlier.</li><li>Next, you need is a function to generate the user IDs (<strong><em>generateUserId</em></strong> function). The first thing you need to do in this function is to load the users from the <strong>users.json</strong> file and store the result in a <strong><em>users</em></strong> variable.</li><li>A good way to generate a unique ID for each user is to use <strong><em>users.length+1</em></strong> when signing up a new user in the controller. However, this doesn’t work well if a user is deleted because the IDs won’t follow a sequence. To solve this, we create a <strong><em>nextUserId </em></strong>variable. If the users array is not empty, <strong><em>nextUserId</em></strong> is set to the last user’s ID plus 1. If the users array is empty, you will simply set <strong><em>nextUserId</em></strong> to 1.</li><li>Finally, in the <strong><em>generateUserId</em></strong> function, return the <strong><em>nextUserId</em></strong> variable. This way, you can make sure that the ID of a new user is always based on the ID of the user that precedes it in the array.</li><li>Don’t forget to export the functions defined in this <strong>users.js</strong> file</li></ol><p>Here’s what your users.js might look like if you followed the steps above</p><pre>// users.js<br><br>import fs from &quot;fs&quot;;<br>const filePath = &quot;./data/users.json&quot;;<br><br>// Make sure the file exists<br>if (!fs.existsSync(filePath)) {<br>  fs.writeFileSync(filePath, &quot;[]&quot;, &quot;utf-8&quot;);<br>}<br><br>// Load users from file<br>function loadUsersFromFile() {<br>  const fileData = fs.readFileSync(filePath, &quot;utf-8&quot;);<br>  return JSON.parse(fileData || &quot;[]&quot;);<br>}<br><br>// Save users to file<br>function saveUsersToFile(users) {<br>  fs.writeFileSync(filePath, JSON.stringify(users, null, 2), &quot;utf-8&quot;);<br>} //The null, 2 arguments format the JSON with indentation, making it human readable<br><br>// Generate next user ID based on current data in the file<br>function generateUserId() {<br>  const users = loadUsersFromFile();  // Load latest users data<br>  const nextUserId = users.length &gt; 0 ? users[users.length - 1].id + 1 : 1;<br>  return nextUserId;<br>}<br><br>// Export functions<br>export { loadUsersFromFile, saveUsersToFile, generateUserId };<br></pre><h4><strong>Storing Sessions in JSON</strong></h4><p>Now that you understand how to store the users without an actual database by storing them in the users.json file. You can repeat the same process for sessions.</p><p>This is what your sessions.js should look like:</p><pre>// sessions.js<br><br>import fs from &quot;fs&quot;;<br>const filePath = &quot;./data/sessions.json&quot;;<br><br>// Make sure the file exists<br>if (!fs.existsSync(filePath)) {<br>  fs.writeFileSync(filePath, &quot;[]&quot;, &quot;utf-8&quot;);<br>}<br><br>// Load sessions from file<br>function loadSessionsFromFile() {<br>  const fileData = fs.readFileSync(filePath, &quot;utf-8&quot;);<br>  return JSON.parse(fileData || &quot;[]&quot;);<br>}<br><br>// Save sessions to file<br>function saveSessionsToFile(sessions) {<br>  fs.writeFileSync(filePath, JSON.stringify(sessions, null, 2), &quot;utf-8&quot;);<br>}<br><br>// Generate next session ID based on current data in the file<br>function generateSessionId() {<br>  const sessions = loadSessionsFromFile();  // Load latest sessions data<br>  const nextSessionId = sessions.length &gt; 0 ? sessions[sessions.length - 1].id + 1 : 1;<br>  return nextSessionId;<br>}<br><br>// Export functions<br>export { loadSessionsFromFile, saveSessionsToFile, generateSessionId };</pre><h3>Building Controller functions for Authentication, Managing Mentors, Admins, and Sessions.</h3><p>Based on the features this API will have, you need to build these important controller functions. The controllers are the backbone of our API because they handle the logic that ensures each endpoint functions properly.</p><p>I know building these controllers may be overwhelming at first. But don’t worry, I’ll walk you through everything, step by step.</p><h4>Building the Authentication Controller</h4><p>The authentication controller will contain functions for signing up and signing in. For any user to be able to perform any action in this API, they must be authenticated. This is why we are starting with this controller.</p><p>As usual, I will walk you through how to do this step by step, then I’ll provide a snippet of what your code should look like.</p><ol><li>First, create a folder called <strong>controllers</strong> (if you don’t have one already). Then, in this folder, you can create the <strong>authController.js </strong>file</li><li>In the <strong>authController.js</strong><em>, </em>import <strong><em>bcrypt</em></strong>. We’ll use <strong><em>bcrypt</em></strong> to hash the user’s password before storing it in our in-memory data storage. This adds an extra layer of security. Imagine if a malicious person gains access to our storage, where all the users&#39; information is stored. If the passwords were stored directly (without some form of encryption), they could easily steal them and access users’ accounts. By hashing the passwords with bcrypt, we are making it very hard for anyone to decrypt them to get the original password.</li><li>You should also import <strong><em>jwt</em></strong> from <strong><em>jswebtoken</em></strong>. We will use JWT to generate a token for a user after every successful sign-up or sign-in. A token is a string that acts like a digital ID card. Whenever a user makes requests to protected parts of our API, like creating a mentorship session, the user must attach their token. Without tokens, the user would have to sign in every time they want to perform a request. Instead of asking the user to sign in again and again, the server just checks the token to confirm that the user is indeed authenticated.</li><li>You also need to import the functions we exported from the <strong><em>users.js</em></strong> file. These are the <strong><em>saveUsersToFile</em></strong>, <strong><em>loadUsersFromFile</em></strong> and <strong><em>generateUserId </em></strong>functions.</li></ol><pre>// authControllr.js<br>import bcrypt from &quot;bcryptjs&quot;;<br>import jwt from &quot;jsonwebtoken&quot;;<br>import {saveUsersToFile, generateUserId, loadUsersFromFile} from &#39;../data/users.js&#39;</pre><h4>Sign Up Function</h4><p>Now let’s start with the sign-up function.</p><p>Most controller functions always have request and response as parameters. They follow the format:</p><pre>function myFunc(req, res){<br>// code here <br>}</pre><ol><li>Create the <strong><em>signUp</em></strong> function using the format above, but make it an async function. We are doing this because we need to use await when hashing the password; <strong><em>bcrypt.hash()</em></strong> is an asynchronous operation.</li><li>The first thing you need to do in this function is to retrieve the necessary information from the request body (<strong><em>req.body</em></strong>). Based on what we know about the user fields, we are expecting a first name, a last name, an email, a password, an address, a bio, and an occupation. We aren’t expecting a role from the request body because by default, when a user signs up, it is assigned a role of <strong><em>“user”</em></strong></li><li>After retrieving the necessary information from the request body, you need to ensure that all the data needed was provided in the request body. If any of the required fields ( a first name, a last name, an email, a password, an address, a bio, an occupation) is missing, you will return a response with a status code of 400 (indicating that the client made a bad request) and a message telling the user that their user information needed to sign them up is incomplete.</li><li>Then, load the users from the <strong>users.json</strong> file by calling <strong><em>loadUsersFromFile(). </em></strong>Store the result in a <strong><em>users</em></strong> variable.</li><li>You need to check if the user exists already. We can’t sign up a user that already exists. You can easily compare the email we got from the request body with the emails of all the users obtained from the <strong>users.json </strong>file (stored in the <strong><em>users</em></strong> variable). You may think that we can use the <strong><em>find</em></strong> method for this, and while this will work, I want to introduce another method that can also work (<strong><em>some</em></strong> method). The <strong><em>find </em></strong>method will return the actual user whose email matches the email we got from the request body. The <strong><em>some</em></strong> method will return true if it finds at least one user whose email is the same as the email we got in the request body. Since we don’t need to store the user, we just want to find out if the user exists, we can use the <strong><em>some</em></strong> method instead.</li><li>If the user exists, you will return a response with a status code of 400 and a message indicating that the user already exists.</li><li>Now that we’ve sorted out the cases of incomplete user information and the user already existing, we can move on to storing the user. But before we do this, we need to hash the password using bcrypt. Don’t forget to add the await keyword when using <strong><em>bcrypt.hash()</em></strong> function: <strong><em>const hashedPassword = await bcrypt.hash(password, 10);</em></strong></li><li>Then you will generate an ID for the user using the <strong><em>generateUserId()</em></strong> defined in the <strong>users.js</strong> file. You can store this ID in an <strong><em>id </em></strong>variable.</li><li>You can then proceed to create a <strong><em>newUser </em></strong>variable and assign it an object that has all the necessary information, like the ID generated earlier, the data from the request body, the hashed password, and finally, role: “user”.</li><li>Push this new user to the <strong><em>users </em></strong>array (the <strong><em>users</em></strong> variable). It doesn’t end here. Don’t forget to call the <strong><em>saveUsersToFile</em></strong> function to save the updated <strong><em>users</em></strong> array to the <strong>users.json</strong> file.</li><li>The next step is to generate a token using the <strong><em>jwt </em></strong>imported earlier. Declare a token variable and assign to it a <strong><em>jwt </em></strong>generated token. For security, you can store your JWT secret key in the .env file so that you can just use it here when generating the token.</li><li>Finally, you will return the response with a status code of 201, a message indicating that the User signed up successfully, and the user data along with the token generated.</li><li>Note that we don’t want to return the password in the user data so we can exclude it and return just the user data without the password.</li><li>Note that you need to wrap everything from steps 2 to 12 in a try block since we are using async await. Then, in the catch block, log the error and return a response with a status code of 500 and an appropriate message.</li></ol><p>If you followed the steps above, your code should look like this:</p><pre>async function signup(req, res) {<br>  try {<br>    const { firstName, lastName, email, password, address, bio, occupation } = req.body;<br><br>    if (!firstName || !lastName || !email || !password || !address || !bio || !occupation) {<br>      return res.status(400).json({<br>        message: &quot;User info not complete. Each user must have first name, last name, email, password, address, bio, and occupation.&quot;,<br>      });<br>    }<br><br>    const users = loadUsersFromFile();<br><br>    //const userExists = users.find((user) =&gt; user.email === email);<br>    const userExists = users.some((user) =&gt; user.email === email);<br>    if (userExists) {<br>      return res.status(400).json({ message: &quot;User already exists&quot; });<br>    }<br><br>    // Hash password with await<br>    const hashedPassword = await bcrypt.hash(password, 10);<br><br>    const id = generateUserId();<br><br>    const newUser = {<br>      id,<br>      firstName,<br>      lastName,<br>      email,<br>      hashedPassword,<br>      address,<br>      bio,<br>      occupation,<br>      role: &quot;user&quot;,<br>    };<br><br>    users.push(newUser);<br>    saveUsersToFile(users);<br><br>    // Generate token with await<br>    const token = jwt.sign(<br>      { userId: newUser.id, email: newUser.email, role: &quot;user&quot; },<br>      process.env.JWT_SECRET_KEY,<br>      { expiresIn: &quot;1h&quot; }<br>    );<br><br>    const { hashedPassword: _, ...safeUser } = newUser;<br>    return res.status(201).json({<br>      message: &quot;User signed up successfully&quot;,<br>      data: { user: safeUser, token },<br>    });<br><br>  } catch (error) {<br>    console.error(error);<br>    return res.status(500).json({ message: &quot;Something went wrong during signup&quot; });<br>  }<br>}</pre><p>Now we move to the sign in function:</p><h4>Sign In Function</h4><ol><li>Create a <strong><em>signin</em></strong> function with request and response as parameters. Make <strong><em>signin</em></strong> an async function because we need to use <strong><em>brcypt.compare()</em></strong> later, which is asynchronous and returns a promise. The best way to deal with this is to use await with the <strong><em>brcypt.compare()</em></strong> to make the code cleaner</li><li>Retrieve the email and password from the request body.</li><li>If the request body doesn’t contain email or password, return a response with a status code of 400 and a message indicating that the user needs to input both email and password to sign in.</li><li>Also, you want to check if the email is valid. You can do this by checking if the email includes @ (since all emails must have this). If the email doesn’t have it, return a response with a status code of 400 and an appropriate message.</li><li>Then you need to load the users from the <strong>users.json</strong> file and store them in a <strong><em>users</em></strong> variable.</li><li>Find the user that matches the email in the request body. You can use the <strong><em>find</em></strong> method for this since you will need to store the user found. If no user was found whose email matched the email in the request body, return a response with a status code of 400 and an appropriate message like “User doesn’t exist.”</li><li>Compare the password from the request body with the stored hashed password of the user found. Use brcypt.compare() for this. Recall that it is asynchronous, so you will use await with it. If there is no match, return a response with a status code of 401 (the user is not authorized) and an appropriate message like “Incorrect password”.</li><li>If there is a match, generate a token and return a response with a status code of 200, an appropriate message, and the token.</li><li>Just like the <strong><em>signup</em></strong> function, wrap everything here from steps 2 to 7 in a try block. Then, in a catch block, log the error, return a response with a status code of 500, and an appropriate message.</li></ol><p>The <strong><em>signin</em></strong> function should look like this:</p><pre>async function signin(req, res) {<br>  try {<br>    const { email, password } = req.body;<br><br>    if (!email || !password) {<br>      return res.status(400).json({ message: &quot;You need both email and password to login&quot; });<br>    }<br>    if (!email.includes(&quot;@&quot;)) {<br>      return res.status(400).json({ message: &quot;Valid email needed&quot; });<br>    }<br><br>    const users = loadUsersFromFile()<br><br>    const existingUser = users.find((user) =&gt; user.email === email);<br>    if (!existingUser) {<br>      return res.status(400).json({ message: &quot;User doesn&#39;t exist&quot; });<br>    }<br><br>    // Compare passwords with await<br>    const isMatch = await bcrypt.compare(password, existingUser.hashedPassword);<br>    if (!isMatch) {<br>      return res.status(401).json({ message: &quot;Incorrect password&quot; });<br>    }<br><br>    const token = jwt.sign(<br>      {<br>        userId: existingUser.id,<br>        email: existingUser.email,<br>        role: existingUser.role,<br>      },<br>      process.env.JWT_SECRET_KEY,<br>      { expiresIn: &quot;1h&quot; }<br>    );<br><br>    return res.status(200).json({ message: &quot;User signed in successfully&quot;, token: token });<br><br>  } catch (error) {<br>    console.error(error);<br>    return res.status(500).json({ message: &quot;Something went wrong during signin&quot; });<br>  }<br>}</pre><p>Don’t forget to export both the signUp and signIn functions from the authController.</p><h4>Building Admin Controller</h4><p>In the admin controller, you are going to create and implement the <strong><em>promoteToMentor </em></strong>function.</p><ol><li>Create a file named <strong>adminController.js</strong> inside the controllers folder.</li><li>Import the <strong><em>saveUsersToFile </em></strong>and <strong><em>loadUsersFromFile </em></strong>functions from the <strong>users.js</strong> file.</li><li>Create the <strong><em>promoteToMentor</em></strong> function with <strong><em>req</em></strong> and <strong><em>res</em></strong> as parameters.</li><li>Extract the user ID from the <strong><em>req.params</em></strong> and store it in the <strong><em>userId </em></strong>variable.</li><li>Load the users from the <strong>users.json</strong> file using the <strong><em>loadUsersFromFile()</em></strong> and store the result in a <strong><em>users</em></strong> variable.</li><li>Search through the <strong><em>users</em></strong> to find the user whose ID matches the <strong><em>userId</em></strong> extracted. You can use the <strong><em>find</em></strong> method for this and store the user found in a <strong><em>user</em></strong> variable.</li><li>If there’s no user, return a response with a status code of 404 and an appropriate message</li><li>Declare a new variable called <strong><em>newRole</em></strong> and assign it a value of <strong><em>“mentor”.</em></strong></li><li>If the role of the user found is the same as this <strong><em>newRole</em></strong>, return a response with a status code of 400 and a message indicating that the user is already a mentor.</li><li>If the user role of the user found is not the same as <strong><em>newRole</em></strong>, set the role of the user to newRole. Then, update the data in the <strong>users.json</strong> file by calling the <strong><em>saveUsersToFile(users).</em></strong></li><li>Extract sensitive data (like the password) from the response by creating a <strong><em>“safeUser”.</em></strong></li><li>Return a response with a status code of 200, an appropriate message, and the <strong><em>“safeUser” </em></strong>object.</li><li>Don’t forget to export this <strong><em>promoteToMentor</em></strong> function</li></ol><p>Below is a snippet of how the adminController should look:</p><pre>// adminController.js<br><br>import { saveUsersToFile, loadUsersFromFile } from &quot;../data/users.js&quot;;<br><br>function promoteToMentor(req, res) {<br>  const userId = parseInt(req.params.id);<br><br>  const users = loadUsersFromFile();<br><br>  const user = users.find((user) =&gt; user.id === userId);<br>  if (!user) {<br>    return res.status(404).json({ message: &quot;User not found&quot; });<br>  }<br>  const newRole = &quot;mentor&quot;;<br>  <br>  if (user.role === newRole) {<br>    return res.status(400).json({ message: `User is already a ${newRole}` });<br>  }<br>  user.role = newRole;<br>  saveUsersToFile(users);<br><br>  const {hashedPassword, ...safeUser} = user;<br><br>  return res<br>    .status(200)<br>    .json({<br>      message: &quot;User successfully promoted to a mentor role&quot;,<br>      user: safeUser,<br>    });<br>}<br><br>export default promoteToMentor</pre><h4>Building Mentors Controller</h4><p>Based on the features of this API, all users should be able to get all mentors and a specific mentor based on their ID. Here’s how you’ll build the mentors controller.</p><ol><li>Create a <strong>mentorController.js</strong> file inside the controllers folder</li><li>First, you need to import the <strong><em>saveUsersToFile</em></strong> and <strong><em>loadUsersFromFile</em></strong> functions from the users.js file.</li></ol><pre>// mentorController.js<br>import {saveUsersToFile, loadUsersFromFile} from &quot;../data/users.js&quot;</pre><p>Then we can proceed to the <strong><em>getAllMentors</em></strong> and <strong><em>getSpecificMentor</em></strong> functions.</p><h4>Get All Mentors Function:</h4><p>Let’s start with the <strong>getAllMentors</strong> function:</p><ol><li>Create a function called <strong><em>getAllMentors</em></strong> with the <strong><em>req</em></strong> and <strong><em>res</em></strong> as parameters.</li><li>Load users from the <strong>users.json</strong> file using the <strong><em>loadUsersFromFile()</em></strong> and store the result in a <strong><em>users</em></strong> variable.</li><li>Use the <strong><em>filter</em></strong> method to find all users whose roles are <strong><em>“mentors”</em></strong> and store this in a <strong><em>mentors</em></strong> variable (this will be an array).</li><li>If the <strong><em>mentors</em></strong> array is empty, return a response with a status code of 404 and a message indicating that there are no mentors available</li><li>If the <strong><em>mentors</em></strong> array contains something, return the response with a status code of 200 and the mentors array.</li></ol><p>Below is a snippet of how this function will look:</p><pre>function getAllMentors(req,res){<br>    const users = loadUsersFromFile()<br>    const mentors = users.filter((user)=&gt; user.role === &quot;mentor&quot;);<br>    if(mentors.length === 0){<br>        return res.status(404).json({message:&quot;No mentors available&quot;})<br>    }<br>    return res.status(200).json({mentors})<br>}</pre><h4>Get a Specific Mentor Function:</h4><p>Let’s move to the <strong><em>getSpecificMentor </em></strong>function:</p><ol><li>Create a function called <strong><em>getSpecificMentor </em></strong>with the <strong><em>req</em></strong> and <strong><em>res</em></strong> as parameters.</li><li>Extract the ID of the mentor from the params using <strong><em>req.params.id</em></strong> (as an integer) and store this in a <strong><em>mentorId</em> </strong>variable.</li><li>Load users from the <strong>users.json</strong> file using the <strong><em>loadUsersFromFile()</em></strong> and store the result in a <strong><em>users</em></strong> variable.</li><li>Find the user whose role is a mentor and whose ID matches the <strong><em>mentorId</em></strong> extracted. Store this user in a <strong><em>mentor</em></strong> variable.</li><li>If no user fulfilled those 2 conditions, return a response wth a status code of 404 and a message of “Mentor not found”.</li><li>If a user who fulfilled those 2 conditions were found, return a response with a status code of 200 and the mentor’s data.</li></ol><pre>function getSpecificMentor(req, res) {<br>    const mentorId = parseInt(req.params.id); <br>    const users = loadUsersFromFile()<br>    const mentor = users.find((user) =&gt; user.role === &quot;mentor&quot; &amp;&amp; user.id === mentorId);<br>  <br>    if (!mentor) {<br>      return res.status(404).json({ message: &quot;Mentor not found&quot; });<br>    }<br>  <br>    return res.status(200).json({ mentor });<br>  }</pre><p>Don’t forget to export both functions:</p><pre>export default {getAllMentors, getSpecificMentor}</pre><h4>Building the Session Controller</h4><p>In this controller, you will implement the functions for creating, accepting, rejecting, reviewing a session, and retrieving all sessions. But first, let’s set up the <strong>sessionController.js</strong> file:</p><ol><li>Create the <strong>sessionController.js</strong> file inside the <strong>controllers</strong> folder.</li><li>Import the <strong><em>saveSessionsToFile</em></strong>, <strong><em>generateSessionId</em></strong>, and <strong><em>loadSessionsFromFile</em></strong> from the <strong>sessions.js</strong> file.</li><li>Also import <strong><em>loadUsersFromFile</em></strong> from the <strong>users.js</strong> file.</li><li>You can create a <strong><em>findSessionById</em></strong> helper function that takes in an id and a sessions array as parameters. This function will search through the sessions array and return the session matching the given ID. You can create this function either in the <strong>sessionController.js</strong> or in the <strong>sessions.js</strong> file</li></ol><pre>// sessionController.js<br>import {saveSessionsToFile , generateSessionId, loadSessionsFromFile} from &quot;../data/sessions.js&quot;;<br>import { loadUsersFromFile } from &quot;../data/users.js&quot;;<br><br>function findSessionById(id, sessions) {<br>  return sessions.find((session) =&gt; session.id === id);<br>}</pre><h4>Creating a Session Function:</h4><ol><li>Create a <strong><em>createSession </em></strong>function with <strong><em>req</em></strong> and <strong><em>res</em></strong> parameters.</li><li>Extract <strong><em>mentorId</em></strong> and <strong><em>questions</em></strong> from the request body.</li><li>Also, extract the ID of the user making the request and store it in a <strong><em>menteeId </em></strong>variable</li><li>Extract the email of the user making the requests and store it in a <strong><em>menteeEmail </em></strong>variable.</li><li>Ensure that <strong><em>mentorId</em></strong> and <strong><em>questions</em></strong> are provided in the request body. If they are not provided, return a response with a status code of 400 and an appropriate message.</li><li>Load the users from the <strong>users.json</strong> file using the <strong><em>loadUsersFromFile()</em></strong> and store the result in a <strong><em>users</em></strong> variable.</li><li>Check if the user with a mentor role and an ID of <strong><em>mentorId</em></strong> exists in the <strong><em>users </em></strong>array. You can use the <strong><em>find</em></strong> method for this. Store the results in a <strong><em>mentor</em></strong> variable.</li><li>If no such user exists (i.e, if <strong><em>mentor</em></strong> variable is null), return a response with a status code of 400 and an appropriate message like “Invalid mentorId. No such mentor exists, or the user is not a mentor.”</li><li>Generate a <strong><em>sessionId</em></strong> using the <strong><em>generateSessionId()</em></strong> function.</li><li>Create a <strong><em>newSession</em></strong> using the id generated, <strong><em>mentorId</em></strong> and <strong><em>questions</em></strong> from the request body, <strong><em>menteeId</em></strong> from the user’s id, <strong><em>menteeEmail</em></strong> from the user’s email, default status of pending, and a <strong><em>createdAt</em></strong> date.</li><li>Load the sessions from the <strong>sessions.json</strong> file using the <strong><em>loadSessionsFromFile()</em></strong> and store the result in a <strong><em>sessions</em></strong> variable (an array).</li><li>Push the new session created to the sessions array and then call the <strong><em>saveSessionsToFile(sessions)</em></strong> function to update the <strong>sessions.json</strong> file.</li><li>Finally, return a response with a status code of 201, an appropriate message, and the new session created.</li></ol><p>The createSession function should look like this:</p><pre><br>function createSession(req, res) {<br>  const { mentorId, questions } = req.body;<br>  const menteeId = req.user.userId;<br>  const menteeEmail = req.user.email;<br><br>  if (mentorId == null || !Array.isArray(questions) || questions.length === 0) {<br>    return res.status(400).json({ message: &quot;Mentor ID and questions are required and questions must be a non-empty array.&quot; });<br>  }<br>  const users = loadUsersFromFile();<br>  // Check if the mentor exists and has the role &#39;mentor&#39;<br>  const mentor = users.find(<br>    (user) =&gt; user.id === mentorId &amp;&amp; user.role === &quot;mentor&quot;<br>  );<br>  if (!mentor) {<br>    return res.status(400).json({<br>      message:<br>        &quot;Invalid mentorId. No such mentor exists or user is not a mentor.&quot;,<br>    });<br>  }<br><br>  const id = generateSessionId();<br>  const newSession = {<br>    id,<br>    menteeId,<br>    mentorId,<br>    questions,<br>    menteeEmail,<br>    status: &quot;pending&quot;,<br>    createdAt: new Date().toISOString(),<br>  };<br><br>  const sessions = loadSessionsFromFile();<br>  sessions.push(newSession);<br>  saveSessionsToFile(sessions);<br>  <br>  res.status(201).json({ message: &quot;Session created successfully&quot;, newSession });<br>}</pre><h4>Accepting a Session Function</h4><ol><li>Create an <strong><em>acceptSession</em></strong> function with <strong><em>req</em></strong> and <strong><em>res</em></strong> parameters.</li><li>Extract the ID of the current user (userId) and store it in a <strong><em>userId </em></strong>variable.</li><li>Extract <strong><em>sessionId</em></strong> from the route params as an integer.</li><li>Load the sessions from the <strong>sessions.json</strong> file using the <strong><em>loadSessionsFromFile()</em></strong> and store the result in a <strong><em>sessions</em></strong> variable (an array).</li><li>Pass the <strong><em>sessionId</em></strong> and <strong><em>sessions </em></strong>to the <strong><em>findSessionById</em></strong> function and store the result in a <strong><em>session</em></strong> variable.</li><li>If no session with <strong><em>sessionId</em></strong> exists, return a response with a status code of 404 and an appropriate message like “Session not found.”</li><li>Ensure that the mentor owns the session by checking if the <strong><em>mentorId </em></strong>of the session matches the ID of the current user (stored in <strong><em>userId</em></strong>). If they don’t match, return a response with a status code of 403 and an appropriate JSON message like “Not authorized to accept the session.”</li><li>If they match, update the status of the session to <strong><em>“accepted”</em></strong> and call <strong><em>saveSessionsToFile(sessions)</em></strong>.</li><li>Finally, return a response with a status code of 200, an appropriate message, and the updated session.</li></ol><pre>function acceptSession(req, res) {<br>  const userId = req.user.userId<br>  const sessionId = parseInt(req.params.id);<br>  const sessions = loadSessionsFromFile();<br>  const session = findSessionById(sessionId, sessions);<br><br>  if (!session) {<br>    return res.status(404).json({ message: &quot;Session not found&quot; });<br>  }<br><br>  //Make sure the mentor owns the session<br>  if (session.mentorId !== userId) {<br>    return res<br>      .status(403)<br>      .json({ message: &quot;Not authorized to accept the session&quot; });<br>  }<br><br>  session.status = &quot;accepted&quot;;<br>  <br>  saveSessionsToFile(sessions);<br><br>  return res.status(200).json({ message: &quot;Session accepted successfully&quot;, session });<br>}</pre><h4>Rejecting a Session Function:</h4><p>The reject session function is very similar to the accept session function. The only difference is that the session status is updated to <strong><em>“rejected”</em></strong> instead of <strong><em>“accepted”</em></strong>.</p><p>Try to write the <strong><em>rejectSession</em></strong> function on your own</p><p>Below is the code:</p><pre>function rejectSession(req, res) {<br>  const userId = req.user.userId;<br>  const sessionId = parseInt(req.params.id);<br>  const sessions = loadSessionsFromFile()<br>  const session = findSessionById(sessionId, sessions);<br>  if (!session) {<br>    return res.status(404).json({ message: &quot;Session not found&quot; });<br>  }<br><br>  //Make sure the mentor owns the session<br>  if (session.mentorId !== userId) {<br>    return res<br>      .status(403)<br>      .json({ message: &quot;Not authorized to reject the session&quot; });<br>  }<br><br>  session.status = &quot;rejected&quot;;<br><br>  saveSessionsToFile(sessions);<br>  return res.json({ message: &quot;Session rejected&quot;, session });<br>}</pre><h4>Reviewing a Session Function</h4><p>Every user can review a session they requested, provided the session was accepted by a mentor, and each review must have rating and comment fields.</p><ol><li>Extract the ID of the current user and store it in <strong><em>userId.</em></strong></li><li>Extract the session ID from the params and store it in <strong><em>sessionId</em></strong>. Make sure to convert it to an integer since the ID in the route is a string.</li><li>Extract the <strong><em>rating</em></strong> and <strong><em>comment</em></strong> from the request body.</li><li>If rating and comment are not provided, return a response with a status code of 400 and an appropriate message.</li><li>Load the sessions from the <strong>sessions.json</strong> file using the <strong><em>loadSessionsFromFile()</em></strong> and store the result in a <strong><em>sessions</em></strong> variable (an array).</li><li>Pass the <strong><em>sessionId</em></strong> and <strong><em>sessions </em></strong>to the <strong><em>findSessionById</em></strong> function and store the result in a <strong><em>session</em></strong> variable.</li><li>If no session is found, return a response with a status code of 404 and an appropriate message.</li><li>Check if the status of the session is accepted. A user can only review a session if it has been accepted by a mentor. If the status of the session is not accepted, return a response with a status code of 400 and an appropriate message.</li><li>Also, check if the <strong><em>menteeId</em></strong> associated with the session is the same as the id extracted from the current user (<strong><em>userId</em></strong>). If they aren’t the same, return a response with a status code of 403 and an appropriate message.</li><li>If <strong><em>session.review</em></strong> exists, this means the session already has a review, so return a response with a status code of 400 and a message of “Session already has a review.”</li><li>Then you can proceed to assign the <strong><em>session.review</em></strong> field to the <strong><em>rating</em></strong> and <strong><em>comment</em></strong> extracted from the request body. Don’t forget to call <strong><em>saveSessionsToFile(sessions)</em></strong> to update the sessions.json file.</li><li>Finally, return a response with a status code of 200, an appropriate message, and the session object.</li></ol><pre>function reviewSession(req, res) {<br>  const userId = req.user.userId;<br>  const sessionId = parseInt(req.params.id);<br>  const { rating, comment } = req.body;<br><br>  if(!rating || !comment){<br>    return res.status(400).json({message:&quot;Rating and comment required to review&quot;})<br>  }<br>  <br>  const sessions = loadSessionsFromFile()<br>  const session = findSessionById(sessionId, sessions);<br>  if (!session) {<br>    return res.status(404).json({ message: &quot;Session not found&quot; });<br>  }<br>  if (session.status !== &quot;accepted&quot;) {<br>    return res<br>      .status(400)<br>      .json({<br>        message: &quot;Session must be accepted before a mentee can review it&quot;,<br>      });<br>  }<br><br>  if (session.menteeId !== userId) {<br>    return res<br>      .status(403)<br>      .json({ message: &quot;Not authorized to review the session&quot; });<br>  }<br>  if (session.review) {<br>    return res.status(400).json({ message: &quot;Session already has a review&quot; });<br>  }<br>  session.review = {<br>    rating,<br>    comment,<br>  };<br>  saveSessionsToFile(sessions);<br>  res.status(200).json({ message: &quot;Review added successfully&quot;, session });<br>}</pre><h4>Retrieve all Sessions Function</h4><p>We need a function to retrieve all sessions where the user either requested or was a mentor in.</p><ol><li>Create a <strong><em>getAllSessions</em></strong> function with the <strong><em>req</em></strong> and <strong><em>res</em></strong> parameters</li><li>Extract the current user’s ID and store it in <strong><em>userId.</em></strong></li><li>Load the users from the <strong>users.json</strong> file using the <strong><em>loadUsersFromFile()</em></strong> and store the result in a <strong><em>users</em></strong> variable.</li><li>Load the sessions from the <strong>sessions.json</strong> file using the <strong><em>loadSessionsFromFile()</em></strong> and store the result in a <strong><em>sessions</em></strong> variable (an array).</li><li>Find the user in the users array whose ID matches the userId extracted. Store the result in a <strong><em>user</em></strong> variable</li><li>If no user is found, return a response with the status code of 404 and an appropriate message.</li><li>If a user is found, store the role of the user in the <strong><em>userRole</em></strong> variable. Also, create an empty userSessions array.</li><li>Check if the role of the user is just <strong><em>“user”</em></strong>, then get all sessions created by that user by filtering through the sessions array to find the one whose <strong><em>menteeId</em></strong> matches the <strong><em>userId</em></strong>. Store the result in <strong><em>userSessions</em></strong></li><li>Do the same to check if the role of the user is <strong><em>“mentor”</em></strong>, filter through the sessions array to find the sessions where the <strong><em>mentorId</em></strong> matches the <strong><em>userId</em></strong>.</li><li>If nothing was found in both 6 and 7, return a response with a status code of 400 and an appropriate message like “Invalid user role”</li><li>Finally, return a response with a status code of 200 and the <strong><em>userSessions</em></strong> data.</li></ol><pre>function getAllSessions(req, res) {<br>    const userId = req.user.userId;<br>    const users = loadUsersFromFile();<br>    const sessions = loadSessionsFromFile();<br><br>    const user = users.find((user) =&gt; user.id === Number(userId));<br>    if (!user) {<br>      return res.status(404).json({ message: &quot;User not found&quot; });<br>    }<br>    <br>    const userRole = user.role;<br>    let userSessions = [];<br>    <br>    if (userRole === &#39;user&#39;) {<br>      // Get all sessions created by the mentee<br>      userSessions = sessions.filter((session) =&gt; session.menteeId === userId);<br>    } else if (userRole === &#39;mentor&#39;) {<br>      // Get all sessions where the mentor is involved<br>      userSessions = sessions.filter((session) =&gt; session.mentorId === userId);<br>    } else {<br>      return res.status(400).json({ message: &quot;Invalid user role&quot; });<br>    }<br>    <br>    return res.status(200).json({<br>      status: 200,<br>      data: userSessions,<br>    });<br>  }</pre><p>Don’t forget to export the functions in the session controller.</p><h3>Adding Authorization and Authentication Middleware.</h3><p>Now that we’ve completed the main logic of our API and set up controllers to handle requests, you might think that we can move straight to setting up the routes. But if you look at the specifications of this API, you will realize that some of the routes are protected. This means not everyone can access them.</p><p>For example, only authorised users can access anything in our API. Also, some actions are only reserved for specific roles. For example, only admins can promote users to mentors, while mentors are the ones who can accept or reject sessions. With middleware, the server can check if specific conditions are met before allowing the user to access the routes and perform requests. It acts as a gatekeeper for your routes, ensuring that only users who meet specific conditions can access certain endpoints.</p><p>You are going to have 4 middleware functions to check if the user is authenticated, is an admin, is a mentor, or is a mentee</p><p>To begin, create a middleware folder where you will define the functions to check user roles and authentication.</p><p>Let’s start with the middleware to check if a user is authenticated.</p><h4>Creating the isAuthenticated Middleware</h4><p>This <strong><em>isAuthenticated </em></strong>middleware ensures that only authenticated users can access any route in our API. This is very important because nobody should be able to perform actions without proving their identity.</p><ol><li>Create a file inside the <strong><em>middleware</em></strong> folder and name it <strong><em>isAuthenticated.js.</em></strong></li><li>Import <strong><em>jwt</em></strong> from <strong><em>jswebtoken</em></strong> since we need it to verify the token of the user.</li><li>Create an <strong><em>isAuthenticated</em></strong> function. The format for middleware functions is a bit different from the ones in our controllers. A middleware function has parameters <strong><em>req</em></strong>, <strong><em>res</em></strong>, and <strong><em>next.</em></strong> The <strong><em>next</em></strong> parameter is usually called at the end of the function to pass control to the next middleware once the current one is done executing.</li><li>In the <strong><em>isAuthenticated </em></strong>function, retrieve the token from the <strong><em>Authorization</em></strong> header. The token is usually sent as a Bearer token.</li><li>If no token is found, return a response with a status code of 403 and a message indicating unauthorized access</li><li>Proceed to verify the token with your secret key using <strong><em>jwt.verify()</em></strong>. If it is valid, add the decoded user data to <strong><em>req.user</em></strong> and call <strong><em>next()</em></strong> to proceed to the next middleware or route handler.</li></ol><p>Your code should look like this:</p><pre>// isAuthenticated.js<br>import jwt from &quot;jsonwebtoken&quot;;<br><br>function isAuthenticated(req, res, next){<br>    console.log(&#39;isAuthenticated called&#39;);<br>   const token = req.header(&#39;Authorization&#39;)?.replace(&#39;Bearer &#39;, &#39;&#39;)<br>   console.log(&#39;Token:&#39;, token);<br><br>   if(!token){<br>    return res.status(403).json({message: &quot;Unauthorized, no token&quot;})<br>   }<br><br>   jwt.verify(token,process.env.JWT_SECRET_KEY, (err, decoded)=&gt;{<br>    if(err){<br>        return res.status(401).json({message: &quot;Unauthorized, invalid token&quot;})<br>    }<br>    console.log(&#39;Decoded JWT:&#39;, decoded);<br>    req.user = decoded;<br>    next();<br>   } )<br>}<br><br>export default isAuthenticated</pre><h4><strong>Creating the isAdmin Middleware:</strong></h4><p>Here, we want to check if a user is not an admin. This is useful since there is a route that only an admin can access (the promote to mentor route)</p><ol><li>Create an <strong>isAdmin.js</strong> file inside the middleware folder.</li><li>Create an <strong><em>isAdmin</em></strong> function using the same format as the <strong><em>isAuthenticated</em></strong> function created earlier (pass in the same parameters)</li><li>In the <strong><em>isAdmin </em></strong>function, check if the role of the current user (<strong><em>req.user.role</em></strong>) is not ‘admin’. Return a response with a status code of 403 and an appropriate message.</li><li>Then call <strong><em>next()</em></strong> and close the function</li></ol><pre>function isAdmin(req, res, next){<br>    if(req.user.role !== &#39;admin&#39;){<br>        return res.status(403).json({message: &quot;Forbidden, admin access required&quot;})<br>    }<br>    next()<br>}<br><br>export default isAdmin;</pre><h4>Creating the isAdmin and isMentee Middleware:</h4><p>Using the same logic, try creating the <strong><em>isMentor</em></strong> middleware and <strong><em>isMentee</em></strong> middleware. For the <strong><em>isMentee</em></strong>, every regular user has the potential to be a mentee and can access certain routes. So, in the isMentee middleware, just check if the current user has a user role.</p><p>Your code should look like this:</p><pre>// isMentor.js<br>function isMentor(req, res, next){<br>    if(req.user.role !== &#39;mentor&#39;){<br>        return res.status(403).json({message: &#39;Only mentors can respond to session requests&#39;});<br>    }<br>    next();<br>}<br><br>export default isMentor</pre><pre>// isMentee<br>function isMentee(req, res, next){<br>    if(req.user.role !== &#39;user&#39;){<br>        return res.status(403).json({message: &#39;Only mentees (regular users) can request sessions&#39;});<br>    }<br>    next();<br>}<br>export default isMentee;</pre><h3>Creating the API Endpoints</h3><p>Now that you’ve built the controllers and middleware, you can move on to the endpoints. Endpoints are the doors through which users interact with your application.</p><p>First, create a <strong><em>routes</em></strong> folder to store all the API endpoint files. Inside the <strong><em>routes</em></strong> folder, you’ll organize the API endpoints into 4 main route files: These different files handle the routes available to the admin, authentication endpoints, mentor endpoints, and the session endpoint.</p><h4>Authentication endpoints</h4><ol><li>Create an <strong>authRoutes.js</strong> file inside the <strong>routes</strong> folder.</li><li>Import express and the authController created earlier inside the controller folder.</li><li>Set up an Express router.</li><li>You’ll have 2 routes here, one for sign up and another sign in.</li><li>Create a post endpoint for the route <strong><em>‘/signup’</em></strong> using the router and <strong><em>signup</em></strong> function defined in <strong><em>authController</em></strong>.</li><li>Do the same for sign up, except the route specified is <strong><em>‘/signin’</em></strong> and it uses the <strong><em>signin</em></strong> function from the <strong><em>authController</em></strong>.</li><li>Finally, export the router so you can use it in your app.js</li></ol><pre>import express from &quot;express&quot;;<br>const router = express.Router();<br>import authController from &quot;../controllers/authController&quot;;<br><br>router.post(&quot;/signup&quot;, authController.signup);<br><br>router.post(&quot;/signin&quot;, authController.signin);<br><br>export default router;</pre><h4>Creating Admin endpoints</h4><p>This is where you define the route for the <strong><em>promoteToMentor</em></strong> feature, which is only available to the admin.</p><ol><li>Create an <strong>adminRoutes.js</strong> file inside the routes folder.</li><li>Import <strong><em>express</em></strong>, <strong><em>promoteToMentor</em></strong> function from <strong>adminController</strong>, <strong><em>is Admin</em></strong> and <strong><em>isAuthenticated</em></strong> middleware.</li><li>Set up an Express router.</li><li>Next, create a <strong><em>patch</em></strong> endpoint at <strong>‘<em>/users/:userId/promoteToMentor’. </em></strong>You are using <strong><em>patch</em></strong> because this route updates an existing user.<strong><em> </em></strong>Apply the <strong><em>isAuthenticated</em></strong> and <strong><em>isAdmin</em></strong> middleware before calling <strong><em>promoteToMentor</em></strong> function.</li></ol><pre>import express from &quot;express&quot;;<br>const router = express.Router();<br>import promoteToMentor from &quot;../controllers/adminController.js&quot;;<br>import isAdmin from &quot;../middleware/isAdmin.js&quot;<br>import isAuthenticated from &quot;../middleware/isAuthenticated.js&quot;;<br><br>router.patch(<br>    &quot;/users/:userId/promoteToMentor&quot;,<br>    isAuthenticated,<br>    isAdmin,<br>    promoteToMentor<br>  );<br><br>export default router;</pre><h4>Creating the Mentor endpoints</h4><p>You need two endpoints: one to get all mentors, and another to get a specific mentor. Users must be authenticated before accessing these endpoints. You can use the isAuthenticated middleware for this. Try this out on your own.</p><pre>import express from &quot;express&quot;;<br>const router = express.Router();<br>import mentorController from &#39;../controllers/mentorController.js&#39;<br>import isAuthenticated from &quot;../middleware/isAuthenticated.js&quot;;<br><br>router.get(&#39;/mentors&#39;, isAuthenticated, mentorController.getAllMentors)<br>router.get(&#39;/mentors/:id&#39;, isAuthenticated, mentorController.getSpecificMentor)<br><br>export default router;</pre><h4>Creating the Session endpoints</h4><ol><li>Create a <strong>sessionRoutes.js</strong> file for session endpoints.</li><li>Import <strong><em>express</em></strong>, <strong><em>sessionController</em></strong>, <strong><em>isMentee</em></strong>, and <strong><em>isMentor</em></strong> middleware.</li><li>Set up an express router.</li><li>Create a <strong><em>post </em></strong>endpoint with the route <strong><em>‘/sessions’</em></strong>. Pass in the <strong><em>isMentee</em></strong> middleware and the <strong><em>createSession</em></strong> function from the <strong><em>sessionController.</em></strong></li><li>Create a <strong><em>patch</em></strong> endpoint for accepting sessions. You can use the route <strong><em>‘/sessions/:id/accept’.</em></strong> Ensure only mentors can access this route.</li><li>Create a <strong><em>patch</em></strong> endpoint for rejecting sessions. You can use the route <strong><em>‘/sessions/:id/reject’.</em></strong> Ensure only mentors can access this route.</li><li>Finally, create a <strong><em>patch</em></strong> endpoint for reviewing mentors. You can use the route <strong><em>‘/sessions/:id/review’</em></strong>. Ensure only mentees can access this route.</li></ol><pre>import express from &quot;express&quot;;<br>import sessionController from &#39;../controllers/sessionController.js&#39;<br>import isMentee from &quot;../middleware/isMentee.js&quot;;<br>import isMentor from &quot;../middleware/isMentor.js&quot;;<br>import isAuthenticated from &quot;../middleware/isAuthenticated.js&quot;;<br>const router = express.Router();<br><br>router.post(&#39;/sessions&#39;, isAuthenticated, isMentee, sessionController.createSession)<br>router.patch(&#39;/sessions/:id/accept&#39;, isAuthenticated, isMentor, sessionController.acceptSession)<br>router.patch(&#39;/sessions/:id/reject&#39;, isAuthenticated, isMentor, sessionController.rejectSession)<br>router.patch(&#39;/sessions/:id/review&#39;, isAuthenticated, isMentee, sessionController.reviewSession)<br><br>export default router;</pre><h3><strong>Populate app.js with the endpoints</strong></h3><p>Remember your app.js from the first section. You’ll want to populate the app.js with the endpoint you defined ealier.</p><p>First, import the routes defined earlier: <strong><em>authRoutes</em></strong>, <strong><em>adminRoutes</em></strong>, <strong><em>mentorRoutes</em></strong>, <strong><em>sessionRoutes. </em></strong>Then, register these routes with the express app using<strong><em> app.use.</em></strong></p><pre>// app.js<br>import express from &#39;express&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>import authRoutes from &#39;./routes/authRoutes.js&#39;<br>import adminRoutes from &#39;./routes/adminRoutes.js&#39;<br>import mentorRoutes from &#39;./routes/mentorRoutes.js&#39;<br>import sessionRoutes from &#39;./routes/sessionRoutes.js&#39;<br><br>dotenv.config(); //load environmental variables from a .env file into process.env<br><br>const app = express();<br>app.use(express.json());<br><br>app.get(&#39;/&#39;,(req,res) =&gt; {<br>  res.send(&#39;Welcome&#39;)<br>})<br><br>app.use(&quot;/api/auth&quot;, authRoutes)<br>app.use(&quot;/api/&quot;, adminRoutes)<br>app.use(&quot;/api/&quot;, mentorRoutes)<br>app.use(&quot;/api/&quot;, sessionRoutes)<br><br>export default app;</pre><p>You can now proceed to test your API with Postman, Swagger, or any tool of your choice</p><h3>Conclusion</h3><p>Congratulations! Your mentorship API can now handle authentication, admin features, mentor listings, and session management, all without a database.</p><p>We used arrays for in-memory storage in this project. However, in terms of performance, constantly searching through long arrays isn’t the most efficient.</p><p>You could also experiment with objects, maps, or sets for faster lookups and better performance.</p><p>This project gives you a strong foundation for building more complex APIs in the future!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aff4de85373" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four Approaches to Solve “LeetCode 217: Contains Duplicate”]]></title>
            <link>https://medium.com/@toye.adedamola/four-approaches-to-solve-leetcode-217-contains-duplicate-5a76ae794fc5?source=rss-d7bb4ead0f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a76ae794fc5</guid>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Toye Adedamola]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 07:58:41 GMT</pubDate>
            <atom:updated>2024-09-17T07:58:41.569Z</atom:updated>
            <content:encoded><![CDATA[<p>Solving Leetcode problems can be very challenging, but the satisfaction that comes with seeing your solution get accepted is like no other. However, the journey doesn’t end there, optimizing your solution is also important.</p><p>I recently attempted to solve LeetCode 217: ‘Contains Duplicate’. This involves checking if an array contains duplicate elements.</p><p>I would like to share my approach and the lessons I learnt while searching for better solutions.</p><h3>💡My Initial Approach (Using a dictionary)</h3><p>My first approach to solving this problem was using a dictionary. I stored each element in the array as the key with a value of 1. Since dictionaries in Python do not contain duplicate values, a duplicate cannot be stored again. I noticed that if I created a dictionary from the array [1, 2, 3, 1] by setting the keys as the elements in the array and the value (which represents the occurrence) as 1, the dictionary only stored the first 3 elements and not the second 1. i.e. {“1”: 1, “2”: 1, “3”: 1}. With this, we can say that if there are duplicates, the length of the dictionary will be less than the length of the array since the duplicate isn’t stored in the dictionary. In the example above, the array’s length is 4, while the length of the dictionary is 3. However, if there is no duplicate, the length of the dictionary and the length of the array would be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnblFPQZvkCLjCGF_NYnUw.png" /></figure><p>This approach worked, it had a time complexity of O(n) and a space complexity of O(n), but it could be better in terms of clarity and performance.</p><h3>Exploring Other Approaches</h3><p>💡The first approach is to compare each element with the element in the rest of the array (excluding the element we are comparing it with).</p><p>This sounds confusing, right? Let’s take a look at the earlier example [1, 2, 3, 1].</p><p>This approach just means: compare 1 with the rest of the array [2, 3, 1] to see if it is equal to any element in the rest of the array; compare 2 with the rest of the array [3, 1], and so on. If when comparing you meet that element again, then that element has a duplicate, and this means the whole array contains a duplicate.</p><p>You may have noticed by now that this approach requires two ‘for loops’. The first one is to loop through the array, and the second is to loop through from the particular element to the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*p8H02sB1aKCf55mMXU3gAA.png" /></figure><p>The time complexity here would be O(n²), which is quite high. It will likely result in a “Time Limit Exceeded” error and won’t pass the tests.</p><p>💡Another approach could be to sort the array so that each element and its duplicate will be adjacent. This way we can just compare each element with the element beside it. If they are equal, the array contains a duplicate. Using the same example [1, 2, 3, 1], after sorting it becomes [1, 1, 2, 3]. Then we compare two adjacent elements, and we can clearly see that 1 has a duplicate. Since we are only comparing adjacent elements, this approach requires one ‘for loop’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*4bweteynP_YgnSGpdmS49Q.png" /></figure><p>This takes less time than the earlier approach. The time complexity here would be O(nlogn) due to sorting. The space complexity is O(1) since we aren’t creating any new variables. But this method could still be better.</p><p>Usually, there would be a tradeoff between space and time. The approach above uses less space but a bit more time. What if we want to prioritize time over space?</p><p>💡Then I came across the best approach: Using a HashSet.</p><p>What is a HashSet?</p><p>A hashset is a data structure that stores unique elements (i.e., it doesn’t allow duplicates). It is known as a set in Python. At first, I was confused because I’d heard of hashmap but not of HashSet. The difference is a hashmap is a data structure that contains key-value pairs where each key is unique but values can be duplicated. In this approach, for each element in the array, we first check if it already exists in the HashSet. If it exists already, we know the array has duplicates. Otherwise, we can add the element to the HashSet. Since we are only going through the array once to add to the HashSet, we only need one ‘for loop’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeIFxZsZJFW8cyR4-2RpOg.png" /></figure><p>The time complexity here is O(n) which is the low and the space complexity is O(n) since we are creating a set with the size of the input array.</p><p>You may be wondering why the HashSet method is better than my first approach of using a dictionary, even though they both have the same time and space complexity. The HashSet method has less overhead (uses fewer computer resources) because it only stores keys, unlike the dictionary approach that stores keys and values. Also, the HashSet approach is more straightforward and easier to understand.</p><p>Although my first approach of using a dictionary was correct, seeking a more efficient method that uses fewer resources is also essential. By exploring different methods and learning from others’ solutions, I found a more efficient approach to solving the problem while balancing time and space complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a76ae794fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Programming]]></title>
            <link>https://medium.com/@toye.adedamola/object-oriented-programming-9e763d75b4c7?source=rss-d7bb4ead0f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e763d75b4c7</guid>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[programming-paradigms]]></category>
            <dc:creator><![CDATA[Toye Adedamola]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 22:22:44 GMT</pubDate>
            <atom:updated>2024-08-11T22:22:44.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*O3K0_zvHUQf9kIp6_CFI9A.jpeg" /></figure><p>Object Oriented Programming (OOP) is a programming paradigm where properties and behaviours are grouped under one entity. It is a programming style built around objects. The objects here aren’t some abstract complex term but can be related to actual objects around us.</p><p>Take a car for an example, a car is an object and it has properties as well as behaviours that make it known to be a car. Some examples of these properties can be its colour, its brand, 4 wheels, a steering wheel etc. Its behaviour could include the ability to move, to reverse, to turn left or right etc.</p><p>What makes up OOP and what are the key things to know about it</p><h3>Fundamental Components Of Object Oriented Programming</h3><h3>Classes</h3><p>Classes are blueprints or templates for creating objects. A class houses the attributes and behaviours from which an object will be created. You can think of classes as a blueprint for a house. Different houses can be built using the same blueprint design but with different characteristics like colour, number of rooms, etc. With a class, you can create many objects with each object having its unique properties. Classes help in code reusability which is one of the benefits of OOP. Imagine you have to draw the blueprint for a house every single time you want to build a house when you can just create a template to follow.</p><h3>Objects</h3><p>An object is an instance (or creation) of a class. There are many objects around us like a table, a chair, a bag, a watch. In fact, the laptop I am using to type this is an object. A Ferrari car is an object (instance) of a car class that has all the attributes and behaviour of a car. Likewise, your table is an instance of a “Table “ class which contains all the properties and behaviours of a table.</p><h3>Attributes</h3><p>Attributes are the properties of an object. They are the characteristics that define an object. Attributes are also sometimes called states. If you think of an object as a noun, then attributes are like the adjectives that describe the noun. For example, a watch has attributes like colour, size, brand etc.</p><h3>Methods</h3><p>A method is like a task or action an object performs. Methods are behaviours of an object. If we look at an object as a noun, a method can be seen as a verb that describes the actions an object can perform. For example, a watch performs some actions like displaying the time, setting the time, starting a stopwatch countdown etc.</p><p>To understand Object Oriented Programming better, there are some concepts you need to know</p><h3>Fundamental Concepts in OOP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DHt6oHW2_xMHshPcNcVNCg.jpeg" /></figure><h3>Encapsulation</h3><p>Encapsulation is the bundling of data and the methods operating on that data into one unit. It is used to hide the data (or attributes) in a single entity along with its methods to protect information from external access. With encapsulation, direct access to some of the object’s components (attributes and methods) is limited.</p><p>For example in a watch, a random user will not know the details of the inner workings of the watch to display the time. All the user knows is that the watch displays the time whenever he or she needs it to. The internal mechanism of the watch is hidden from the user. This protects the watch’s inner mechanism from outside misuse and manipulation. Suppose a new brand of watch changes the mechanism behind how the watch displays the time, it is none of the user’s business as far as the watch displays the time correctly.</p><p>Encapsulation ensures that users do not have to know the workings of the class before they can create objects from it. Also, it’s easy to modify the class without affecting how it is used.</p><p>A class has all the methods defined in it and whenever we want to call that method on an object created from the class, we do not have to know the nitty-gritty of how that method works and its inner details.</p><p>A perfect example is when we use the ‘print()’ method in Python. Whenever we call this method, we do not need to worry about how the print method works. We just call the print method, pass in a string and it displays it.</p><h3>Abstraction</h3><p>Abstraction in OOP involves displaying only necessary information to the users and hiding unnecessary information. By exposing only essential details, abstraction simplifies complex programs for the user.</p><p>Abstraction and encapsulation are similar concepts. The goal of abstraction is to simplify complex systems. Encapsulation on the other hand hides internal state and implementation and restricts random access.</p><h3>Inheritance</h3><p>Inheritance is a concept that enables a class to inherit attributes and behaviours from another class (usually called the <strong><em>parent class</em></strong>). The class inherited from the parent class is called the<em> </em><strong><em>subclass</em></strong>.</p><p>It is similar to us as humans inheriting properties from our parents. As a child, we inherit attributes from our parents while having our unique properties and behaviours.</p><p>Inheritance enhances code reusability since you don’t have to redefine the same attributes and methods every single time.</p><p>For example in our watch analogy, we can have a subclass called a ‘Smartwatch’ which inherits properties and behaviours from the parent class- ‘Watch’. It can inherit attributes and methods such as displaying time, setting time, size, colour etc. but the ‘Smartwatch’ will have added behaviours like internet connectivity.</p><p>Another example is a subclass ‘Convertible’ that inherits properties and behaviours from an ‘Automobile’ class. One of its added features will be a retractable roof.</p><p>A subclass can also override properties inherited from the parent class.</p><h3>Polymorphism</h3><p>Polymorphism is a word derived from Greek meaning “having multiple forms”. Polymorphism is the ability of different objects to respond to a method call in different ways. Different classes can have the same method name but different implementation details. Just like how humans can walk but people walk differently.</p><p>There are 2 main types of polymorphism: Method overloading and Method overriding.</p><p>Method overloading occurs when a class has multiple methods with the same method name but different parameter lists (the parameters list specifies the number, type and order of parameters the method can accept). The method that gets called depends on the number and type of argument passed.</p><p>Method overriding allows a subclass to have a new implementation of a method inherited from the parent class. The method must have the same name, parameters and return type as the one in the parent class.</p><p>Polymorphism allows for more flexibility in OOP.</p><p>In conclusion, OOP isn’t some complex computer science term, it is something we see in our everyday life. Some object-oriented languages include Python, Java, C#, Ruby, C++ etc. The applications of object-oriented programming vary. In game development, for example, characters and weapons can be represented as objects</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e763d75b4c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP AND ITS ROLE IN HOW THE WEB WORKS]]></title>
            <link>https://medium.com/@toye.adedamola/http-and-its-role-in-how-the-web-works-2bbc3c73a944?source=rss-d7bb4ead0f86------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bbc3c73a944</guid>
            <category><![CDATA[dns-servers]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[internet-protocol]]></category>
            <dc:creator><![CDATA[Toye Adedamola]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 18:29:18 GMT</pubDate>
            <atom:updated>2024-04-17T18:29:18.350Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time I came across the acronym HTTP was in secondary school. Data processing was a compulsory subject at my school and we were just taught the meaning of some abbreviated protocols like FTP, SMTP, HTTP, etc. At that point I didn’t know how important this was and its role in how the web works.</p><p>Years later, I encountered this term in Coursera&#39;s Meta Frontend Developer Certificate course. There was a section dedicated to how the web works and what goes on when we search for something on the internet but then I didn’t fully understand the relevance. I thought: “What’s the point of learning this if I can write the code for the website”</p><p>It wasn’t until the first day of the Hatchdev training organized by Nithub and Moniepoint that I understood how important this was. It’s not enough to just know how to write the code for the website to work. Understanding what goes on behind the scenes is just as crucial. A software engineer who understands how the web works will be able to optimize the website to tackle traffic, easily handle errors, and debug problems that improve overall performance.</p><p>To understand HTTP and how the web works there are some terms you need to know:</p><ul><li><strong>CLIENT</strong>: A client is any computer that requests access to information from the server</li><li><strong>SERVER</strong>: A server is a computer that provides the information requested by the client. It stores webpages or websites.</li><li><strong>DNS</strong> : Domain Name System is like an address book or a phone book of the internet which contains web address and their corresponding IP addresses. DNS helps to find the IP address of the domain name you entered (the normal web address you type into the browser e.g. <a href="http://www.youtube.com/">www.youtube.com</a>). The whole point of the DNS is to find the server the web address entered resides on.</li><li><strong>TCP/IP</strong>: Transmission Control Protocol or Internet Protocol is a communication protocol that defines how data travels across the Internet. You can think of TCP as a transport system that lets you move around.</li></ul><h4>WHAT IS HTTP?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*a7qEzlp5c1HJCSK9BhfxMg.png" /><figcaption>source: freeCodeCamp.com</figcaption></figure><p>HTTP is a protocol that allows the client and server to communicate with each other. For this communication to happen, the client and the server need to be connected via the Internet. HTTP relies on TCP which is connection-based.</p><p>HTTP was originally used to retrieve html files from the server but it evolved over the years to retrieve videos, images, etc.</p><p>HTTP is connectionless in the sense that after a request is sent by the client, the client disconnects from the server. When the server wants to send a response back to the client, a connection is re-established (the client and the server connect again) but after the response is sent, they disconnect.</p><p>HTTP is also stateless which means that the client and server know information about each other just during the current request. When the request is completed, both the client and the server forget any information about each other. If they both want to connect again, they need to provide information about each other making this connection act like the first one.</p><h4>WHAT EXACTLY HAPPENS WHEN YOU SEARCH FOR A WEBSITE ON YOUR DEVICE AND WHAT IS THE ROLE OF HTTP IN THIS??</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*47gdQSI4sDi8RPHZHH-nQg.png" /><figcaption>source: academind.com</figcaption></figure><p>When you type a web address like <a href="http://www.google.com/">www.google.com</a> in your browser, the browser goes to the DNS server and looks up the IP address of the website you are searching. This IP address is the real address of the server the website resides in.</p><p>The browser which acts like a client here sends an HTTP request message to the server. This message is basically asking the server to send a copy of the website to the client(the browser). This HTTP request message is sent to the server using TCP/IP.</p><p>If the website exists and there is no error, the server approves this request from the client and sends an HTTP response back to the client. The server sends the website’s files to the browser (client) in small chunks called <a href="https://www.cloudflare.com/learning/network-layer/what-is-a-packet/#:~:text=In%20networking%2C%20a%20packet%20is,or%20device%20that%20receives%20them.">packets</a>.</p><p>Then the browser assembles the small chunks and displays them to you as a complete web page.</p><p>Just like that, you can see the content of the website you searched. It&#39;s so fascinating that all of this has to go on behind the scenes before you can search something as simple as www.google.com</p><p>I hope you understand the role of HTTP in how the web works just like I have!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bbc3c73a944" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>