<?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 Rajeshwaran K on Medium]]></title>
        <description><![CDATA[Stories by Rajeshwaran K on Medium]]></description>
        <link>https://medium.com/@rajeshwaran-blog?source=rss-c1ec8f1a27e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zqMz7mfR_PIsc9s3AkEUDA.jpeg</url>
            <title>Stories by Rajeshwaran K on Medium</title>
            <link>https://medium.com/@rajeshwaran-blog?source=rss-c1ec8f1a27e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:42:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajeshwaran-blog/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[ Let AI Watch Me Work: Automate Daily Activity Reports with AI]]></title>
            <link>https://medium.com/@rajeshwaran-blog/let-ai-watch-me-work-automate-daily-activity-reports-with-ai-0c5a1fd0ff95?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c5a1fd0ff95</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 08:10:25 GMT</pubDate>
            <atom:updated>2025-06-07T08:29:10.986Z</atom:updated>
            <content:encoded><![CDATA[<p>Built with Python, ActivityWatch, and Mistral AI to eliminate manual timesheet pain.</p><blockquote>“I always forgot to update my timesheet at the end of the day… so I built an AI that does it for me.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1KN_pQX18xvfM6N2uvlOw.png" /></figure><h3>👋 Introduction</h3><p>In today’s fast-paced development environments, tracking your work isn’t just about billing time — it’s about <strong>understanding your productivity patterns</strong>.</p><p>But let’s be honest:</p><p>Filling out timesheets is tedious, manual, and easy to forget.</p><p>So I built a solution that:</p><ul><li>Monitors my daily work activity</li><li>Uses <strong>Mistral AI</strong> to generate human-like activity summaries</li><li>Sends me a <strong>daily email report</strong></li><li>Logs everything in a CSV for historical analysis</li></ul><p>Let me walk you through how I automated my timesheet using Python, <strong>ActivityWatch</strong>, <strong>Mistral AI</strong>, and Gmail.</p><h3>🛠️ Tech Stack</h3><ul><li><strong>Python</strong> for automation scripting</li><li><strong>ActivityWatch</strong> to capture detailed work activity</li><li><strong>mistral-large-latest </strong>model for natural language summarization via their API</li><li><strong>smtplib</strong> and <strong>email</strong> packages for sending email reports</li><li><strong>schedule</strong> for running the script hourly/daily</li><li>CSV files for persistent logging</li></ul><h3>⚙️ How It Works</h3><p>Every Day, the script:</p><ul><li>Fetches activity data from <a href="https://activitywatch.net/">ActivityWatch</a></li><li>Sends that raw data to Mistral AI to generate a concise summary</li><li>Appends the summary to a CSV file</li><li>Sends an email report with the summary</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Udr5zpX8WSaGUcFu687yRw.png" /><figcaption>Flow chart</figcaption></figure><p>It even runs daily at 12:00 PM using the schedule package.</p><h3>🧠 Sample Summary Generated by Mistral AI</h3><p>Here’s what <strong>Mistral AI </strong>wrote about one of my work hours:</p><blockquote><em>“From 10:20 to 11:10 AM, the user was deeply engaged in software development. The majority of time was spent in Visual Studio Code, toggling between Python source files, terminal logs, and GitHub. Short interactions on Microsoft Teams indicated collaboration with teammates. There was occasional browser use, likely for referencing documentation or testing.”</em></blockquote><p>Sounds like a human, right?</p><p>🧪 Code Snippet (Main Logic)</p><pre>def generate_report():<br>    now = datetime.datetime.now(datetime.UTC)<br>    start = now - datetime.timedelta(hours=1)<br>    <br>    # Fetch ActivityWatch buckets<br>    response = requests.get(f&quot;{AW_SERVER}/api/0/buckets&quot;)<br>    buckets = response.json()<br><br>    all_logs = []<br>    for bucket_id in buckets:<br>        if &quot;aw-watcher-window_&quot; in bucket_id or &quot;aw-watcher-web&quot; in bucket_id:<br>            events = get_bucket_data(bucket_id, start, now)<br>            for e in events:<br>                all_logs.append({<br>                    &#39;timestamp&#39;: e[&#39;timestamp&#39;],<br>                    &#39;duration_sec&#39;: e[&#39;duration&#39;],<br>                    &#39;app&#39;: e[&#39;data&#39;].get(&#39;app&#39;, &#39;web&#39;),<br>                    &#39;title&#39;: e[&#39;data&#39;].get(&#39;title&#39;, &#39;unknown&#39;)<br>                })<br>    <br>    summary = generate_comprehensive_summary(all_logs)<br>    append_to_csv(current_date, summary, total_hours)<br>    send_email_report(summary)</pre><h3>📧 What the Email Report Looks Like</h3><p>You receive an email like this:</p><p><strong>Subject:</strong> Activity Summary - 2025-06-07 12:00</p><p><strong>Body:</strong></p><pre>&lt;h2&gt;Activity Summary&lt;/h2&gt;<br>&lt;p&gt;<br>From 10 AM to 11 AM, you worked primarily on Visual Studio Code, reviewing logs and switching between modules. A few quick messages were sent over Microsoft Teams. Most of the time was spent productively coding and reviewing issues.<br>&lt;/p&gt;</pre><h3>📈 CSV Logging for History</h3><p>Every report is logged in a CSV file like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*OUrGGFsddV8oA_7KP33wDA.png" /></figure><h3>💡 Why I Built This</h3><p>Every month-end, I used to scramble to remember what I worked on. It was frustrating.</p><p>Now I don’t worry — this system sends me summaries automatically.<br> It’s like having an AI-powered <strong>productivity assistant</strong>.</p><p>📌 What You Can Build on Top</p><ul><li>✅ Add productivity score (based on app category)</li><li>📊 Visualize historical logs</li><li>🔁 Integrate with Jira or Trello</li><li>🗂️ Create a dashboard (with Streamlit or Angular)</li></ul><h3>📦 Code Repository</h3><blockquote><em>I’ll be publishing the completed source code on GitHub .<br></em><a href="https://github.com/Rajeshwaran7/activity-logs"><strong>Github Repo</strong></a></blockquote><h3>🙌 Wrapping Up</h3><p>This little side project saved me hours and mental load — all with Python, AI, and a bit of automation.</p><p>If you’re a developer, freelancer, or just want to track your time without the pain of manual entry, give this a try.</p><h3>💬 Have questions or ideas to improve this?</h3><p>Drop a comment or DM me on LinkedIn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c5a1fd0ff95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ I Made an AI Wedding on the Moon — And It Looked Like a Hollywood Sci-Fi Love Story]]></title>
            <link>https://medium.com/@rajeshwaran-blog/i-made-an-ai-wedding-on-the-moon-and-it-looked-like-a-hollywood-sci-fi-love-story-3fec39e0186a?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fec39e0186a</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 10:32:23 GMT</pubDate>
            <atom:updated>2025-04-24T10:32:23.940Z</atom:updated>
            <content:encoded><![CDATA[<h3>💍 I Made an AI Wedding on the Moon — And It Looked Like a Hollywood Sci-Fi Love Story</h3><blockquote>“A couple getting married on the moon, Earth rising behind them… all generated by AI? Yep. I did that.”</blockquote><p>When I got access to <strong>Google Veo 2</strong>, I knew I wanted to go big. No cats dancing. No neon city. I wanted to test its limits — emotionally and visually. So I asked it to generate a cinematic video of a wedding…</p><p><strong>On. The. Moon.</strong></p><p>The results? Pure sci-fi magic.</p><h3>🧠 The Prompt That Made the AI Dream</h3><p>Here’s the exact prompt I used:</p><blockquote>“A romantic cinematic video of a couple getting married on the moon. They are wearing futuristic wedding outfits, exchanging vows under a glass dome with Earth visible in the background. The lunar surface is glowing softly, and guests in space suits are seated in a semi-circle. The scene has a dreamy, sci-fi atmosphere with ambient lighting and gentle background music. 4K resolution, 8 seconds, realistic style.”</blockquote><p>You read that right. I asked Google’s AI to generate a literal <em>moon wedding</em>. And it delivered like a cosmic Spielberg.</p><p>🎥 The Output: Like a Love Story</p><p>The video came back in <strong>4K</strong> and packed with cinematic beauty:</p><ul><li>A glass dome shimmering under ambient lights</li><li>Earth hanging like a glowing orb in the sky</li><li>Futuristic outfits with subtle, elegant tech flair</li><li>Guests in pristine space suits, watching in silence</li><li>Gentle motion. Dreamy vibe. Pure emotion.</li></ul><p>The whole scene had this <strong>melancholy-meets-marvel</strong> aesthetic. Like something out of <em>Interstellar x Her</em>.</p><p>And all I did was write a paragraph.</p><h3><strong>Here’s the videos I produced:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*fadGRT6tqs0ulTxpWguKvw.gif" /><figcaption>AI generated Video</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*9mX8YQ4dYBFgcKt5ncXr5Q.gif" /><figcaption>AI generated Video</figcaption></figure><h3>✨ Why Veo 2 Isn’t Just Cool — It’s a Creative Leap</h3><p>Google’s Veo 2 is not your average text-to-video model. It’s the closest thing we’ve got to an AI cinematographer. It doesn’t just “generate clips” — it <strong>interprets emotion</strong>, <strong>sets the tone</strong>, and <strong>crafts moments</strong>.</p><p>What stood out to me:</p><ul><li>🎯 <em>Prompt accuracy?</em> Freakishly good.</li><li>💡 <em>Lighting + depth?</em> Cinematic and moody.</li></ul><p>I wasn’t just watching a video. I was watching an idea come alive.</p><h3>🎯 The Big Picture: What Can You Use Veo 2 For?</h3><p>Beyond moon weddings? 😄</p><ul><li>🎥 Pre-vis for sci-fi short films</li><li>🛍️ Ad creatives that break the scroll</li><li>🎮 Game world teasers</li><li>📚 Edutainment — space, history, even literature</li><li>🧠 Brainstorming visual narratives faster than you can sketch</li></ul><p>It’s a tool. A muse. A production partner that never sleeps.</p><h3>🗣️ So… What Will You Create?</h3><p>Seriously, if you had an AI that could make <em>anything</em>, what would you prompt?</p><p>🔥 Dragons flying over floating islands?<br> 🌊 Mermaids DJing under glowing coral reefs?<br> 🌌 A kid flying through Saturn’s rings in a paper plane?</p><p>Whatever it is — <strong>Veo 2 can probably show it to you</strong> in 8 seconds.</p><h3>🛸 Final Thoughts: The Future Just Got Personal</h3><p>I didn’t expect my first video with Veo 2 to be a <em>love story on the moon</em>, but here we are. That’s the beauty of this tool — it turns dreams into data and renders imagination in 4K.</p><p>And this is just version 2. Imagine what version 5 will do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fec39e0186a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Studio Ghibli Meets Machine Learning: An Open Source Adventure]]></title>
            <link>https://medium.com/@rajeshwaran-blog/studio-ghibli-meets-machine-learning-an-open-source-adventure-f30892de4725?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f30892de4725</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 18:15:13 GMT</pubDate>
            <atom:updated>2025-04-24T17:00:36.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>🎨 <strong>Studio Ghibli Meets Machine Learning: An Open Source Adventure</strong></h3><blockquote>Everyone’s running to OpenAI and Midjourney to transform their selfies into Ghibli-inspired art. The results are beautiful, no doubt. But as someone who thrives on curiosity and code, I couldn’t help but ask:<br><strong>“What if I could build this magic myself? From scratch?”</strong></blockquote><p>That one question turned into an experimental weekend project that spiraled into a full-blown learning journey. What started as a simple image transformer idea turned into an AI-powered platform that lets users upload any image — a portrait, a pet photo, a landscape — and watch it morph into a dreamy, painterly scene reminiscent of <em>Spirited Away</em> or <em>Howl’s Moving Castle</em>. And the best part? It’s entirely open source, GPU-accelerated, and built with Hugging Face models, FastAPI, and React.</p><p>This blog post is not just a technical walkthrough. It’s a story about what happens when engineering curiosity meets a love for art. So if you’re into AI, anime, side projects, or just want to build something cool that’ll wow your friends, read on. Let’s build Ghibli-style magic — line by line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ar6h9w5HJbypfZSlolYwsw.png" /></figure><h3>🔍 Why Ghibli and Why Now?</h3><p>There’s a certain emotional depth and artistry in Studio Ghibli films that makes them timeless. The color palette, brush-stroke textures, and whimsical scenery have a kind of visual poetry. Translating that into a machine learning pipeline is no small feat — but thanks to the work of researchers and community contributors on Hugging Face, it’s now possible to emulate that style using diffusion models.</p><p>The model I chose, nitrosocke/Ghibli-Diffusion, is fine-tuned on the original Stable Diffusion architecture, sculpted specifically to reproduce the visual vibe of Ghibli. Unlike typical filters or GAN-based stylizers, diffusion models like this one understand structure, texture, and aesthetics at a much deeper level — making them perfect for truly artistic image generation.</p><h3>🧠 Model Selection: The Core of the Magic</h3><p>I explored several style transfer options before settling on the Hugging Face-hosted Ghibli-Diffusion model. Here&#39;s why it stood out:</p><ul><li>Trained explicitly on Ghibli-style illustrations</li><li>Easy to integrate using diffusers library</li><li>Accepts images as inputs (img2img), not just text</li><li>Optimized for torch.float16 (which makes GPU runs buttery smooth)</li></ul><p>It supports prompt-based style control while maintaining the structure of the original image — which is exactly what you want when working with portraits or landscapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8p0D68-UxWVr8OZkA2N3w.png" /></figure><h3>⚙️ Backend Architecture: FastAPI + Diffusers + PyTorch</h3><p>I wanted the backend to be lightweight, GPU-friendly, and easy to run locally or deploy to the cloud. FastAPI was a no-brainer. It’s fast, intuitive, and lets you create a RESTful API in minutes.</p><p>Here’s a high-level breakdown of what happens:</p><ol><li>User uploads an image</li><li>Image is resized and converted to RGB</li><li>We invoke the diffusion model with a “ghibli style” prompt</li><li>The stylized image is returned as a PNG</li></ol><h3>⚖️Backend Code( sample):</h3><pre>from fastapi import FastAPI, UploadFile, File<br>from fastapi.responses import FileResponse<br>from diffusers import StableDiffusionImg2ImgPipeline<br>import torch<br>from PIL import Image<br>import io<br><br>app = FastAPI()<br><br>pipe = StableDiffusionImg2ImgPipeline.from_pretrained(<br>    &quot;nitrosocke/Ghibli-Diffusion&quot;, torch_dtype=torch.float16<br>).to(&quot;cuda&quot;)<br><br>@app.post(&quot;/ghibli&quot;)<br>async def ghibli_style(file: UploadFile = File(...)):<br>    contents = await file.read()<br>    init_image = Image.open(io.BytesIO(contents)).convert(&quot;RGB&quot;).resize((512, 512))<br><br>    result = pipe(prompt=&quot;ghibli style&quot;, image=init_image, strength=0.75, guidance_scale=7.5).images[0]<br>    result.save(&quot;output.png&quot;)<br>    return FileResponse(&quot;output.png&quot;, media_type=&quot;image/png&quot;)</pre><p>This script uses the StableDiffusionImg2ImgPipeline from Hugging Face and leverages the GPU for fast image transformation. You can run this locally or deploy via Docker to Render, Hugging Face Spaces, or any GPU-enabled server.</p><h3>🌐 Frontend: Sleek, Simple, React-Powered ( sample)</h3><p>For the UI, I went with React — nothing fancy, just a clean uploader that shows you before and after images side-by-side. This minimal interface keeps the focus on the magic: your transformed image.</p><pre>import { useState } from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br><br>function App() {<br>  const [image, setImage] = useState(null);<br>  const [result, setResult] = useState(null);<br><br>  const handleUpload = async () =&gt; {<br>    const formData = new FormData();<br>    formData.append(&quot;file&quot;, image);<br><br>    const response = await axios.post(&quot;http://localhost:8000/ghibli&quot;, formData, {<br>      responseType: &quot;blob&quot;<br>    });<br><br>    const imageUrl = URL.createObjectURL(response.data);<br>    setResult(imageUrl);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Ghibli Style Converter&lt;/h1&gt;<br>      &lt;input type=&quot;file&quot; onChange={(e) =&gt; setImage(e.target.files[0])} /&gt;<br>      &lt;button onClick={handleUpload}&gt;Convert&lt;/button&gt;<br>      {result &amp;&amp; &lt;img src={result} alt=&quot;ghibli-style&quot; /&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>🚀 Step 4: Try It Locally</h3><ol><li>Clone backend &amp; frontend repos</li><li>Install Python dependencies: pip install fastapi diffusers torch pillow</li><li>Start backend: uvicorn main:app --reload</li><li>Start frontend: npm start</li><li>Upload image and see it Ghibli-fied ✨</li></ol><h3>📷 Sample Output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mghHKCkZ3yGPw9Hne7Rttg.png" /><figcaption>My Ghibli image converter sample pic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qo0bH6Wq4jDZURvT0lKCxg.png" /><figcaption>My Ghibli image converter sample pic</figcaption></figure><p>Landscapes turn into painted dreamscapes. Faces get a soft anime glow. Pets look like mythical companions. It’s addictive.</p><h3>🧠 Why Build It Yourself?</h3><p>While tools like Midjourney and OpenAI’s DALL·E offer one-click conversions, building something like this by hand gives you:</p><ul><li>Control over the pipeline (prompts, model choice, tuning)</li><li>Full data privacy — everything runs locally</li><li>A killer portfolio project</li><li>Deeper understanding of how generative models work</li></ul><p>This isn’t just style transfer. It’s engineering meets creativity. Art through code.</p><h3>🚀 What’s Next?</h3><p>This is just the beginning. I’m already thinking about v2:</p><ul><li>Add prompt customization</li><li>Support batch uploads or video frames</li><li>Build a community gallery</li><li>Allow style switching (Pixar, Van Gogh, Cyberpunk)</li><li>Deploy on GPU-enabled cloud platform with auth and usage stats</li></ul><p>I might even explore training my own style model in the future — imagine building your own custom aesthetic into an AI model. Now that’s the dream.</p><h3>🛠️ Tech Stack</h3><ul><li><strong>Backend Framework:</strong> FastAPI with Uvicorn server, Python 3.8+</li><li><strong>Model &amp; Inference:</strong> Hugging Face diffusers (StableDiffusionImg2ImgPipeline), PyTorch, CUDA (auto‑detect GPU or fallback to CPU)</li><li><strong>API Protocols:</strong> REST for fallback (/convert-to-ghibli), WebSocket for real‑time progress updates</li><li><strong>Frontend:</strong> React with Hooks, React Dropzone for file uploads, Axios for HTTP, native WebSocket API for real‑time communication</li><li><strong>Image Processing:</strong> Pillow for decoding/resizing, Base64 for encoding/transport, io and asyncio for streaming and background tasks</li><li><strong>DevOps &amp; Deployment:</strong> Docker (containerize backend), Render or Hugging Face Spaces (GPU‑enabled hosting), Vercel/Netlify (frontend), GitHub Actions for CI/CD</li><li><strong>CORS &amp; Security:</strong> FastAPI CORS middleware (allow_origins configuration), input validation, size/type checks on uploads</li></ul><h3>✨ Conclusion: From Engineer to Dreamweaver</h3><p>This project reminded me that code isn’t just about logic and function — it’s about possibility. In just a few days, I turned a wild idea into something tangible, shareable, and straight-up magical.</p><p>If you’re a developer reading this, my advice is simple: <strong>don’t just use the magic. Build it.</strong></p><p>Even in a world full of API shortcuts and prebuilt tools, the joy of creating something with your own hands is unmatched.</p><p>Let the world turn their selfies into Ghibli art using other apps — you’re the kind of person who builds the Ghibli converter from the ground up.</p><p>🔗 Links</p><ul><li>GitHub Repo: <a href="https://github.com/Rajeshwaran7/img-edit-poc">Rajeshwaran7/img-edit-poc</a></li><li>Hugging Face Model: <a href="https://huggingface.co/nitrosocke/Ghibli-Diffusion">https://huggingface.co/nitrosocke/Ghibli-Diffusion</a></li><li>Diffusers: <a href="https://huggingface.co/docs/diffusers">https://huggingface.co/docs/diffusers</a></li></ul><p>Let’s keep building cool, beautiful things. 🚀</p><p>#AI #MachineLearning #OpenSource #DeepLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f30892de4725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Exploring Google Agent Development Kit (ADK): Building Multi-Tool Agents with Gemini Pro]]></title>
            <link>https://medium.com/@rajeshwaran-blog/exploring-google-agent-development-kit-adk-building-multi-tool-agents-with-gemini-pro-0228276e7935?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0228276e7935</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 08:07:44 GMT</pubDate>
            <atom:updated>2025-04-13T09:46:00.062Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“The future of AI lies in intelligent agents that can reason, decide, and act across domains. Google’s Agent Development Kit (ADK) is a leap forward — and I got my hands dirty building real-world agents!”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiIAf90qktVfg-6oR6xKyw.png" /></figure><p><strong>Introduction</strong><br> The era of single‑purpose language models is giving way to intelligent, autonomous multi‑agent systems. At Google Cloud NEXT 2025, Google unveiled the <strong>Agent Development Kit (ADK)</strong> — an open‑source, Python‑first framework that streamlines the full agent lifecycle, from design and orchestration to evaluation and deployment. In this post, we’ll explore ADK’s core features and walk through a proof‑of‑concept: a <strong>Wellness Advisor</strong> that unites a Fitness Coach and a Wealth Advisor into a single, multi‑tool agent.</p><h3>🚀 What is Google ADK?</h3><p>Google’s Agent Development Kit is designed to help you:</p><ul><li><strong>Manage the Agent Lifecycle</strong><br> Define, test, evaluate, and deploy agents without stitching together disparate libraries.</li><li><strong>Orchestrate Multiple Tools</strong><br> Plug in custom functions, third‑party APIs, or even other agents as tools.</li><li><strong>Leverage Multi‑Modal Models</strong><br> Support for text, audio, and video via models like gemini-1.5-pro and gemini-2.0-flash-exp.</li><li><strong>Iterate Rapidly</strong><br> Use the built‑in CLI (adk run, adk web) and interactive Dev UI at http://localhost:8000/dev-ui for visual debugging.</li><li><strong>Deploy Anywhere</strong><br> Containerize your agents or run them on Kubernetes, Cloud Run, or Google’s managed Agent Engine.</li></ul><h3>Multi‑Modal Interaction</h3><p>ADK isn’t limited to text. By choosing a model such as gemini-2.0-flash-exp, you can enable:</p><ul><li><strong>Bidirectional Audio</strong>: Agents can listen and speak.</li><li><strong>Video Streams</strong>: Agents can process camera input or display visual outputs.</li><li><strong>Hybrid Workflows</strong>: Combine text prompts, voice commands, and visual data in a single session.</li></ul><h3>💡 Gemini Model Integration</h3><p>I integrated my agents using <strong>Gemini 1.5 Pro</strong> via Python. ADK makes it seamless to configure the model backend and wrap it inside custom agent workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDqqUk64qJjOfDHTB72Oww.png" /><figcaption>Gemini API key created in Google AI Studio</figcaption></figure><h3>🧪 My Experiment: Building Fitness + Wealth Agents</h3><p>I built two independent agents:</p><ul><li>🏋️‍♂️ A <strong>Fitness Coach Agent</strong> to calculate BMI, calories burned, and generate personalized workout plans.</li><li>💸 A <strong>Wealth Advisor Agent</strong> to project investment growth and analyze portfolios.</li></ul><p>Then, I combined them into a single <strong>Wellness Advisor</strong> agent — because in today’s world, health and wealth go hand-in-hand!</p><h3>📦 Agent Implementation in Python (Using gemini-1.5-pro)</h3><p>Here’s how I structured the agents in agent.py.</p><h3>🏋️‍♂️ Fitness Coach Agent</h3><pre>fitness_agent = Agent(<br>    name=&quot;fitness_coach&quot;,<br>    model=&quot;gemini-1.5-pro&quot;,<br>    description=(<br>        &quot;Agent to help with fitness tracking, workout planning, and health metrics calculation. &quot;<br>        &quot;Provides personalized advice based on user&#39;s fitness level and goals.&quot;<br>    ),<br>    instruction=(<br>        &quot;I can calculate health metrics like BMI and calories burned, create personalized &quot;<br>        &quot;workout plans, and provide fitness advice based on your specific needs and goals.&quot;<br>    ),<br>    tools=[calculate_bmi, calculate_calories_burned, create_workout_plan],<br>)</pre><h3>💰 Wealth Advisor Agent</h3><pre>wealth_agent = Agent(<br>    name=&quot;wealth_advisor&quot;,<br>    model=&quot;gemini-1.5-pro&quot;,<br>    description=(<br>        &quot;Agent to help with financial planning, investment analysis, and wealth building strategies. &quot;<br>        &quot;Provides guidance on investment growth and portfolio management.&quot;<br>    ),<br>    instruction=(<br>        &quot;I can help you project investment growth using compound interest calculations, &quot;<br>        &quot;analyze your investment portfolio allocation, and provide guidance on wealth building strategies.&quot;<br>    ),<br>    tools=[calculate_compound_interest, analyze_investment_portfolio],<br>)</pre><h3>🌱 Root Agent: Wellness Advisor</h3><pre>root_agent = Agent(<br>    name=&quot;wellness_advisor&quot;,<br>    model=&quot;gemini-1.5-pro&quot;,<br>    description=(<br>        &quot;Agent to help with both physical and financial wellness. &quot;<br>        &quot;Provides guidance on fitness, health metrics, investment planning, and wealth building.&quot;<br>    ),<br>    instruction=(<br>        &quot;I can help you with fitness tracking, workout planning, financial projections, &quot;<br>        &quot;and investment analysis to support both your physical and financial well-being.&quot;<br>    ),<br>    tools=[<br>        calculate_bmi, calculate_calories_burned, create_workout_plan,<br>        calculate_compound_interest, analyze_investment_portfolio<br>    ],<br>)</pre><h3>🧩 The Agent Tools I Created</h3><p>Each tool is a Python function that performs a specific task. For example:</p><pre>def calculate_bmi(weight, height):<br>    return round(weight / (height ** 2), 2)<br><br>def calculate_calories_burned(activity, duration_minutes):<br>    # Simplified logic<br>    return duration_minutes * 5  # placeholder<br><br>def calculate_compound_interest(principal, rate, time):<br>    return principal * (1 + rate/100) ** time</pre><blockquote><em>You can keep extending these tools as plugins and register them under agents as needed.</em></blockquote><h3>🌐 Run the Agent Locally with ADK CLI</h3><p>To run your agent and interact via browser:</p><pre>adk web</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wFWeNbTeTLY3Lwlxlbfiw.png" /><figcaption>You can see the logs in terminal</figcaption></figure><p>Then open your browser to:</p><pre>http://localhost:8000/dev-ui?app=multi_tool_agent</pre><p>You’ll be able to:</p><p>✅ View your multi-tool agent setup<br> ✅ Interact with your agents<br> ✅ Inspect agent request-response workflows<br> ✅ Debug tools and reasoning paths visually</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iv69NyJuz-IqBqPl1S60yw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euRbzdmuREgtY72S7mwi9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sn1WEKMjfwu4rUFi9angvg.png" /></figure><h3>🗣️ What About Multimodal?</h3><p>Currently, <strong>gemini-2.0-flash-exp</strong> is the only model supporting audio/video inputs and outputs for agents.</p><p>You can run it via:</p><ul><li>🔑 Your API Key from Google AI Studio</li><li>☁️ Google Cloud Vertex AI (for production-scale deployment)</li></ul><p>So, imagine a future where your fitness agent can take <strong>video form inputs</strong> and give <strong>voice-based health feedback</strong> — we’re almost there!</p><h3>🧠 What I Learned</h3><ul><li>ADK makes it insanely easy to build intelligent agents with tool integration.</li><li>Gemini models work well with natural language instructions tied to concrete tools.</li><li>Agent chaining and multi-domain use cases (like wellness) are very powerful.</li><li>Debugging via browser is a game-changer!</li></ul><h3>🛣️ What’s Next?</h3><p>I plan to:</p><ul><li>🔗 Deploy the agent to the cloud using Vertex AI</li><li>🎙️ Explore voice and video inputs using gemini-2.0-flash-exp</li><li>🧠 Try chaining agents together (fitness → wellness → mental health)</li><li>🧪 Build more agents like nutrition advisors and habit trackers</li></ul><h3>📌 Final Thoughts</h3><p>Google ADK is an exciting step toward real-world autonomous agents. With just a few lines of Python, I was able to simulate a mini-personal advisor system for fitness and finance. If you’re curious about where AI agents are headed — this is where you start!</p><h3>📦 Resources</h3><ul><li><strong>ADK Quickstart &amp; Docs</strong><br> <a href="https://google.github.io/adk-docs/get-started/quickstart">https://google.github.io/adk-docs/get-started/quickstart</a></li><li><strong>GitHub Repository</strong><br> <a href="https://github.com/google/adk-python">https://github.com/google/adk-python</a></li><li><strong>My POC Code</strong><br> <a href="https://github.com/Rajeshwaran7/poc-google-adk">https://github.com/Rajeshwaran7/poc-google-adk</a></li><li><strong>Google AI Studio (API Keys)</strong><br> <a href="https://studio.ai.google.com/">https://studio.ai.google.com</a></li><li><strong>Vertex AI</strong><br> <a href="https://cloud.google.com/vertex-ai">https://cloud.google.com/vertex-ai</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0228276e7935" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Scrum with OpenAI & Jira: Daily Standup Reports on Autopilot! ⚡]]></title>
            <link>https://medium.com/@rajeshwaran-blog/revolutionizing-scrum-with-openai-jira-daily-standup-reports-on-autopilot-440b443309a4?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/440b443309a4</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 11:39:56 GMT</pubDate>
            <atom:updated>2025-02-24T08:40:19.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdagOHWrG7Rlfhw0KKx8Ng.png" /></figure><p>Managing daily standups efficiently is a challenge for Scrum Masters, especially when juggling multiple projects. Keeping track of Jira boards, summarizing tasks, identifying blockers, and preparing concise reports can be time-consuming. To streamline this, I built an <strong>OpenAI-powered Jira Insights Scrum Report solution</strong>, which automates daily standup tracking by generating insightful reports delivered via email and Teams alerts.</p><p>In this article, I’ll walk you through how I built this solution using <strong>Python, OpenAI, FastAPI, and NestJS</strong>, integrated seamlessly with Jira.</p><h3>🎯 The Problem</h3><p>Scrum Masters often face these challenges during daily standups:</p><ol><li>Manually gathering and summarizing Jira tickets for each team member.</li><li>Identifying blockers and progress updates from scattered Jira boards.</li><li>Ensuring timely and consistent reporting across projects.</li><li>Lack of insights into task trends and potential risks.</li></ol><p>The manual process is inefficient and prone to missed details. A solution was needed to <strong>automate report generation, highlight blockers, and deliver insights proactively</strong>.</p><h3>💡 The Solution</h3><p>I developed an <strong>OpenAI-powered daily standup report solution</strong> that:</p><ol><li>Fetches <strong>raw Jira data</strong> using NestJS.</li><li>Passes the data to a <strong>Python FastAPI service</strong> for ML-based log analysis and report generation.</li><li>Uses <strong>OpenAI</strong> to summarize tasks, identify blockers, and provide insights.</li><li>Sends reports via <strong>email and Teams alerts</strong> to Scrum Masters and stakeholders.</li></ol><h3>🛠️ Architecture Overview</h3><p>Here’s how the solution works under the hood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_9B3sEA1v2zCP3o5yYM8A.png" /></figure><ol><li><strong>Jira Integration (NestJS):</strong></li></ol><ul><li>A <strong>NestJS microservice</strong> handles Jira integration, using cron jobs to fetch daily raw data.</li><li>This data includes user stories, tasks, bugs, and their current status.</li></ul><p>2. <strong>Data Processing (Python &amp; FastAPI):</strong></p><ul><li>The <strong>Python FastAPI service</strong> receives raw Jira data and processes it using custom <strong>ML-based log analysis</strong>.</li><li><strong>OpenAI API</strong> generates concise summaries, highlights blockers, and suggests next steps.</li></ul><p><strong>3. Alerting System (NestJS):</strong></p><ul><li>The processed report is passed back to the <strong>NestJS service</strong> for delivery.</li><li>Reports are sent via <strong>email and Teams alerts</strong>, ensuring timely updates for standups.</li></ul><h3>⚙️ Tech Stack</h3><p>The solution leverages the following technologies:</p><ul><li><strong>NestJS:</strong> Jira integration, cron jobs, and alerting system.</li><li><strong>Python &amp; FastAPI:</strong> Log analysis, report generation, and OpenAI integration.</li><li><strong>OpenAI API:</strong> Task summarization, blocker identification, and trend analysis.</li><li><strong>Email &amp; Teams Alerts:</strong> For report delivery.</li></ul><h3>📊 Key Features</h3><ol><li><strong>Automated Daily Reports:</strong> No manual Jira digging — get reports delivered every morning.</li><li><strong>Insightful Summaries:</strong> Highlights task progress, blockers, and overdue items.</li><li><strong>Trend Analysis:</strong> Detects sprint risks and workload imbalances.</li><li><strong>Multi-Channel Alerts:</strong> Reports sent via email and Teams for easy access.</li><li><strong>Customizable Scheduling:</strong> Cron jobs trigger report generation based on team preferences.</li></ol><p><strong>Existing Jira board:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nn6d69THnvuXwGoy9eI8Q.png" /><figcaption><strong>Existing Jira board</strong></figcaption></figure><h3>📝 Code Implementation</h3><p>Here’s a glimpse of the core implementation:</p><h3>1. Jira Data Fetching (NestJS)</h3><pre>import { HttpException, HttpStatus, Injectable } from &#39;@nestjs/common&#39;;<br>import axios from &#39;axios&#39;;<br>import PDFDocument from &#39;pdfkit&#39;;<br>@Injectable()<br>export class JiraService {<br>  private readonly jiraBaseUrl: string;<br>  private readonly jiraToken: string;<br>  private readonly jiraEmail: string;<br><br>  constructor() {<br>    this.jiraBaseUrl = process.env.JIRA_BASE_URL || &#39;&#39;;<br>    this.jiraToken = process.env.JIRA_API_TOKEN || &#39;&#39;;<br>    this.jiraEmail = process.env.JIRA_EMAIL || &#39;&#39;;<br>  }<br><br>  /**<br>   * Process the Jira webhook<br>   * @returns A JSON object containing the board details, active sprint, and epics with their stories<br>   */<br>  async processWebhook() {<br>    try {<br>      // Get board details with error handling<br>      const boardResponse = await axios.get(`${this.jiraBaseUrl}/rest/agile/1.0/board`, {<br>        auth: {<br>          username: this.jiraEmail,<br>          password: this.jiraToken<br>        }<br>      });<br>      <br>      if (!boardResponse.data.values || boardResponse.data.values.length === 0) {<br>        throw new HttpException(<br>          &#39;No boards found in Jira response&#39;,<br>          HttpStatus.NOT_FOUND<br>        );<br>      }<br><br>      const board = boardResponse.data.values[0];<br>      if (!board || !board.id) {<br>        throw new HttpException(<br>          &#39;Invalid board data received from Jira&#39;,<br>          HttpStatus.BAD_REQUEST<br>        );<br>      }<br><br>      const boardDetails = await this.getBoardDetails(board.id);<br>      <br>      // Get active sprint with error handling<br>      const activeSprint = await this.getActiveSprint(board.id);<br>      if (!activeSprint) {<br>        return {<br>          board: {<br>            id: board.id,<br>            name: board.name,<br>            ...boardDetails<br>          },<br>          message: &#39;No active sprint found&#39;,<br>          epics: []<br>        };<br>      }<br>      <br>      // Get sprint issues<br>      const sprintIssues = await this.getSprintIssues(activeSprint.id);<br>      <br>      // Get epics with error handling<br>      const {values: epics} = await this.getBoardEpics(board.id);<br>      if (!epics.length) {<br>        return {<br>          board: {<br>            id: board.id,<br>            name: board.name,<br>            ...boardDetails<br>          },<br>          activeSprint: {<br>            id: activeSprint.id,<br>            name: activeSprint.name,<br>            startDate: activeSprint.startDate,<br>            endDate: activeSprint.endDate,<br>            issues: sprintIssues?.map(issue =&gt; ({<br>              key: issue.key,<br>              summary: issue.fields?.summary,<br>              status: issue.fields?.status?.name,<br>              storyPoints: issue.fields?.customfield_10016 || null,<br>              assignee: issue.fields?.assignee ? {<br>                name: issue.fields.assignee.displayName,<br>                email: issue.fields.assignee.emailAddress<br>              } : null,<br>              priority: issue.fields?.priority?.name<br>            })) || []<br>          },<br>          epics: []<br>        };<br>      }<br><br>      // Get stories for each epic with error handling<br>      const epicsWithStories = await Promise.all(<br>        epics.map(async (epic) =&gt; {<br>          try {<br>            console.log(epic)<br>            const stories = await this.getEpicStories(epic.id);<br>            <br>            return {<br>              ...epic,<br>              stories: stories || []<br>            };<br>          } catch (error) {<br>            console.warn(`Failed to fetch stories for epic ${epic.id}:`, error.message);<br>            return {<br>              ...epic,<br>              stories: []<br>            };<br>          }<br>        })<br>      );<br><br>      return {<br>        board: {<br>          id: board.id,<br>          name: board.name,<br>          ...boardDetails<br>        },<br>        activeSprint: {<br>          id: activeSprint.id,<br>          name: activeSprint.name,<br>          startDate: activeSprint.startDate,<br>          endDate: activeSprint.endDate,<br>          issues: sprintIssues?.map(issue =&gt; ({<br>            key: issue.key,<br>            summary: issue.fields?.summary,<br>            status: issue.fields?.status?.name,<br>            storyPoints: issue.fields?.customfield_10016 || null,<br>            assignee: issue.fields?.assignee ? {<br>              name: issue.fields.assignee.displayName,<br>              email: issue.fields.assignee.emailAddress<br>            } : null,<br>            priority: issue.fields?.priority?.name<br>          })) || []<br>        },<br>        epics: epicsWithStories.map(epic =&gt; ({<br>          id: epic.id,<br>          key: epic.key,<br>          summary: epic.summary,<br>          stories: (epic.stories || []).map(story =&gt; ({<br>            key: story.key,<br>            summary: story.fields?.summary,<br>            status: story.fields?.status?.name,<br>            storyPoints: story.fields?.customfield_10016 || null,<br>            assignee: story.fields?.assignee ? {<br>              name: story.fields.assignee.displayName,<br>              email: story.fields.assignee.emailAddress<br>            } : null,<br>            priority: story.fields?.priority?.name<br>          }))<br>        }))<br>      };<br>    } catch (error) {<br>      console.error(&#39;Error in processWebhook:&#39;, error);<br>      throw new HttpException(<br>        `Failed to fetch Jira details: ${error.response?.data?.errorMessages?.[0] || error.message}`,<br>        HttpStatus.BAD_REQUEST<br>      );<br>    }<br>  }<br><br>  /**<br>   * Get the board details<br>   * @param boardId The ID of the board to get the details for<br>   * @returns A JSON object containing the board details<br>   */<br>  async getBoardDetails(boardId: number): Promise&lt;any&gt; {<br>    try {<br>      const response = await axios.get(`${this.jiraBaseUrl}/rest/agile/1.0/board/${boardId}/configuration`, {<br>        auth: {<br>          username: this.jiraEmail,<br>          password: this.jiraToken<br>        }<br>      });<br>      return response.data;<br>    } catch (error) {<br>      throw new HttpException(<br>        `Failed to fetch board details: ${error.message}`,<br>        HttpStatus.BAD_REQUEST<br>      );<br>    }<br>  }<br><br>  /**<br>   * Get the active sprint<br>   * @param boardId The ID of the board to get the active sprint for<br>   * @returns A JSON object containing the active sprint<br>   */<br>  async getActiveSprint(boardId: number): Promise&lt;any&gt; {<br>    try {<br>      const response = await axios.get(<br>        `${this.jiraBaseUrl}/rest/agile/1.0/board/${boardId}/sprint?state=active`,<br>        {<br>          auth: {<br>            username: this.jiraEmail,<br>            password: this.jiraToken<br>          }<br>        }<br>      );<br>      console.log(response.data)<br>      return response.data.values[0];<br>    } catch (error) {<br>      throw new HttpException(<br>        `Failed to fetch active sprint: ${error.message}`,<br>        HttpStatus.BAD_REQUEST<br>      );<br>    }<br>  }<br><br>  /**<br>   * Get the sprint issues<br>   * @param sprintId The ID of the sprint to get the issues for<br>   * @returns A JSON object containing the sprint issues<br>   */<br>  async getSprintIssues(sprintId: number): Promise&lt;any&gt; {<br>    try {<br>      const response = await axios.get(<br>        `${this.jiraBaseUrl}/rest/agile/1.0/sprint/${sprintId}/issue`,<br>        {<br>          auth: {<br>            username: this.jiraEmail,<br>            password: this.jiraToken<br>          },<br>          params: {<br>            fields: [&#39;summary&#39;, &#39;status&#39;, &#39;assignee&#39;, &#39;priority&#39;, &#39;customfield_10016&#39;]<br>          }<br>        }<br>      );<br>      return response.data.issues;<br>    } catch (error) {<br>      throw new HttpException(<br>        `Failed to fetch sprint issues: ${error.message}`,<br>        HttpStatus.BAD_REQUEST<br>      );<br>    }<br>  }<br><br>  /**<br>   * Get the board epics<br>   * @param boardId The ID of the board to get the epics for<br>   * @returns A JSON object containing the board epics<br>   */<br>  async getBoardEpics(boardId: number): Promise&lt;any&gt; {<br>    try {<br>      const response = await axios.get(<br>        `${this.jiraBaseUrl}/rest/agile/1.0/board/${boardId}/epic`,<br>        {<br>          auth: {<br>            username: this.jiraEmail,<br>            password: this.jiraToken<br>          }<br>        }<br>      );<br>      console.log(response.data)<br>      return response.data;<br>    } catch (error) {<br>      throw new HttpException(<br>        `Failed to fetch epics: ${error.message}`,<br>        HttpStatus.BAD_REQUEST<br>      );<br>    }<br>  }<br><br>  /**<br>   * Get the epic stories<br>   * @param epicId The ID of the epic to get the stories for<br>   * @returns A JSON object containing the epic stories<br>   */<br>  async getEpicStories(epicId: string): Promise&lt;any&gt; {<br>    try {<br>      // Try the Next-gen project API endpoint first<br>      const url = `${this.jiraBaseUrl}/rest/api/3/search`;<br>      console.log(`Fetching epic stories using JQL search`);<br><br>      const response = await axios.post(url, {<br>        jql: `parent = ${epicId}`,<br>        fields: [&#39;summary&#39;, &#39;status&#39;, &#39;assignee&#39;, &#39;priority&#39;, &#39;customfield_10016&#39;]<br>      }, {<br>        auth: {<br>          username: this.jiraEmail,<br>          password: this.jiraToken<br>        },<br>        validateStatus: (status) =&gt; status &lt; 500<br>      });<br><br>      console.log(`Epic stories response status: ${response.status}`);<br><br>      if (response.status !== 200) {<br>        console.warn(`Unexpected status ${response.status} for epic ${epicId}:`, response.data);<br>        return [];<br>      }<br>      console.log(response.data)<br>      return response.data.issues || [];<br>    } catch (error) {<br>      console.error(`Error fetching epic stories for epic ${epicId}:`, {<br>        message: error.message,<br>        response: error.response?.data<br>      });<br>      return [];<br>    }<br>  }<br><br>  /**<br>   * Get the board issues<br>   * @param boardId The ID of the board to get the issues for<br>   * @returns A JSON object containing the board issues<br>   */<br>  async getBoardIssues(boardId: number): Promise&lt;any&gt; {<br>    try {<br>        const response = await axios.get(`${this.jiraBaseUrl}/rest/agile/1.0/board/${boardId}/issue`, {<br>            auth: {<br>                username: this.jiraEmail,<br>                password: this.jiraToken<br>            }<br>        });<br><br>        return response.data;<br>    } catch (error) {<br>        throw new HttpException(<br>            `Failed to fetch issues for board ${boardId}: ${error.response?.data?.errorMessages || error.message}`,<br>            HttpStatus.BAD_REQUEST<br>        );<br>    }<br>}<br><br>/**<br> * Get the issue details<br> * @param issueKey The key of the issue to get the details for<br> * @returns A JSON object containing the issue details<br> */<br>async getIssueDetails(issueKey: string): Promise&lt;any&gt; {<br>    try {<br>        const response = await axios.get(`${this.jiraBaseUrl}/rest/api/3/issue/${issueKey}`, {<br>            auth: {<br>                username: this.jiraEmail,<br>                password: this.jiraToken<br>            }<br>        });<br><br>        return response.data;<br>    } catch (error) {<br>        throw new HttpException(<br>            `Failed to fetch issue details for ${issueKey}: ${error.response?.data?.errorMessages || error.message}`,<br>            HttpStatus.BAD_REQUEST<br>        );<br>    }<br>}<br>}<br></pre><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { JiraService } from &#39;../jira.service&#39;;<br>import { JiraController } from &#39;../jira.controller&#39;;<br>import { JiraAlertingService } from &#39;../alerting/jira-alerting.service&#39;;<br>import * as PDFDocument from &#39;pdfkit&#39;;<br>import { CronJob } from &#39;cron&#39;;<br>import { SchedulerRegistry } from &#39;@nestjs/schedule&#39;;<br>import axios from &#39;axios&#39;;<br><br>@Injectable()<br>export class JiraCronService {<br>  constructor(<br>    private readonly jiraService: JiraService,<br>    private readonly jiraAlertingService: JiraAlertingService,<br>    private readonly schedulerRegistry: SchedulerRegistry<br>  ) {}<br><br>  onModuleInit() {<br>    const job = new CronJob(&#39;0 9 * * *&#39;, () =&gt; {<br>      this.handleDailyJiraSync();<br>    });<br>    console.log(&#39;JiraCronService initialized&#39;);<br>    this.schedulerRegistry.addCronJob(<br>        `jiraCronJob`,<br>        job,<br>      );<br>   <br>    job.start();<br>  }<br><br>  async handleDailyJiraSync() {<br>    console.log(&#39;handleDailyJiraSync&#39;);<br>    try {<br>        const jiraData = await this.jiraService.processWebhook();<br>        const response = await axios.post(&#39;http://127.0.0.1:8000/generate-scrum-report&#39;, {<br>            jira_data: jiraData<br>        });<br>        const report = response.data.report;<br>     <br>      await this.jiraAlertingService.sendAlert(report,&#39;Daily Jira Sync Report&#39;);<br>      return &#39;response&#39;;<br>    } catch (error) {<br>      console.error(&#39;Error in daily Jira sync:&#39;, error);<br>      <br>    }<br>    console.log(&#39;Daily Jira sync completed successfully&#39;);<br>  }<br><br>  <br>}</pre><h3>2. Data Processing (Python &amp; FastAPI)</h3><pre>from fastapi import FastAPI, HTTPException, Request<br>from pydantic import BaseModel<br>import openai<br>import uvicorn<br>import json<br>from fastapi.middleware.cors import CORSMiddleware<br><br># Initialize FastAPI app<br>app = FastAPI()<br><br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br># Set your OpenAI API key<br>openai.api_key = &quot;&quot;<br><br># Pydantic model for request body<br>class JiraData(BaseModel):<br>    jira_data: dict<br><br># Function to generate AI-report<br>def generate_ai_report(jira_data):<br>    json_string = json.dumps(jira_data, indent=4)<br>    # Generate prompt for OpenAI<br>    prompt = (<br>        &quot;You are an AI Scrum Master. Analyze the following Jira sprint data and generate a detailed sprint report. &quot;<br>        &quot;The report should include the following sections:\n&quot;<br>        &quot;1. 📊 **Sprint Overview:** Brief summary of the sprint, including start and end dates.\n&quot;<br>        &quot;2. ✅ **Completed Work:** List of completed user stories and tasks with their story points.\n&quot;<br>        &quot;3. ⏳ **Incompleted Work:** Highlight unfinished tasks, blockers, and reasons for incompletion.\n&quot;<br>        &quot;4. 📈 **Team Performance:** Analyze velocity, burndown trends, and team collaboration.\n&quot;<br>        &quot;5. ⚠️ **Risks and Issues:** Identify any risks or impediments faced during the sprint.\n&quot;<br>        &quot;6. 💡 **Recommendations:** Suggestions for process improvements and how to increase efficiency.\n\n&quot;<br>        &quot;Here is the Jira sprint data:\n&quot;<br>        f&quot;{json_string}&quot;<br>    )<br><br>    # Call OpenAI API<br>    try:<br>        response = openai.chat.completions.create(<br>            model=&quot;gpt-4o-mini&quot;,<br>            messages=[<br>                {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are an AI Scrum Master assistant.&quot;},<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}<br>            ],<br>            max_tokens=700,<br>            temperature=0.7<br>        )<br>        return response.choices[0].message.content.strip()<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=f&quot;OpenAI API error: {str(e)}&quot;)<br>    <br># API endpoint to receive Jira board data and generate report<br>@app.post(&quot;/generate-scrum-report&quot;)<br>async def generate_scrum_report(data: JiraData):  # Updated to use Pydantic model<br>    try:<br>        report = generate_ai_report(data.jira_data)<br>        return {&quot;report&quot;: report}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))<br><br># Run the application<br>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(&quot;main:app&quot;, host=&quot;0.0.0.0&quot;, port=8000, reload=True)</pre><h3>3. Alerting System (NestJS)</h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import axios from &#39;axios&#39;;<br>import { marked } from &#39;marked&#39;;<br>import * as nodemailer from &#39;nodemailer&#39;;<br><br>@Injectable()<br>export class JiraAlertingService {<br>  private readonly emailEnabled: boolean;<br>  private readonly teamsEnabled: boolean;<br>  private readonly emailConfig: {<br>    host: string;<br>    port: number;<br>    secure: boolean;<br>    auth: {<br>      user: string;<br>      pass: string;<br>    };<br>  };<br>  private readonly teamsWebhookUrl: string;<br><br>  constructor() {<br>    // Initialize from environment variables<br>    this.emailEnabled = process.env.ENABLE_EMAIL_ALERTS === &#39;true&#39;;<br>    this.teamsEnabled = process.env.ENABLE_TEAMS_ALERTS === &#39;true&#39;;<br>    <br>    if (this.emailEnabled) {<br>      this.emailConfig = {<br>        host: process.env.EMAIL_HOST || &#39;smtp.gmail.com&#39;,<br>        port: parseInt(process.env.EMAIL_PORT || &#39;587&#39;),<br>        secure: process.env.EMAIL_SECURE === &#39;true&#39;,<br>        auth: {<br>          user: process.env.EMAIL_USER!,<br>          pass: process.env.EMAIL_PASSWORD!<br>        }<br>      };<br>    }<br><br>    if (this.teamsEnabled) {<br>      this.teamsWebhookUrl = process.env.TEAMS_WEBHOOK_URL || &#39;https://your-teams-webhook-url.com&#39;;<br>    }<br>  }<br><br>  async sendAlert(message: string, subject: string,buffer?: Buffer | string) {<br>    console.log(&#39;Sending alerts...&#39;);<br>    try {<br>      if (this.emailEnabled) {<br>        await this.sendEmailAlert(message, subject,buffer);<br>      }<br><br>      if (this.teamsEnabled) {<br>        await this.sendTeamsAlert(message);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error sending alerts:&#39;, error);<br>      throw error;<br>    }<br>  }<br><br>  private async sendEmailAlert(message: string, subject: string,buffer?: Buffer | string) {<br>    if (!this.emailEnabled) return;<br><br>    const transporter = nodemailer.createTransport(this.emailConfig);<br>    const formattedHtml = marked.parse(message);<br>    console.log(&#39;formattedHtml&#39;,formattedHtml);<br>    await transporter.sendMail({<br>      from: this.emailConfig.auth.user,<br>      to: process.env.ALERT_EMAIL_RECIPIENTS,<br>      subject: subject,<br>      text: message,<br>      html: `<br>      &lt;!DOCTYPE html&gt;<br>      &lt;html&gt;<br>      &lt;head&gt;&lt;title&gt;${subject}&lt;/title&gt;&lt;/head&gt;<br>      &lt;body&gt;<br>        ${formattedHtml}<br>      &lt;/body&gt;<br>      &lt;/html&gt;<br>    `,<br>  <br>    });<br>    console.log(&#39;Email sent successfully&#39;);<br>  }<br><br>  private async sendTeamsAlert(message: string) {<br>    if (!this.teamsEnabled) return;<br><br>    await axios.post(this.teamsWebhookUrl, {<br>      text: message<br>    });<br>  }<br>}</pre><h3>🚀 Impact and Benefits</h3><p>Since implementing this solution, the following improvements will be observed:</p><ol><li><strong>Time Saved:</strong> Scrum Masters save hours previously spent on manual Jira analysis.</li><li><strong>Improved Standups:</strong> Daily standups are now focused on <strong>resolving blockers</strong>, not status updates.</li><li><strong>Better Transparency:</strong> Stakeholders get clear insights into project progress.</li><li><strong>Early Risk Detection:</strong> Trends and potential delays are flagged proactively.</li></ol><p><strong>AI powered Jira reports in mail alert:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*856LqOJAee85uBV-B6Mdvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjJvZd115gl3TsMOeZ88hw.png" /><figcaption>AI powered Jira Reports in mail</figcaption></figure><h3>🔮 What’s Next?</h3><p>Future enhancements include:</p><ul><li><strong>Sentiment Analysis:</strong> Understanding team mood based on task comments.</li><li><strong>Advanced Risk Prediction:</strong> Using historical data to forecast sprint success.</li><li><strong>Multi-Project Support:</strong> Generating separate reports for multiple Jira projects</li></ul><h3>🎬 Conclusion</h3><p>By combining <strong>NestJS, Python, OpenAI, and FastAPI</strong>, this solution transformed daily standup preparation. What was once a tedious manual process is now an <strong>automated, insightful, and actionable report</strong> delivered every morning.</p><p>If you’re a Scrum Master, project manager, or developer dealing with Jira overload, this approach can <strong>boost productivity, improve standups, and keep your team on track</strong>.</p><p>💬 <strong>What do you think?</strong> Would you like to implement something similar in your team? Let’s discuss in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=440b443309a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“AI-Powered Code Reviews in NestJS: Automate PR Approvals with Intelligence!” ]]></title>
            <link>https://medium.com/@rajeshwaran-blog/ai-powered-code-reviews-in-nestjs-automate-pr-approvals-with-intelligence-aad38451373b?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aad38451373b</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 09:55:21 GMT</pubDate>
            <atom:updated>2025-02-24T04:50:04.268Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Leverage NestJS, ngrok, OpenAI and GitHub Actions to Build an Intelligent PR Review System</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzYiNmTNctpk-wJ1bIcP8g.jpeg" /></figure><h3>Introduction</h3><p>Code reviews are the backbone of high-quality software, but manual reviews can be slow, inconsistent, and exhausting. What if AI could handle the heavy lifting — analyzing code, detecting issues, and providing instant feedback? In this article, we’ll build a powerful AI-driven code review system using NestJS, OpenAI, and GitHub Actions. By integrating OpenAI’s API, our system will intelligently review pull requests (PRs) and generate insightful, automated comments. GitHub Actions will orchestrate the AI review process, triggering analysis the moment a PR is opened or updated. For seamless local testing, Ngrok will expose our NestJS service to GitHub’s webhook ecosystem. The AI will not just scan code but also detect vulnerabilities, enforce best practices, and suggest precise improvements. A dedicated NestJS microservice will handle AI interactions, ensuring smooth communication between the system and GitHub. Every PR will receive instant AI-powered feedback, streamlining collaboration and accelerating development cycles. Let’s dive into the architecture, implementation, and deployment of this game-changing AI review system!</p><h3>1. Creating a GitHub Token with Appropriate Permissions</h3><p>🔑 <strong>Why a GitHub Token?</strong></p><p>GitHub tokens enable secure, automated interactions with repositories, allowing scripts to perform actions programmatically. 🚀 For this project, the token must have the necessary permissions to <strong>read and write comments on pull requests</strong>, ensuring seamless AI-powered code reviews. 💬✅</p><ol><li>Go to <strong>GitHub Settings &gt; Developer Settings &gt; Personal Access Tokens (Classic)</strong>.</li><li>Click <strong>Generate New Token</strong> and name it (e.g., AI-Review-Token).</li><li>Select these scopes:</li></ol><ul><li>repo (full control of private repositories)</li><li>workflow (manage GitHub Actions)</li><li>admin:org (if your repo is organization-owned)</li></ul><p>4. Save the token securely (you won’t see it again!).</p><h3>2: Developing an AI-Powered Code Review Service in NestJS</h3><p><strong>Prerequisites:</strong></p><ul><li>Node.js v18+</li><li>NestJS CLI (npm i -g @nestjs/cli)</li><li>OpenAI API Key (from <a href="https://platform.openai.com/">OpenAI Platform</a>)</li></ul><p><strong>Step 1: Initialize the NestJS Project</strong></p><pre>nest new ai-code-reviewer<br>cd ai-code-reviewer</pre><p><strong>Step 2: Integrate OpenAI</strong><br>Install dependencies:</p><pre>npm install @nestjs/axios openai</pre><p><strong>Step 3: Create the Code Review Service</strong><br>In src/openai/openai.service.ts:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import axios from &#39;axios&#39;;<br><br>@Injectable()<br>export class OpenAIService {<br>  private readonly openAIUrl = process.env.AZURE_OPENAI_URL;<br>  private readonly apiKey = process.env.AZURE_OPENAI_API_KEY;<br>  private readonly deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT;<br><br>  async reviewCode(code: string): Promise&lt;string&gt; {<br>    const prompt = `Analyze the following TypeScript/NodeJS code for best practices, security vulnerabilities, and performance optimizations. Provide a detailed review:\n\n${code}`;<br><br>    const response = await axios.post(<br>      `${this.openAIUrl}/openai/deployments/${this.deploymentName}/chat/completions?api-version=2023-05-15`,<br>      {<br>        messages: [<br>          { role: &#39;system&#39;, content: &#39;You are a senior NestJS code reviewer.&#39; },<br>          { role: &#39;user&#39;, content: prompt }<br>        ],<br>        max_tokens: 500,<br>      },<br>      { headers: { &#39;Content-Type&#39;: &#39;application/json&#39;, &#39;api-key&#39;: this.apiKey } }<br>    );<br><br>    return response.data.choices[0].message.content;<br>  }<br>}</pre><p>In src/github/github.service.ts:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import axios from &#39;axios&#39;;<br>import { OpenAIService } from &#39;src/openai/openai.service&#39;;<br><br>@Injectable()<br>export class GithubService {<br>  private readonly githubToken = process.env.GITHUB_TOKEN;<br><br>  constructor(private readonly openAIService: OpenAIService) {}<br><br>  /**<br>   * Processes a pull request from GitHub.<br>   * @param payload The payload containing the pull request data.<br>   * @returns A promise that resolves to the processed pull request.<br>   */<br>  async processPullRequest(payload: any) {<br>    console.log(&quot;Processing pull request&quot;);<br>    const repo = payload.repository.full_name;<br>    const branch = payload.pull_request.head.ref;<br>    const prNumber = payload.number;<br>    const files = await this.getChangedFiles(repo, prNumber);<br>    console.log(&quot;Files: &quot;, files);<br>    for (const file of files) {<br>      const code = await this.getFileContent(repo, file.filename, branch);<br>      console.log(&quot;Code: &quot;, code);<br>      if (code) {<br>        const reviewComments = await this.openAIService.reviewCode(code);<br>        console.log(&quot;Review Comments: &quot;, reviewComments);<br>        if (reviewComments) {<br>          await this.commentOnPR(repo, prNumber, file.filename, reviewComments);<br>          console.log(&quot;Commented on PR&quot;);<br>        }<br>      }<br>    }<br>  }<br><br>  /**<br>   * Retrieves the changed files from a pull request.<br>   * @param repo The repository name.<br>   * @param prNumber The pull request number.<br>   * @returns A promise that resolves to the changed files.<br>   */<br>  private async getChangedFiles(repo: string, prNumber: number) {<br>    const url = `https://api.github.com/repos/${repo}/pulls/${prNumber}/files`;<br>    const response = await axios.get(url, { headers: this.getAuthHeaders() });<br>    return response.data;<br>  }<br><br>  /**<br>   * Retrieves the content of a file from a repository.<br>   * @param repo The repository name.<br>   * @param filename The filename to retrieve.<br>   * @param branch The branch to retrieve the file from.<br>   * @returns A promise that resolves to the file content.<br>   */<br>  private async getFileContent(repo: string, filename: string, branch: string) {<br>    try {<br>      const encodedFilename = encodeURIComponent(filename);<br>      const url = `https://api.github.com/repos/${repo}/contents/${encodedFilename}?ref=${branch}`; // Change &#39;main&#39; to your default branch<br>  <br>      console.log(`Fetching file from: ${url}`);<br>      const response = await axios.get(url, { headers: this.getAuthHeaders() });<br>  <br>      if (!response.data.content) {<br>        throw new Error(`File content not found for ${filename}`);<br>      }<br>  <br>      return Buffer.from(response.data.content, &#39;base64&#39;).toString(&#39;utf-8&#39;);<br>    } catch (error) {<br>      console.error(`Error fetching file content: ${error.message}`);<br>      return null;<br>    }<br>  }<br>  <br>  /**<br>   * Comments on a pull request.<br>   * @param repo The repository name.<br>   * @param prNumber The pull request number.<br>   * @param filename The filename to comment on.<br>   * @param comment The comment to add.<br>   */<br>  private async commentOnPR(repo: string, prNumber: number, filename: string, comment: string) {<br>    console.log(&quot;Commenting on PR&quot;);<br>    const url = `https://api.github.com/repos/${repo}/issues/${prNumber}/comments`;<br>    await axios.post(url, { body: `Code Review for \`${filename}\`:\n${comment}` }, { headers: this.getAuthHeaders() });<br>  }<br><br>  /**<br>   * Retrieves the authentication headers for GitHub API requests.<br>   * @returns An object containing the authentication headers.<br>   */<br>  private getAuthHeaders() {<br>    return { Authorization: `token ${this.githubToken}`, Accept: &#39;application/vnd.github.v3+json&#39; };<br>  }<br>}</pre><p>In src/webhook.controller.ts:</p><pre>import { Controller, Post, Headers, Body } from &#39;@nestjs/common&#39;;<br>import { GithubService } from &#39;./github/github.service&#39;;<br><br>@Controller(&#39;webhook&#39;)<br>export class WebhookController {<br>  constructor(private readonly githubService: GithubService) {}<br><br>  /**<br>   * Handles the webhook event from GitHub.<br>   * @param event The GitHub event type.<br>   * @param payload The payload containing the webhook data.<br>   * @returns A promise that resolves to the processed webhook.<br>   */<br>  @Post()<br>  async handleWebhook(@Headers(&#39;X-GitHub-Event&#39;) event: string, @Body() payload: any) {<br> <br>    if (payload.number &amp;&amp; payload.action === &#39;opened&#39;) {<br>      console.log(&quot;Processing pull request&quot;);<br>      await this.githubService.processPullRequest(payload);<br>    }<br>    return { message: &#39;Webhook received&#39; };<br>  }<br>}</pre><p><strong>Step 5: Run the Service Locally</strong></p><pre>npm run start:dev</pre><h3>3. Exposing the Service to the Internet Using ngrok</h3><p>Since my service runs locally, I needed to expose it to GitHub via a <strong>public HTTPS URL</strong>. I installed <strong>ngrok</strong> and ran the following command:</p><pre>ngrok http 3000</pre><p>This provided a secure, temporary URL that I used in my GitHub webhook configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJcZBvsGvnAoUbpD2weqgQ.png" /><figcaption><strong>Here we can see the logs and exposed HTTPS url</strong></figcaption></figure><p>🚀 Successfully deployed the AI-powered PR review service!<br>🔍 Logs are accessible for real-time monitoring and troubleshooting.<br>🔒 Secure HTTPS endpoint now active: <a href="https://b763-120-60-167-20.ngrok-free.app/">https://b763-120-60-167-20.ngrok-free.app</a> -&gt; <a href="http://localhost:3000/">http://localhost:3000</a>.<br>🤖 Automated code analysis, feedback, and quality checks enabled for pull requests.<br>📋 Next step: Team testing and integration with CI/CD pipelines.</p><h3>4. Integrating AI Code Review into GitHub Actions</h3><p>🚀 To streamline the <strong>code review process</strong> with the power of <strong>AI</strong>, you can seamlessly integrate an <strong>AI-powered review tool</strong> into <strong>GitHub Actions</strong>! 🔍</p><p>💡 This setup ensures that <strong>whenever a pull request (PR) is opened</strong>, the AI service automatically analyzes the code, provides insights, and enhances code quality without manual intervention.</p><p>✅ By leveraging <strong>GitHub Actions</strong>, you can create a fully <strong>automated workflow</strong> that triggers the AI review process, ensuring <strong>efficient, consistent, and intelligent code assessments</strong>. 🤖📊</p><p>🔗 With this integration, your repository benefits from <strong>real-time feedback</strong>, improved <strong>code maintainability</strong>, and a <strong>smoother development workflow</strong>. 🚀💻</p><p>📌 Follow these steps to set it up effectively and <strong>unlock the full potential</strong> of AI-driven code reviews in your GitHub projects! 🛠️</p><p>Here is the structure of your project for PR Review by AI:</p><pre>project-root/<br>│── src/                     # Source code directory  <br>│── .github/  <br>│   ├── workflows/           # GitHub Actions workflow files  <br>│   │   ├── aireview.yml     # AI Code Review workflow  <br>│── package.json             # Node.js dependencies and scripts  <br>│── README.md                # Project documentation</pre><p>Here’s .github/workflows/aireview.yml file:</p><pre>name: AI Code Review<br><br>on:<br>  pull_request:<br>    types: [opened]<br><br>jobs:<br>  review_code:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v3<br><br>      - name: Install dependencies<br>        run: npm install<br><br>      - name: Run AI Code Review<br>        run: |<br>          curl -X POST https://b763-120-60-167-20.ngrok-free.app/webhook \<br>          -H &quot;Content-Type: application/json&quot; \<br>          -d &#39;${{ toJson(github.event) }}&#39;</pre><p>This workflow sends a request to my AI review service whenever a pull request is created or updated.</p><ul><li><strong>Trigger</strong>: This GitHub Actions workflow runs when a pull request is opened.</li><li><strong>Job Setup</strong>: It runs a job named review_code on an ubuntu-latest machine.(Github hosted)</li><li><strong>Checkout Code</strong>: It fetches the repository using actions/checkout@v3.</li><li><strong>Install Dependencies</strong>: It installs required Node.js dependencies with npm install.</li><li><strong>AI Code Review</strong>: It sends a POST request with PR event data to an external AI review service via curl.</li></ul><blockquote><strong>After you raise a pull request (PR), the middleware processes the request by verifying the webhook event. It then determines whether to trigger the AI service for analysis. If the conditions are met, the AI service is activated to review and analyze the modified files. This ensures that only relevant changes are assessed before merging.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LukEjjHqJkoAUxfiSM9ZVg.png" /><figcaption><strong>Pull request review</strong></figcaption></figure><blockquote><strong>You can navigate to the Actions tab in your GitHub repository to view the triggered jobs and track the workflow execution for the pull request (PR) changes. This allows you to monitor the status, logs, and results of each step in the automated process.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8n2TAncsSsF1W6gXA-pYQ.png" /><figcaption>Post checkout review</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0jXIJGimG54DRWP6IO0bg.png" /><figcaption>AI PR review summary</figcaption></figure><p>After the AI review job has successfully completed ✅, the automated system intelligently analyzes the pull request 🔍, evaluates the modifications made to the files 📂, and seamlessly adds insightful comments 💬 directly on the changed lines . This ensures a streamlined code review process 🚀 by providing precise feedback 🎯 on the modified sections, helping developers identify potential issues ⚠️, improvement 🔧, or optimizations ⚡ efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOjunhQFZmn95JaOzGtPOQ.png" /><figcaption>Code comments by OpenAI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TP8Mr6kvb6P8Qop7PqVPw.png" /><figcaption>Code comments by OpenAI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHFtLjELAwthQQ2bSmZ3FA.png" /></figure><h3>Conclusion</h3><p>🚀 <strong>Revolutionizing Code Reviews with AI!</strong> 🤖✨</p><p>By combining <strong>NestJS, OpenAI, GitHub Actions, and ngrok</strong>, I’ve built a powerful <strong>AI-driven automated code reviewer</strong> that seamlessly integrates into any repository! 🔥 This innovation not only <strong>accelerates the review process</strong> but also <strong>ensures consistent, high-quality code checks</strong> with the power of AI. ⚡</p><p>Want to experience it yourself? <strong>Clone the repo, configure your secrets, and start automating your code reviews today!</strong> 🚀</p><p>🌍 Should I <strong>open-source</strong> this project? Let me know in the comments! also reach out me ,If you suggest for more enhancement of this project</p><p>💬👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aad38451373b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Clean Code: The Art of Writing Maintainable and Scalable Software]]></title>
            <link>https://medium.com/@rajeshwaran-blog/mastering-clean-code-the-art-of-writing-maintainable-and-scalable-software-4fb85085ccde?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb85085ccde</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 16:07:23 GMT</pubDate>
            <atom:updated>2025-02-13T16:14:19.213Z</atom:updated>
            <content:encoded><![CDATA[<p>In the fast-paced world of software development, writing clean code is more than a best practice — it’s an essential discipline. Clean code is not just about aesthetics; it’s about crafting solutions that are easy to read, maintain, and scale. This guide will walk you through core principles, refactoring strategies, and best practices to elevate your coding skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkDs0Mwb2W7szRRGPRTe3g.jpeg" /></figure><h3>Why Clean Code is a Game-Changer</h3><h3>1. Maintainability</h3><p>A well-structured codebase is like a well-organized library — easy to navigate, modify, and enhance without unnecessary headaches.</p><h3>2. Readability</h3><p>Clean code should be self-explanatory. Future developers (including yourself) should be able to grasp the logic without digging through excessive comments.</p><h3>3. Scalability</h3><p>As applications grow, unreadable and convoluted code becomes a liability. Clean, modular code allows projects to scale seamlessly.</p><h3>4. Collaboration</h3><p>Team projects thrive on clarity. Writing code that others can understand minimizes friction and enhances team efficiency.</p><h3>The Power of Refactoring: Crafting Better Code Without Altering Behavior</h3><p>Refactoring is the secret weapon for keeping your codebase robust. It improves internal structure while preserving functionality. Here’s how you can do it right:</p><h3>1. Choose Meaningful Variable and Function Names</h3><p>Names should be self-explanatory and convey intent.</p><p>❌ Poor Naming:</p><pre>let a = 10;<br>function x(y) {<br>    return y * a;<br>}</pre><p>✅ Clear Naming:</p><pre>const TAX_RATE = 0.10;<br>function calculateTax(amount) {<br>    return amount * TAX_RATE;<br>}</pre><h3>2. Extract Functions for Simplicity</h3><p>Break down complex functions into modular ones.</p><p>❌ Overloaded Function:</p><pre>function processOrder(order) {<br>    validate(order);<br>    applyDiscount(order);<br>    calculateTotal(order);<br>    sendConfirmation(order);<br>}</pre><p>✅ Refactored:</p><pre>function processOrder(order) {<br>    validateOrder(order);<br>    applyOrderDiscount(order);<br>    finalizeOrder(order);<br>}<br><br><br>function finalizeOrder(order) {<br>    calculateTotal(order);<br>    sendConfirmation(order);<br>}</pre><h3>3. Reduce Deep Nesting</h3><p>Nested code is a readability killer. Simplify with early returns.</p><p>❌ Too Nested:</p><pre>function checkAccess(user) {<br>    if (user) {<br>        if (user.role === &#39;admin&#39;) {<br>            if (user.permissions.includes(&#39;write&#39;)) {<br>                return true;<br>            }<br>        }<br>    }<br>    return false;<br>}</pre><p>✅ Optimized:</p><pre>function hasWriteAccess(user) {<br>    return user &amp;&amp; user.role === &#39;admin&#39; &amp;&amp; user.permissions.includes(&#39;write&#39;);<br>}</pre><h3>4. Eliminate Magic Numbers</h3><p>Use constants instead of hardcoded values to improve clarity.</p><p>❌ Hardcoded Value:</p><pre>if (speed &gt; 80) {<br>    applyPenalty();<br>}</pre><p>✅ Defined Constant:</p><pre>const SPEED_LIMIT = 80;<br>if (speed &gt; SPEED_LIMIT) {<br>    applyPenalty();<br>}</pre><h3>5. Apply the DRY Principle (Don’t Repeat Yourself)</h3><p>Avoid redundancy by creating reusable functions.</p><p>❌ Repetitive Code:</p><pre>function getUserEmail(user) {<br>    return user.firstName + &#39;.&#39; + user.lastName + &#39;@example.com&#39;;<br>}</pre><pre>function getAdminEmail(admin) {<br>    return admin.firstName + &#39;.&#39; + admin.lastName + &#39;@example.com&#39;;<br>}</pre><p>✅ Refactored:</p><pre>function getEmail(person) {<br>    return `${person.firstName}.${person.lastName}@example.com`;<br>}</pre><h3>Best Practices for Writing Clean Code</h3><h3>1. Adopt a Consistent Naming Convention</h3><p>Follow a uniform style (e.g., camelCase for JavaScript, snake_case for Python) to maintain consistency.</p><h3>2. Keep Functions Short and Focused</h3><p>Functions should serve a single purpose, adhering to the <strong>Single Responsibility Principle</strong>.</p><h3>3. Write Comments That Add Value</h3><p>Avoid stating the obvious; instead, provide insights where necessary.</p><p>❌ Unhelpful Comment:</p><pre>// This function adds two numbers<br>function add(a, b) {<br>    return a + b;<br>}</pre><p>✅ Informative Comment:</p><pre>// Formats user data into a standard email string<br>function formatUserEmail(user) {<br>    return `${user.firstName}.${user.lastName}@example.com`;<br>}</pre><h3>4. Write Unit Tests</h3><p>Well-written tests ensure that your clean code remains functional over time.</p><h3>5. Utilize Code Linters and Formatters</h3><p>Automate code consistency with tools like <strong>ESLint</strong> (JavaScript) and <strong>Prettier</strong>.</p><h3>6. Embrace Code Reviews</h3><p>Peer reviews help catch issues early and maintain coding standards.</p><h3>Conclusion</h3><p>Writing clean code is a mindset that requires ongoing effort. By leveraging refactoring techniques and best practices, you create code that is readable, maintainable, and scalable. Whether you are working solo or in a team, investing in clean code today will save you from technical debt tomorrow.</p><p><strong>What’s your go-to clean coding practice? Share your thoughts in the comments!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb85085ccde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fortify Your Nodejs Apps: Implementing Snyk for Effective Vulnerability Detection]]></title>
            <link>https://medium.com/@rajeshwaran-blog/fortify-your-nodejs-apps-implementing-snyk-for-effective-vulnerability-detection-ea85a2839228?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea85a2839228</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 13:00:28 GMT</pubDate>
            <atom:updated>2024-09-14T13:22:12.632Z</atom:updated>
            <content:encoded><![CDATA[<p>In the rapidly evolving world of software development, securing applications has become a top priority. As projects become more intricate and their components more interconnected, the potential security risks increase significantly. Node.js, a widely-used runtime for developing scalable network applications, faces its own set of challenges in this regard. The vast array of third-party packages and libraries available can make it particularly challenging to ensure a secure codebase.</p><p>Enter Snyk, a powerful tool designed to address these security concerns by identifying and mitigating vulnerabilities within your code, dependencies, and container configurations. Snyk provides developers with real-time insights into potential security issues, allowing them to address vulnerabilities before they can be exploited in production environments. This proactive approach to security helps ensure that your applications remain robust and resilient against attacks.</p><p>In this article, we will explore how to integrate Snyk into a NestJS application, a popular framework for building efficient, reliable, and scalable server-side applications. We will delve into the process of setting up Snyk, running security scans, and interpreting the results to enhance your application’s security posture. By the end of this guide, you’ll have a clear understanding of how to leverage Snyk’s capabilities to safeguard your NestJS projects, contributing to a more secure and reliable software development lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*ISbBqmuYvHDXq-ErbBUOWA.png" /></figure><h3><strong>Why Snyk ?</strong></h3><p>Snyk offers several compelling reasons for its adoption, particularly when securing applications and managing vulnerabilities in your projects:</p><p><strong>1. Comprehensive Vulnerability Detection</strong></p><p>Snyk scans your code, dependencies, container images, and infrastructure-as-code for vulnerabilities. It covers various types of issues, from known vulnerabilities in open-source libraries to misconfigurations in your deployment setups.</p><p><strong>2. Real-Time Updates</strong></p><p>Snyk provides real-time vulnerability updates. As new threats emerge, Snyk’s database is continuously updated, ensuring you have the latest information about vulnerabilities affecting your dependencies.</p><p><strong>3. Ease of Integration</strong></p><p>Snyk integrates seamlessly with popular development tools and workflows, including CI/CD pipelines, IDEs, and version control systems. This integration allows for automated security checks and alerts as part of your regular development process.</p><p><strong>4. Actionable Fixes</strong></p><p>Snyk doesn’t just identify vulnerabilities; it also offers actionable recommendations and automated fixes. It can suggest and even apply fixes for known vulnerabilities in your dependencies, making it easier to maintain a secure codebase.</p><p><strong>5. Comprehensive Reporting</strong></p><p>Snyk generates detailed reports on vulnerabilities, including their severity, affected versions, and recommended fixes. These reports help you understand the risks and prioritize remediation efforts effectively.</p><p><strong>6. Developer-Friendly</strong></p><p>Snyk is designed with developers in mind, providing easy-to-understand information about vulnerabilities and fixes. Its tools and interface are user-friendly, which helps developers quickly address security issues without deep security expertise.</p><p><strong>7. Security in Depth</strong></p><p>Snyk supports a range of security checks beyond just dependency scanning, including container security and infrastructure-as-code assessments. This holistic approach helps secure your entire application stack, from development to deployment.</p><p><strong>8. Community and Support</strong></p><p>Snyk has an active community and offers support through various channels. The extensive documentation, tutorials, and community forums can help you get the most out of the tool and address any issues that arise.</p><p><strong>9. Open Source and Commercial Options</strong></p><p>Snyk offers both free and paid plans, making it accessible for individual developers and large enterprises alike. The free tier provides basic vulnerability scanning, while the paid plans offer advanced features and enterprise support.</p><p><strong>10. Regulatory Compliance</strong></p><p>Snyk helps ensure compliance with industry standards and regulations by addressing known vulnerabilities and providing insights into potential compliance issues related to your dependencies and configurations.</p><p>By incorporating Snyk into your development workflow, you can proactively manage security risks, streamline vulnerability remediation, and maintain a secure application environment. This helps not only in safeguarding your code but also in fostering a culture of security within your development team.</p><h3><strong>Setting Up Snyk for a NestJS Application</strong></h3><h4><strong>To set up Snyk for a NestJS application, follow these steps to integrate it effectively:</strong></h4><h3>1. Set Up a NestJS Application</h3><p>If you don’t already have a NestJS application, you’ll need to create one. Here’s a quick guide to get started with a new NestJS project:</p><h4>Install the NestJS CLI</h4><p>If you haven’t installed the NestJS CLI, you can do so globally:</p><pre>npm i -g @nestjs/cli</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*RUyoLphdau2BfPuxhTR01w.png" /></figure><h4>Navigate to Your Project Directory</h4><p>Change to the project directory:</p><pre>cd snyk-poc</pre><h4>Run the application</h4><p>Start to run the NestJs app:</p><pre>npm run start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9me1VRaeMdy3pMumk56tQ.png" /></figure><p>We’ve successfully set up a basic NestJS app. Next, we’ll integrate Snyk to enhance security by scanning for vulnerabilities.</p><h3>2. Snyk Implement</h3><p>Snyk is a robust tool designed to help developers secure their Node.js applications by identifying and addressing vulnerabilities in dependencies, code, and container configurations. Integrating Snyk into your development workflow can significantly enhance the security posture of your Node.js backend applications. Here’s a step-by-step guide on how to utilize Snyk for vulnerability scanning:</p><ol><li><strong>Install Snyk CLI</strong>: First, you need to install the Snyk Command Line Interface (CLI) on your development machine. You can do this using npm (Node Package Manager) with the following command:</li></ol><pre>npm install -g snyk</pre><blockquote><strong>This command installs Snyk globally, allowing you to use it from any directory on your system.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*O4PRZ6cowLe5jU_t3dEBJg.png" /></figure><p><strong>2. Authenticate Snyk</strong>: After installing the CLI, you need to authenticate it with your Snyk account. Run:</p><pre>snyk auth</pre><blockquote><strong>This command opens a browser window where you can log in to your Snyk account or sign up if you don’t have one. Authentication ensures that your scans are linked to your Snyk dashboard for ongoing management and reporting.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGbZ6uc0Bdh6lronTqOXBQ.png" /><figcaption><strong>You just grant app access</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fqq2tlW_NkpiKBXisjBc6w.png" /><figcaption><strong>Authenticated</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qoe4vy8pKBDk1JcpqbKDfw.png" /></figure><p><strong>3. Scan Your Dependencies</strong>: Navigate to the root directory of your Node.js project where your package.json and package-lock.json files are located. Run the following command to scan these files for vulnerabilities:</p><pre>snyk test</pre><blockquote><strong>Snyk will analyze your project’s dependencies, including those specified in </strong><strong>package.json and </strong><strong>package-lock.json, to detect known security vulnerabilities.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfDYFUVV1FhQ_2KbfRCPVw.png" /><figcaption>Report</figcaption></figure><p><strong>4. Review Scan Results</strong>: After the scan is complete, Snyk will provide a detailed report of vulnerabilities found. The report includes information such as the severity of each vulnerability (e.g., low, medium, high), the affected package, and recommended fixes or updates.</p><p><strong>5. Fix Vulnerabilities</strong>: Based on the results, you can use Snyk’s automated fix feature to attempt to resolve some vulnerabilities directly. Run:</p><pre>snyk wizard</pre><blockquote><strong>This command guides you through the process of updating dependencies or applying patches to address the vulnerabilities.</strong></blockquote><p><strong>6. Monitor for New Vulnerabilities</strong>: Vulnerabilities can emerge over time as new threats are discovered. To continuously monitor your project for new vulnerabilities, you can set up Snyk’s monitoring feature. This involves running:</p><pre>snyk monitor</pre><blockquote><strong>This command creates a snapshot of your dependencies and schedules regular checks to identify any newly discovered vulnerabilities.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YZOyYoGtemgOOSMlUSjmg.png" /><figcaption><strong>monitor</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hcc1HyBMmhIzWuFN44W9JA.png" /><figcaption><strong>You can see the board</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSMWcS0XYcLQgBd8L4xMFw.png" /><figcaption><strong>We can analysis and view reports</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRlZyDuan2WOguAbUBXvQg.png" /><figcaption><strong>Dependencies</strong></figcaption></figure><p>7.<strong>Integrate Snyk into CI/CD Pipelines</strong>: To ensure ongoing security, integrate Snyk into your Continuous Integration/Continuous Deployment (CI/CD) pipeline. By adding Snyk commands to your pipeline configuration files (e.g., in Jenkins, GitHub Actions, or GitLab CI), you can automate vulnerability scanning and remediation checks as part of your build and deployment processes.</p><p>To integrate Snyk into your Git workflow using GitHub Actions, create a GitHub Actions workflow file .<strong>github/workflows/security.yml:</strong></p><pre>name: Security Check<br><br>on:<br>  push:<br>    branches:<br>      - main<br>  pull_request:<br>    branches:<br>      - main<br><br>jobs:<br>  snyk:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br><br>      - name: Set up Node.js<br>        uses: actions/setup-node@v2<br>        with:<br>          node-version: &#39;18&#39;<br><br>      - name: Install dependencies<br>        run: npm install<br><br>      - name: Run Snyk tests<br>        uses: snyk/actions@v1<br>        with:<br>          args: test<br>        env:<br>          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}<br><br>      - name: Build Docker image<br>        run: docker build -t my-nestjs-app .<br><br>      - name: Test Docker image with Snyk<br>        run: snyk container test my-nestjs-app<br>        env:<br>          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}</pre><blockquote><strong>a. Go to your repository on GitHub.</strong></blockquote><blockquote><strong>b. Click on </strong><strong>Settings &gt; </strong><strong>Secrets &gt; </strong><strong>Actions.</strong></blockquote><blockquote><strong>c. Add a new secret named </strong><strong>SNYK_TOKEN with your Snyk API token.</strong></blockquote><p><strong>8. Monitoring Container Security: </strong>If you are using Docker, Snyk can also be used to check for vulnerabilities in your container images:</p><p><strong>Scan Docker Images</strong>:</p><pre>snyk container test &lt;image-name&gt;</pre><p><strong>Monitor Docker Images</strong>:</p><pre>snyk container monitor &lt;image-name&gt;</pre><blockquote><strong>This helps to secure the entire deployment environment, not just your application code.</strong></blockquote><p><strong>9.License Management : </strong>Snyk can also help you manage open-source licenses in your project, ensuring compliance with legal requirements:</p><ul><li><strong>Test for License Issues</strong>:</li></ul><pre>snyk test --all-projects --show-vulnerable-paths</pre><blockquote><strong>It checks all project dependencies and flags licenses that are incompatible with your use case.</strong></blockquote><p><strong>10. Code Security: </strong>Snyk’s snyk code feature helps in scanning your own source code for potential security issues such as SQL injections, path traversal vulnerabilities, etc.:</p><pre>snyk code test</pre><blockquote><strong>It provides actionable feedback on issues within your code and how to fix them.</strong></blockquote><p><strong>11. Snyk IDE Plugins : </strong>Snyk provides plugins for popular IDEs like VSCode and IntelliJ. These plugins allow you to catch vulnerabilities in real time as you develop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYRqg40RRGwbHNtYJCSsCA.png" /><figcaption><strong>VS Code IDE Plugin</strong></figcaption></figure><p><strong>12. Snyk Integration with Git Hooks : </strong>You can configure Snyk to run as a Git pre-commit or pre-push hook using husky to prevent pushing code with vulnerabilities:</p><ul><li><strong>Install Husky</strong>:</li></ul><pre>npm install husky --save-dev<br>npx husky install</pre><ul><li><strong>Add a Pre-Commit Hook</strong>:</li></ul><p>Add the following to your .husky/pre-commit file to run Snyk before every commit:</p><pre>#!/bin/sh<br>snyk test</pre><blockquote><strong>By integrating Snyk in your backend development process, you can greatly improve the security and compliance of your Node.js applications.</strong></blockquote><p>The concepts and tools mentioned in this article about integrating Snyk into a Docker-based NestJS application and GitHub Actions workflow were drawn from a variety of sources, including the official documentation and examples from real-world use cases. Below are the key references you can explore for more details:</p><h3>1. Snyk Official Documentation</h3><ul><li><a href="https://snyk.io/docs/cli"><strong>Snyk CLI</strong><br></a>Documentation for using the Snyk command-line interface to test for vulnerabilities.</li><li><a href="https://snyk.io/docs/snyk-container"><strong>Snyk Docker Scanning</strong><br></a>Guide to scanning Docker images with Snyk for vulnerabilities.</li><li><a href="https://snyk.io/docs/github-actions"><strong>Snyk Integration with GitHub Actions</strong></a><strong><br></strong>Details on integrating Snyk with GitHub Actions for continuous vulnerability monitoring.</li></ul><h3>2. NestJS Official Documentation</h3><ul><li><a href="https://docs.nestjs.com/recipes/docker"><strong>NestJS — Docker Setup</strong><br></a>Official documentation on how to create Docker containers for NestJS applications.</li><li><a href="https://docs.nestjs.com/recipes/docker#example-dockerfile"><strong>NestJS — Building Docker Images</strong><br></a>Step-by-step guide to building Docker images for NestJS projects.</li></ul><h3>3. GitHub Actions Documentation</h3><ul><li><a href="https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions"><strong>GitHub Actions — Workflow Syntax</strong></a><strong><br></strong>Documentation on GitHub Actions workflow syntax and structure.</li><li><a href="https://docs.github.com/en/actions/security-guides/encrypted-secrets"><strong>GitHub Actions — Using Secrets in Workflows</strong></a><strong><br></strong>Guide to setting up and using encrypted secrets in GitHub Actions workflows.</li></ul><h3>4. Docker Documentation</h3><ul><li><a href="https://docs.docker.com/engine/reference/builder"><strong>Dockerfile Reference</strong><br></a>Reference guide for Dockerfile instructions to build Docker images.</li><li><a href="https://docs.docker.com/compose"><strong>Docker Compose</strong></a><strong><br></strong>Documentation for using Docker Compose to define and run multi-container Docker applications.</li></ul><h3>5. Husky Documentation</h3><ul><li><a href="https://typicode.github.io/husky/#/"><strong>Husky — Git Hooks Integration</strong><br></a>Guide for integrating Git hooks like pre-commit and pre-push checks using Husky in your project.</li></ul><p>These links provide the foundational knowledge for setting up Docker, Snyk, and GitHub Actions in a Node.js/NestJS project for security and continuous integration.</p><h3>Conclusion</h3><p>Integrating Snyk into your Node.js and NestJS application ensures continuous monitoring and proactive remediation of security vulnerabilities. By integrating it into a Dockerized application and leveraging GitHub Actions, you automate the process of vulnerability scanning, making your CI/CD pipeline secure. With Snyk’s capabilities in both application dependencies and container security, your code and images stay protected from potential threats. Furthermore, tools like Husky help enforce security checks locally, preventing vulnerable code from being committed.</p><h3>GitHub Repository Example</h3><p>You can find an example of a repository that uses Snyk with a NestJS Docker setup and GitHub Actions here: <a href="https://github.com/Rajeshwaran7/snyk-poc">click here</a></p><blockquote><strong>Feel free to explore the repo and customize it for your project!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea85a2839228" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Data Efficiency: Automating High-Performance CSV to Parquet Conversions with Node.js,]]></title>
            <link>https://medium.com/@rajeshwaran-blog/mastering-data-efficiency-automating-high-performance-csv-to-parquet-conversions-with-node-js-bb9fc20c307e?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb9fc20c307e</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 19:07:32 GMT</pubDate>
            <atom:updated>2024-09-08T19:19:57.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Data Efficiency: Automating High-Performance CSV to Parquet Conversions with Node.js, Azure Blob Storage, and Cron Jobs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wAY0qWMsVn4yR203_hMuA.png" /></figure><p>In the rapidly evolving landscape of data processing, the choice of file format plays a critical role in optimizing both system performance and operational workflows. CSV, with its lightweight, row-based structure, remains a widely-adopted format due to its simplicity and ease of integration across various tools and platforms. However, as data scales exponentially and analytics pipelines become more sophisticated, CSV’s inherent limitations in terms of storage efficiency, query performance, and schema management surface. This is where the <strong>Parquet</strong> format demonstrates its superiority, especially for complex, data-intensive use cases.</p><p>Parquet is a highly-efficient, <strong>columnar storage</strong> format designed for the specific needs of <strong>big data</strong> operations. Its columnar design enables <strong>data compression</strong> at a much higher ratio compared to row-based formats like CSV, significantly reducing storage footprints and improving I/O performance. Furthermore, Parquet supports <strong>predicate pushdown</strong>, making it ideal for scenarios where efficient query filtering is paramount. By preserving the <strong>schema</strong> within the file itself, Parquet ensures data consistency and integrity across various stages of the data pipeline, streamlining transformations and analytics workflows.</p><p>In this technical deep dive, we will explore a hands-on guide for converting CSV to Parquet using <strong>Node.js</strong> and <strong>TypeScript</strong>, automating the entire workflow with <strong>Cron</strong> jobs to maintain continuous data ingestion and transformation. The process kicks off with a Cron-triggered function to download CSV files from <strong>Azure Blob Storage</strong> via a <strong>readable stream</strong>, ensuring seamless integration with cloud-native storage. We will leverage <strong>fast-csv</strong> for efficient parsing of the CSV stream and <strong>schema inference</strong>, providing the foundation for structured data transformation.</p><p>Next, we will use the <strong>parquet-lite</strong> library to map the inferred CSV schema to a <strong>Parquet schema</strong> and perform the conversion. The Parquet file generation step is pivotal for enhancing storage efficiency and query performance, especially in data warehouses or distributed data systems. Once the Parquet file is created, we will securely upload it back to <strong>Azure Blob Storage</strong> using a <strong>Shared Access Signature (SAS)</strong> with a proxy configuration to handle secure, high-throughput uploads.</p><p>By implementing this solution, you’ll automate and optimize your data pipeline, transitioning from legacy formats like CSV to Parquet, which is better suited for modern analytical tasks. This method not only minimizes storage costs but also maximizes the <strong>computational efficiency</strong> of your data operations, enabling scalable, robust analytics workflows that handle complex data sets with ease.</p><h3>Why Parquet Over CSV?</h3><p>CSV files are lightweight, text-based formats perfect for small datasets and simple applications. However, they lack several key features required for large-scale data operations:</p><ol><li><strong>No Schema Support</strong>: CSV files don’t store metadata or schema, leading to potential inconsistencies.</li><li><strong>Row-based Structure</strong>: This is inefficient when querying large datasets, as you often need only specific columns.</li><li><strong>Inefficient Storage</strong>: No data compression means CSV files take up more space and result in slower I/O operations.</li></ol><p>Parquet <strong>solves</strong> these issues by storing data in a <strong>columnar format</strong>, optimizing for:</p><ul><li><strong>Compression</strong>: Parquet compresses data at a much higher ratio.</li><li><strong>Query Performance</strong>: Its columnar format allows for <strong>predicate pushdown</strong>, enabling faster queries.</li><li><strong>Schema Enforcement</strong>: Parquet files retain the schema, ensuring data consistency across pipelines.</li></ul><h3>Project Overview</h3><p>In this tutorial, we will automate a data pipeline that converts CSV files into Parquet format using Node.js. We’ll retrieve CSV files from <strong>Azure Blob Storage</strong>, process them, and convert them to Parquet before uploading them back to Blob Storage. Here’s a breakdown of the key steps:</p><ol><li><strong>Trigger Function</strong>: Use Cron to schedule the download of CSV files from Azure Blob Storage.</li><li><strong>Parse CSV</strong>: Use fast-csv to parse the CSV file and infer its schema.</li><li><strong>Convert to Parquet</strong>: Use parquet-lite to convert the CSV data into Parquet format.</li><li><strong>Upload to Blob</strong>: Securely upload the Parquet file back to Azure Blob Storage.</li></ol><h3>Step 1. Install Node.js</h3><p>Make sure you have Node.js installed. You can download it from <a href="https://nodejs.org/">Node.js official website</a>.</p><pre>node -v</pre><h3>2. Create Project Directory</h3><pre>mkdir csv-parquet<br>cd csv-parquet</pre><h3>3. Initialize a Node.js Project</h3><pre>npm init -y</pre><p>This will generate a package.json file.</p><h3>4. Install TypeScript and Necessary Packages</h3><p>Install TypeScript and related packages for development:</p><pre>npm install typescript ts-node @types/node --save-dev</pre><ul><li>typescript: The TypeScript compiler.</li><li>ts-node: Allows you to run TypeScript directly without compiling it to JavaScript first.</li><li>@types/node: Type definitions for Node.js, useful when writing TypeScript code for Node.js.</li></ul><h3>5. Set Up the TypeScript Configuration</h3><p>Run the following command to generate the tsconfig.json file:</p><pre>npx tsc --init</pre><p>In tsconfig.json, you can customize the compiler options. Here’s an example configuration:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES6&quot;,                                <br>    &quot;module&quot;: &quot;commonjs&quot;,                            <br>    &quot;rootDir&quot;: &quot;./src&quot;,                              <br>    &quot;outDir&quot;: &quot;./dist&quot;,                              <br>    &quot;strict&quot;: true,                                 <br>    &quot;esModuleInterop&quot;: true,                        <br>    &quot;skipLibCheck&quot;: true,                           <br>    &quot;forceConsistentCasingInFileNames&quot;: true        <br>  },<br>  &quot;include&quot;: [&quot;src/**/*.ts&quot;],<br>  &quot;exclude&quot;: [&quot;node_modules&quot;]<br>}</pre><h3>6. Set Up Project Structure</h3><p>Create the following directory structure:</p><pre>csv-parquet/<br>├── src/<br>│   ├── config/<br>│   │   ├── azure/<br>│   │   │   ├── index.ts       # Azure Blob configuration and helper functions<br>│   │   │   ├── config.ts      # Blob storage credentials/configs<br>│   │   ├── index.ts           # General configuration<br>│   ├── utils/<br>│   │   ├── index.ts           # Utility functions like CSV parsing<br>│   │   ├── memorywritable.ts  # Custom memory stream to manage blob stream processing<br>│   ├── interfaces/<br>│   │   ├── csv-parquet.corn.interface.ts  # Interfaces for the cron job setup<br>│   ├── csv-parquet-job/<br>│   │   ├── csv-parquet.corn.ts # Cron job definition to manage scheduled tasks<br>│   │   ├── index.ts            # Entry point for the CSV to Parquet job<br>│   ├── index.ts                # Main entry point of the application<br>├── dist/                       # Compiled JavaScript output<br>├── node_modules/                # Dependencies<br>├── package.json                 # Project configuration<br>└── tsconfig.json                # TypeScript configuration</pre><h3>5. Code Implementation</h3><blockquote>Azure Blob Configuration (config/azure/config.ts)</blockquote><pre>import { BlobServiceClient, newPipeline, StoragePipelineOptions, AnonymousCredential } from &quot;@azure/storage-blob&quot;;<br>import * as dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>/**<br> * Configuration for Azure Storage operations<br> *<br> * @class AzureStorageConfig<br> */<br>class AzureStorageConfig {<br>  private readonly containerName: string;<br>  private readonly targetConnectionString: string;<br>  private readonly blobServiceClient: BlobServiceClient;<br>  private readonly containerClient: any; // Consider defining a more specific type if possible<br>  private readonly sasUrl: string;<br>  private readonly proxyPort: string;<br>  private readonly zenProxy: string;<br>  private readonly proxyOptions: { host: string; port: string; } | any;<br><br>  public constructor() {<br>    this.containerName =  this.getEnvVariable(&#39;CONTAINER&#39;);<br>    this.targetConnectionString = this.getEnvVariable(&#39;TARGET_CONNECTION_CONTAINER&#39;);<br>    this.sasUrl = this.getEnvVariable(&#39;SAS_KEY_UPLOAD_PARQUET&#39;)<br>    this.proxyPort = this.getEnvVariable(&#39;PROXY_SAS_PORT&#39;)<br>    this.zenProxy = this.getEnvVariable(&#39;ZEN_PROXY&#39;)<br><br>    if (!this.containerName || !this.targetConnectionString || !this.sasUrl || !this.proxyPort || !this.zenProxy) {<br>      throw new Error(&#39;One or more required environment variables are missing.&#39;);<br>    }<br><br>    this.blobServiceClient = BlobServiceClient.fromConnectionString(this.targetConnectionString);<br>    this.containerClient = this.blobServiceClient.getContainerClient(this.containerName);<br><br>    this.proxyOptions = {<br>      host: this.zenProxy,<br>      port: this.proxyPort,<br>    };<br>  }<br><br><br>  private getEnvVariable(name: string): string {<br>    const value = process.env[name];<br>    console.log(value);<br>    <br>    if (!value) {<br>      throw new Error(`Environment variable ${name} is missing`);<br>    }<br>    return value;<br>  }<br><br><br>  public getBlobServiceClient(): BlobServiceClient {<br>    return this.blobServiceClient;<br>  }<br><br>  public getContainerClient(): any { // Consider defining a more specific type if possible<br>    return this.containerClient;<br>  }<br><br>  public getSasUrl(): string {<br>    return this.sasUrl;<br>  }<br><br>  public getProxyOptions(): { host: string; port: string; } {<br>    return this.proxyOptions;<br>  }<br><br>  public getPipeline() {<br>    const pipelineOptions: StoragePipelineOptions = { proxyOptions: this.proxyOptions };<br>    const anonymousCredential = new AnonymousCredential();<br>    return newPipeline(anonymousCredential, pipelineOptions);<br>  }<br>}<br><br>export default new AzureStorageConfig();</pre><p>Here’s an explanation of the AzureStorageConfig class, which is designed to configure and manage Azure Blob Storage operations in a Node.js environment using TypeScript. It integrates environment variables for secure configuration and manages proxy settings for specific upload operations.</p><h3>Key Features of AzureStorageConfig</h3><ol><li><strong>Environment Variable Configuration</strong>: The class pulls sensitive information (like the container name, connection strings, SAS keys, and proxy details) from environment variables using dotenv. This ensures that credentials and sensitive details are not hardcoded, allowing for more secure and scalable deployments.</li><li><strong>Blob Service Client Creation</strong>:</li></ol><ul><li>BlobServiceClient is created using the Azure Blob Storage connection string (this.targetConnectionString), which is a vital part of interacting with Azure Storage.</li><li>The containerClient is used to access a specific container in Blob Storage (this.containerName), which holds the blob files.</li></ul><p><strong>3. Proxy Configuration</strong>:</p><ul><li>proxyOptions specifies the proxy settings used to route requests through a proxy server. This is useful in enterprise environments where outgoing network traffic must be routed via a proxy.</li></ul><p><strong>4. Pipeline Creation</strong>:</p><ul><li>The getPipeline method creates a custom Azure Storage pipeline, which applies proxy settings to the blob operations. The pipeline uses an AnonymousCredential because this example doesn&#39;t need authentication within the pipeline itself but relies on a shared access signature (SAS) for secure operations.</li><li><strong>Pipelines in Azure Blob Storage</strong> allow you to customize the requests sent to the Azure Blob service by adding middleware (e.g., proxies, logging, etc.). In this case, the pipeline is mainly used for routing through a proxy.</li></ul><h3>Step-by-Step Breakdown of the Class</h3><ol><li><strong>Class Properties:</strong></li></ol><ul><li>containerName: The name of the blob container in Azure Storage, fetched from the environment variable CONTAINER.</li><li>targetConnectionString: The connection string to the Azure Storage account, fetched from the environment variable TARGET_CONNECTION_CONTAINER.</li><li>blobServiceClient: The client used to interact with Azure Blob Storage.</li><li>containerClient: This is used to interact with the specific container (containerName) in the storage account.</li><li>sasUrl: The URL with a Shared Access Signature (SAS) that allows uploading the Parquet file with secure permissions.</li><li>proxyPort and zenProxy: Environment variables used to configure the proxy.</li><li>proxyOptions: An object containing proxy settings (host and port), used for routing Azure Storage requests through a proxy.</li></ul><p><strong>2. Constructor Logic:</strong></p><p>The constructor initializes the key variables (containerName, targetConnectionString, sasUrl, proxyPort, zenProxy) by calling the getEnvVariable method, which safely retrieves values from the environment.</p><ul><li>The BlobServiceClient is initialized using BlobServiceClient.fromConnectionString(), which allows communication with Azure Blob Storage using the connection string.</li><li>The containerClient is initialized using blobServiceClient.getContainerClient(containerName) to interact with a specific blob container.</li></ul><ol><li><strong>Environment Variable Validation (</strong><strong>getEnvVariable method):</strong></li></ol><ul><li>This method ensures that if any environment variable is missing, an error is thrown. This protects against incomplete configurations and provides clarity when debugging issues with missing environment variables.</li></ul><p>2.<strong> Public Methods:</strong></p><ul><li>getBlobServiceClient(): Returns the BlobServiceClient instance, allowing other parts of the application to interact with the storage service.</li><li>getContainerClient(): Returns the containerClient instance for container-specific operations.</li><li>getSasUrl(): Returns the SAS URL for secure uploads.</li><li>getProxyOptions(): Returns the proxy settings (host and port), ensuring that the right proxy is used for uploads.</li><li>getPipeline(): Returns a custom pipeline that includes the proxy settings, which is essential for routing the blob operations through the specified proxy.</li></ul><h4><strong>Code Summary</strong></h4><p><strong>Main Operations</strong>:</p><p>This class is designed to encapsulate all configuration details needed to interact with Azure Blob Storage. It hides away complexities like connection strings, container names, and proxy configurations, providing simple access to blob operations via a client.</p><p><strong>Why Use This?</strong></p><ul><li><strong>Environment Variables</strong>: Keeping sensitive data (like connection strings and SAS keys) in environment variables ensures security.</li><li><strong>Proxy Support</strong>: Configuring the proxy settings ensures that the application can function in network environments where proxies are required.</li><li><strong>SAS URL Handling</strong>: By using SAS (Shared Access Signatures), the application can securely upload files to Azure Blob Storage without storing long-term credentials in the code.</li></ul><p>This structure is modular, and the class can easily be expanded or reused in other parts of your application that require interaction with Azure Blob Storage.</p><blockquote>Azure Blob Helper (config/azure/index.ts)</blockquote><pre>export * from &#39;./config&#39;;</pre><p>The statement export * from &#39;./config&#39;; re-exports everything that is exported from the ./config module. This means that all functions, classes, or variables that are exported from the config file will be available for import in other files where this module is imported.</p><p>In short, it acts as a bridge, allowing you to aggregate exports from multiple files in a single place for cleaner and easier imports elsewhere in your project.</p><blockquote>Memory Writable Stream (utils/memorywritable.ts)</blockquote><pre>import { Writable } from &quot;stream&quot;;<br><br>export class MemoryWritable extends Writable {<br>  private chunks: Buffer[] = [];<br><br>  _write(chunk: Buffer, encoding: string, callback: Function) {<br>    this.chunks.push(chunk);<br>    callback();<br>  }<br><br>  getBuffer(): Buffer {<br>    return Buffer.concat(this.chunks);<br>  }<br>}</pre><p>The MemoryWritable class extends Node.js&#39;s Writable stream and is used to collect chunks of data written to it. It stores the chunks in a Buffer[] array. The _write method pushes each chunk into the array and calls the callback to indicate the write is complete. The getBuffer method concatenates all the stored chunks into a single Buffer, which represents the entire stream of data. This is useful for buffering data streams in memory before processing or saving them.</p><blockquote>Interface CSV to Parquet Cron Job (interfaces/icorn/csv-parquet.interface.ts)</blockquote><pre>import { Readable } from &quot;stream&quot;;<br>import { ParquetSchema } from &quot;parquetjs-lite/lib/schema&quot;;<br><br>export interface ICsvToParquetFile {<br>  /**<br>   * Downloads a CSV file from Blob Storage, converts it to Parquet format, and uploads it back to Blob Storage.<br>   * @param {string} blobName The name of the blob (CSV file) to process.<br>   * @returns {Promise&lt;void&gt;}<br>   */<br>   onCSVUpdateAndSuccess(blobName: string): Promise&lt;void&gt;;<br><br>  /**<br>   * Uploads Parquet data to Blob Storage.<br>   * @param {Buffer} buffer The Parquet data.<br>   * @param {string} blobName The name of the blob (Parquet file) to upload.<br>   * @returns {Promise&lt;void&gt;}<br>   */<br>  uploadParquetToBlobStorage(buffer: Buffer, blobName: string): Promise&lt;void&gt;;<br><br>  /**<br>   * Converts CSV data to Parquet format.<br>   * @param {Readable} csvStream A readable stream containing CSV data.<br>   * @returns {Promise&lt;Buffer&gt;} The Parquet data as a Buffer.<br>   */<br>  convertCSVtoParquet(csvStream: Readable): Promise&lt;Buffer&gt;;<br><br>  /**<br>   * Infers the schema for the Parquet file based on the CSV headers and a sample row.<br>   * @param {string[]} headers The headers from the CSV file.<br>   * @param {any} sampleRow A sample row from the CSV file.<br>   * @returns {ParquetSchema} The inferred Parquet schema.<br>   */<br>  inferSchema(headers: string[], sampleRow: any): ParquetSchema;<br><br>  /**<br>   * Downloads a CSV file from Blob Storage.<br>   * @param {string} blobName The name of the blob (CSV file) to download.<br>   * @returns {Promise&lt;Readable&gt;} A readable stream containing the CSV data.<br>   */<br>  downloadCSVFromBlobStorage(blobName: string): Promise&lt;Readable&gt;;<br>}</pre><p>The ICsvToParquetFile interface defines methods for handling a CSV-to-Parquet conversion process, specifically in the context of Azure Blob Storage. It includes methods to:</p><ol><li><strong>onCSVUpdateAndSuccess</strong>: Download a CSV from Blob Storage, convert it to Parquet, and re-upload it.</li><li><strong>uploadParquetToBlobStorage</strong>: Upload the Parquet data to Blob Storage.</li><li><strong>convertCSVtoParquet</strong>: Convert CSV data from a stream into Parquet format.</li><li><strong>inferSchema</strong>: Generate the Parquet schema based on CSV headers and a sample row.</li><li><strong>downloadCSVFromBlobStorage</strong>: Download a CSV file as a readable stream from Blob Storage.</li></ol><p>This interface outlines the essential functions required to automate the CSV-to-Parquet conversion and cloud upload process.</p><blockquote>CSV to Parquet Cron Job (csv-parquet-job/csv-parquet.corn.ts)</blockquote><pre>import cron from &quot;node-cron&quot;;<br>import { Readable } from &quot;stream&quot;;<br>import AzureStorageConfig from &quot;../config/azure/config&quot;;<br>import { ParquetWriter } from &quot;parquetjs-lite&quot;;<br>import { parse } from &quot;fast-csv&quot;;<br>import { MemoryWritable } from &quot;../utils/memorywritable&quot;;<br>import { BlobServiceClient } from &quot;@azure/storage-blob&quot;;<br>import { ParquetSchema } from &quot;parquetjs-lite/lib/schema&quot;;<br>import { ICsvToParquetFile } from &quot;../interfaces/icron/csv-parquet.interface&quot;;<br><br>/**<br> *<br> *<br> * @export<br> * @class CsvToParquetFile<br> * @implements {ICsvToParquetFile}<br> */<br>export class CsvToParquetFile implements ICsvToParquetFile{<br>  public constructor() {<br>    cron.schedule(&quot;*/5 * * * * *&quot;, async () =&gt; {<br>      console.log(&quot;Cron Start&quot;);<br>      await this.onCSVUpdateAndSuccess(&quot;blobName&quot;);<br>    });<br>  }<br><br>  /**<br>   *<br>   * Download CSV From BlobStorage<br>   * @param {string} blobName<br>   * @return  {Promise&lt;string&gt;}<br>   * @memberof CodeGen<br>   */<br>  public async onCSVUpdateAndSuccess(blobName: string): Promise&lt;void&gt; {<br>    try {<br>      const csvData = await this.downloadCSVFromBlobStorage(blobName);<br>      const parquetBuffer = await this.convertCSVtoParquet(csvData);<br>      const parquetBlobName = `${blobName.replace(&quot;.csv&quot;, &quot;.parquet&quot;)}`;<br>      await this.uploadParquetToBlobStorage(parquetBuffer, parquetBlobName);<br>    } catch (error) {<br>      console.error(&quot;Error:&quot;, error);<br>    }<br>  }<br><br>  /**<br>   * Upload Parquet data to Blob Storage<br>   * @param {string} blobName Blob name for the Parquet file<br>   * @param {Buffer} parquetData Parquet data<br>   * @returns {Promise&lt;void&gt;}<br>   */<br>  public async uploadParquetToBlobStorage(<br>    buffer: Buffer,<br>    blobName: string<br>  ): Promise&lt;void&gt; {<br>    const pipeline = AzureStorageConfig.getPipeline();<br>    const blobServiceClients = new BlobServiceClient(<br>      AzureStorageConfig.getSasUrl(),<br>      pipeline<br>    );<br>    const containerClients = blobServiceClients.getContainerClient(<br>      &quot;blob-container-name&quot;<br>    );<br>    const blockBlobClients = containerClients.getBlockBlobClient(blobName);<br>    await blockBlobClients.uploadData(buffer);<br>  }<br><br>  /**<br>   * Converts the csv to parquet format<br>   * @param {string} csvData<br>   * @return {Promise&lt;Buffer&gt;}<br>   * @memberof CodeGen<br>   */<br>  public async convertCSVtoParquet(csvStream: Readable): Promise&lt;Buffer&gt; {<br>    let schema: ParquetSchema;<br>    let csvHeaders: string[] = [];<br>    const rows: any[] = [];<br><br>    return new Promise((resolve, reject) =&gt; {<br>      csvStream<br>        .pipe(parse({ headers: true }))<br>        .on(&quot;headers&quot;, (headers) =&gt; {<br>          csvHeaders = headers;<br>        })<br>        .on(&quot;data&quot;, (data) =&gt; {<br>          rows.push(data);<br>        })<br>        .on(&quot;end&quot;, async () =&gt; {<br>          try {<br>            if (rows.length &gt; 0) {<br>              schema = this.inferSchema(csvHeaders, rows[0]);<br>              const memoryWritable = new MemoryWritable();<br>              const writer = await ParquetWriter.openStream(<br>                schema,<br>                memoryWritable<br>              );<br>              for (const row of rows) {<br>                await writer.appendRow(row);<br>              }<br><br>              await writer.close();<br>              const parquetBuffer = memoryWritable.getBuffer();<br><br>              resolve(parquetBuffer);<br>            } else {<br>              reject(new Error(&quot;No data to process&quot;));<br>            }<br>          } catch (error) {<br>            console.error(&quot;Error processing rows:&quot;, error);<br>            reject(error);<br>          }<br>        })<br>        .on(&quot;error&quot;, (error) =&gt; {<br>          console.error(&quot;Error processing CSV:&quot;, error);<br>          reject(error);<br>        });<br>    });<br>  }<br><br>  /**<br>   *<br>   * This function allows you to configure the configuration of the CSV file with the given options and callback function that will be called when the configuration<br>   * @public<br>   * @param {string[]} headers<br>   * @return {*}<br>   * @memberof CodeGen<br>   */<br>  public inferSchema(headers: string[], sampleRow: any): ParquetSchema {<br>    const fields: any = {};<br>    headers.forEach((header) =&gt; {<br>      const sampleValue = sampleRow[header];<br>      let fieldType: any = {<br>        type: &quot;UTF8&quot;,<br>        encoding: &quot;PLAIN&quot;,<br>        compression: &quot;SNAPPY&quot;,<br>      };<br><br>      if (sampleValue) {<br>        if (!isNaN(Number(sampleValue))) {<br>          fieldType = {<br>            type: &quot;DOUBLE&quot;,<br>            encoding: &quot;PLAIN&quot;,<br>            compression: &quot;SNAPPY&quot;,<br>          };<br>        } else if (new Date(sampleValue).toString() !== &quot;Invalid Date&quot;) {<br>          fieldType = {<br>            type: &quot;TIMESTAMP_MILLIS&quot;,<br>            encoding: &quot;PLAIN&quot;,<br>            compression: &quot;SNAPPY&quot;,<br>          };<br>        }<br>      }<br><br>      fields[header] = fieldType;<br>    });<br><br>    return new ParquetSchema(fields);<br>  }<br><br>  /**<br>   *<br>   * Download CSV From BlobStorage<br>   * @param {string} blobName<br>   * @return  {Promise&lt;string&gt;}<br>   * @memberof CodeGen<br>   */<br>  public async downloadCSVFromBlobStorage(<br>    blobName: string<br>  ): Promise&lt;Readable&gt; {<br>    const blobClient =<br>      AzureStorageConfig.getContainerClient().getBlobClient(blobName);<br>    const downloadBlockBlobResponse = await blobClient.download();<br>    return downloadBlockBlobResponse.readableStreamBody as Readable;<br>  }<br>}</pre><p>This class CsvToParquetFile implements the ICsvToParquetFile interface to automate the process of downloading a CSV file from Azure Blob Storage, converting it to Parquet format, and uploading it back to Blob Storage.</p><ol><li><strong>Cron Job</strong>: The class schedules a cron job to run every 5 seconds (*/5 * * * * *), which triggers the process of downloading and converting a specified CSV file (blobName)</li><li><strong>onCSVUpdateAndSuccess</strong>: This method orchestrates the main process. It downloads the CSV file, converts it to Parquet format, and then uploads the Parquet file back to Blob Storage.</li><li><strong>uploadParquetToBlobStorage</strong>: This method uploads the converted Parquet data to Azure Blob Storage using a SAS URL for secure access.</li><li><strong>convertCSVtoParquet</strong>: This method reads the CSV file as a stream, parses the data, infers the schema, and writes it into Parquet format using ParquetWriter. The data is stored in memory using a custom MemoryWritable stream.</li><li><strong>inferSchema</strong>: It infers the Parquet schema from the CSV headers and a sample row, determining field types (e.g., string, double, timestamp) for Parquet.</li><li><strong>downloadCSVFromBlobStorage</strong>: This method downloads the CSV file from Azure Blob Storage and returns it as a readable stream.</li></ol><p>This class efficiently automates CSV-to-Parquet conversion, ensuring the data is stored in a more optimized format for modern analytics and query performance.</p><blockquote>Main entry point(src/index.ts)</blockquote><pre>import express, { Application, Request, Response } from &quot;express&quot;;<br>import { CsvToParquetFile } from &#39;./csv-parquet-job/csv-parquet.corn&#39;;<br>import * as dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>const app: Application = express();<br>const port = 3000;<br><br>app.use(express.json());<br><br><br>app.get(&quot;/&quot;, (req: Request, res: Response) =&gt; {<br>  res.send(&quot;Welcome to the Express TypeScript REST API&quot;);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server is running on http://localhost:${port}`);<br>  new CsvToParquetFile(); <br><br>});<br></pre><p>This code sets up an Express.js server in TypeScript and initializes the CSV-to-Parquet conversion process using a cron job.</p><p><strong>Express Server Setup</strong>:</p><ul><li>An Express application is created (app) with a single route (&quot;/&quot;) that sends a welcome message.</li><li>The server listens on port 3000 and logs the URL when it starts.</li></ul><p><strong>CSV-to-Parquet Cron Job</strong>:</p><ul><li>The CsvToParquetFile class is instantiated when the server starts. This class handles the conversion of CSV files to Parquet format using a cron job that runs every 5 seconds.</li></ul><p>This setup effectively combines the REST API with an automated file conversion process in Node.js.</p><blockquote><strong>package.json</strong></blockquote><p>Here’s a list of the dependencies from package.json file categorized into SDKs and libraries:</p><h3>SDKs</h3><p><a href="https://www.npmjs.com/package/@azure/storage-blob"><strong>@azure/storage-blob</strong></a>: ^12.24.0</p><ul><li>Azure Blob Storage SDK for interacting with Azure Blob Storage</li></ul><p><a href="https://www.npmjs.com/package/azure-storage"><strong>azure-storage</strong></a>: ^2.10.7</p><ul><li>Azure Storage SDK for older Azure Storage APIs.</li></ul><h3>Libraries</h3><p><a href="https://www.npmjs.com/package/dotenv"><strong>dotenv</strong></a>: ^16.4.5</p><ul><li>Loads environment variables from a .env file.</li></ul><p><a href="https://www.npmjs.com/package/express"><strong>express</strong></a>: ^4.19.2</p><ul><li>Web framework for building web applications and APIs.</li></ul><p><a href="https://www.npmjs.com/package/fast-csv"><strong>fast-csv</strong></a>: ^5.0.1</p><ul><li>Library for parsing and formatting CSV files.</li></ul><p><a href="https://www.npmjs.com/package/lodash"><strong>lodash</strong></a>: ^4.17.21</p><ul><li>Utility library for working with arrays, objects, and other data types.</li></ul><p><a href="https://www.npmjs.com/package/node-cron"><strong>node-cron</strong></a>: ^3.0.3</p><ul><li>Scheduling library for running tasks at specific intervals.</li></ul><p><a href="https://www.npmjs.com/package/parquetjs-lite"><strong>parquetjs-lite</strong></a>: ^0.8.7</p><ul><li>Library for working with Parquet files.</li></ul><h3>Development Dependencies</h3><p><a href="https://www.npmjs.com/package/@types/express"><strong>@types/express</strong></a>: ^4.17.21</p><ul><li>TypeScript definitions for Express.</li></ul><p><a href="https://www.npmjs.com/package/@types/lodash"><strong>@types/lodash</strong></a>: ^4.17.7</p><ul><li>TypeScript definitions for Lodash.</li></ul><p><a href="https://www.npmjs.com/package/@types/node"><strong>@types/node</strong></a>: ^22.5.4</p><ul><li>TypeScript definitions for Node.js.</li></ul><p><a href="https://www.npmjs.com/package/@types/node-cron"><strong>@types/node-cron</strong></a>: ^3.0.11</p><ul><li>TypeScript definitions for Node-cron.</li></ul><p><a href="https://www.npmjs.com/package/nodemon"><strong>nodemon</strong></a>: ^3.1.4</p><ul><li>Tool for automatically restarting Node.js applications.</li></ul><p><a href="https://www.npmjs.com/package/ts-node"><strong>ts-node</strong></a>: ^10.9.2</p><ul><li>TypeScript execution engine for Node.js.</li></ul><p><a href="https://www.npmjs.com/package/ts-node-dev"><strong>ts-node-dev</strong></a>: ^2.0.0</p><ul><li>TypeScript development environment with hot-reloading.</li></ul><p><a href="https://www.npmjs.com/package/typescript"><strong>typescript</strong></a>: ^5.5.4</p><ul><li>TypeScript compiler for TypeScript projects.</li></ul><p>You can find the repository <a href="https://github.com/Rajeshwaran7/csv-parquet">here</a>.</p><h3>Solution</h3><p>To streamline the conversion of CSV files to Parquet format, we employ a robust, asynchronous processing pipeline that leverages modern Node.js capabilities and cloud infrastructure. Here’s a breakdown of the approach:</p><ol><li><strong>Scheduled Execution</strong>: Utilizing node-cron, we set up a cron job that triggers every 5 seconds to process CSV files. This periodic execution ensures that the data pipeline is responsive and capable of handling updates in near real-time.</li><li><strong>Streaming CSV Download</strong>: We download CSV files from Azure Blob Storage as readable streams. This method is memory-efficient and allows for handling large files without requiring them to be fully loaded into memory.</li><li><strong>Asynchronous Parsing and Conversion</strong>: Using fast-csv, we asynchronously parse the CSV stream, which allows for efficient handling of large datasets. During parsing, we infer the schema dynamically, ensuring that the conversion to Parquet is accurately structured. We then use parquetjs-lite to convert the parsed data into Parquet format, writing the data to an in-memory buffer (MemoryWritable). This buffer-based approach facilitates fast and efficient data manipulation.</li><li><strong>Secure Parquet Upload</strong>: After converting the data, we upload the Parquet file back to Azure Blob Storage using a BlobServiceClient configured with a SAS URL. Additionally, we leverage a custom pipeline configuration with proxy settings to handle the upload. This setup ensures secure and efficient storage of the converted files while accommodating specific network requirements and enhancing the robustness of our data pipeline.</li></ol><h3>Conclusion</h3><p>By implementing an asynchronous, stream-based approach for converting CSV to Parquet, we achieve significant improvements in performance and scalability. The use of Node.js with fast-csv and parquetjs-lite allows for efficient data processing and conversion, while leveraging Azure Blob Storage ensures reliable and secure file handling. The integration of cron scheduling automates the entire process, minimizing manual intervention and maximizing operational efficiency. This method not only optimizes storage and query performance but also ensures that your data pipeline is robust, scalable, and capable of handling large volumes of data with ease.</p><p>You can find the repository <a href="https://github.com/Rajeshwaran7/csv-parquet">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb9fc20c307e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future of Scalable Applications: Micro frontends with Angular and NX Module Federation]]></title>
            <link>https://medium.com/@rajeshwaran-blog/the-future-of-scalable-applications-micro-frontends-with-angular-and-nx-module-federation-c32c2c01764c?source=rss-c1ec8f1a27e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c32c2c01764c</guid>
            <dc:creator><![CDATA[Rajeshwaran K]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:54:27 GMT</pubDate>
            <atom:updated>2025-02-23T14:12:36.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGCZPz49fG0aOSVrxkFTtw.png" /></figure><p>In the fast-paced world of frontend development, managing large-scale applications can be a daunting task. Traditional monolithic architectures, while simple to begin with, often become difficult to scale and maintain as applications grow. This is where <strong>microfrontend architecture</strong> comes into play, offering a modular, scalable solution to frontend development. By breaking down the application into smaller, independently deployable units, microfrontends allow teams to work autonomously, speeding up development and reducing inter-team dependencies.</p><p><strong>NX</strong>, a powerful toolkit for monorepos, combined with <strong>Webpack’s Module Federation</strong>, brings this concept to life in Angular. NX allows developers to manage a <strong>monorepo</strong> with multiple applications or microfrontends, enabling code sharing, easier dependency management, and better organization. At the same time, <strong>Module Federation</strong> enables dynamic loading of Angular modules from different applications (called remotes), thus allowing parts of the application to be developed and deployed separately.</p><p>Imagine a scenario where a large e-commerce platform has different teams responsible for various sections: the product listing, the user profile, and the checkout process. With <strong>microfrontends</strong>, each team can independently build and deploy their sections as individual micro-applications. By using NX, all these microfrontends can live in a single monorepo, allowing code sharing and consistency across the platform, while <strong>Module Federation</strong> enables seamless integration of these modules into one cohesive application.</p><p>To set up microfrontends in an Angular project using NX, the process begins by creating the host and remote applications. After setting up the ModuleFederationPlugin for both apps, the <strong>remote application</strong> can expose its modules (like a user profile or product listing), and the <strong>host application</strong> can dynamically load these modules at runtime. This setup allows for truly decoupled development and deployment, where updates to one part of the frontend (like the checkout process) can be rolled out without affecting other parts.</p><p>Using NX also provides powerful tools for managing the monorepo, including dependency graphs and code generators, ensuring that the microfrontends remain in sync. With lazy loading and dynamic module federation, applications are optimized, loading only what is necessary at the moment, which improves both performance and user experience.</p><p>Microfrontends offer an ideal solution for growing businesses that want to maintain speed and flexibility without compromising on stability. The combination of <strong>Angular</strong>, <strong>NX</strong>, and <strong>Module Federation</strong> ensures that even the most complex frontend architectures remain manageable, scalable, and future-proof.</p><p>In this blog post, we’ll dive into building a microfrontend application using Angular, powered by NX Module Federation. We’ll explore the advantages of this approach, walk through a comprehensive guide to setting up your development environment, and illustrate how to seamlessly integrate these technologies for a scalable and cohesive application. By adopting microfrontends with NX Module Federation, you’ll leverage the latest best practices to streamline and enhance your development workflow, setting your project up for success in a modern, modular architecture.</p><h3>Setting Up Your Development Environment:</h3><h3>Prerequisites:</h3><p>Before diving into setting up your microfrontend application with Angular and NX Module Federation, ensure you have the following prerequisites in place:</p><p>1. <strong>Node.js and npm/yarn</strong>: Make sure you have Node.js (version 18.x or later) and npm (version 8.x or later) or yarn installed on your machine. These tools are essential for managing dependencies and running your Angular and NX applications.</p><p>· Install Node.js from the <a href="https://nodejs.org/">official website</a>.</p><p>· Verify your installation by running:</p><pre>node -v<br>npm -v<br> # or if using yarn<br>yarn -v</pre><p>2. <strong>Angular CLI</strong>: Install the Angular CLI globally if you haven’t already. This tool helps in creating and managing Angular projects.</p><pre>npm install -g @angular/cli</pre><p>. Verify installation:</p><pre>ng - version</pre><p>3. <strong>NX CLI</strong>: Install the NX CLI globally to manage your monorepo setup and to use NX’s powerful features.</p><pre>npm install -g nx</pre><p>Verify installation:</p><pre>nx - version</pre><p>4. <strong>Webpack Module Federation</strong>: Understanding Webpack Module Federation is crucial as it allows dynamic loading of modules between different applications. You don’t need to install it separately, but familiarizing yourself with its concepts will be beneficial.</p><p>5. <strong>Basic Knowledge of Angular and NX</strong>: You should have a basic understanding of Angular components, services, and modules, as well as NX’s workspace structure, including its workspace configuration and project management.</p><p>6. <strong>Code Editor</strong>: Have a code editor such as Visual Studio Code installed to write and manage your code.</p><h3>Step-by-Step Installation Guide</h3><p><strong>Create an NX workspace<br></strong>To start with, we need to create a new Nx Workspace. We can do this easily with :</p><p>You’ll be prompted with several questions during setup. Focus on selecting the integrated monorepo layout and the Webpack bundler. You can accept the default values for the remaining prompts. Since the default application created isn’t needed for this guide, feel free to remove it after setup.</p><pre>npx create-nx-workspace ng-mf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*IKCyVgPwVHx3x5csyI9x6g.png" /></figure><p><strong>Creating our applications</strong></p><p>We need to create 2 or 3applications that will utilize Module Federation.</p><p>First, we’ll set up the Dashboard application, which will serve as the host for the Micro-Frontends (MFEs):</p><pre>nx g @nx/angular:host apps/dashboard - prefix=ng-mf</pre><p>The host generator will create and configure the necessary files for setting up the Angular application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*yeWjEHtYWmBz_ovBBP572g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*l0o1eOAKQH0OimEIgkWMfg.png" /></figure><p><strong>Next, let’s generate the Login application as a remote module that will be integrated and used by the Dashboard host application.</strong></p><pre>nx g @nx/angular:remote apps/login - prefix=ng-mf - host=dashboard</pre><p>Notice that we used the — host=dashboard option. This instructs the generator that the Login application will be consumed by the Dashboard application. The generator made the following updates to automatically link these two applications:</p><p>· Added the remote configuration to apps/dashboard/module-federation.config.ts</p><p>· Included a TypeScript path mapping in the root tsconfig file</p><p>Updated the routes in apps/dashboard/src/app/app.routes.ts to incorporate the new remote application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*eZQzUteTRr-X4dWuMcMPlA.png" /></figure><p><strong>Let’s review what happens after generating each application.</strong></p><p>For both the host and remote applications, the generators performed the following steps:</p><blockquote>· Created the standard Angular application files</blockquote><blockquote>· Added module-federation.config.ts for Module Federation configuration</blockquote><blockquote>· Created webpack.config.ts and webpack.prod.config.ts for custom Webpack settings</blockquote><blockquote>· Introduced src/bootstrap.ts to handle the module federation setup</blockquote><blockquote>· Moved the contents of src/main.ts to src/bootstrap.ts</blockquote><blockquote>· Updated src/main.ts to dynamically import src/bootstrap.ts to correctly load shared library versions</blockquote><blockquote>· Adjusted the build target in project.json to use @nx/angular:webpack-browser, enabling custom Webpack configuration</blockquote><blockquote>· Modified the serve target to use @nx/angular:dev-server to build the application with Webpack first</blockquote><p>The primary distinctions lie in how the Module Federation Plugin is configured within each application’s module-federation.config.ts.</p><p>We can see the following in the <strong>Login </strong>micro frontend configuration:</p><p><strong>apps/login/module-federation.config.ts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*3aMCEIkU9sNhRJSU0PJN7Q.png" /></figure><p>Let’s break down each property of the configuration:</p><blockquote><strong>name</strong>: This property specifies the name assigned to the remote application by Webpack. It should match the name of your project to ensure proper identification and integration.</blockquote><blockquote><strong>exposes</strong>: This property lists the source files or modules that the remote application makes available to other applications (the consuming shell applications). These are the parts of the application that can be dynamically loaded and used by the host application.</blockquote><p>This configuration is then utilized in the webpack.config.ts file, which is responsible for setting up and applying Webpack’s Module Federation settings. This setup ensures that the remote application is correctly integrated and its exposed modules can be accessed by the host application.</p><p><strong>apps/login/webpack.config.ts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PhBiIiYD1KMJ5FsYuexAaA.png" /></figure><p><strong>Note: create the user app(remote-app) as same as login app if you needed.</strong></p><p>Here’s what we find in the configuration for the Dashboard micro frontend:</p><p><strong>apps/dashboard/module-federation.config.ts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*xSnTyx-6f4OX0oWL5njNAg.png" /></figure><p>The key difference to note with the Dashboard configuration is the remotes array. This is where you list the remote applications you want to consume in your host application.</p><p>You give it a name that you can reference in your code, in this case login and user. Nx will find where it is served.</p><p>Now that we have our applications generated, let’s move on to building out some functionality for each.</p><p><strong>User Library</strong></p><blockquote><strong>In a monorepo setup, libraries (libs) serve several important purposes:</strong></blockquote><p><strong>1. Code Reusability</strong>: Libraries allow you to encapsulate common functionality, utilities, or shared components that can be used across multiple applications within the monorepo. This reduces code duplication and ensures consistency.</p><p><strong>2. Separation of Concerns</strong>: By organizing shared code into libraries, you can maintain a clear separation between different aspects of your codebase. This modular approach helps in managing and maintaining the code more effectively.</p><p><strong>3. Simplified Updates</strong>: When a shared library needs to be updated, you can make changes in one place, and those changes automatically propagate to all consuming applications. This simplifies the process of applying updates or fixes.</p><p><strong>4. Improved Collaboration</strong>: Libraries enable teams to work on different parts of the codebase independently. For instance, one team can develop and maintain a UI component library, while another team focuses on business logic or data access libraries.</p><p><strong>5. Encapsulation and Abstraction</strong>: Libraries can encapsulate complex functionality or business logic, providing a clear and well-defined API for consuming applications. This abstraction helps in managing complexity and improving code readability.</p><p><strong>6. Dependency Management</strong>: Libraries can define their own dependencies, which helps in isolating and managing third-party packages. This can prevent version conflicts and ensure that each library has the correct version of its dependencies.</p><p><strong>7. Testing and Quality Assurance</strong>: Libraries can include their own unit tests and quality checks. This allows you to verify that shared code works correctly and meets quality standards before it’s used by other applications.</p><p><strong>8. Modular Architecture</strong>: Using libraries supports a modular architecture, making it easier to scale and refactor the codebase as the project grows. It also facilitates adopting new technologies or frameworks in a more controlled manner.</p><p>In summary, libraries in a monorepo setup help in managing shared code efficiently, promoting modularity, and improving collaboration across teams.</p><p><strong>Adding Functionality under Libs</strong></p><p>Under the libs directory, you typically have two key categories:</p><p>There are UI ,Services and Shared Components</p><ol><li><strong>Shared Components</strong>: These components are specifically designed for the user interface and might include more specialized or complex elements that are used within a particular context or application. UI components might include things like dashboards, charts, or modals that are tailored to the specific needs of your application.</li></ol><blockquote>Here we’re gonna use for footer layout across microfrontend apps</blockquote><pre>nx g @nx/angular:lib libs/shared/data-access-user</pre><p>This will create a new library for us to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*bc-mdgY_9zgZBxbyEpjsZA.png" /></figure><p><strong>ng-mf/libs/shared/data-access-user/src/lib/shared-data-access-user/shared-data-access-user.component.html</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpSH3rrNCLsHmlsTodBtZQ.png" /></figure><p><strong>ng-mf/libs/shared/data-access-user/src/lib/shared-data-access-user/shared-data-access-user.component.ts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*UsixQImnuW-0jbWepqYdCg.png" /></figure><blockquote>Similarly we should create ui library under libs folder for button component</blockquote><p><strong>2. Ui Components</strong>: These are reusable components that are used across multiple applications. They often include common elements like buttons, form controls, and layout components that are consistent throughout your application or across different applications.</p><pre>ng-mf/libs/ui/button/src/lib/ui-button/ui-button.component.ts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*zTB5j9kz2Lukwd4d0lDEtQ.png" /></figure><pre>ng-mf/libs/ui/button/src/lib/ui-button/ui-button.component.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*AFkOQPhj1JsfjCtvwwTsUg.png" /></figure><p><strong>3. Service: </strong>Services handle business logic, data management, and communication with APIs, providing a centralized place for these functionalities that can be used across different applications and components.</p><p>We need an Angular Service that we will use to hold state:</p><pre>nx g @nx/angular:service user - project=data-access-user</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*8TaqT_xvzJncTwDPFI6vzw.png" /></figure><p>libs/shared/data-access-user/src/lib/user.service.ts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEywFHhFthuN6bDg8Xmo4Q.png" /></figure><p>Now that we’ve successfully set up our microfrontend application, let’s implement the some logic needed to achieve a fully functional microfrontend architecture using module federation within our monorepo.</p><p><strong>Login Application (Remote app):</strong></p><blockquote>Let’s set up our <strong>entry.component.ts</strong> file in the <strong>Login</strong> application so that it renders a login form. We’ll import <strong>FormsModule</strong> and inject our <strong>UserService</strong> to allow us to sign the user in:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1O_xcUe4TA854Y3w_9XMA.png" /></figure><blockquote>The <strong>Login</strong> button is part of the UI component, which we’ve imported from the UI library.<strong> &lt;lib-ui-button&gt;Login&lt;/lib-ui-button&gt;</strong></blockquote><blockquote>We’ve also imported and are utilizing the <strong>shared</strong> <strong>Footer</strong> <strong>layout</strong> from the shared library. <strong>&lt;lib-shared-data-access-user&gt;&lt;/lib-shared-data-access-user&gt;</strong></blockquote><blockquote>The <strong>User Service</strong> is injected here, leveraging functionality from the libs/service directory, which is registered at the root level.</blockquote><p>Now let’s serve the application and view it in a browser to check that the form renders correctly.</p><pre>nx run login:serve</pre><p>We can see if we navigate a browser to <a href="http://localhost:4201/"><strong>http://localhost:4201</strong></a> that we see the <strong>login </strong>(remote app)<strong> </strong>form rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*iE_BN9vUsA4_ZD6_gXLAXQ.png" /></figure><p>If we type in the correct username and password (demo, demo), then we can also see the user gets authenticated!</p><p><strong>User Application (Remote app):</strong></p><p>Let’s configure the entry.component.ts file in the User application to display a list of users. We&#39;ll import the <strong>CommonModule</strong> and <strong>UserListComponent</strong> to handle the rendering of user data efficiently.</p><p><strong>UserListComponent.ts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIt0Wbpstg-R00PZ-U0FsQ.png" /></figure><p>Now let’s serve the application and view it in a browser to check that the user list renders correctly.</p><pre>nx run user:serve</pre><p>We can see if we navigate a browser to <a href="http://localhost:4201/"><strong>http://localhost:420</strong></a><strong>2</strong> that we see the <strong>user </strong>(remote app)<strong> </strong>form rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgTmC2969L0KXB7oAPLEzA.png" /></figure><blockquote>We’ve also imported and are utilizing the <strong>shared</strong> <strong>Footer</strong> <strong>layout</strong> from the shared library. <strong>&lt;lib-shared-data-access-user&gt;&lt;/lib-shared-data-access-user&gt;</strong></blockquote><blockquote>In the <strong>Login application</strong>, we authenticate the user’s data, and based on the authentication status, we grant access to navigate to the <strong>User application</strong>.</blockquote><p><strong>Dashboard Application (host app):</strong></p><p>In the Dashboard app, we’ve implemented a simple homepage featuring a navigation menu, allowing users to easily switch between different microfrontend applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*BHIdhq9hAqsWxpe85Im5Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vO3VW8XiKbQbJ0YxSNJ72w.png" /></figure><p>We can run the host application alongside the remote applications by using the following command:</p><pre>nx serve dashboard --devRemotes=login,user</pre><p>This command will start the host Dashboard application along with the remote Login and User applications. The host will be accessible at http://localhost:4200. This setup enables seamless integration between the host and remote applications during development.</p><p>We have successfully completed the module federation setup using NX in our Angular monorepo application. This allows seamless integration of microfrontends, enabling independent development and deployment of different application modules.</p><blockquote>Check out the repository for a demonstration of module federation using NX in a monorepo setup: <a href="https://github.com/Rajeshwaran7/microfrontend-poc">microfrontend-poc</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c32c2c01764c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>