<?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 Elijah Banjo on Medium]]></title>
        <description><![CDATA[Stories by Elijah Banjo on Medium]]></description>
        <link>https://medium.com/@elijahbanjo?source=rss-19845d95a1e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5OdpE13nk8qxbIUn</url>
            <title>Stories by Elijah Banjo on Medium</title>
            <link>https://medium.com/@elijahbanjo?source=rss-19845d95a1e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:27:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elijahbanjo/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[What are MCPs?… Why are they important]]></title>
            <link>https://medium.com/@elijahbanjo/what-are-mcps-why-are-they-important-5f693c98137b?source=rss-19845d95a1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f693c98137b</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Elijah Banjo]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 21:39:06 GMT</pubDate>
            <atom:updated>2026-07-20T17:24:44.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIgKlPz2ryD7JSuq4DpPPg.png" /><figcaption>MCPs Illustration</figcaption></figure><p>There’s almost no way, as a developer, you haven’t seen the word “MCP” somewhere. You try to use Supabase, or Figma, or some other application, and the next thing you know, they’ve got an MCP. And you’re sitting there wondering: what exactly do you mean by MCP? How is this even meant to help me? It’s one of those words you see and just vibe along with, nodding, “yeah, MCPs”, while deep down you know nothing about what it actually means. Lol. So in this brief article, I’ll try to explain it in clear, simple terms.</p><p>I recently had to build a landing page for an app I had built. I was provided with a Figma design, and then Claude told me the best approach would be to use Figma’s MCP. So I connected it, and boom, in a moment, the page was built without me writing a single line of code.</p><p>So what exactly is this thing, and why is it such a game-changer in this age of AI?</p><h4><strong>How backends traditionally work</strong></h4><p>Traditionally, when you build an API layer, you already know exactly what it’s for. A client asks for something specific (say, a list of products), and your service or repository goes and gets exactly that, maybe with something like SELECT * FROM products, or productRepository.find() if you’re using an ORM. You define the endpoint around one known, fixed purpose, and that’s it. You don’t leave it open-ended.</p><p>That’s the whole game with traditional APIs: the client already knows what it wants, and you build narrowly for that specific want. The client’s intent is known ahead of time, by you, the developer, before you ever write the endpoint.</p><h4><strong>What changed with AI</strong></h4><p>Now, in this age of AI, humans are no longer the only ones accessing your app. AI agents need to interact with it too. So the natural question is: why not just let AIs use APIs, the same way humans’ clients do?</p><p>The problem is that APIs are designed for a specific, known use case. When you build an endpoint, you already know what it’s for; you’re not going to change its purpose later. But with AI agents, you often don’t know in advance what they’ll need to do with your app. So instead of building one more rigid, narrow-purpose endpoint, the idea behind MCP is to make broader parts of your application available for an AI to explore and use however it needs to.</p><h4><strong>So… what are they?</strong></h4><p>For a proper definition: MCP (Model Context Protocol) is an open standard, introduced by Anthropic, that defines a common way for AI applications (like Claude) to connect to external tools, data sources, and systems, a protocol, a standard every agent follows, in order to access MCP-enabled applications. It’s not a specific product or a specific integration; anyone can build to it.</p><p>Concretely, it works as client and server: your application (or a service like Figma or Render) exposes an “MCP server,” and an AI application like Claude acts as the “MCP client” that connects to it. The server defines what’s available; the client (the AI) discovers and uses it.</p><p>On the server side, that standard is built around a few core pieces: Tools it can invoke, Resources it can read, and Prompts it can reuse, so it never has to guess how to approach a common task. The client side, the AI application itself, has its own piece too: Roots, which define the boundaries of what a server is allowed to access. Any agent that understands MCP already understands these pieces, which is what makes it plug-and-play instead of custom integration work every time.</p><p>MCP also helps with security: the agent still touches your data, but only indirectly: the MCP server is the only thing that ever talks to the database directly, exposing just the specific capabilities you’ve defined. It doesn’t get to run its own queries or see your schema; it just interacts with the interface you’ve built, and the server does the real work on its behalf, and you can abstract the MCP as much as possible so the agent has limited knowledge of your internal implementation.</p><p>All of this sits on top of your existing APIs: MCP doesn’t replace them, it wraps them in this standard, discoverable interface that any AI agent can connect to and understand. The key shift from a normal API: instead of deciding up front exactly what a client can do, you expose a broader range of what’s available, tools, resources, data, and let the AI agent decide, based on context, what it actually wants to do with them.</p><p>Once an agent connects to your application via MCP, it discovers the capabilities you’ve exposed and reasons over them to figure out how to achieve a given task, instead of you having to hard-code every possible thing it might want to do.</p><h4><strong>A real example: Figma and Claude</strong></h4><p>Let me back up and tell that landing page story in full, because it’s the clearest way to see what MCP actually changes.</p><p>When I’m designing a frontend (specifically the UI and styling side of things), what I’d do is take a screenshot, feed it to an agent, and then go back and forth: pointing out what it missed, zooming into a specific detail, explicitly explaining what I meant. Because I have the eyes for it, and the agent, working off a flat screenshot, just can’t see it as precisely as I do.</p><p>But, and this is worth learning as a separate lesson about using AI well, the first thing I did this time was tell the AI agent what I wanted to achieve and ask it for the best possible way to do it. It suggested using Figma’s MCP.</p><p>This is a good habit in general: AI is a prediction engine, and the quality of what you get back depends heavily on the context you give it. So it’s often worth asking the AI itself for the best approach, rather than limiting it to only the approach you already know. Don’t box the AI in; feed it more context and let it suggest the path, especially when you’re dealing with something new. In this case, it told me the right tool for the job was an MCP.</p><p>So I checked, then set up the Figma MCP to run locally, and connected Claude to it, and boom. It exposed the design data once I authenticated, and now Claude could access the actual design directly, no more screenshots. It went through the design stage by stage, broke the work into a plan, and executed it.</p><p>The result was almost 100% done, basically a one-shot implementation. It was almost perfect.</p><p>MCP basically gave the agent the same eyes I have. Instead of me being the middleman (translating what I see in the design into something the agent can act on), it could just see the design itself, the same way I do.</p><h4><strong>more whysss</strong></h4><p>That Figma experience was me on the consuming side, using someone else’s MCP. But it’s also what got me thinking about the other side, building one for my own application, so agents, and the people using them, could do more with it than I’d originally planned for.</p><p>Render is a platform that allows you to deploy applications. They have an MCP server that exposes deployment logs, service performance metrics (CPU, memory, request latency), and even read-only access to your Postgres database. Normally, you’d have to log into the Render dashboard yourself to check any of this. But with their MCP server connected, you could ask your agent to build a custom dashboard that monitors your app’s deployment stats, flags a spike in error logs, or tracks resource usage over time, all without Render having had to predict that specific dashboard and build an API for it. They just expose the underlying capabilities, and your agent assembles them into whatever you actually need.</p><p>Here’s the core of it: as a developer, you might assume your customers want feature “ABC.” But they might actually want “XYZ.” If you only ever build fixed APIs, your users are limited to exactly what you thought to give them. MCP flips that: it doesn’t limit the agent (or the user behind it) to only what you predefined. It exposes the possibilities of your application and lets the agent decide what to build or do with them, the same way Render’s MCP leaves the dashboard decision to you, instead of Render having to guess what you’d want.</p><p>So instead of a user dashboard that only shows the handful of views you designed, a user could ask their agent for a completely custom view, and the agent, because it can see what’s actually possible in your application, can build it. That changes the whole game: from “here are the fixed things you can do with my app” to “here’s what my app can do, figure out what you need.”</p><p>And because MCP is a standard, this isn’t just about your one app talking to your one agent. Any AI agent that understands MCP can connect to any application that exposes one, using the same protocol. That’s what makes it a genuine shift, not just a convenience feature.</p><h4><strong>…in conclusion</strong></h4><p>MCP isn’t just “APIs for AI.” It’s a shift in mindset: from building for a specific, known use case, to exposing possibilities and letting the AI, guided by context, figure out what to do with them. It’s also a safer way to let AI agents interact with your application, since they never get direct access to your database or internals, only the interface you choose to expose, with your MCP server doing the real work behind the scenes.</p><p>If you’re building anything AI agents might touch, this is the boundary worth understanding: what you predefine versus what you make possible.</p><p>Thank you for reading. Now you understand what MCPs are and why they are important. In my next article, we’ll be building an actual MCP, keep an eye out for that. I would appreciate your thoughts in the comments</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f693c98137b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying IPv4/IPv6: Solving a Real-World Prisma + Supabase Error]]></title>
            <link>https://medium.com/@elijahbanjo/demystifying-ipv4-ipv6-solving-a-real-world-prisma-supabase-error-f603f793ffa2?source=rss-19845d95a1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f603f793ffa2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ipv4]]></category>
            <category><![CDATA[ipv6]]></category>
            <dc:creator><![CDATA[Elijah Banjo]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 13:42:40 GMT</pubDate>
            <atom:updated>2025-06-27T14:54:18.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSwVTELtiYacG_yOcx_yOw.png" /><figcaption>An image that depicts IPv4, IPv6, Postgres, SupaBase, Prisma, NestJS and the Internet</figcaption></figure><p>This was one of the days my paying attention during university classes came through for me. While trying to connect to my Postgres DB hosted on <strong>SupaBase</strong>, I kept getting this error:</p><blockquote><em>PrismaClientInitializationError: Can&#39;t reach database server at...</em></blockquote><p>I did my basic checks, and it still wasn’t working. I was initially using the <strong>Direct Connection</strong> URI, then I noticed this message right beside it:</p><blockquote><em>“Not IPv4 compatible. Use Session Pooler if on an IPv4 network or purchase IPv4 add-on.”</em></blockquote><p>Supabase offers three connection options:</p><ul><li><strong>Direct Connection:</strong> Ideal for persistent connections (e.g., virtual machines or long-running containers).</li><li><strong>Transaction Pooler:</strong> Best for stateless applications like serverless functions.</li><li><strong>Session Pooler:</strong> Recommended only as an alternative to Direct Connection for IPv4 networks.</li></ul><p>While <strong>Prisma</strong> benefits from or works best with persistent connections, it doesn’t strictly require them in the same way a stateful application might. It can work with connection pooling, but the Direct Connection is indeed optimal for performance. I then switched to the <strong>Session Pooler</strong> URI since it supported IPv4, and voila! I stopped getting that error.</p><h3>What actually happened?</h3><p>What are <strong>IPv4</strong> and <strong>IPv6</strong>? At their core, they are network addresses that allow devices to connect to the internet. Back in my university days, we were taught about network protocols. Network protocols are simply rules that guide communication on a network, meaning each network has its own set of rules for engagement, called protocols.</p><p>Now, in connecting to the internet (a type of network), two of the ways we can connect/engage with this network (protocols) are the <strong>IPv4</strong> and <strong>IPv6</strong>. Both protocols provide clients/connected devices with an address, just like a school provides its students with an ID card. So, when you connect to the internet, it needs to know where the connection is coming from. This is your address, and it’s usually a set of numbers.</p><p>However, since IPv4 and IPv6 are different protocols, both assign addresses differently.</p><ul><li><strong>IPv4</strong> uses a format like 192.168.1.10—four numbers separated by dots, with each number ranging from 0-255 (32 bits in total).</li><li><strong>IPv6</strong> uses a format like 2001:0db8:85a3:0000:0000:8a2e:0370:7334—eight groups of four hexadecimal digits separated by colons (128 bits in total).</li></ul><p>When you try to connect to the internet, your ISP (MTN, Airtel, Starlink, etc.) provides you with an IP address with which you can communicate with other devices on the internet. However, not all ISPs(Internet Service providers) provide <strong>dual-stack</strong> connectivity (i.e., providing you with both an IPv4 and IPv6 address). If you need to communicate with a device/service that uses an IPv4 address, you can use your IPv4 address to initiate that communication; the same goes with IPv6.</p><p>However, when you try to communicate with a device/service that uses a different protocol (e.g., an IPv4 client trying to connect to an IPv6 server). Their rules of engagement are different, hence they can’t interact directly. Just like in maths when you try to add two numbers in different base systems without conversion, e.g., binary with a decimal (00111000 base2 + 7892732 base 10), you cannot directly perform that addition because they operate in different ways, or trying to send Naira directly to a Dollar account; the transfer will simply fail., or finally, trying to use your University ID Card to write an exam in a different University — they are not compatible.</p><h3>How do we make IPv4 and IPv6 Communicate?</h3><p>To bridge this gap, a few solutions exist:</p><ol><li><strong>NAT64 /DNS64 :</strong> These are proxy systems that allow IPv6 only clients to access IPv4-only servers. The communication here is handled via proxy (like a middleman, what happens here is that the request is translated or forwarded to the required source). NAT64 handles the actual network translation, while DNS64 synthesizes DNS records to make it possible. <em>DNS - Domain Name System. NAT - Network Address Translation</em></li><li><strong>Tunneling </strong>(e.g., 6to4, Teredo)<strong>:</strong> This allows IPv6 traffic to be sent over IPv4-only networks by encapsulating IPv6 packets inside IPv4. It doesn’t convert protocols but enables IPv6 connectivity where native IPv6 isn’t available. Basically, it wraps one protocol inside another — a process called encapsulation. It carries traffic over an unsupported network. Think of it like an event that requires a specific dress to be worn, instead of denying someone access because of the “dress” being put on, give the person the required “dress” and the person doesn’t have to take off the former “dress”, the person just wears this over it.</li><li><strong>Dual-Stack:</strong> This is the most straightforward solution where the server or service you’re accessing has both an IPv4 and an IPv6 address. This allows clients to connect using whichever protocol they support, Just like if you want to send naira to a person who has both a dollar and naira account, you just ask for the naira account and send it.</li></ol><p>So, that’s why I couldn’t connect to the Supabase Direct Connection — I was using an IPv4 address provided by my ISP, while the service was waiting for a connection on an IPv6 address.</p><p>It’s a powerful reminder that as developers, understanding the network layers beneath our applications isn’t just academic; it’s a critical skill for debugging real-world problems. The next time you hit a mysterious connection error, it might be worth checking the protocol!</p><p>Thank you for reading. Feel free to share your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f603f793ffa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding GraphQL APIs from a REST API point of view]]></title>
            <link>https://medium.com/@elijahbanjo/understanding-graphql-apis-from-a-rest-api-point-of-view-08196600c667?source=rss-19845d95a1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/08196600c667</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Elijah Banjo]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 17:25:45 GMT</pubDate>
            <atom:updated>2023-12-15T18:16:05.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="An image depicting transitioning from Rest API to GraphQL API" src="https://cdn-images-1.medium.com/max/1024/1*a-dIwIJsosdy_zn4II0hrQ.png" /></figure><p>I had a take-home assessment for a role. The instructions were quite confusing and even after I sent a mail requesting clarity there was none. Even If I didn’t understand anything about the assessment, I did understand something, I had to develop a GraphQL API, which then was a challenge as all my previous APIs have all been RESTFul APIs. Although I understood a bit of how GraphQL APIs worked, I did not know how to implement it. Luckily, I was able to find a blog post series that explained it and I was able to complete the assessment. Interestingly, from the feedback I got, I was told I did well, but sadly I didn’t end up landing the role because I didn&#39;t meet some “criteria”. So I said, I’ll milk this learning experience and write about GraphQL so that people can understand it which is why I am writing this post. Enjoy!</p><p>I am assuming you already know REST APIs, a bit of javascript and you are familiar and comfortable with them. Even if you don&#39;t, just read along, I’m sure you’ll get a thing or more. I’ll go right into it. In RESTFul API there are primarily 4 types of requests: CREATE[POST], RETRIVE[GET], UPDATE[PUT/PATCH], and DELETE. Although there are variants to this, any variant can still be traced back to these 4. In GraphQL we only have two types of requests: Queries and Mutations. I’m sure you must be wondering how to post, update, get, and delete. Let’s touch on Queries first.</p><p>In REST APIs you have a defined set of data to send anytime a GET request is made. Let’s say I make a GET request to a User API, there’s already a predefined set of data that would be sent and this will always be sent irrespective of how many times you make the request. However, in GraphQL, you can specify the parts of the data you want. If in a REST API scenario, the User API sends the name, email, ID, password, and age of a user on every get request, in a GraphQL API we can decide that we only want the name and email. To do this, in our request, we specify this in a query. This query specifies exactly what we want from the server and only the content of our query gets sent to us. So as compared to a REST API GET request, a GraphQL query would look something like this</p><figure><img alt="An image that shows a sample GraphQL Query" src="https://cdn-images-1.medium.com/max/1024/1*5aqqX45d5eN_EP8TcjD8Dw.png" /><figcaption>GraphQL Query</figcaption></figure><p>In the image above you see on the right-hand side we have a query for users that returns an array of users. So we then specify the attributes of users that we want to get. The GraphQL model is already predefined so if you’re using a tool like Postman, it already knows the schema/attributes of the data you are requesting and will provide you with an option to select what attributes of the data you want to retrieve(as shown on the left side of this image). This specification of what we want is what is referred to as our query as shown on the right side of the image.</p><p>We specify what exactly we want and get our results. A sample result would look like this</p><figure><img alt="An image that shows the result of a GraphQL Query" src="https://cdn-images-1.medium.com/max/1024/1*6mGADsEtBsAU_pbm4_5EQQ.png" /><figcaption>GraphQL Query Result</figcaption></figure><p>This is what is called Queries in GraphQL. The way this works behind the scenes is that in our code we define what parameter users can get/request in our model/schema and then write functions to handle how we get the entire data. In essence, we explicitly specify the parts/attributes of the data we return. This specification gives our GraphQL server the power to return a specific part of the requested data.</p><p>To do this in Javascript we can have a model. I’m using mongoose, you can use any one. Mine looks like this</p><pre>const userSchema = new Schema({<br>   name: {<br>       type: String,<br>       required: true,<br>       index: {unique: true}<br>   },<br>   email: {<br>       type: String,<br>       required: true,<br>       index: {unique: true}<br>   },<br>   password: {<br>      type: String,<br>      required: true<br>  },<br>  number: {<br>   type: Number,<br>   required: true<br>}<br>},<br>{<br>   timestamps: true<br>});</pre><p>Then we can have a query resolver/handler that determines how we get data when a query is made. It would look like this</p><pre>const userModel = require(&#39;../model&#39;)<br><br><br>module.exports = {<br>    user: async () =&gt; {<br>        return await userModel.User.find()<br>    },<br>    useraccount: async (parent, args) =&gt; {<br>        return await userModel.User.findById(args.id)<br>    }  <br>};</pre><p>Next, we can have a GraphQL-type definition that we would use when we start our GraphQL server. It would look like this</p><pre>const { gql} = require(&#39;apollo-server-express&#39;)<br><br>module.exports = gql`<br>type User {<br>    id: ID!<br>    email: String!<br>    password: String!<br>    name: String!<br>    number: String!<br>    <br>}<br><br>type Query {<br>    user: [User!]!,<br>    useraccount(id: ID!): User!<br>}`</pre><p>Here we have a Query type. This refers to the kind of things we can make queries for. In the postman image above I have already done a query request for user (that gets all users) and the data returned is with the type of User(i.e. every item in the user list would look like the data we defined in `type User`]. We could also have a query for getting a singular user as shown in `Query useraccount`. This returns a single user as opposed to `Query user` that returns an array of users, this returns just one user with the data type of User.</p><p>The method that handles the processing for `Query user` and `Query useraccount` is already in the query resolver code just before this. That is how our Query resolver works.</p><p>That concludes the first concept in GraphQL: Queries</p><p>Just a recap. Instead of giving the user all the data, they can ask for specific kinds of data called queries and we write functions that handle these queries and explicitly define the attributes of the data being returned so that our GraphQL Server can know which part of the data to return. If the query asks for a User name, we already defined User name in our GraphQL User type so it just returns that specific attribute.</p><p>Just for further illustration, if I were to make a request query for useraccount with a specific ID and we just wanted to get the email and number, we would have something like this in our Postman</p><figure><img alt="An GraphQL Query to get a userAccount" src="https://cdn-images-1.medium.com/max/1024/1*ocv9foWNFdbYE5y0R-PFUg.png" /><figcaption>useraccount Query</figcaption></figure><p>Here we see a request being made for a useraccount with id: 64fc59f68e07d9e3ed5b23da. This is called an argument and we defined this already in our userAccount Query where we had an attribute ID</p><pre>useraccount(id: ID!): User!</pre><p>If we look at the bottom of the image we see the result of the request. We can also make multiple queries at once like this</p><figure><img alt="An image that shows how to make multiple queries in a single request in GraphQL" src="https://cdn-images-1.medium.com/max/1024/1*4NXhCzd2DrYGzmigsiSfiQ.png" /><figcaption>Making multiple requests in GraphQL</figcaption></figure><p>This will give us a result like this</p><figure><img alt="An image that shows the result of making multiple Queries" src="https://cdn-images-1.medium.com/max/1024/1*dsOiTWaihnuyeUmgOi9M-A.png" /><figcaption>Result of making multiple Queries</figcaption></figure><p>You might wonder why we have to do query User before putting our queries. This just simply means that the query we are getting is of the “User” Type.</p><p>Finally the second concept in GraphQL: Mutations. So if you agree with me, you know that POST, DELETE AND UPDATE are like write(editing) actions, if we look at it from the read-and-write perspective we are trying to edit things, or let’s say mutate things. Mutate means to change something. So, if you think that for every mutation action you have to write a function that handles that, you’re 100% right. In mutations, we write functions that handle different mutation[actions], either to delete, edit, or create. They are all mutations.</p><p>These 2 concepts, Queries and Mutations are what make up what we call resolvers. So in GraphQL, we resolve your requests either it’s a query or a mutation.</p><p>So you might be wondering how the server knows I want to change something. You specify in your request, like this</p><figure><img alt="An image that shows a example of a GraphQL Mutation" src="https://cdn-images-1.medium.com/max/1024/1*Qad2_bkuupwffQ4DSudLKg.png" /><figcaption>GraphQL Mutation</figcaption></figure><p>In your request, you specify that’s it a mutation and the name of the mutation. For the request in this image, it’s a Signup mutation. So we then pass in the required arguments, like name, email, etc.</p><p>How does this work behind the scenes?</p><p>Just like we defined our query types, we also define our mutation types like this</p><pre>type Mutation {<br>    signUp(name: String!, email: String!, password: String, number: String!): String!<br>    signIn(name: String, email: String, password: String!): String!<br>    createUser(email: String!, password: String, name: String, number: String): User!<br>}</pre><p>Here we see 3 mutations: signUp, signIn, and createUser together with the arguments they take(shown by the values inside the bracket) and the values they return (as shown at the end after the colon).</p><p>After defining the mutation types we need to create the mutation resolver that handles the mutations.</p><p>I’ll just show one of them here for the signup</p><pre> signUp : async(parent, { email, password, name, number}, {userModel}) =&gt;{<br>        email = email.trim().toLowerCase();<br><br>        const hashed = await bcrypt.hash(password, 10);<br><br>        try{<br>            const user = await userModel.User.create({<br>                email, <br>                name,<br>                number,<br>                password: hashed<br>            })<br><br>            return jwt.sign({ id: user._id}, process.env.JWT_SECRET);<br>        }<br>        catch(err){<br>            console.log(err);<br>            throw new Error (&#39;Error creating account&#39;);<br>        }<br>},</pre><p>Pretty straightforward! These queries and mutations make up our resolver file which we call when we are setting up our GraphQL server, like this</p><pre>//file: src/resolvers/index.js<br>const Query = require(&#39;./queries&#39;);<br>const Mutation = require(&#39;./mutations&#39;);<br>module.exports = {<br>    Query,<br>    Mutation<br>};</pre><p>Then call it in our server.js file alongside our types definition file</p><pre>const resolvers = require(&#39;./resolver/index&#39;)</pre><p>Then set these values in our server like this</p><pre>const server = new ApolloServer({<br>    typeDefs,<br>    resolvers,<br>})</pre><p>Type definition tells our server what kind of data we are expecting, Resolvers help handle the queries and mutations</p><p>So that’s it on GraphQL! This is to a large extent theoretical, and it’s so just to give you a brief understanding of how it works. If want to learn the dark practical mysteries(hahaha) of GraphQL using Javascript, watch out for my future blog post where I’ll be creating a basic CRUD API with authentication. I’ll update this article with the link to it once it’s ready, but in the meantime, you could just subscribe so you can be notified when I drop the link. If you want to see a full project in the meantime, you can check out this link to the project I submitted for this assessment <a href="https://github.com/SheyiB/EaziPay-Assesment">here</a></p><p>What are your thoughts on GraphQL and this article, please let me know in the comment sections. I personally think GraphQL APIs allow anyone to understand and use them without reading so much documentation. Simply put it makes new users&#39; interaction with your API super easy. Thank you for reading my thoughts, have a great day. Keep coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08196600c667" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Event-Driven Architecture in TypeScript with Node.js and Express]]></title>
            <link>https://medium.com/@elijahbanjo/implementing-event-driven-architecture-in-typescript-with-node-js-and-express-eefecadaf95f?source=rss-19845d95a1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefecadaf95f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Elijah Banjo]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 15:22:20 GMT</pubDate>
            <atom:updated>2023-07-23T15:22:20.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOybd0586mN30JsUVwXjAw.png" /><figcaption><a href="https://www.freepik.com/free-ai-image/integrated-microchip-circuit-board-server-central-computer-processor-with-neon-lights_39518209.htm#query=computer%20architecture&amp;position=27&amp;from_view=keyword&amp;track=ais">https://www.freepik.com/free-ai-image/integrated-microchip-circuit-board-server-central-computer-processor-with-neon-lights_39518209.htm#query=computer%20architecture&amp;position=27&amp;from_view=keyword&amp;track=ais</a></figcaption></figure><p>If you are familiar with the solid principles you know that S stands for single responsibility which means that a function or method should be focused on performing a single action. This being said, if you needed to perform other actions when a specific action occurs how would you do that? Enter Event-driven Architecture! The idea here is that those other actions that you want to carry out when this specific action occurs are defined in an event, and when this specific action occurs, you just announce that it has happened and then it triggers the other actions to get carried out</p><p>I was working on my final year project on an online auction platform and I needed to update the list of auctions a market database has whenever an auction is created. One approach was to directly update the market database, directly from the method where I created the auction. This would have been probably easy to go on with, but then this does not make your code neat or scalable, moreover it doesn&#39;t allow modularity in your code.</p><p>This was what led me to my discovery of Event-driven architecture. It helps your code to be more readable, easy to scale, and maintain. More interestingly, if the actions in these events break or fail to get carried out when the main action occurs, the main action still gets carried out and your system doesn&#39;t crash. It’s just the parts of these events that would fail while the rest of your program keeps working fine. EDA provides fault tolerance and resilience to failures. Amazing, ain’t it?</p><p>So just a breakdown before we start coding, to implement this we would have a method that performs an action and then declares the occurrence of an event and another file that contains these events. Finally, anywhere we call this method, we would have to initialise our event handler. So in summary we would have 3 files, one that contains our methods, another that contains our events and finally one that calls our method.</p><p>I would be demonstrating this by creating a simple server using Express that just logs some messages whenever a particular endpoint is accessed. I would be implementing this in typescript and would be using the events package to emit these events. So create a folder and run</p><pre>npm init -y</pre><p>Next up install typescript using</p><pre>npm install typescript</pre><p>next up create 3 files: services.ts, events.ts, and index.ts. To run our typescript codes I’ll be using the ts-node-dev module. You can install that using</p><pre>npm install ts-node-dev</pre><p>Next, we install the events module using</p><pre>npm install events @types/events</pre><p>Once this is done let’s go to our package.json and adjust some things. First would be to adjust the main to index.ts then in our Scripts section we create a new key: dev with these attributes: ts-node-dev — respawn — transpile-only index.ts. You should have something similar to what is in this image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*KfLuILfMeK4G3cAK83DOlA.png" /><figcaption>package.json</figcaption></figure><p>Finally, we would install express using</p><pre>npm install express @types/express.</pre><p>Next up, go into the events file and let’s create our event. You can type/paste in the code below and I’ll explain what it does</p><pre>import {EventEmitter} from &#39;events&#39;<br><br>export class EventHandlers{<br><br>    private eventEmitter: EventEmitter;<br><br>    constructor(eventEmitter: EventEmitter){<br>        this.eventEmitter = eventEmitter;<br>    }<br><br>    registerRouteEventHandlers() {<br>        console.log(&#39;Events FiredUp&#39;)<br><br>        this.eventEmitter.on(&#39;routeAccess&#39;, (route) =&gt; {<br>            try{<br>                this.anounceRouteAccess(route);<br>                this.upgradeSecurity(route)<br>            }<br>            catch(error){<br>                console.log(&#39;An error occured while perform Route accessed actions&#39;)<br>            }<br>        });<br>    }<br><br>    private anounceRouteAccess( route: string){<br>        console.log(`${route} has been accessed`)<br>    }<br><br><br>    private upgradeSecurity(route: string){<br>        console.log(`Locking all other routes and initiating higher security measures on ${route} route`)<br>    }<br><br>}</pre><p>First, we import the event emitter. Next up we create a class EventHandlers. After that we create an eventEmitter property and assign the EventEmiiter type to it and also make it private to this class, so it can only be accessed within this class. Next, we initialize this event using a constructor, assigning the eventEmitter property of our class to the eventEmitter supplied. Next up we create our method ‘routeEventHandlers’ which would listen for all events as regards route access. We could have multiple methods for handling different events.</p><p>Inside the ‘registerRouteEventHandlers’ method we just print a message to show that this event handler is up and running. Then we define our events. We would be going with just one event for now ‘routeAcess’. We can take in data that will be passed/sent anytime the occurrence of this event is declared. For this case, we would be supplying the route&#39;s name. With this information, we can perform various actions, but for the sake of this article, I would just be printing simple messages. Our event would perform 2 actions, one would be a function that announces that a route has been accessed, and another that announces that we are upgrading security.</p><p>For error handling, we would be using the try-catch module so if any occurs we can catch it. These functions would be private to this class alone. We use the ‘this’ keyword because we are referring to instance properties of the class.</p><p>Finally, we would create our functions, which said ab into (from the beginning) are private to this class. They take in the route name and print simple messages. You can always replace these messages with the actions you want to perform.</p><p>Next up, we move to our service file. You can type in these codes and I’ll explain what they do.</p><pre>import {EventEmitter} from &#39;events&#39;<br><br>export class MyService{<br><br>    private eventEmitter: EventEmitter;<br><br>    constructor(eventEmitter: EventEmitter){<br>        this.eventEmitter = eventEmitter<br>    }<br><br>    accessRoute (routeName: string ){<br>            try{    <br>                console.log(`Opening ${routeName} Route`)<br>                this.eventEmitter.emit(&#39;routeAccess&#39;, routeName);<br><br>            }<br>            catch(e: any){<br>                console.log(e)<br>            }<br>    }<br><br>}</pre><p>First, We import the EventEmitter from the events. We then create our class and then create a eventEmitter property private to this class that we would use to declare the occurrence of our events. We then initialize it using a constructor. Next up, we create a method that takes in the route’s name. In this method, We would simply just print a basic message, and then emit(declare/announce) the event ‘routeAccess’.</p><p>Finally, we move to our index file. For the last time, you can type/paste this code and I’ll explain what it does</p><pre>import express, {Request, Response} from &#39;express&#39;<br>import {EventHandlers} from &#39;./events&#39;<br>import {MyService} from &#39;./services&#39;<br>import {EventEmitter} from &#39;events&#39;<br><br>const app = express()<br><br>const eventEmitter = new EventEmitter();<br><br>const eventHandler = new EventHandlers(eventEmitter)<br>const myService = new MyService(eventEmitter)<br><br>eventHandler.registerRouteEventHandlers()<br><br>app.get(&#39;/start&#39;, (req: Request,res: Response) =&gt; {<br>    try {<br>        myService.accessRoute(&#39;start&#39;)<br>        return res.status(200).json({&quot;message&quot; : &quot;Welcome to EDA&quot;})<br>    } catch (error) {<br>        return res.status(500).json({&quot;message&quot; : &quot;An Error Occured on The Server&quot;})   <br>    }<br><br>})<br><br>const PORT = 8083<br><br>app.listen(PORT, ()=&gt;{<br>    console.log(`Server Running on Port ${PORT}`)<br>})</pre><p>Here we first import express, the request and response types, then the eventHandlers we created from our event file, then our service class from the service file. Finally, we import the EventEmitter from the events package.</p><p>Next up, we create an instance of our express app. Then instances of the EventEmitter, our EventHandler, and our service. Next, we call the registerRouteEventHandlers method from the instance of the event handler we created. This now starts listening for events. Before I move on, for every instance of EventHandler and MyService we create, we pass in the eventEmitter because of the eventEmitter property they both posses. Next, we create an endpoint that listens for requests. Then inside it call the accessRoute method. Then finally listen for requests.</p><p>You can start the server using the npm run dev command, when you hit the start route using postman or any other option of your choice you can see the Event Handling in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*YYT28HOd6MfeLik6SGO34A.png" /><figcaption>Result when you start up the server</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*OwJ1haDTWprC2nl6s57yLg.png" /><figcaption>Accessing the route with Postman</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*bWhaucgMiz7d9KL57CL6yA.png" /><figcaption>Event-Driven Architecture in Motion</figcaption></figure><p>So that’s How you handle events in NodeJs. Hopefully, this has been helpful Thank you for reading till this point. Let me know your thoughts in the comment section. You can find the complete code on my Github Repo <a href="https://github.com/SheyiB/EventDrivenArchitecture">here</a>. Happy Hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eefecadaf95f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Backend Engineering/Development For Non-Techies]]></title>
            <link>https://medium.com/@elijahbanjo/what-is-backend-engineering-development-for-non-techies-d03a0d5a5907?source=rss-19845d95a1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03a0d5a5907</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[for-beginers]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[easy-to-understand]]></category>
            <dc:creator><![CDATA[Elijah Banjo]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 10:29:21 GMT</pubDate>
            <atom:updated>2023-06-19T10:29:21.836Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a 98% chance you clicked on a link that brought you to this page(prove me wrong in the comment section). What happened when you clicked on that link? Simple answer: Backend ish!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9DiGk1kRDJMr1UlfUXBMg.jpeg" /><figcaption><a href="https://www.freepik.com/free-vector/programmer-work-with-working-day-symbols-flat-illustration_15329611.htm#query=backend%20developer&amp;position=1&amp;from_view=keyword&amp;track=ais">https://www.freepik.com/free-vector/programmer-work-with-working-day-symbols-flat-illustration_15329611.htm#query=backend%20developer&amp;position=1&amp;from_view=keyword&amp;track=ais</a></figcaption></figure><p>Let&#39;s look at it through this lens, let’s assume there’s a very big library and, obviously, there are a lot of books in it. Let’s call all the books in the library <em>data</em>, and let’s call our library our <em>Server</em>. Now we need to get some books from the library <em>or data from our server</em>, but then going to the library ourselves will take us a lot of time, so we write a letter to the library, let’s call this a <em>request</em>, to the library(<em>Server</em>), that we need some books. When the letter gets to the library, the people at the library take our letter and read it properly. Ideally, they should have ways for handling letters like this, let’s call these <em>APIs </em>(hey-pee-his). There are a lot of books in this library so the way they get specific books from a particular shelf or end in the library could also be well-defined, let’s call this an <em>endpoint</em> or <em>route</em>. So once our letter gets to them they know what we want, they search the library for the books we want and send them back to us, let’s call that a <em>response</em>.</p><p>In summary, we sent a <em>request</em> to our <em>server</em> to get some <em>data</em> and in the end, we got a <em>response</em>. How we <em>handle</em> all that happens from the point of <em>sending requests</em> to the point of receiving a <em>response</em> is what we call <em>Backend Engineering!</em> The backend engineer organizes our <em>server</em>, designs <em>endpoints</em>, and arranges and stores our <em>data</em> properly so that anytime we need a particular information we can get it.</p><p>Now, back to what I said at the beginning, when you clicked on that link that brought you to this page, you made a <em>request</em> to the <em>server</em>(library) containing this page(book) and they <em>respon</em>ded by sending you the page that contains this information you are currently reading.</p><p>Just a piece of extra information, and just skip it if you don&#39;t get it, the data the server sends doesn’t look visually appealing the way they are being sent because they are just raw data in a specific data form called JSON. So the frontend engineer takes this JSON and organizes them in a way that looks nicer and easier to understand and interact with, which is what you see.</p><p>Ever see a 404-Not found Page when browsing? Responses have a property we call status-code, they are numbers that tell us what happened to our request, 404 means what we are looking for cannot be found, there are other status codes also. Status codes starting with 2 e.g 201, 200 tell us our request is successful, those that start with 3 e.g 300 take us somewhere else(redirect us), those that start with 4 e.g 400, 404, tell us something wrong has happened based on what we have sent and those that start with 5 e.g 500 tell us that something has gone wrong on our Server, that’s when we hear stuffs like “The server is down”, very annoying!</p><p>There you go! <em>backend development/engineering</em> is how we handle <em>requests</em> being sent to our <em>server</em> and how we determine what <em>response</em> we send back. Now you understand what backend is. Stay tuned for a deeper dive, and thank you for reading till this point!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03a0d5a5907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Paystack API in your Backend NodeJs Project]]></title>
            <link>https://medium.com/@elijahbanjo/integrating-paystack-api-in-your-backend-nodejs-project-bc085ebc2a?source=rss-19845d95a1e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc085ebc2a</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[paystack]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Elijah Banjo]]></dc:creator>
            <pubDate>Wed, 04 May 2022 17:31:09 GMT</pubDate>
            <atom:updated>2022-05-04T17:31:09.610Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating Pay-stack API in NodeJS</p><p>Paystack is a fintech company that helps in facilitating financial transactions. Assuming you were building an application that users would have to pay for anything, using paystack’s API would be very helpful.</p><p>I’m writing this post with the assumption that you are already familiar with using Javascript, NodeJs, MongoDB, and ExpressJs.</p><p>Before we start writing codes, let’s understand how we would be integrating Paystack. Basically, it consists of 2 parts.</p><p>The first part makes a post request with the information about the payment to be made. A reference number and a URL that directs us to paystack’s platform to input card details, alongside other information, are generated for that transaction. When this is done, we can now put the URL generated into our browser and visit paystack platform where we can put in card details and make payment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FPu86U28Zi-_YsPsHyfntw.jpeg" /></figure><p>The second part is the verification endpoint, we make a get request to the verification endpoint with the reference number generated. This then tells us if the transaction was successful or not.</p><p>Paystack requires that we pass in a header that contains our authorization keys for each transaction. So, instead of inputting our transaction key using postman or any HTTP requester, we would be creating our own function that automatically puts our authorization keys in headers alongside the other information regarding the transaction any time we make a request to their API. We would also be making API calls to Paystack from our function.</p><p>In order to use Paystack API, you need to have an account with them. You can register for free at <a href="https://paystack.com/">https://paystack.com</a>. Then set up a test account. The downside of this is you won’t be getting any real money, but if you need a real one you can also apply for that. Once you’ve done that copy your secret keys and key them somewhere safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gF5U0Q-OhV428OgpCouE-g.png" /><figcaption>Secret Key</figcaption></figure><p>Now let’s code!</p><p>Create a folder for this project with any name you want. For this project, I’ll be creating an app that allows us to contribute money to make the world clean. I’ll call it Project-Clean-Earth. So inside this folder create 5 folders: utils, models, service, controllers, config, and routes. Once you’ve done that initialize the project using “npm init” or “npm init -y”. Then install the following packages: dotenv, express, lodash, mongoose, nodemon, and request. We use dotenv to add our config file to the process environment. We use lodash to perform simple operations like selecting specific data from a given data, nodemon to always restart our server anytime we make changes and request to make HTTP requests. You can install all of them using npm install dotenv express lodash mongoose nodemon request</p><p>Inside the utils folder create a file, name it payment.js. This file is where the magic happens. This is where we would create our function that calls paystack-API and submits our transaction details and authorization headers to initialize and verify them.</p><p>So inside this folder type the following lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tilYZZVEGAfdzacqqw78A.png" /><figcaption>payment.js in utils folder</figcaption></figure><p>Just type it and I’ll explain what it does. What we are simply doing is creating a function we can call that will consist of 2 methods: initialize payment and verify payment.</p><p>The function takes in a request hence the first line. On the second line we put in our secret key, we’ll retrieve it from our env folder.</p><p>On the fourth line, we create the first of the 2 Immediately Invoked Function Expression (a JavaScript function that runs as soon as it is defined) we would be creating. This one is the initialize payment function. It takes in 2 parameters, a form, and a callback. The form consists of the information of the person making a contribution to our project, the amount, and other details.</p><p>I said earlier on that the initialize API for Paystack takes in 2 values, the options, and the callback. So we would be properly formatting our option parameter alongside the callback parameter.</p><p>So in line 5, we create an array object “options” which would be submitted to paystack.In options we would be defining the endpoint we are assessing which is the paystack initialize endpoint, we would assign the value of that to a variable called URL. We would then set our headers and include our authorization key (Secret Key) in it. Also, we would set the content type and catch control.</p><p>Finally, on line 12, we include the information from the form</p><p>*The form consists of all the other information that we collect from the contributor, which could include, name, amount, email, etc.</p><p>This concludes the options parameter.</p><p>Moving on, we would create another callback based on the call back that is passed into our initialize payment function. We simply define a callback function then it takes in the error, response, and the body then we return the callback given at the beginning with the new parameters of the error and body.</p><p>Once we are done with this, we make a request with our options and call back.</p><p>Next, on line 21 we define our verify payment method. This is very similar to the initialize payment. The only difference between this and the initialize payment is the URL. So let’s look at it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*YLkOOYoSkie6FF5QXdO9-Q.png" /><figcaption>Adding the reference to the Paystack URL endpoint</figcaption></figure><p>Here we are making a request to the Paystack verify endpoint and it takes a query which is the reference of the transaction we want to verify. So we add the reference of the transaction to it as a query by using the encodeURIComponent method. After doing this we export our functions so they can be accessed outside this file.</p><p>Before we continue, let’s create our payment database model using mongoose. So we switch to the model folder and create a file called payment.js. Once that is done, paste in this code I’ll explain.</p><figure><img alt="mongodb model for our payment model" src="https://cdn-images-1.medium.com/max/1024/1*R4cZt2h9LOvq_5hMLh0vow.png" /><figcaption>Payment Model</figcaption></figure><p>Since you are familiar with Mongoose, you should not have any problem understanding this. We simply require the mongoose library in line 1. In line 3 we use mongoose to create a schema (a JSON object that defines the structure and contents of your data). Our data is going to consist of full name, email, amount, reference (we make this unique so that it can’t be stored twice), the status of the transaction, and we use the timestamp option(it creates the date created and the date updated ). Finally, we create our model based on the schema we just defined and export it.</p><p>Now switch to the Service folder and create a file: payment.service.js. This will call our payment file in the utils folder so we can access the functions there. So this service folder will call the methods and will allow us to always call these methods we want easily. So type in the following lines of code and I’ll explain the parts that need to be explained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3gGRDf7H93e0KW7bPk_cQ.png" /><figcaption>Payment Service</figcaption></figure><p>So we call the request package, the package we would be using to make HTTP requests from our API. We also call lodash. Then we call our initialize payment and verify payment from our utils folder and pass in the request package with it so that anytime we call them in the rest of our code, the request is made automatically.</p><p>Moving on, we create a class “PaymentService”. We do this so that we can always reuse the Payment service to call our functions anytime we need them. So in this class, we create three methods, the first is the start payment (this initiates the payment). Here in line 9, we take in data [The information about the person making the contribution] then in line 10 we return a new promise. We use the pick method of the lodash package to select the amount, email and full name from the data provided (this data will be our req.body) then we add the full name to the form metadata and multiply the amount by 100 because Paystack takes amount as kobo. Then we call our initializePayment method and pass in the form and our callback. If there is an error we handle it using the reject callback, else we parse what is returned(this will contain the reference number, a URL we can paste into our browser to make the transaction, the transaction status, and other details), and store it in a variable called response and return using our resolve callback.</p><p>We then move on to the createPayment method. Here we pass in the transaction reference generated from the result of our startPayment service as a query. In line 43 we then call our verify method and pass in our transaction reference and add a callback. If there is an error we handle it using the reject callback, else we parse the result [body] and store it in a variable called response. It contains a lot of information (you can console.log the body/response to see what it contains), but we just extract the reference, amount, status, email, and full name and pass them into the array newPayment (line 53). Then using the model we have created, we create a new Payment data in our database using the information in the newPayment array.</p><p>Finally, we create a method called Payment receipt that allows us to get the details of any receipt. We pass in the reference and search our model for any payment that matches the reference number generated. Depending on the output we handle it using the resolve or reject method.</p><p>Moving on, we move to our controller folder and create a file called payment.js. Type in this and I’ll explain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7BbS5YdHW9-hgZp9w3tuA.png" /><figcaption>Payment Controller</figcaption></figure><p>First, we call the paymentservice from our service folder. Since it’s a class we create an instance of it. Then we create 3 endpoints for the three services and call each of the methods passing the required information and export the function.</p><p>Whew! We are almost done. We now go to our routes folder and create a file called payment.route.js. Type in these codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bf3LYZS1CUX6NpZaj8_oA.png" /><figcaption>Payment Route</figcaption></figure><p>Here, we just call our express module and create a router using the express router method. We then route our routes and export our router.</p><p>Rounding up, go to the config folder. Inside this file create two files config.env and db.js.</p><p>In the db.js we connect to our local mongo database. Type in these codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_Qvvjx6ljEGIHOaJWW3Zg.png" /><figcaption>Connecting to MongoDB</figcaption></figure><p>We simply connect to our database and using the then and catch callbacks we give the required response.</p><p>Next, we switch to our config.env and type in these codes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIPtJIKi1-LMvsHfhWHpQw.png" /><figcaption>config.env</figcaption></figure><p>This just defines our env variables. Ensure you replace YOURSECRET KEY with your paystack secret key.</p><p>For the cherry on the cake, we move to our root folder and create a new file called app.js. Type in these codes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*W9l0oPR99FfquWCjoWauvA.png" /><figcaption>Our Sever: App.js</figcaption></figure><p>We simply just call everything we would be using and listen to our server. We also set our config folder so we can access our own initialized config variables. Before we run our code, let’s go to our paystack. Where we copied our keys, there’s a section for callback URL. So what we are going to do is this; we are going to put the URL to access our createPayment endpoint in the Test CallbackURL so that anytime we complete the payment, we don’t have to go back to postman to put in the reference id and create the payment. It does that automatically. It’s not compulsory, but it makes life easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*TzwJUuwnSlLNcNDHp2ylrA.png" /><figcaption>Adding our createPayment endpoint to the callback URL</figcaption></figure><p>Now that is done we can save and enter nodemon app.js in our terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*5QEHM2dLcjptKleHUgBPGA.png" /><figcaption>Starting our server with Nodemon</figcaption></figure><p>We can now open postman and make a post request to <a href="http://localhost:3000/api/projectCleanEarth/pay">http://localhost:3000/api/projectCleanEarth/pay</a> to initiate a payment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymtuMZ_aIyPiI0bLwEo3gg.png" /><figcaption>Initating a Payment</figcaption></figure><p>You should get a result as seen in the image above. In our result, we see that there is an authorization_url in the data returned. We can now copy this link which will direct us to Paystack platform so we can make the payment.</p><p>If we paste the link into our browser, we should get something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_NsKp4znLBhCIgNJ5JAbQ.png" /><figcaption>The result of the authorization link when we paste it into our browser</figcaption></figure><p>We can now select any option and pay. Once this is done since we have added the createPayment endpoint in our paystack call back URL, it will access that endpoint and our payment information will be created in our database. If you added the createPayment endpoint in your callback URL, you should get something like this once you complete the payment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqLCRtTcZH6qNOBOmTu2-g.png" /><figcaption>Result when we add our createPayment endpoint in Our Paystack URL Callback</figcaption></figure><p>If you didn’t, you can copy the reference number created at the initiatePayment endpoint and add it as a query parameter in your postman and make a get request to our createPayment endpoint. You should get something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rf1_F0sDpAi5m3PM99KwZg.png" /><figcaption>Making API call to our createPayment route using PostMan</figcaption></figure><p>For our last endpoint, we can make a get request to our getReciept endpoint to see the details of any transaction. We pass in the reference number in our req.body, like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uSNZDPt9iwRAWGQ2RphXg.png" /><figcaption>Getting payment details using Postman</figcaption></figure><p>Whew! That brings us to the end of integrating Paystack API in your backend project. Hopefully, you were able to learn one or two things. You can see the full code here: <a href="https://github.com/SheyiB/ProjectCleanEarth">https://github.com/SheyiB/ProjectCleanEarth</a>. Kindly leave a comment and like if you have any questions or enjoyed this. Thank you very much for reading. See you at the top. THE END!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc085ebc2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>