<?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 SHERIN RAJ THANGAPPA D. on Medium]]></title>
        <description><![CDATA[Stories by SHERIN RAJ THANGAPPA D. on Medium]]></description>
        <link>https://medium.com/@sherinofficial98?source=rss-07908e60e743------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Aq3YVjwuXhhOiU-U</url>
            <title>Stories by SHERIN RAJ THANGAPPA D. on Medium</title>
            <link>https://medium.com/@sherinofficial98?source=rss-07908e60e743------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:58:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sherinofficial98/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[Database Seeding in NestJS: A Backend Developer's Guide]]></title>
            <link>https://medium.com/@sherinofficial98/database-seeding-in-nestjs-a-backend-developers-guide-490770fe6037?source=rss-07908e60e743------2</link>
            <guid isPermaLink="false">https://medium.com/p/490770fe6037</guid>
            <dc:creator><![CDATA[SHERIN RAJ THANGAPPA D.]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 16:11:49 GMT</pubDate>
            <atom:updated>2026-06-19T16:11:49.215Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing a backend application, we often need some sample data in the database to test our APIs and features.</p><p>Creating this data manually every time can be time-consuming. This is where <strong>Seed Data</strong> becomes useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAbmusJsTDFi1DMn3mnCQw.png" /></figure><h3>What is Seed Data?</h3><p>Seed data is the initial data that is automatically inserted into a database.</p><p>Think of it as adding some ready-made records so that your application has data to work with immediately.</p><p>For example, in an Employee Management System, you may need:</p><ul><li>An Admin User</li><li>A Few Employees</li><li>Departments</li><li>Roles</li></ul><p>Instead of creating these records one by one, we can create them automatically using a seed script.</p><h3>Why Do We Need Seed Data?</h3><p>Imagine you delete your database and create it again.Without seed data, you would have to:</p><ul><li>Create users manually</li><li>Add departments manually</li><li>Add test records manually</li></ul><p>This takes time and can become repetitive.</p><p>With seed data, you simply run one command and all the required data is created automatically.</p><h3>Simple Example in NestJS</h3><p>Let’s assume we are using NestJS with Prisma.</p><p>Create a file called seed.ts.</p><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br><br>const prisma = new PrismaClient();<br>async function main() {<br>  await prisma.user.createMany({<br>    data: [<br>      {<br>        name: &#39;Admin&#39;,<br>        email: &#39;admin@example.com&#39;,<br>      },<br>      {<br>        name: &#39;John&#39;,<br>        email: &#39;john@example.com&#39;,<br>      },<br>    ],<br>  });<br>  console.log(&#39;Seed data created successfully&#39;);<br>}<br>main()<br>  .catch(console.error)<br>  .finally(async () =&gt; {<br>    await prisma.$disconnect();<br>  });</pre><h3>What Does This Code Do?</h3><p>Let’s understand it step by step.</p><h3>Create Prisma Client</h3><pre>const prisma = new PrismaClient();</pre><p>This connects our application to the database.</p><h3>Insert Sample Data</h3><pre>await prisma.user.createMany({<br>  data: [<br>    {<br>      name: &#39;Admin&#39;,<br>      email: &#39;admin@example.com&#39;,<br>    },<br>    {<br>      name: &#39;sherin&#39;,<br>      email: &#39;sherinraj@gmail.com&#39;,<br>    },<br>  ],<br>});</pre><p>This creates two user records in the database.</p><h3>Display Success Message</h3><pre>console.log(&#39;Seed data created successfully&#39;);</pre><p>This message appears after the data is inserted successfully.</p><h3>Add a Seed Command</h3><p>In your package.json, add:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;seed&quot;: &quot;ts-node prisma/seed.ts&quot;<br>  }<br>}</pre><p>Now run:</p><pre>npm run seed</pre><p>Output:</p><pre>Seed data created successfully</pre><h3>Benefits of Seed Data</h3><ul><li>Saves development time</li><li>No need to enter data manually</li><li>Makes testing easier</li><li>Helps new developers set up the project quickly</li><li>Creates a consistent development environment</li></ul><h3>Real-Life Example</h3><p>Suppose your application requires an Admin account to log in.</p><p>Without seed data:</p><ol><li>Create the database.</li><li>Open the database tool.</li><li>Insert an admin record manually.</li></ol><p>With seed data:</p><pre>npm run seed</pre><p>The Admin account is created automatically.</p><p>Simple and fast!</p><h3>Conclusion</h3><p>Seed data is a simple but powerful feature that helps developers work more efficiently. Instead of manually creating records every time, we can use a seed script to populate the database with sample data in seconds.</p><p>If you’re building applications with NestJS, learning how to use seed data will save time and make development much smoother.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490770fe6037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Smart QR Codes with Python in Minutes]]></title>
            <link>https://medium.com/@sherinofficial98/generate-smart-qr-codes-with-python-in-minutes-bd4526d71fe1?source=rss-07908e60e743------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4526d71fe1</guid>
            <dc:creator><![CDATA[SHERIN RAJ THANGAPPA D.]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 09:28:38 GMT</pubDate>
            <atom:updated>2026-04-07T09:28:38.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>QR codes are everywhere today — from payments and product packaging to event check-ins and restaurant menus. But have you ever wondered how easy it is to <strong>create your own QR codes using Python</strong>?</p><p>In this article, we’ll explore:</p><ul><li>What QR codes are</li><li>How to generate them using Python</li><li>Real-world use cases</li><li>And how you can integrate them into your projects</li></ul><p>Let’s turn simple data into powerful scannable experiences!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tR3FOGVMgu_PIWhD2ldZzg.png" /></figure><h3>What is a QR Code?</h3><p>A <strong>QR (Quick Response) Code</strong> is a type of barcode that stores information like:</p><ul><li>URLs</li><li>Contact details</li><li>Payment info</li><li>Text messages</li></ul><p>Unlike traditional barcodes, QR codes can store more data and are easily scanned using smartphones.</p><h4>Why Use Python for QR Code Generation?</h4><p>Python makes QR code generation super simple because:</p><ul><li>Easy-to-use libraries</li><li>Minimal code required</li><li>Highly customizable</li><li>Great for automation</li></ul><h3>Setting Up the Environment</h3><p>Before we begin, install the required library:</p><pre>pip install qrcode[pil]</pre><h4>Basic QR Code Generation</h4><p>Let’s create your first QR code</p><pre>import qrcode<br><br>data = &quot;https://yourwebsite.com&quot;<br><br>qr = qrcode.make(data)<br>qr.save(&quot;basic_qr.png&quot;)<br><br>print(&quot;QR Code generated successfully!&quot;)</pre><p>O/P: This will generate a simple QR code image.</p><h4>Custom QR Code (Advanced)</h4><p>Want to customize your QR code? Try this:</p><pre>import qrcode<br><br>qr = qrcode.QRCode(<br>    version=1,<br>    box_size=10,<br>    border=5<br>)<br><br>qr.add_data(&quot;Hello from Python QR!&quot;)<br>qr.make(fit=True)<br><br>img = qr.make_image(fill=&quot;black&quot;, back_color=&quot;white&quot;)<br>img.save(&quot;custom_qr.png&quot;)</pre><p>You can change:</p><ul><li>Colors</li><li>Size</li><li>Border</li><li>Data content</li></ul><h3>Real-World Use Cases</h3><p>Here’s where things get exciting</p><h4><strong>1. Digital Payments</strong></h4><p>Apps like Google Pay and PhonePe use QR codes for instant transactions.</p><h4>2. Event Check-ins</h4><p>Generate unique QR codes for tickets and scan them at entry points.</p><h4>3. Product Tracking</h4><p>Attach QR codes to products for:</p><ul><li>Details</li><li>Warranty</li><li>Authenticity verification</li></ul><h4>4. Contactless Menus</h4><p>Restaurants use QR codes to display menus digitally.</p><h4>5. Personal Branding</h4><p>Share your:</p><ul><li>Portfolio</li><li>LinkedIn</li><li>Resume</li></ul><p>Just with a scan!</p><h3>Integrating QR Codes into Your Projects</h3><p>QR code generation is not just a standalone feature — it can be integrated into real applications to solve practical problems.</p><p>Here are some ways you can use it in your projects:</p><h4>1. Web Applications (Flask / Django)</h4><ul><li>Generate QR codes dynamically for users</li><li>Example: Create a QR code for user profile links or downloads</li></ul><h4>2. Authentication Systems</h4><ul><li>Use QR codes for login or verification</li><li>Example: Scan QR to log in (like WhatsApp Web)</li></ul><h4>3. Attendance Systems</h4><ul><li>Generate unique QR codes for users</li><li>Scan to mark attendance automatically</li></ul><h4>4. E-commerce &amp; Product Systems</h4><ul><li>Attach QR codes to products</li><li>Store product details, tracking info, or verification links</li></ul><h4>5. API Integration</h4><ul><li>Build a backend API that generates QR codes on request</li><li>Can be used by mobile apps or frontend systems</li></ul><h3>Pro Tips</h3><ul><li>Use high contrast colors for better scanning</li><li>Keep data size minimal for faster scanning</li><li>Test QR codes on multiple devices</li><li>Use dynamic QR codes for editable content</li></ul><h3>Conclusion</h3><p>QR codes are more than just squares — they are powerful tools that bridge the physical and digital worlds.</p><p>With Python, you can:</p><ul><li>Generate QR codes easily</li><li>Customize them</li><li>Use them in real-world applications</li></ul><p>Whether you’re building a startup, a college project, or a simple automation script — QR codes can add real value.</p><p>So go ahead and start building something amazing today!</p><p>#Python #QRCode #Programming #Automation #TechForBeginners #DeveloperTools #PythonProjects #Coding #SoftwareDevelopment #LearnPython</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd4526d71fe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving CORS Issues in Node.js and NestJS: A Backend Developer’s Guide]]></title>
            <link>https://medium.com/@sherinofficial98/solving-cors-issues-in-node-js-and-nestjs-a-backend-developers-guide-7bb0fbb44907?source=rss-07908e60e743------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb0fbb44907</guid>
            <dc:creator><![CDATA[SHERIN RAJ THANGAPPA D.]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 10:07:15 GMT</pubDate>
            <atom:updated>2025-07-17T17:58:19.920Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>If you’re a backend developer working with Node.js and NestJS, chances are you’ve heard this from your frontend teammate:</p><p><strong><em>“Hey, your API is throwing a CORS error!”</em></strong><em><br> </em><strong><em>“It’s working fine in Postman… must be your frontend.”</em></strong></p><p>At first, it might seem like the frontend is doing something wrong — especially when your API works perfectly in <strong>Postman</strong>. But then you open the browser console and see those scary red CORS errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNLhbrQNc-eievcxgvGVUQ.png" /><figcaption>Frontend vs Backend: Fighting over a CORS problem</figcaption></figure><p>In this article, I’ll explain what CORS is, why it happens, how to fix it in <strong>Node.js</strong> and <strong>NestJS</strong>, and share some useful tips to avoid wasting time in the future.</p><h4><strong>What is CORS?</strong></h4><p><strong>CORS</strong> stands for <strong>Cross-Origin Resource Sharing</strong>.</p><p>It’s a browser security feature that <strong>blocks frontend apps</strong> from calling APIs that are hosted on a different origin (domain, protocol, or port). This is to prevent malicious scripts from accessing sensitive data.</p><p><strong>For example:</strong></p><ul><li>Your <strong>frontend</strong> is running on <a href="http://localhost:3000/">http://localhost:3000</a></li><li>Your <strong>backend</strong> API is running on <a href="http://localhost:5000/">http://localhost:5000</a></li></ul><p>Even though both are on localhost, the ports are different — which means <strong>different origins</strong> — and that triggers CORS.</p><h4><strong>Why CORS Happens??</strong></h4><p>Browsers <strong>block cross-origin requests</strong> unless the backend explicitly allows them. If your backend doesn’t send specific headers like:</p><pre>Access-Control-Allow-Origin: http://localhost:3000</pre><p>Then the browser blocks the request — even if the backend is working fine.</p><p>That’s why your API works in <strong>Postman</strong> (which doesn’t follow CORS rules), but not in the <strong>browser</strong>.</p><h3>How to Fix CORS in Node.js with NestJS</h3><p>When you’re using the <strong>NestJS framework</strong> for your backend, fixing CORS is very easy. You just need to make changes in the main.ts file.</p><h4>Step-by-Step Implementation</h4><ul><li>Open your NestJS project.</li><li>Go to the main.ts file (usually in the root src folder).</li><li>Add or update the following code:</li></ul><pre>// main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  //Enable CORS for a specific frontend URL<br>  app.enableCors({<br>    origin: &#39;http://localhost:3000&#39;, // your frontend URL<br>    credentials: true, // use this if you&#39;re sending cookies or tokens<br>  });<br><br>  await app.listen(5000);<br>}<br>bootstrap();</pre><h4>Notes:</h4><ul><li>Use &#39;http://localhost:3000&#39; if your frontend is running locally (like React or Angular).</li><li>In production, replace it with your deployed frontend URL like &#39;https://yourfrontend.com&#39;.</li><li>credentials: true is needed only if you&#39;re using <strong>cookies</strong>, <strong>JWT tokens</strong>, or <strong>sessions</strong>.</li></ul><h4>Conclusion</h4><p>CORS errors can be frustrating, especially when everything looks good in Postman. But once you understand how CORS works, fixing it becomes easy.</p><p>As backend developers, we need to:</p><ul><li>Understand what the frontend needs</li><li>Configure our APIs to allow cross-origin requests safely</li><li>Avoid the blame game and work as a team</li></ul><p>Next time someone says “CORS error,” you’ll know exactly what to do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb0fbb44907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Rate Limiting Techniques for Node.js API Security]]></title>
            <link>https://medium.com/@sherinofficial98/exploring-rate-limiting-techniques-for-node-js-api-security-007cddd6aed0?source=rss-07908e60e743------2</link>
            <guid isPermaLink="false">https://medium.com/p/007cddd6aed0</guid>
            <dc:creator><![CDATA[SHERIN RAJ THANGAPPA D.]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 05:17:11 GMT</pubDate>
            <atom:updated>2024-08-23T05:17:11.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Rate limiting is crucial for safeguarding your application from misuse and ensuring that resources are used fairly. In this article, I will cover the fundamental steps to implement rate limiting in a Node.js application using the express-rate-limit library .</p><p>Let’s dive in!</p><h4>What is Rate Limiting?</h4><p>Rate limiting is a technique used to control the number of requests a user can make to a server within a specific time period. It helps prevent abuse by limiting excessive requests, ensuring that resources are used fairly and the server remains stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*gpwhYP8gvjTdP0iUJmNbkw.png" /></figure><h4>Real-World Scenario:</h4><p>Think of rate limiting like the withdrawal limit on an ATM. A bank sets a limit on the amount of money you can take out in a day. This helps prevent fraud and makes sure everyone has fair access to their money. If one person could withdraw unlimited amounts, it might run the ATM out of cash, leaving others without access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*0YpGke0aHuXM0z6xRDRauQ.png" /></figure><p>Similarly, rate limiting in a server sets a limit on how many times a user can request data in a certain period. This stops any single user from making too many requests and potentially crashing the server. By limiting the number of requests, we ensure that all users get a fair chance to access the server’s resources and that the server remains stable and available for everyone.</p><h3>Setting Up Your Node.js Project</h3><p>First, let’s initialize a new Node.js project. If you don’t already have Node.js and npm installed, you’ll need to install them from <a href="https://nodejs.org/">nodejs.org</a>.</p><h4>Installing Required Packages</h4><p>We’ll need express for our web server and express-rate-limit for rate limiting.</p><pre>npm install express express-rate-limit</pre><h4>Creating the Basic Express Server</h4><p>Create a file named server.js and set up a basic Express server.</p><pre>const express = require(&#39;express&#39;);<br>const rateLimit = require(&#39;express-rate-limit&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>// Apply rate limiting to all requests<br>const limiter = rateLimit({<br>  windowMs: (process.env.TIME_GAP_IN_MINUTES) * 60 * 1000, // window duration in minutes<br>  max: process.env.NUMBER_OF_REQUEST, // limit each IP to this number of requests per window<br>});<br><br>app.use(limiter);<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Welcome to the Rate Limiting Demo!&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><h4>Configuring Environment Variables</h4><p>Create a .env file in your project root to store configuration variables.</p><pre>PORT=3000<br>TIME_GAP_IN_MINUTES=15<br>NUMBER_OF_REQUEST=100</pre><h4>Response Details</h4><p>You can test the rate limiter by sending multiple requests to the server. After exceeding the defined number of requests (NUMBER_OF_REQUEST),the server responds with a 429 Too Many Requests status code. The response body typically includes a message explaining the error.</p><p>For example,</p><pre>{<br>  &quot;message&quot;: &quot;Too many requests, please try again later.&quot;<br>}</pre><h4>Customizing the Rate Limit Response</h4><p>You can customize the response message when the rate limit is exceeded by passing a custom message to the rateLimit middleware:</p><pre>const limiter = rateLimit({<br>  windowMs: (process.env.TIME_GAP_IN_MINUTES) * 60 * 1000,<br>  max: process.env.NUMBER_OF_REQUEST,<br>  message: {<br>    status: 429,<br>    message: &quot;You have exceeded the request limit. Please try again later.&quot;<br>  }<br>});</pre><p>This customization helps provide more informative and user-friendly messages to clients.</p><p>It’s important to handle rate limit errors gracefully in your application. When a 429 Too Many Requests error is encountered, you can inform users about the rate limit and suggest trying again later. This can be done by catching the error in your client-side code and displaying an appropriate message.</p><h4>Advantages of Rate Limiting</h4><ul><li><strong>Prevents Abuse</strong>: Stops malicious users from overwhelming your server with too many requests.</li><li><strong>Ensures Fair Usage</strong>: Guarantees that all users get equal access to your resources.</li><li><strong>Improves Stability</strong>: Reduces the risk of server crashes due to high traffic.</li><li><strong>Improves User Experience</strong>: When the server is not overloaded, it can respond to requests more quickly.</li></ul><h3>Conclusion</h3><p>This guide covers the basics of implementing rate limiting in a Node.js application using the express-rate-limit library. By setting up rate limiting, you can effectively manage the traffic to your server, prevent abuse, and ensure fair usage of your resources. Integrating this feature is straightforward and provides a significant boost to the security and reliability of your application.</p><p>As you continue to develop and scale your applications, remember that rate limiting is just one of many tools available to you. It’s important to consider other security measures and optimizations to keep your application running smoothly and securely. With rate limiting in place, you can confidently manage your server’s traffic and provide a better experience for your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=007cddd6aed0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Interactive Learning Assistant with NestJS and Google Generative AI]]></title>
            <link>https://medium.com/@sherinofficial98/creating-an-interactive-learning-assistant-with-nestjs-and-google-generative-ai-76e31e9b9602?source=rss-07908e60e743------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e31e9b9602</guid>
            <dc:creator><![CDATA[SHERIN RAJ THANGAPPA D.]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 04:58:14 GMT</pubDate>
            <atom:updated>2024-07-21T15:05:12.344Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, I will explore how to build an interactive learning assistant using NestJS and Google Generative AI. I’ll guide you through the process of setting up a NestJS service that leverages Google’s AI capabilities to create dynamic learning content based on specified topics. From configuring the service to defining data transfer objects (DTOs) and managing requests in a controller, join me as I uncover the process of harnessing AI for engaging and personalized learning. Let’s get started on transforming ideas into interactive learning experiences!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*XFPkHkKCJlYNwqYt.jpeg" /></figure><h3>What is Gemini AI?</h3><p>Gemini AI is an advanced artificial intelligence platform developed by Google. It’s designed to create interactive and engaging content based on user inputs. By using natural language processing and machine learning models, Gemini AI can understand prompts and generate responses that are contextually relevant. This platform leverages deep learning techniques to improve its ability to produce high-quality content, including text, images, and other media. Its versatility allows customization for various creative and educational purposes, making it a powerful tool for generating dynamic learning experiences.</p><h3>Why AI?</h3><p>AI is transforming many industries, including education, by providing tools that enhance learning experiences and make educational content more accessible and engaging. In our case, leveraging Google’s Generative AI allows us to dynamically generate learning content tailored to user-defined topics. This capability showcases AI’s potential in creating interactive and personalized educational experiences, revolutionizing how we learn and interact with information.</p><h3>Prerequisites</h3><p>Before we start, ensure you have the following:</p><p><strong>Node.js and npm installed</strong></p><ul><li>Download and install from the <a href="https://nodejs.org/">official Node.js website</a>.</li></ul><p><strong>NestJS CLI installed</strong></p><ul><li>Install globally using the command: npm install -g @nestjs/cli.</li></ul><p><strong>A Google Cloud account</strong></p><ul><li>Sign up for a Google Cloud account and ensure you have access to the Generative AI API.</li></ul><h3>Creating the DTO</h3><p>Data Transfer Objects (DTOs) are used to define the shape of data for requests and responses. Let’s create a DTO to validate the topic parameter for our learning content generation.</p><p><strong>Define the DTO class</strong></p><ul><li>Create a file named learning.dto.ts in the src directory.</li><li>Use @ApiProperty to provide metadata for Swagger documentation..</li><li>Use @IsString and @IsNotEmpty from class-validator for validation.</li></ul><pre>import { ApiProperty } from &#39;@nestjs/swagger&#39;;<br>import { IsString, IsNotEmpty } from &#39;class-validator&#39;;<br><br>export class CreateLearningContentDto {<br>  @ApiProperty({<br>    example: &#39;Any_Topic&#39;,<br>  })<br>  @IsString()<br>  @IsNotEmpty()<br>  topic: string;<br>}</pre><h3>Implementing the Service</h3><p>The service will handle the interaction with the Google Generative AI API.</p><p><strong>Create the service class</strong></p><ul><li>Create a file named learning.service.ts in the src directory.</li><li>Use @Injectable to mark the class as a provider.</li></ul><p><strong>Initialize the Google Generative AI client</strong></p><ul><li>Use the @google/generative-ai package to interact with the API.</li></ul><h4>Define the method to generate learning content</h4><ul><li>Create a method generateLearningContent that accepts a topic as an argument.</li><li>Use a prompt to request learning content from the API.</li><li>Process the API response and format it as needed.</li></ul><pre>import { GoogleGenerativeAI } from &#39;@google/generative-ai&#39;;<br>import { BadRequestException, Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class LearningService {<br>  constructor() {}<br><br>  async generateLearningContent(topic: string) {<br>    try {<br>      const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);<br><br>      const model = genAI.getGenerativeModel({ model: &#39;gemini-1.5-flash&#39; });<br><br>      const prompt = `Create a flashcard about ${topic}. Provide a question and an answer.`;<br><br>      const result = await model.generateContent([prompt]);<br><br>      const responseText = await result.response.text();<br>      const cleanedResponse = responseText.replace(/```json|```/g, &#39;&#39;).trim();<br>      const jsonResponse = JSON.parse(cleanedResponse);<br><br>      return {<br>        question: jsonResponse.question,<br>        answer: jsonResponse.answer,<br>      };<br>    } catch (error) {<br>      console.error(&#39;Error generating learning content:&#39;, error);<br>      throw new BadRequestException(&#39;Invalid input to create content&#39;);<br>    }<br>  }<br>}</pre><h3>Creating the Controller</h3><p>The controller will handle incoming HTTP requests and use the service to generate quiz questions.</p><p><strong>Define the controller class</strong></p><ul><li>Create a file named learning.controller.ts in the src directory.</li><li>Use @Controller to define the base route for the controller.</li><li>Inject the LearningService to handle the business logic.</li></ul><p><strong>Define the route handler</strong></p><p>A router in NestJS defines how HTTP requests are handled. Here’s how you define a route handler:</p><ul><li>Use @Get to define the GET endpoint.</li><li>Use @Query to bind query parameters to the DTO.</li><li>Use @UseGuards to apply middleware for authorization (optional).</li></ul><pre>import {<br>  Controller,<br>  Get,<br>  Query,<br>  BadRequestException,<br>  UseGuards,<br>} from &#39;@nestjs/common&#39;;<br>import { CreateLearningContentDto } from &#39;./learning.dto&#39;;<br>import { LearningService } from &#39;./learning.service&#39;;<br>import { AuthGuard } from &#39;src/middleware/authorization&#39;;<br><br>@Controller(&#39;learning&#39;)<br>export class LearningController {<br>  constructor(private readonly learningService: LearningService) {}<br><br>  @UseGuards(AuthGuard)<br>  @Get(&#39;/generate&#39;)<br>  async generateContent(@Query() createLearningContentDto: CreateLearningContentDto) {<br>    if (!createLearningContentDto.topic) {<br>      throw new BadRequestException(&#39;Topic is required&#39;);<br>    }<br><br>    const content = await this.learningService.generateLearningContent(createLearningContentDto.topic);<br>    return content;<br>  }<br>}</pre><h3>Input and Output Overview</h3><h3>Input</h3><p>When making a request to our learning content generator API, you need to provide a topic as a query parameter.</p><h4>Example Request</h4><pre><strong>GET /gemini/results?topic=science</strong></pre><p><strong>Query Parameter:</strong></p><ul><li>Topic: This is the subject or area for which you want to generate a quiz question, provided as a string. Here, I’m specifying “science” as the topic.</li></ul><h3>Output</h3><p>The output will be a JSON object containing the generated question and answer for the learning content.</p><h4>Example Response</h4><pre>{<br>  &quot;question&quot;: &quot;What is the chemical symbol for water?&quot;,<br>  &quot;answer&quot;: &quot;H2O&quot;<br>}</pre><h3>Conclusion</h3><p>Leveraging Google’s Generative AI, we’ve built an interactive learning assistant with remarkable capabilities. This innovative tool utilizes AI to dynamically generate learning content tailored to user-defined topics, showcasing the transformative potential of artificial intelligence in educational content creation and interactive learning.</p><p>AI has the power to revolutionize education and other fields by making tasks more efficient and personalized. Embrace the potential of AI to innovate and enhance the way we learn and interact with information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e31e9b9602" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing Websockets for Real-Time Development in Nest.js]]></title>
            <link>https://medium.com/@sherinofficial98/harnessing-websockets-for-real-time-development-in-nest-js-674abcf157b2?source=rss-07908e60e743------2</link>
            <guid isPermaLink="false">https://medium.com/p/674abcf157b2</guid>
            <dc:creator><![CDATA[SHERIN RAJ THANGAPPA D.]]></dc:creator>
            <pubDate>Mon, 17 Jun 2024 15:39:53 GMT</pubDate>
            <atom:updated>2024-06-17T16:02:26.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Websockets provide a powerful way to enable real-time communication between a client (like a web browser) and a server. In this article, we’ll explore how to set up a websocket server using Nest.js, a modern TypeScript framework for building efficient and scalable server-side applications. We’ll also create a simple client application that connects to our websocket server using socket.io-client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*zdy9cGI3GfmPacUuG_qFJQ.jpeg" /></figure><h4>Real-World Use Cases</h4><p>Websockets are employed in various industries and applications to enhance user experience and deliver dynamic content. Some common use cases include:</p><ul><li><strong>Live Chat and Messaging Applications</strong></li><li><strong>Real-Time Collaborative Editing</strong></li><li><strong>Financial Trading and Stock Market Updates</strong></li><li><strong>Gaming and Interactive Entertainment</strong></li></ul><h4><strong>Why Websockets?</strong></h4><p>Websockets provide several advantages over traditional HTTP communication methods, making them well-suited for applications that require real-time updates and interactive features:</p><ul><li><strong>Low Latency Communication</strong>: Websockets enable real-time communication with minimal delay, essential for applications like online gaming, live streaming, and chat applications.</li><li><strong>Bidirectional Data Flow</strong>: Unlike HTTP, which follows a request-response model, Websockets allow for continuous two-way communication between the client and server.</li><li><strong>Reduced Bandwidth Usage</strong>: Websockets reduce overhead by eliminating the need for HTTP headers after the initial handshake, making them more efficient for frequent message exchanges.</li><li><strong>Scalability</strong>: Websockets support high concurrency with fewer resources, making them ideal for scaling applications that handle many simultaneous connections.</li><li><strong>Simplified Development</strong>: With Websockets, developers can create more interactive and dynamic user experiences without relying on complex polling mechanisms or workarounds.</li><li><strong>Improved User Experience</strong>: Real-time updates and instant data transmission lead to a smoother and more responsive user experience, crucial for modern web applications.</li></ul><h4>Comparison Between HTTP and Websockets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*58qaRWFt3s5zTLrjDSgeGA.png" /></figure><h3>Setting Up the Backend</h3><ol><li><strong>Install Necessary Packages</strong></li></ol><p>Make sure you have Node.js installed on your system. You can create a new Nest.js project or add websocket functionality to an existing project.</p><pre><strong>npm install @nestjs/websockets socket.io</strong></pre><p>This command installs the @nestjs/websockets package, which provides websocket functionality within Nest.js, and socket.io, a library that simplifies websocket communication.</p><p><strong>2. Implement WebSocket Gateway</strong></p><p>Implement the websocket gateway to handle connections and events:</p><pre>import { WebSocketGateway, WebSocketServer } from &#39;@nestjs/websockets&#39;;<br>import { Server, Socket } from &#39;socket.io&#39;;<br><br>@WebSocketGateway()<br>export class WebsocketGateway {<br><br>  @WebSocketServer() server: Server;<br><br>  constructor() {<br>    this.server.on(&#39;connection&#39;, (socket: Socket) =&gt; {<br>      console.log(`Client connected: ${socket.id}`);<br><br>      // Example: Send a welcome message to the client<br>      socket.emit(&#39;message&#39;, &#39;Welcome to the websocket server!&#39;);<br><br>      // Example: Handle &#39;events&#39; sent by the client<br>      socket.on(&#39;events&#39;, (data) =&gt; {<br>      <br>      socket.emit(&#39;response&#39;, `Received: ${data}`);<br>      });<br>    });<br>  }<br>}</pre><p>In this example:</p><ul><li>@WebSocketGateway() decorates the class to indicate it&#39;s a websocket gateway.</li><li>@WebSocketServer() provides access to the websocket server instance.</li><li>Inside the constructor, this.server.on(&#39;connection&#39;, ...) listens for new client connections and handles them. It sends a welcome message to the client upon connection and listens for and responds to &#39;events&#39; from the client.</li></ul><h3>Setting Up the Frontend</h3><ol><li><strong>Install </strong><strong>socket.io-client</strong></li></ol><p>In your client-side application, install socket.io-client:</p><pre><strong>npm install socket.io-client</strong></pre><p><strong>2. Client-side Code</strong></p><p>Create a client script (like client.tsx or integrate it within your frontend application) to establish a connection with the WebSocket server and manage message reception and transmission:</p><pre>import io from &#39;socket.io-client&#39;;<br><br>const socket = io(&#39;server_URL&#39;); // Replace with your websocket server URL<br><br>socket.on(&#39;connect&#39;, () =&gt; {<br>  console.log(&#39;Connected to websocket server&#39;);<br>});<br><br>socket.on(&#39;message&#39;, (message) =&gt; {<br>  console.log(&#39;Received message:&#39;, message);<br>});<br><br>// Example: Send a message from client to server<br>setTimeout(() =&gt; {<br>  socket.emit(&#39;events&#39;, &#39;Hello from client&#39;);<br>}, 1000); // Delay to simulate connection establishment<br><br>// Example: Receive a message from server to client<br>socket.on(&#39;response&#39;, (data) =&gt; {<br>  console.log(&#39;Received response:&#39;, data);<br>});</pre><p>This client script connects to the websocket server (&#39;server_URL&#39;), logs when it successfully connects, sends an &#39;events&#39; message to the server after a delay, and listens for &#39;message&#39; and &#39;response&#39; events from the server.</p><p><strong>Code Explanation:</strong></p><p><strong>socket.emit(event, data)</strong>:</p><ul><li>This method is used to send a message to the client. The first argument is the name of the event, and the second argument is the data you want to send. In the example above, socket.emit(&#39;message&#39;, &#39;Welcome to the WebSocket server!&#39;) sends a &#39;message&#39; event with a welcome message to the client.</li></ul><p><strong>socket.on(event, callback)</strong>:</p><ul><li>This method is used to listen for an event from the client. The first argument is the name of the event, and the second argument is a callback function that handles the event. In the example above, socket.on(&#39;events&#39;, (data) =&gt; {...}) listens for &#39;events&#39; sent by the client and handles them.</li></ul><h3><strong>Conclusion</strong></h3><p>Websockets are a powerful technology for enabling real-time communication between clients and servers. By leveraging Websockets with Nest.js, developers can build scalable, efficient, and interactive applications. This article provided an overview of Websockets, their advantages over traditional HTTP, and a step-by-step guide to setting up a WebSocket server and client using Nest.js and <strong>socket.io-client</strong>. Whether you are building live chat applications, real-time collaborative tools, or online gaming platforms, Websockets can significantly enhance the user experience with instant, bidirectional data flow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674abcf157b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>