<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Konan69</title>
    <description>The latest articles on DEV Community by Konan69 (@konan69).</description>
    <link>https://dev.to/konan69</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1703441%2F485d3632-fd9b-48f1-acc8-4bd0ef95bd1b.png</url>
      <title>DEV Community: Konan69</title>
      <link>https://dev.to/konan69</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/konan69"/>
    <language>en</language>
    <item>
      <title>Creating a simple referral System in ExpressJS</title>
      <dc:creator>Konan69</dc:creator>
      <pubDate>Sat, 29 Jun 2024 19:26:20 +0000</pubDate>
      <link>https://dev.to/konan69/creating-a-simple-referral-system-in-expressjs-3b3b</link>
      <guid>https://dev.to/konan69/creating-a-simple-referral-system-in-expressjs-3b3b</guid>
      <description>&lt;p&gt;What is a Referral System&lt;/p&gt;

&lt;p&gt;A referral system is a platform where current users of an application can invite other people to sign up/join the application. &lt;br&gt;
It is a marketing tactic used to promote the growth of an application by offering incentives (rewards) by keeping track of the number of users they invite successfully.&lt;/p&gt;

&lt;p&gt;Overview of the application.&lt;br&gt;
The fullstack application where this system is implemented in, is one where users are prompted to connect their web3 (metamask) wallets &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flijd388wethl3p1jr91h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flijd388wethl3p1jr91h.png" alt="Image description" width="800" height="826"&gt;&lt;/a&gt;&lt;br&gt;
in order to unlock the social tasks page which contains the invite (referral) task&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2vpq856qyukn7v1ovbxa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2vpq856qyukn7v1ovbxa.png" alt="Referral task" width="800" height="112"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that the basic introduction is over, lets get to the code and logic.&lt;/p&gt;

&lt;p&gt;After initializing the nodejs project with &lt;code&gt;npm init&lt;/code&gt; and installing relevant dependencies&lt;/p&gt;

&lt;p&gt;a server.js file was created to serve as an entrypoint to the backend application using mongoose as the ORM for mongoDB&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();

// env strings
const mongo = process.env.CONNECTION_STRING;

// middleware
app.use(cors());
app.options("*", cors);
app.use(express.json());

//routes
const usersRouter = require("./Router/users");

app.use("/api/users", usersRouter);

app.get("/", (req, res) =&amp;gt; {
  res.json("hello");
});

// db connect
mongoose
  .connect(mongo)
  .then(() =&amp;gt; console.log("connected to db"))
  .catch((err) =&amp;gt; console.log(err));

app.listen(8080, () =&amp;gt; {
  console.log("listening to server");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A simple express router was used route all API endpoints related to the user, for organisation purposes &lt;/p&gt;




&lt;p&gt;In the userRoutes file, a simple user schema containing the shape of how the user document would look in the database&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { User } = require("../Models/user");
const express = require("express");
const router = express.Router();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The userId was used as the unique identifier for each user, and sent from the frontend to the backend endpoint through a URL string Parameter&lt;br&gt;
example:&lt;br&gt;
&lt;code&gt;https://backendserver.com/api?referral=referralId&amp;amp;foo=bar&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;everything after the question make becomes a 'query parameter' and can be chained with the '&amp;amp;' character&lt;/p&gt;




&lt;p&gt;in the actual api route,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the referral id is received from the fronted through query param&lt;/li&gt;
&lt;li&gt;the user's wallet is sent through the request body&lt;/li&gt;
&lt;li&gt;uses Mongoose methods on the User object to perform dB queries&lt;/li&gt;
&lt;li&gt;adds points when the requirements are satisfied
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Route handler for signing in by connecting wallet/ creating new user
router.post("/", async (req, res) =&amp;gt; {
  try {
    const { r } = req.query; // Get the id from the query parameters
    const { wallet } = req.body;

    if (r) {
      try {
        // Signup with referral
        const inviter = await User.findOne({ _id: r });
        console.log(inviter);
        const invited = await User.findOne({ wallet });

   // If invited user doesn't exist, create their account in db, 
    log them in, and add points to inviter
        if (!invited) {
          const newUser = new User({ wallet });
          await newUser.save();

          // add points to inviter
          const updatedInviter = await User.findOneAndUpdate(
            { _id: r },
            { $inc: { referrals: 1, points: 1 } },
            { new: true },
          );

          return res.status(200).json(newUser);
        } else {
          // If the invited user exists in db, return its details
          return res.status(200).json(invited);
        }
      } catch (error) {
        console.error("Error adding referral point:", error);
        return res.status(500).json({ error: "Internal server error" });
      }
    } else {
      // Regular signup process
      try {
        // Check if the wallet address already exists
        const existingUser = await User.findOne({ wallet });
        if (existingUser) {
          // Wallet address already exists
          return res.status(200).json(existingUser);
        } else {
          // Wallet address doesn't exist, create a new user
          const newUser = new User({
            wallet,
          });
          await newUser.save();
          return res.status(200).json(newUser);
        }
      } catch (error) {
        console.error("Error connecting wallet:", error);
        return res.status(500).json({ error: "Internal server error" });
      }
    }
  } catch (error) {
    console.error("Error:", error);
    return res.status(500).json({ error: "Internal server error" });
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;thanks for reading ;)&lt;/p&gt;

&lt;p&gt;to learn more:&lt;br&gt;
&lt;a href="https://hng.tech/internship"&gt;https://hng.tech/internship&lt;/a&gt;&lt;br&gt;
&lt;a href="https://hng.tech/hire"&gt;https://hng.tech/hire&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>mongodb</category>
      <category>api</category>
    </item>
  </channel>
</rss>
