<?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 Gnanabillian on Medium]]></title>
        <description><![CDATA[Stories by Gnanabillian on Medium]]></description>
        <link>https://medium.com/@gnanabillian?source=rss-fad26f02d8f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X2RJ3NQcImtYqTk4UiNhcw.jpeg</url>
            <title>Stories by Gnanabillian on Medium</title>
            <link>https://medium.com/@gnanabillian?source=rss-fad26f02d8f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:02:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gnanabillian/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[More Work, Same Title: The Hidden Cost of Silent Promotions in Tech]]></title>
            <link>https://medium.com/@gnanabillian/more-work-same-title-the-hidden-cost-of-silent-promotions-in-tech-bb97e4125f77?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb97e4125f77</guid>
            <category><![CDATA[career-growth]]></category>
            <category><![CDATA[workplace-equity]]></category>
            <category><![CDATA[workplace-culture]]></category>
            <category><![CDATA[leadership-development]]></category>
            <category><![CDATA[fair-pay]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 13:27:26 GMT</pubDate>
            <atom:updated>2025-04-04T13:27:26.327Z</atom:updated>
            <content:encoded><![CDATA[<p>The tech industry moves fast, rewarding innovation and hard work — but sometimes, that hard work comes with an <strong>invisible cost</strong>. Many employees find themselves in <strong>“silent promotions”</strong> — a situation where they take on more responsibilities without the title, pay, or recognition that should come with it.</p><p>While this might seem like a stepping stone to career growth, it can actually be a <strong>trap</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_3Ysu13IxnzNl5fH" /></figure><h3>🚀 What Is a Silent Promotion?</h3><p>A silent promotion happens when an employee is given additional responsibilities that align with a higher role <strong>without the formal recognition</strong> — no title change, no salary adjustment, just more work.</p><p>It often looks like this:</p><ul><li>A <strong>developer</strong> starts mentoring others and handling architecture discussions — without the “Senior” title.</li><li>A <strong>team lead</strong> begins managing cross-functional projects — but remains a lead, not a manager.</li><li>A <strong>software engineer</strong> takes ownership of a critical system, but their role on paper remains unchanged.</li></ul><p>At first, it feels like a <strong>growth opportunity</strong>. But if there’s no recognition <strong>over time</strong>, it becomes an <strong>exploitation tactic</strong> — more responsibilities with no added benefits.</p><h3>❌ Why Silent Promotions Are a Problem</h3><p>Silent promotions don’t just impact individuals — they create <strong>a broken system</strong> where extra effort isn’t rewarded properly. Here’s why they’re harmful:</p><h3>1️⃣ They Normalize Unfair Workloads</h3><p>When employees take on extra work without official promotion, companies get <strong>free labor</strong> while others remain at the same level <strong>doing less work</strong> for the same pay.</p><h3>2️⃣ They Delay Real Promotions</h3><p>Why should a company officially promote you if you’re already <strong>doing the job without the title?</strong> Some employers intentionally <strong>drag out promotions</strong> because they know you’re committed and will continue working without questioning it.</p><h3>3️⃣ They Lead to Burnout</h3><p>Without proper recognition, employees start questioning their worth. Over time, this leads to <strong>frustration, disengagement, and burnout</strong>, making top talent leave instead of feeling valued.</p><h3>🛑 How to Break Free from the Silent Promotion Trap</h3><p>If you’re experiencing a silent promotion, here’s what you can do:</p><p>🔹 <strong>Track Your Contributions</strong> — Keep a record of additional responsibilities, leadership tasks, and impact.<br> 🔹 <strong>Initiate the Conversation</strong> — Don’t wait for recognition. Speak up about a title and compensation change.<br> 🔹 <strong>Set Boundaries</strong> — If promotions and raises aren’t coming, consider stepping back to your <strong>actual</strong> job description.<br> 🔹 <strong>Explore Your Options</strong> — If your growth isn’t acknowledged, it might be time to look elsewhere.</p><h3>🌱 A Healthy Workplace Rewards Growth</h3><p>Taking on new challenges is great — but real growth happens when <strong>your efforts are valued and rewarded</strong>. Tech thrives on innovation, but <strong>no one should be silently promoted without recognition</strong>.</p><p>💬 Have you ever experienced a <strong>silent promotion</strong>? How did you handle it? Let’s discuss in the comments. 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb97e4125f77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Silent Divide: Unspoken Messages That Shape Workplace Culture]]></title>
            <link>https://medium.com/@gnanabillian/the-silent-divide-unspoken-messages-that-shape-workplace-culture-74de3947be6d?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/74de3947be6d</guid>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[workplace-culture]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[employee-recognition]]></category>
            <category><![CDATA[employee-engagement]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 08:49:04 GMT</pubDate>
            <atom:updated>2025-04-04T08:49:04.866Z</atom:updated>
            <content:encoded><![CDATA[<p>A workplace is like a big team, where everyone plays a role. But sometimes, not everyone gets the same chance to shine. While teamwork and success are often emphasized, the way people are included in important moments can tell a different story.</p><h3>A Simple Story</h3><p>Imagine a group of friends planning a trip. They say everyone is important, but when the trip happens, only a few get invited. The rest find out later through pictures or stories. No one says it out loud, but the message is clear — some are part of the group, and some are not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHRmcNOhVVuyLktEsigJIg.png" /></figure><p>This happens in workplaces too. Some employees are included in key meetings, projects, or decisions, while others only hear about them afterward. Even though everyone contributes, not all efforts receive the same recognition.</p><h3>Why This Matters</h3><p>Feeling valued at work is more than just receiving a paycheck or a compliment. It’s about knowing that one’s efforts make a difference. When people feel excluded, they start to question their roles and contributions.</p><p>Over time, this can impact motivation. Employees may still perform their tasks, but their energy and enthusiasm fade. They stop going the extra mile — not because they don’t care, but because they feel unseen.</p><h3>Real Growth Means Valuing Everyone</h3><p>True success isn’t just about financial growth or expansion. A strong and committed team is built when every employee feels included and valued. Workplaces that foster fairness and appreciation often see higher engagement, creativity, and long-term success.</p><h3>How to Build an Inclusive Workplace</h3><p>Creating a positive and inclusive work environment doesn’t require big changes — small actions can make a significant impact:</p><ul><li><strong>Recognizing contributions</strong>, no matter how big or small.</li><li><strong>Encouraging open communication</strong> and making sure everyone has access to opportunities.</li><li><strong>Creating space for employees to share ideas</strong> and feel heard.</li></ul><p>When people feel included, they bring their best selves to work. They don’t just complete tasks — they contribute with passion and purpose. And that is what truly makes a workplace thrive.</p><p>At the end of the day, success is not just about reaching goals. It’s about ensuring that everyone who contributes along the way knows they matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74de3947be6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safeguarding Your NestJS Application with Fastify Helmet]]></title>
            <link>https://blog.devgenius.io/safeguarding-your-nestjs-application-with-fastify-helmet-e354502fd056?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e354502fd056</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[helmet]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Tue, 07 May 2024 05:50:19 GMT</pubDate>
            <atom:updated>2025-04-09T17:46:27.724Z</atom:updated>
            <content:encoded><![CDATA[<p>Securing web applications is crucial in today’s digital landscape, where cyber threats are prevalent. NestJS, a popular Node.js framework, offers seamless integration with Fastify, a high-performance web framework. When it comes to enhancing the security of our NestJS application, Fastify Helmet becomes an invaluable tool. Fastify Helmet is a plugin that provides essential security headers to protect our application from common web vulnerabilities. In this article, we will explore how to integrate Fastify Helmet into a NestJS application.</p><h4>What is Helmet.js?</h4><p>Helmet.js is a collection of middleware functions that help secure web applications by setting appropriate HTTP headers. These headers play a crucial role in protecting your application from attacks like cross-site scripting (XSS), clickjacking, MIME-type sniffing, and more. By integrating Helmet.js into your application, you can easily and efficiently implement these security measures.</p><pre>import fastifyHelmet from &#39;@fastify/helmet&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import {<br>  FastifyAdapter,<br>  NestFastifyApplication<br>} from &#39;@nestjs/platform-fastify&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create&lt;NestFastifyApplication&gt;(<br>    AppModule,<br>    new FastifyAdapter()<br>  );<br><br>  app.register(fastifyHelmet, {});<br><br>  await app.listen(3000);<br>}<br><br>bootstrap();</pre><h4>Exploring Fastify Helmet Security Headers</h4><p>Fastify Helmet offers a range of security headers that we can configure based on our application’s requirements.</p><h4>Content Security Policy (CSP)</h4><p>Content Security Policy (CSP) helps protect against cross-site scripting (XSS) attacks by controlling the sources from which various resources can be loaded. We can define a policy to specify approved sources for scripts, stylesheets, images, fonts, and more.</p><p>Here’s an example of configuring the CSP directive using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  contentSecurityPolicy: {<br>    directives: {<br>      defaultSrc: [&quot;&#39;self&#39;&quot;],<br>      scriptSrc: [&quot;&#39;self&#39;&quot;, &quot;&#39;unsafe-inline&#39;&quot;],<br>      styleSrc: [&quot;&#39;self&#39;&quot;, &quot;&#39;unsafe-inline&#39;&quot;],<br>      imgSrc: [&quot;&#39;self&#39;&quot;, &quot;data:&quot;],<br>      fontSrc: [&quot;&#39;self&#39;&quot;],<br>    },<br>  },<br>});</pre><p>In this example, we’ve defined the following directives:</p><ul><li>defaultSrc: Restricts the default source to the same domain.</li><li>scriptSrc: Allows scripts from the same domain and allows inline scripts (not recommended in production).</li><li>styleSrc: Allows stylesheets from the same domain and allows inline styles (not recommended in production).</li><li>imgSrc: Allows images from the same domain and allows the use of data URIs.</li><li>fontSrc: Allows fonts from the same domain.</li></ul><h4>Cross-Origin Embedder Policy (COEP)</h4><p>Cross-Origin Embedder Policy (COEP) helps prevent cross-origin attacks by ensuring that embedded resources are served from the same origin. It helps mitigate risks associated with embedding resources from untrusted sources.</p><p>Here’s an example of configuring the COEP directive using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  crossOriginEmbedderPolicy: { policy: &#39;require-corp&#39; },<br>});</pre><p>In this example, we’ve set the policy to &#39;require-corp&#39;, which mandates that all embedded resources must be served from the same origin.</p><h4>Cross-Origin Opener Policy (COOP)</h4><p>Cross-Origin Opener Policy (COOP) prevents a document from being opened in a different browsing context, reducing the risk of cross-site attacks. It ensures that documents are not opened in pop-ups or iframes from other origins.</p><p>Here’s an example of configuring the COOP directive using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  crossOriginOpenerPolicy: { policy: &#39;same-origin&#39; },<br>});</pre><p>In this example, we’ve set the policy to &#39;same-origin&#39;, which allows documents to be opened only in the same origin.</p><h4>Cross-Origin Resource Policy (CORP)</h4><p>Cross-Origin Resource Policy (CORP) controls whether resources on a page can be requested from another domain. It helps mitigate cross-site scripting (XSS) and other cross-origin attacks.</p><p>Here’s an example of configuring the CORP directive using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  crossOriginResourcePolicy: { policy: &#39;same-origin&#39; },<br>});</pre><p>In this example, we’ve set the policy to &#39;same-origin&#39;, which restricts all resource requests to the same origin.</p><h4>Origin Agent Cluster</h4><p>Origin Agent Cluster determines whether an application should expose itself as part of a cluster of origins. We can enable or disable this feature based on our requirements.</p><p>Here’s an example of enabling the Origin Agent Cluster using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  originAgentCluster: true,<br>});</pre><p>In this example, we’ve enabled the Origin Agent Cluster.</p><h4>Referrer Policy</h4><p>Referrer Policy controls how much referrer information is sent when navigating from external sources to our application. It helps protect against information leakage and cross-site request forgery attacks.</p><p>Here’s an example of configuring the Referrer Policy directive using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  referrerPolicy: { policy: &#39;same-origin&#39; },<br>});</pre><p>In this example, we’ve set the policy to &#39;same-origin&#39;, meaning referrer information will only be sent for same-origin requests.</p><h4>X-Content-Type-Options</h4><p>X-Content-Type-Options prevents the browser from MIME-sniffing the response, reducing the risk of certain types of attacks.</p><p>Here’s an example of enabling X-Content-Type-Options using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  xContentTypeOptions: true,<br>});</pre><p>In this example, we’ve enabled X-Content-Type-Options.</p><h4>X-DNS-Prefetch-Control</h4><p>X-DNS-Prefetch-Control controls browser DNS prefetching, which is a technique used by modern browsers to resolve domain names in advance. We can enable or disable DNS prefetching as needed.</p><p>Here’s an example of enabling DNS prefetching using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  xDnsPrefetchControl: { allow: true },<br>});</pre><p>In this example, we’ve allowed DNS prefetching.</p><h4>X-Download-Options</h4><p>X-Download-Options prevents Internet Explorer from executing downloads in the context of the HTML document, reducing the risk of certain types of attacks.</p><p>Here’s an example of enabling X-Download-Options using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  xDownloadOptions: true,<br>});</pre><p>In this example, we’ve enabled X-Download-Options.</p><h4>X-Frame-Options</h4><p>X-Frame-Options mitigates clickjacking attacks by specifying whether a browser should be allowed to render a page in a frame or iframe.</p><p>Here’s an example of configuring X-Frame-Options using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  xFrameOptions: { action: &#39;sameorigin&#39; },<br>});</pre><p>In this example, we’ve set the action to &#39;sameorigin&#39;, allowing the page to be displayed in a frame only if the origin is the same.</p><h4>X-Permitted-Cross-Domain-Policies</h4><p>X-Permitted-Cross-Domain-Policies restricts the types of cross-domain policy files that can be accessed. We can specify the permitted policies to control the behavior of cross-domain requests.</p><p>Here’s an example of configuring X-Permitted-Cross-Domain-Policies using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  xPermittedCrossDomainPolicies: { permittedPolicies: &#39;none&#39; },<br>});</pre><p>In this example, we’ve set the permittedPolicies to &#39;none&#39;, indicating that no cross-domain policies should be permitted.</p><h4>X-XSS-Protection</h4><p>X-XSS-Protection enables or disables the built-in cross-site scripting (XSS) protection mechanism in the browser.</p><p>Here’s an example of enabling X-XSS-Protection using Fastify Helmet:</p><pre>app.register(fastifyHelmet, {<br>  xXssProtection: true,<br>});</pre><p>In this example, we’ve enabled X-XSS-Protection.</p><h4>Conclusion</h4><p>Fastify Helmet provides essential security headers to enhance the security of our NestJS Fastify applications. By configuring these headers according to our application’s requirements, we can mitigate common web vulnerabilities and protect our users’ data. Implementing robust security measures is crucial in today’s threat landscape, and Fastify Helmet makes it easier for us to achieve that. So, don’t forget to integrate Fastify Helmet into your NestJS Fastify applications and secure them effectively!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e354502fd056" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/safeguarding-your-nestjs-application-with-fastify-helmet-e354502fd056">Safeguarding Your NestJS Application with Fastify Helmet</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Apache NiFi 2.0.0-M1 on Ubuntu 20.04]]></title>
            <link>https://blog.devgenius.io/installing-apache-nifi-2-0-0-m1-on-ubuntu-20-04-ec40ca9e10b1?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec40ca9e10b1</guid>
            <category><![CDATA[apache-nifi]]></category>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[ubuntu-20-04]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 07:27:55 GMT</pubDate>
            <atom:updated>2023-12-20T14:37:33.814Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache NiFi is an open-source data integration tool that provides a user-friendly interface to design data flows between systems. In this guide, we’ll walk through the process of installing Apache NiFi 2.0.0-M1 on Ubuntu 20.04.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hi4CcvV-lkdOOH4L.jpg" /></figure><h4>Prerequisite:</h4><p>Before proceeding with the installation, ensure you meet the minimum requirement of Java 21. If not already installed, refer to the guide below on how to install Java 21 on your system.</p><h3>Installing Java 21</h3><h4>Step 1: Download Java 21</h4><p>Visit the Oracle Java Downloads page and download the Java 21 package for Linux x64 <a href="https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.deb">here</a>.</p><h4>Step 2: Install the .deb package</h4><p>Open a terminal and run the following command to install the downloaded .deb package:</p><pre>$ sudo apt install ~/Downloads/jdk-21_linux-x64_bin.deb</pre><h4>Step 3: Set JDK 21 as default (for ARM only)</h4><p>For ARM architecture, follow additional steps to set Java 21 as the default. Skip this section if you’re not on ARM.</p><p>a.) Create the /usr/lib/jvm directory if it does not exist:</p><pre>$ sudo mkdir -p /usr/lib/jvm</pre><p>b.) Extract the tarball to the directory:</p><pre>$ sudo tar -zxf ~/Downloads/jdk-21_linux-aarch64_bin.tar.gz -C /usr/lib/jvm</pre><p>c.) Create symbolic links for the executable files:</p><pre>$ sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-21.0.1/bin/java 1<br>$ sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-21.0.1/bin/javac 1<br>$ sudo update-alternatives --install /usr/bin/jar jar /usr/lib/jvm/jdk-21.0.1/bin/jar 1</pre><p>d.) Set Java JDK 21 as default:</p><pre>$ sudo update-alternatives --config java<br>$ sudo update-alternatives --config javac<br>$ sudo update-alternatives --config jar</pre><p>Verify the installation by running:</p><pre>$ java -version<br>$ javac -version</pre><p>Set JAVA_HOME for the current command console</p><pre>$ export JAVA_HOME=/usr/lib/jvm/jdk-21-oracle-x64</pre><p>This sets the JAVA_HOME variable for the current command console, and it will remain effective until you close it.</p><p>Alternatively, you can add the JAVA_HOME path to your .bashrc file to make the change persistent across sessions:</p><pre>$ sudo nano ~/.bashrc</pre><p>Add the java home file path in the .bashrc file</p><pre>export JAVA_HOME=/usr/lib/jvm/jdk-21-oracle-x64</pre><pre>$ source ~/.bashrc</pre><p>Now, JAVA_HOME will be set every time you open a new terminal session.</p><h3>Installing Apache NiFi 2.0.0-M1</h3><h4>Step 1: Download Apache NiFi</h4><p>Download Apache NiFi 2.0.0-M1 from <a href="https://dlcdn.apache.org/nifi/2.0.0-M1/nifi-2.0.0-M1-bin.zip">here</a>.</p><h4>Step 2: Extract NiFi</h4><p>Navigate to the directory where NiFi was downloaded and extract the files:</p><pre>$ tar -zxvf nifi-2.0.0-M1-bin.zip</pre><h4>Step 3: Configure NiFi</h4><p>Open the conf/nifi.properties file and set the desired port and host configurations.</p><h4>Step 4: Start NiFi</h4><p>Start the NiFi service:</p><pre>$ cd nifi-2.0.0-M1/bin<br>$ ./nifi.sh start</pre><p>NiFi should now be running, and you can access the NiFi UI by navigating to http://localhost:8443/nifi in your web browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkN9lyWifdOTuoxI1Pfm4w.png" /></figure><p><strong>The following command can be used to change the username and password:</strong></p><pre>$ ./bin/nifi.sh set-single-user-credentials &lt;username&gt; &lt;password&gt;</pre><p>Verify that the users.xml file in the NiFi conf directory has the correct user information. Make sure the identifier and identity attributes are set appropriately for the user.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;<br>&lt;tenants&gt;<br>    &lt;groups/&gt;<br>    &lt;users&gt;<br>        &lt;user identifier=&quot;admin&quot; identity=&quot;admin&quot;/&gt;<br>    &lt;/users&gt;<br>&lt;/tenants&gt;</pre><p><strong>Restart NiFi:</strong></p><ul><li>After making changes to the users.xml file or after running the set-single-user-credentials command, restart NiFi to apply the changes.</li></ul><pre>$ ./nifi.sh restart</pre><p><strong>Log File Inspection:</strong></p><ul><li>Check the NiFi logs for any error messages or warnings related to authentication. The logs are typically located in the logs directory. You can tail the logs using:</li></ul><pre>tail -f /home/billian/Tools/nifi-2.0.0-M1/logs/nifi-app.log</pre><h3>Conclusion</h3><p>Congratulations! You have successfully installed Apache NiFi 2.0.0-M1 on Ubuntu 20.04 with Java 21. This powerful data integration tool opens up a world of possibilities for managing and automating data flows. Explore NiFi’s capabilities and streamline your data workflows effortlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec40ca9e10b1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/installing-apache-nifi-2-0-0-m1-on-ubuntu-20-04-ec40ca9e10b1">Installing Apache NiFi 2.0.0-M1 on Ubuntu 20.04</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma runtime custom validation to models]]></title>
            <link>https://medium.com/yavar/prisma-runtime-custom-validation-to-models-acd4362efaa5?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/acd4362efaa5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[model-validation]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[joi]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 06:00:39 GMT</pubDate>
            <atom:updated>2023-07-06T06:00:39.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, In this post, we learn about how to do Prisma custom runtime validation in model level</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*hvrLERGZGGWVV0tQ7i4-YQ.jpeg" /></figure><p>My existing applications are implemented by Sequelize with the Fastify framework. In that application, we have validated the input data at the schema level and model level. The schema level validates the request’s type and which fields are required and etc. The model level is a runtime validation of our application, this validation will be executed before the data write-in database. So it provides data accuracy, and completeness of the dataset by eliminating data errors from any project to ensure that the data is not corrupted.</p><p>Prisma Client has type-safety and run-time type validation but we can not implement custom validation. So, In my Prisma with NestJs application, I have implemented the run time validation to models with the Joi library. If you want more information Joi, kindly refer to the official page and <a href="https://joi.dev/api/?v=17.7.0"><strong><em>click here</em></strong></a></p><p>First, we need to install the Joi package in our application:</p><pre>npm install joi</pre><p>I will handle this model validation in the business service file. Here I define the input fields at the inside of the Joi schema object. Joi schema objects are immutable which means every additional rule added (e.g. alphanum(), min(3), max(30), required() ) will return a new schema object.</p><p>We can validate the input fields with regex using a pattern. The Joi error with a custom error if the rule fails, it will throw the error. Here we have used Joi to extend the method for custom validation, it will be helpful to validate the input param with the database, and we can implement all validation and we can throw the custom error also. Here I have validated a value using the schema and options. Why I preferred this Joi library? Because I can do the custom validation and also a lot of features are default provided by them. In the initial stage, I also tried to implement it in Prisma but the Prisma official website also prefers some libraries <a href="https://github.com/sideway/joi">joi</a>, <a href="https://github.com/validatorjs/validator.js">validator.js</a>, <a href="https://github.com/jquense/yup">Yup</a>, <a href="https://github.com/colinhacks/zod">Zod</a>, and <a href="https://github.com/ianstormtaylor/superstruct">Superstruct</a>. <a href="https://www.prisma.io/docs/concepts/components/prisma-client/custom-validation"><strong><em>For your reference</em></strong></a></p><pre>import * as Joi from &#39;joi&#39;;<br>import { user } from &#39;@prisma/client&#39;;<br>import { PrismaService } from &#39;src/prisma/prisma.service&#39;;<br>import {<br>  Injectable,<br>  UnprocessableEntityException,<br>} from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class UserService {<br>  constructor(private prisma: PrismaService) {}<br><br>  async create(userDto: any): Promise&lt;user&gt; {<br><br>    //check the email is unique or not<br>    const method = async (value) =&gt; {<br>      const userEmail = await this.prisma.user.findFirst({<br>        where: { email: value },<br>        select: { email: true },<br>      });<br>      if (userEmail)<br>        throw new UnprocessableEntityException(&#39;Email already exists&#39;);<br>    };<br><br>    //run time model validation<br>    const schema = Joi.object({<br>      first_name: Joi.string()<br>        .min(3)<br>        .max(30)<br>        .pattern(new RegExp(/^[a-zA-Z0-9 _-]*$/))<br>        .error(<br>          new UnprocessableEntityException(&#39;first_name should be valid format&#39;),<br>        ),<br>      last_name: Joi.string()<br>        .pattern(new RegExp(/^[a-zA-Z0-9 _-]*$/))<br>        .min(3)<br>        .max(30)<br>        .error(<br>          new UnprocessableEntityException(&#39;last_name should be valid format&#39;),<br>        ),<br>      password: Joi.string()<br>        .pattern(<br>          new RegExp(<br>            /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@~()$!%*?&amp;])[A-Za-z\d@~()$!%*?&amp;]/,<br>          ),<br>        )<br>        .error(<br>          new UnprocessableEntityException(<br>            &#39;Password must have at least one uppercase letter, one lowercase letter, one number and one special character (~@$!%*?&amp;)&#39;,<br>          ),<br>        ),<br>      confirm_password: Joi.string()<br>        .equal(Joi.ref(&#39;password&#39;))<br>        .error(<br>          new UnprocessableEntityException(<br>            &#39;confirm_password should be match with pssword&#39;,<br>          ),<br>        ),<br>      email: Joi.string()<br>        .email({<br>          minDomainSegments: 2,<br>          tlds: { allow: [&#39;com&#39;, &#39;net&#39;] },<br>        })<br>        .external(method)<br>        .error(<br>          new UnprocessableEntityException(&#39;Email should be valid format&#39;),<br>        ),<br>    });<br><br>    //validate the model by validateAsync<br>    await schema.validateAsync(userDto);<br>    return await this.prisma.user.create({<br>      data: userDto,<br>    });<br>  }<br>}</pre><p>The other method we should move the validate async into the Prisma service file. Because we call the validateAsync model validation once when the action is performed (create or update a user record by Prisma). That’s why we use the Prisma $use. In the following example, I will cover these changes:</p><p>In the main.ts file, define the port for the server and also migrate the application into Fastify for performance. We import useContainer from class-validator and pass our NestJS application instance (app.select(AppModule)) to it. This configures class-validator to use NestJS&#39;s DI container. Then, we create a global ValidationPipe using app.useGlobalPipes() to enable validation throughout our application. The useGlobalFilter method is used to set a global filter for our application. We can create a custom filter by implementing the HttpExceptionFilter interface provided by NestJS. Once the filter is created, we can use useGlobalFilter to register it globally and specify its scope.</p><pre>                                main.ts<br><br>import { AppModule } from &#39;./app.module&#39;;<br>import { useContainer } from &#39;class-validator&#39;;<br>import { ValidationPipe } from &#39;@nestjs/common&#39;;<br>import { HttpExceptionFilter } from &#39;./exceptions/all-exception.filter&#39;;<br>import { NestFactory, HttpAdapterHost} from &#39;@nestjs/core&#39;;<br><br>import {<br>  FastifyAdapter,<br>  NestFastifyApplication,<br>} from &#39;@nestjs/platform-fastify&#39;;<br><br>async function bootstrap() {<br>  try {<br>    const app = await NestFactory.create&lt;NestFastifyApplication&gt;(<br>      AppModule,<br>      new FastifyAdapter(),<br>    );<br><br>    useContainer(app.select(AppModule), { fallbackOnErrors: true });<br><br>    app.useGlobalPipes(<br>      new ValidationPipe({ whitelist: true, transform: true }),<br>    );<br><br>    const { httpAdapter } = app.get(HttpAdapterHost);<br>    app.useGlobalFilters(new HttpExceptionFilter(httpAdapter));<br><br>    await app.listen(process.env.PORT, &#39;0.0.0.0&#39;);<br>  } catch (error) {<br>    process.exit();<br>  }<br>}<br>bootstrap();</pre><p>In the all-exception.filter.ts file, We can create our own custom exception filters by implementing the ExceptionFilter interface provided by NestJS. Custom exception filters allow us to handle specific types of exceptions or add custom logic to error handling. To register exception filters in our NestJS application, we can use the @Catch() decorator to specify the exceptions the filter should handle. Then, we can use the useGlobalFilters() method in the application module to apply the filters globally.</p><pre>                           all-exception.filter.ts<br><br>import { FastifyError } from &#39;fastify&#39;;<br>import { AbstractHttpAdapter } from &#39;@nestjs/core&#39;;<br><br>import {<br>  Catch,<br>  HttpException,<br>  ArgumentsHost,<br>  ExceptionFilter,<br>  BadRequestException,<br>} from &#39;@nestjs/common&#39;;<br>import {<br>  PrismaClientRustPanicError,<br>  PrismaClientValidationError,<br>  PrismaClientKnownRequestError,<br>  PrismaClientUnknownRequestError,<br>  PrismaClientInitializationError,<br>} from &#39;@prisma/client/runtime&#39;;<br><br>@Catch()<br>export class HttpExceptionFilter implements ExceptionFilter {<br>  constructor(private readonly httpAdapterHost: AbstractHttpAdapter) {}<br>  catch(exception: FastifyError, host: ArgumentsHost): void {<br>    let errorMessage: unknown;<br>    let httpStatus: number;<br>    const httpAdapter = this.httpAdapterHost;<br>    const ctx = host.switchToHttp();<br>    if (exception instanceof HttpException) {<br>      if (exception instanceof BadRequestException) {<br>        httpStatus = 422;<br>        errorMessage = exception.getResponse()[&#39;message&#39;];<br>      } else {<br>        httpStatus = exception.getStatus();<br>        errorMessage = exception.getResponse()[&#39;message&#39;];<br>      }<br>    } else if (exception instanceof PrismaClientRustPanicError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientValidationError) {<br>      httpStatus = 404;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientKnownRequestError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientUnknownRequestError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientInitializationError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (<br>      exception.statusCode &amp;&amp;<br>      exception.statusCode &gt;= 400 &amp;&amp;<br>      exception.statusCode &lt;= 499<br>    ) {<br>      httpStatus = exception.statusCode;<br>      errorMessage = exception.message;<br>    } else {<br>      httpStatus = 500;<br>      errorMessage = [<br>        &#39;Sorry! something went to wrong on our end, Please try again later&#39;,<br>      ];<br>    }<br>    const errorResponse = {<br>      errors: typeof errorMessage === &#39;string&#39; ? [errorMessage] : errorMessage,<br>    };<br>    httpAdapter.reply(ctx.getResponse(), errorResponse, httpStatus);<br>  }<br>}</pre><p>In the user.module.ts file, importing the Prisma module allows us to access its components, services, and controllers. And also controllers and services are typically defined within modules to encapsulate related functionality and promote modular design.</p><pre>                            user.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br>import { PrismaModule } from &#39;src/configs/database&#39;;<br>import { UsersController } from &#39;./users.controller&#39;;<br><br>@Module({<br>  imports: [PrismaModule],<br>  controllers: [UsersController],<br>  providers: [UsersService],<br>})<br>export class UsersModule {}</pre><p>In the user.controller.ts file, we have two APIs, one for creating a user and another for updating a user, it means that the controller is responsible for handling HTTP requests related to user management.</p><pre>                              user.controller.ts<br><br>import { User } from &#39;@prisma/client&#39;;<br>import { FastifyReply } from &#39;fastify&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br><br>import {<br>  Put,<br>  Res,<br>  Post,<br>  Body,<br>  Param,<br>  HttpStatus,<br>  Controller,<br>} from &#39;@nestjs/common&#39;;<br>import {<br>  ApiTags,<br>  ApiHeader,<br>  ApiResponse,<br>  ApiOkResponse,<br>  ApiNotFoundResponse,<br>} from &#39;@nestjs/swagger&#39;;<br><br>@Controller(&#39;v1/users&#39;)<br>export class UsersController {<br>  constructor(private readonly usersService: UsersService) {}<br><br>  @Post()<br>  create(@Body() createUserDto: any, @Res() reply: FastifyReply) {<br>    return this.usersService<br>      .create(createUserDto)<br>      .then((user) =&gt; {<br>        reply.code(HttpStatus.CREATED).send(user);<br>      })<br>      .catch((error) =&gt; reply.send(error));<br>  }<br><br>  @Put(&#39;:id&#39;)<br>  async update(<br>    @Param(&#39;id&#39;) id: number,<br>    @Body() updateUserDto: any,<br>    @Res() reply: FastifyReply,<br>  ) {<br>    return this.usersService<br>      .update(id, updateUserDto)<br>      .then((updatedUser) =&gt; {<br>        reply.code(HttpStatus.OK).send(updatedUser);<br>      })<br>      .catch((error) =&gt; reply.send(error));<br>  }<br>}</pre><p>In the user.service.ts file, we would typically define these functions and implement the necessary logic to handle the create and update operations. This service interacts with a database.</p><pre>import { User } from &#39;@prisma/client&#39;;<br>import { PrismaService } from &#39;src/configs/database&#39;;<br><br>@Injectable()<br>export class UsersService {<br>  constructor(private prisma: PrismaService) {}<br><br>  async create(createUserDto: any) {<br>    const user = await this.prisma.user.create({<br>      data: { ...createUserDto },<br>    });<br><br>    return user;<br>  }<br><br>  async update(userId: number, updateUserDto: any) {<br>    return await this.prisma.user.update({<br>      where: {<br>        id: userId,<br>      },<br>      data: {<br>        first_name: updateUserDto.first_name,<br>        last_name: updateUserDto.last_name,<br>      },<br>    });<br>  }<br>}</pre><p>In the user.model.ts file, we would define the validation schemas using Joi to specify the expected structure and constraints for the user data during creation and update.</p><pre>                                user.model.ts<br><br>import * as Joi from &#39;joi&#39;;<br><br>import { forwardRef, Inject, Module } from &#39;@nestjs/common&#39;;<br>import { PrismaModule, PrismaService } from &#39;src/configs/database&#39;;<br><br>export class UserModel {<br>  constructor(<br>    @Inject(forwardRef(() =&gt; PrismaService)) private prisma: PrismaService,<br>  ) {}<br><br>  isEmailUnique = async (value: string) =&gt; {<br>    const userEmail = await this.prisma.user.findFirst({<br>      where: { email: value },<br>      select: { email: true },<br>    });<br>    if (userEmail) throw new Error(&#39;Email already exists&#39;);<br>  };<br><br>  user = Joi.object({<br>    first_name: Joi.string()<br>      .min(1)<br>      .max(100)<br>      .pattern(new RegExp(/^([a-zA-Z ]){1,100}$/))<br>      .error(new Error(&#39;First name should be alphabet format&#39;)),<br><br>    last_name: Joi.string()<br>      .min(1)<br>      .max(100)<br>      .pattern(new RegExp(/^([a-zA-Z ]){1,100}$/))<br>      .error(new Error(&#39;Last name should be alphabet format&#39;)),<br><br>    email: Joi.string()<br>      .min(1)<br>      .max(100)<br>      .empty()<br>      .external(this.isEmailUnique)<br>      .error(new Error(&#39;Email should be valid format&#39;)),<br><br>  });<br>}<br><br>@Module({<br>  imports: [forwardRef(() =&gt; PrismaModule)],<br>  providers: [UserModel],<br>  exports: [UserModel],<br>})<br>export class UserModelModule {}</pre><p>In the prisma.service.ts file, we establish a connection with the database using Prisma Client, which is an auto-generated database client provided by Prisma. This client allows you to interact with the database and perform CRUD operations. In this example, we use Prisma Client’s $use method to define a middleware that intercepts all create or update operations on the User model. Inside the middleware, we define a Joi schema to validate the create and update data. If the data fails the validation, an error is thrown, indicating that the create and update data is invalid.</p><pre>                            prisma.service.ts<br><br>import { Model } from &#39;src/configs/constants&#39;;<br>import { PrismaClient } from &#39;@prisma/client&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import { UserModel, UserModelModule } from &#39;src/models/user/user.model&#39;;<br><br>import {<br>  Global,<br>  Inject,<br>  Module,<br>  forwardRef,<br>  Injectable,<br>  OnModuleInit,<br>  OnModuleDestroy,<br>  UnprocessableEntityException,<br>} from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class PrismaService<br>  extends PrismaClient<br>  implements OnModuleInit, OnModuleDestroy<br>{  <br>constructor( <br>  config: ConfigService, <br>  @Inject(forwardRef(() =&gt; UserModel)) private userModel: UserModel<br> ) {<br>    super({<br>      datasources: {<br>        db: {<br>          url: config.get(&#39;postgresql://user_name:password@localhost:5432/database_name?schema=public&#39;),<br>        },<br>      },<br>    });<br>  }  <br><br> async onModuleInit() {<br>    await this.$connect();<br>    await this.main();<br>  }<br><br>  async onModuleDestroy() {<br>    await this.$disconnect();<br>  }<br>}<br><br>async main() {<br>    this.$use(async (params, next) =&gt; {<br>      if (params.model === &#39;User&#39;) {<br>        if (params.action === &#39;create&#39;) {<br>          try {<br>            await this.userModel.user.validateAsync(params.args?.data);<br>          } catch (err) {<br>            throw new UnprocessableEntityException(err);<br>          }<br>        }<br>        if (params.action === &#39;update&#39;) {<br>          try {<br>            await this.userModel.user.validateAsync(params.args?.data, {<br>              externals: false,<br>            });<br>          } catch (err) {<br>            throw new UnprocessableEntityException(err);<br>          }<br>        }<br>      }<br>   })<br>}<br></pre><p>In the app.module.ts file, we define all the modules in the AppModule to establish the overall structure and functionality of our NestJS application</p><pre>                              app.module.ts<br>  <br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersModule } from &#39;./users/users.module&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { PrismaModule } from &#39;./configs/database&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>    }),<br>    UsersModule,<br>    PrismaModule,<br>  ],<br>  controllers: [],<br>  providers: [],<br>})<br>export class AppModule {}</pre><h4><strong>Conclusion</strong></h4><p>Hope this little post will help you with common scenarios during your application development with the Prisma ORM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acd4362efaa5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yavar/prisma-runtime-custom-validation-to-models-acd4362efaa5">Prisma runtime custom validation to models</a> was originally published in <a href="https://medium.com/yavar">YavarTechWorks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Single Sign-On (SSO) with Azure Active Directory (Azure AD)]]></title>
            <link>https://blog.devgenius.io/integrating-single-sign-on-sso-with-azure-active-directory-azure-ad-in-nestjs-210b07e7420d?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/210b07e7420d</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[single-sign-on]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 07:22:00 GMT</pubDate>
            <atom:updated>2023-07-10T11:26:03.921Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will be explaining how to Integrate SPA(Single Page Application) Single Sign-On (SSO) with Azure Active Directory (Azure AD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*1zWCBODZ69ScD9Az.png" /></figure><ol><li><strong>Registering the SPA in Azure AD</strong></li></ol><ul><li>Log in to the Azure portal (<a href="https://portal.azure.com/"><strong><em>portal.azure.com</em></strong></a>) and navigate the Azure Active Directory section.</li><li>Select App Registrations and click on New registration.</li><li>Provide a name for your application and choose the appropriate account types.</li><li>Set the Redirect URI to the URL where your SPA is hosted.</li><li>After registration, note down the Client ID generated by Azure AD. You’ll need it later.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*_AV_ZAcHvx7vPyUBtLY9MQ.png" /></figure><p>2. <strong>Create a secret key in Azure AD</strong></p><ul><li>In the application overview page, navigate to the Certificates &amp; Secrets section.</li><li>Click on the New client secret button.</li><li>Describe the secret and choose the expiration duration (e.g., 1 or 2 years).</li><li>Click on the Add button.</li><li>Once the secret is generated, make sure to note it down(Value) immediately as it will not be visible again</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*yPNNuFPmcsENT4DTRuKO_w.png" /></figure><p>3. <strong>Add an optional claim in Azure AD</strong></p><ul><li>In the application’s blade, select Token configuration or Single sign-on depending on the type of application you are working with.</li><li>In the Optional claims panel, you will see a list of available optional claims. Click on “Add optional claim.”</li><li>Choose the claim type Access from the drop-down list. After that select a aud claim.</li><li>Click “Add” to add the optional claim.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*AiNoruqDx2HibvoJ0M_gxg.png" /></figure><p>4. <strong>Create a scope to define the permissions for your API</strong></p><ul><li>In the Azure portal, navigate to the Expose an API section within your registered application.</li><li>Delete the default API permission of Microsoft Graph to avoid the invalid signature error while validating Access token.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWJU2KgymwiVVTMpOkUbVw.png" /></figure><ul><li>Click on the Add a scope button.</li><li>Define a scope name, admin consent display name, and admin consent description for the scope.</li><li>Select an Admin and users option for Who can consent?</li><li>Click Add scope to add the scope configuration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*xkhC4EvSLoq-cKb3jBQPOQ.jpeg" /></figure><p>5. <strong>Add API permissions in Azure AD</strong></p><ul><li>Click on the API permissions option.</li><li>In the “Configured permissions” tab, click on the Add a permissio button.</li><li>In the Request API permissions panel click on the My APIs tab.</li><li>If you have already registered your API in Azure AD, you should see it listed. Select your API from the list to give grant permissions to your API registered in Azure AD</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*lqrQGP_xKIgXzKSum-MrrQ.jpeg" /></figure><ul><li>Once you’ve selected your API, you will see the available permissions for your API. Choose the specific permissions required by your application from the list.</li><li>Click on the Add permissions button to add the selected permissions to your application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*dIo22DgUS6TV9T3PhYbfWQ.jpeg" /></figure><p><strong>Overall architecture:</strong></p><p>The following diagram shows the entire implicit sign-in flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JK_AA4Qc42OPr86XiR_3Cw.png" /></figure><ul><li>The user initiates the sign-in process by clicking on a sign-in button or a protected resource.</li><li>The application redirects the user to the identity provider’s authentication endpoint.</li><li>The user authenticates with the identity provider (e.g., Azure AD) by providing their credentials.</li><li>Upon successful authentication, the identity provider issues an authorization response containing an access token and/or an ID token.</li><li>Validate the access token to make authorized requests to protected web API.</li></ul><p><strong>Setup the frontend app in Node.js for integrating Single Sign-On (SSO) with Azure Active Directory (Azure AD):</strong></p><p>Clone the code from the below link:</p><p><a href="https://github.com/david-billian/Azure-AD-SSO/tree/master/SPA">https://github.com/david-billian/Azure-AD-SSO/tree/master/SPA</a></p><p><strong>Note</strong>: Please provide your azure AD application details in authConfig.js</p><p>Get the access token after you signed in. Set this access token as an Authorization header while calling the backend API.</p><p><strong>Validate the Azure AD access token in NestJs (Backend):</strong></p><p><strong><em>Step 1</em></strong>: Install Dependencies</p><ul><li>Create a new Nest.js project or navigate to your existing project.</li><li>Install the required dependencies for Azure AD integration:</li></ul><pre>npm install passport passport-azure-ad @nestjs/passport</pre><p><strong><em>Step 2</em></strong>: Configure the Azure AD strategy in your Nest.js application</p><pre>// azure-ad.strategy.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { PassportStrategy } from &#39;@nestjs/passport&#39;;<br>import { BearerStrategy } from &#39;passport-azure-ad&#39;;<br><br>const config = {<br>  credentials: {<br>    tenantID: &#39;Enter_your_tenant_id&#39;,<br>    clientID: &#39;Enter_your_client_id&#39;,<br>    audience: &#39;Enter_your_client_id&#39;,<br>  },<br>  metadata: {<br>    authority: &#39;login.microsoftonline.com&#39;,<br>    discovery: &#39;.well-known/openid-configuration&#39;,<br>    version: &#39;v2.0&#39;,<br>  },<br>  settings: {<br>    validateIssuer: true,<br>    passReqToCallback: false,<br>    loggingLevel: &#39;info&#39;,<br>  },<br>};<br>const EXPOSED_SCOPES = [&#39;Files.Read&#39;];//provide a scope of your azure AD<br><br>@Injectable()<br>export class AzureAdStrategy extends PassportStrategy(<br>  BearerStrategy,<br>  &#39;azure-ad&#39;,<br>) {<br>  constructor() {<br>    super({<br>      identityMetadata: `https://${config.metadata.authority}/${config.credentials.tenantID}/${config.metadata.version}/${config.metadata.discovery}`,<br>      issuer: `https://${config.metadata.authority}/${config.credentials.tenantID}/${config.metadata.version}`,<br>      clientID: config.credentials.clientID,<br>      audience: config.credentials.audience,<br>      validateIssuer: config.settings.validateIssuer,<br>      passReqToCallback: config.settings.passReqToCallback,<br>      loggingLevel: config.settings.loggingLevel,<br>      scope: EXPOSED_SCOPES,<br>      loggingNoPII: false,<br>    });<br>  }<br><br>  async validate(profile: any): Promise&lt;any&gt; {<br>    // Implement user validation and extraction of necessary user information from profile<br>    // Example: Extract and store user details in a session<br>    return profile;<br>  }<br>}</pre><pre>// auth.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { PassportModule } from &#39;@nestjs/passport&#39;;<br>import { AzureAdStrategy } from &#39;./azure-ad.strategy&#39;;<br><br>@Module({<br>  imports: [PassportModule.register({ defaultStrategy: &#39;azure-ad&#39; })],<br>  providers: [AzureAdStrategy],<br>})<br>export class AuthModule {}<br></pre><pre>//app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { AuthModule } from &#39;./auth.module&#39;;<br><br>@Module({<br>  imports: [AuthModule],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><pre>// app.controller.ts<br>import { Controller, Get, Req, Res, UseGuards } from &#39;@nestjs/common&#39;;<br>import { AuthGuard } from &#39;@nestjs/passport&#39;;<br>import { Request, Response } from &#39;express&#39;;<br><br>@Controller(&#39;user&#39;)<br>export class AppController {<br>  @Get(&#39;details&#39;)<br>  @UseGuards(AuthGuard(&#39;azure-ad&#39;))<br>  login(@Req() req: Request, @Res() reply: Response) {<br>    console.log(&#39;signed-in user:&#39;, req[&#39;user&#39;]);<br>    reply.status(200).send({ message: &#39;access token validated successfully&#39; });<br>  }<br>}</pre><p><strong>Conclusion</strong></p><p>I hope you have successfully integrated Single Sign-On (SSO) with Azure Active Directory (Azure AD) in your Nest.js application. Users can now authenticate using their Azure AD credentials, providing a seamless and secure login experience. Feel free to extend this implementation to suit your specific application requirements and enhance the user authentication flow further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=210b07e7420d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/integrating-single-sign-on-sso-with-azure-active-directory-azure-ad-in-nestjs-210b07e7420d">Integrating Single Sign-On (SSO) with Azure Active Directory (Azure AD)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma client errors with NestJs]]></title>
            <link>https://medium.com/yavar/how-to-handle-prisma-client-errors-with-nestjs-ac81fb368c0f?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac81fb368c0f</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Thu, 04 May 2023 05:48:19 GMT</pubDate>
            <atom:updated>2023-05-15T13:01:36.203Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I am going to explain how to handle the Prisma client error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UP7zO4ggHVUYloVqBNlGag.jpeg" /></figure><p>Prisma clients have some error types, we split that error depending upon that type. If you want more information to refer <a href="https://www.prisma.io/docs/reference/api-reference/error-reference">click here</a></p><p>I have handled all of these Prisma client errors with the help of an instance. The reason for this means we can define which HTTP status code match that particular error. Because my application is implemented by REST API so must follow which standards provided by REST.</p><p>If you don’t aware of how to implement an exception filter refer to <a href="https://docs.nestjs.com/exception-filters">here</a> and also I will cover that in this post. It’s nothing but we have captured all errors in our whole application with the help of this exception filter. If we define this class as the main file the NestJs handle it.</p><p>To create a global-scoped filter in the main.ts file, you would do the following:</p><pre>import { AppModule } from &#39;./app.module&#39;;<br>import { useContainer } from &#39;class-validator&#39;;<br>import { ValidationPipe } from &#39;@nestjs/common&#39;;<br>import { HttpExceptionFilter } from &#39;./exceptions/all-exception.filter&#39;;<br>import { NestFactory, HttpAdapterHost, Reflector } from &#39;@nestjs/core&#39;;<br><br>import {<br>  FastifyAdapter,<br>  NestFastifyApplication,<br>} from &#39;@nestjs/platform-fastify&#39;;<br><br>async function bootstrap() {<br>  try {<br>    const app = await NestFactory.create&lt;NestFastifyApplication&gt;(<br>      AppModule,<br>      new FastifyAdapter(),<br>    );<br><br>    useContainer(app.select(AppModule), { fallbackOnErrors: true });<br><br>    app.useGlobalPipes(<br>      new ValidationPipe({ whitelist: true, transform: true }),<br>    );<br><br>    //exception-filter<br>    const { httpAdapter } = app.get(HttpAdapterHost);<br>    app.useGlobalFilters(new HttpExceptionFilter(httpAdapter));<br><br>    await app.listen(3000, &#39;0.0.0.0&#39;);<br>  } catch (error) {<br>    logger.error({ err: error });<br>    process.exit();<br>  }<br>}<br>bootstrap();</pre><p>While the base (built-in) exception filter can automatically handle many cases for you, you may want full control over the exceptions layer. Exception filters are designed for exactly this purpose. They let you control the exact flow of control and the content of the response sent back to the client.</p><p>Let’s create an exception filter that is responsible for catching exceptions that are an instance of the HttpException class, and implementing custom response logic for them. To do this, we&#39;ll need to access the underlying platform Request and Response objects. In my application, I have implemented it in Fastify. So I can get the error instance and message with the help of FastifyError. Easily I can split the error based on the Prisma client-type error.</p><pre>import { FastifyError } from &#39;fastify&#39;;<br>import { AbstractHttpAdapter } from &#39;@nestjs/core&#39;;<br><br>import {<br>  Catch,<br>  HttpException,<br>  ArgumentsHost,<br>  ExceptionFilter,<br>} from &#39;@nestjs/common&#39;;<br>import {<br>  PrismaClientRustPanicError,<br>  PrismaClientValidationError,<br>  PrismaClientKnownRequestError,<br>  PrismaClientUnknownRequestError,<br>  PrismaClientInitializationError,<br>} from &#39;@prisma/client/runtime&#39;;<br><br>@Catch()<br>export class HttpExceptionFilter implements ExceptionFilter {<br>  constructor(private readonly httpAdapterHost: AbstractHttpAdapter) {}<br>  catch(exception: FastifyError, host: ArgumentsHost): void {<br>    let errorMessage: unknown;<br>    let httpStatus: number;<br>    const httpAdapter = this.httpAdapterHost;<br>    const ctx = host.switchToHttp();<br>    if (exception instanceof PrismaClientRustPanicError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientValidationError) {<br>      httpStatus = 422;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientKnownRequestError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientUnknownRequestError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (exception instanceof PrismaClientInitializationError) {<br>      httpStatus = 400;<br>      errorMessage = exception.message;<br>    } else if (<br>      exception.statusCode &amp;&amp;<br>      exception.statusCode &gt;= 400 &amp;&amp;<br>      exception.statusCode &lt;= 499<br>    ) {<br>      httpStatus = exception.statusCode;<br>      errorMessage = exception.message;<br>    } else {<br>      httpStatus = 500;<br>      errorMessage = [<br>        &#39;Sorry! something went to wrong on our end, Please try again later&#39;,<br>      ];<br>    }<br>    const errorResponse = {<br>      errors: typeof errorMessage === &#39;string&#39; ? [errorMessage] : errorMessage,<br>    };<br>    httpAdapter.reply(ctx.getResponse(), errorResponse, httpStatus);<br>  }<br>}</pre><p>Catch all errors and return them from the controller. Already defined the exception filter as a global filter in the main.ts file, it will handle all errors through by HttpExceptionFilter class</p><pre>import { FastifyReply } from &#39;fastify&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br><br>import {<br>  Res,<br>  Post,<br>  Body,<br>  HttpStatus,<br>  Controller,<br>} from &#39;@nestjs/common&#39;;<br><br>@Controller(&#39;v1/users&#39;)<br>export class UsersController {<br>  constructor(private readonly usersService: UsersService) {}<br><br>  @Post()<br>  create(<br>    @Body() createUserDto: any,<br>    @Res() reply: FastifyReply,<br>  ) {<br>    return this.usersService<br>      .create(createUserDto, )<br>      .then((user) =&gt; {<br>        reply.code(HttpStatus.CREATED).send(user);<br>      })<br>      .catch((error) =&gt; reply.send(error));//catch the error in your controller level<br>}</pre><p>At the service level, we are handling the business logic and creating a new user record in the database by Prisma.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { PrismaClient } from &#39;@prisma/client&#39;;<br>import { PrismaService } from &#39;src/configs/database&#39;;<br><br>const prisma = new PrismaClient();<br><br>@Injectable()<br>export class UsersService {<br>  constructor() {}<br><br>  async create(createUserDto: any,) {<br>    const user = await prisma.user.create({<br>      data: { ...createUserAttribites },<br>    });<br><br>    return user;<br>  }<br>}</pre><h4>Conclusion</h4><p>I hope, In this post, we have learned about how to handle the Prisma client error, Thank you for reading this post, See you soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac81fb368c0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yavar/how-to-handle-prisma-client-errors-with-nestjs-ac81fb368c0f">Prisma client errors with NestJs</a> was originally published in <a href="https://medium.com/yavar">YavarTechWorks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Queues]]></title>
            <link>https://medium.com/yavar/nestjs-queues-c8040ca61b79?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8040ca61b79</guid>
            <category><![CDATA[queue-management]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[bulls]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 05:01:55 GMT</pubDate>
            <atom:updated>2023-02-07T05:05:49.104Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi friends, In this post, We are learning about Queue management by NestJS Bull.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*iBA-WxgXkCmwpbXt.png" /></figure><p>Queues are a powerful design pattern that helps you deal with common application scaling and performance challenges.</p><p>you can add these tasks to a queue instead of performing them synchronously. Then you can have worker processes pull tasks from the queue in a controlled manner. You can easily add new Queue consumers to scale up the back-end task handling as the application scales up.</p><p>When Queue producers or consumers fail, their state is preserved and task handling can restart automatically when nodes are restarted.</p><p>Nest provides a @nestjs/bull package it easy to integrate Bull Queues in a Nest-friendly way into your application.</p><p>Bull uses <strong><em>Redis to persist job data</em></strong>, so you’ll need to have Redis installed on your system. Because it is Redis-backed, your Queue architecture can be completely distributed and platform-independent.</p><p>— To begin using it, we first install the required dependencies.</p><pre>npm install --save @nestjs/bull bull<br>npm install --save-dev @types/bull</pre><p>— Once the installation process is complete, we can import the BullModule into the root AppModule.</p><p><strong><em>src/app.module.ts:</em></strong></p><pre>import { BullModule } from &#39;@nestjs/bull&#39;;<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { AudioModule } from &#39;./audio/audio.module&#39;;<br><br>@Module({<br>  imports: [<br>    BullModule.forRootAsync({<br>      useFactory: () =&gt; ({<br>        redis: {<br>          host: &#39;localhost&#39;,<br>          port: 6379,<br>        },<br>      }),<br>    }),<br>    AudioModule,<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>The forRootAsync() method is used to register the bull configuration that will be used by all queues registered in the application. It consists of the following properties:</p><ul><li>limiter: RateLimiter - Control the rate at which the queue&#39;s jobs are processed.</li><li>redis: RedisOpts - Configure the Redis connection.</li><li>prefix: string - Prefix for all queue keys. It’s Optional.</li><li>defaultJobOptions: JobOpts - Control the default settings for new jobs.</li><li>settings: AdvancedSettings - Advanced Queue configuration settings. These should usually not be changed.</li></ul><p>— To register a queue in the <strong><em>src/audio/audio.module.ts</em></strong>, as follows:</p><pre>import { BullModule } from &#39;@nestjs/bull&#39;;<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AudioController } from &#39;./audio.controller&#39;;<br>import { AudioConsumer, VideoConsumer } from &#39;./audio.processor&#39;;<br><br>@Module({<br>  imports: [<br>    BullModule.registerQueueAsync(<br>      {<br>        name: &#39;audio&#39;,<br>      },<br>      {<br>        name: &#39;video&#39;,<br>      },<br>    ),<br>  ],<br>  controllers: [AudioController],<br>  providers: [AudioConsumer, VideoConsumer],<br>})<br>export class AudioModule {}</pre><p>We can register the <strong><em>queues</em></strong> by this method. Provide multiple queues by comma-separated configuration objects to the <em>registerQueue() </em>method<em>. </em>The name property should be unique because the queue is unique by its.</p><p>Since jobs are persisted in Redis, each time a specifically named queue is instantiated (e.g., when an app is started/restarted), it attempts to process any old jobs that may exist from a previous unfinished session.</p><p>Each queue can have one or many producers, consumers, and listeners. Consumers retrieve jobs from the queue in a specific order: FIFO (the default), LIFO, or according to priorities.</p><h4>Producers</h4><p>Job producers add jobs to queues. Producers are typically application services. To add jobs to a queue, first, inject the queue into the service as follows:</p><p>— so let’s create a new Producer in <strong><em>src/audio/audio.controller.ts</em></strong></p><pre>import { Queue } from &#39;bull&#39;;<br>import { InjectQueue } from &#39;@nestjs/bull&#39;;<br>import { Controller, Post } from &#39;@nestjs/common&#39;;<br><br>@Controller(&#39;v1/file&#39;)<br>export class AudioController {<br>  constructor(<br>    @InjectQueue(&#39;audio&#39;) private readonly audioQueue: Queue,<br>    @InjectQueue(&#39;video&#39;) private readonly videoQueue: Queue,<br>  ) {}<br><br>  @Post()<br>  async transcode() {<br>    await this.audioQueue.add(&#39;audio-job&#39;, {<br>      file: &#39;audio.mp3&#39;,<br>    });<br>    await this.videoQueue.add(&#39;video-job&#39;, {<br>      file: &#39;video.mp4&#39;,<br>    });<br>  }<br>}</pre><p>When using named jobs, you must create <strong><em>processors</em></strong> for each unique name added to a queue, or the queue will complain that you are missing a processor for the given job</p><ul><li>to read the queue we have to use the ‘@InjectQueue’ decorator along with the name of the queue like ‘audio’ or ‘video’.</li><li>To push the job into the queue, we have to use the ‘add’ method of the ‘Queue’ instance. Here we can specify the job name as well. So this job name will be used by the consumer to read files as well.</li><li>So the jobs are saved into the assigned Redis port.</li></ul><h4>Consumers</h4><p>A consumer is a class-defining method that either process jobs added into the queue, listen for events on the queue or both. To make a class consumer it should be decorated with ‘@Processor()’ and with the queue name. A consumer class must contain a handler method to process the jobs. The handler method should register with ‘@Process()’.</p><pre>import { Job } from &#39;bull&#39;;<br>import { Process, Processor } from &#39;@nestjs/bull&#39;;<br><br>@Processor(&#39;audio&#39;)<br>export class AudioConsumer {<br>  @Process(&#39;audio-job&#39;)<br>  handleTranscode(job: Job) {<br>    console.log(&#39;Start audio compress into mp3...&#39;);<br>    console.log(job.data);<br>    console.log(&#39;completed!!&#39;);<br>  }<br>}<br><br>@Processor(&#39;video&#39;)<br>export class VideoConsumer {<br>  @Process(&#39;video-job&#39;)<br>  handleTransvideo(job: Job) {<br>    console.log(&#39;Start vidoe compress into mp4...&#39;);<br>    console.log(job.data);<br>    console.log(&#39;completed!!&#39;);<br>  }<br>}</pre><p>Provide the consumer class of AudioConsumer and VideoConsumer into the AppModule providers. By registering automatically NestJS application activates consumers to read and process jobs.</p><p>Now we should start the server and trigger the endpoint after that the consumer logged the data from the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdsGDbN320wNSTwXy6qIeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZRRxrEbJMD0xjvCGGHUlQ.png" /></figure><h3>Conclusion</h3><p>I hope, In this post, we have learned about queue management, Thank you for reading this post, See you soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8040ca61b79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yavar/nestjs-queues-c8040ca61b79">NestJS Queues</a> was originally published in <a href="https://medium.com/yavar">YavarTechWorks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS-Localization]]></title>
            <link>https://medium.com/yavar/localization-of-nestjs-cee2eae50392?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cee2eae50392</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[localization]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 08:35:23 GMT</pubDate>
            <atom:updated>2023-01-05T10:38:35.498Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi friends, In this post, I am explaining how to implement the localization of NestJS using nestjs-i18n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*EU5Htj1cZ-BU_e7h9mi3yQ.png" /></figure><p>In our application, we are using the i18n library for NestJS. It&#39;s working with languages in your NestJS project. We can write and plug-in your own language resolvers or loaders.</p><p>Install the nestjs-i18n package in your application:</p><pre>npm install --save nestjs-i18n</pre><p>After that, we should be stored the language strings in files within the directory and also defined them in JSON files. When taking this approach, each language supported by your application would have a corresponding JSON file within this directory. This approach is recommended for applications that have a large number of translatable strings. By default nestjs-i18n uses the I18nJsonLoader loader class. This loader reads translations from json files. Create a folder named i18n in the src folder of your project.</p><pre>src<br>└── i18n<br>    ├── en<br>    │   └── test.json<br>    └── nl<br>        └── test.json</pre><p>src/i18n/en/test.json:</p><pre>{<br>  &quot;here&quot;: &quot;here&quot;,<br>  &quot;greet&quot;: &quot;Dear&quot;,<br>  &quot;click&quot;: &quot;Please click&quot;,<br>  &quot;greet_hello&quot;: &quot;Hello there,&quot;<br>}</pre><p>src/i18n/nl/test.json:</p><pre>{<br>  &quot;here&quot;: &quot;hier&quot;,<br>  &quot;greet&quot;: &quot;Beste&quot;,<br>  &quot;click&quot;: &quot;Klik&quot;,<br>  &quot;greet_hello&quot;: &quot;Hello there, &quot;<br>}</pre><p>Initially try to get the JSON file by absolute path, but I couldn’t get it. The reason is that the i18n directory is not automatically copied to our dist folder while starting the server. That&#39;s why To enable nestjs to do this modify the compilerOptions inside nest-cli.json.</p><pre>{<br>  &quot;collection&quot;: &quot;@nestjs/schematics&quot;,<br>  &quot;sourceRoot&quot;: &quot;src&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;assets&quot;: [<br>      { &quot;include&quot;: &quot;i18n/**/*&quot;, &quot;watchAssets&quot;: true }<br>    ]<br>  }<br>}</pre><p>We should register the i18nModule module once in the root module. After that, it’s accessible throughout the whole application. InloaderOption, To enable the watch option to be true, it will be enabling live reloading. resolvers are used for getting the current language of our request. In my web applications, this is done via the Accept-Language header. The way nestjs-i18n works it&#39;s going to resolve the language in order. So in this case it tries the QueryResolver first, if it can&#39;t resolve a language it&#39;ll jump to the next one.</p><pre>import * as path from &#39;path&#39;;<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AcceptLanguageResolver, I18nModule, QueryResolver } from &#39;nestjs-i18n&#39;;<br><br>@Module({<br>  imports: [<br>    I18nModule.forRoot({<br>      fallbackLanguage: &#39;en&#39;,<br>      loaderOptions: {<br>        path: path.join(__dirname, &#39;/i18n/&#39;),<br>        watch: true,<br>      },<br>      resolvers: [<br>        { use: QueryResolver, options: [&#39;lang&#39;] },<br>        AcceptLanguageResolver,<br>        ],<br>    }),<br>  ],<br>  controllers: [AppController],<br>})<br>export class AppModule {}</pre><p>setup everything is done, and now we can start to do translations! The easiest way to do this is in controller level.</p><pre>import { Controller, Get, Req } from &#39;@nestjs/common&#39;;<br>import { Request } from &#39;express&#39;;<br>import { I18n, I18nContext } from &#39;nestjs-i18n&#39;;<br><br>@Controller()<br>export class AppController {<br>  @Get()<br>  getHello(@I18n() i18n: I18nContext) {<br>    return i18n.t(`test.here`);<br>  }<br>}</pre><h3>Conclusion</h3><p>I hope, In this post, we have learned about NestJS localization, Thank you for reading this post, See you soon in the next post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cee2eae50392" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yavar/localization-of-nestjs-cee2eae50392">NestJS-Localization</a> was originally published in <a href="https://medium.com/yavar">YavarTechWorks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to compare columns from the same table in Prisma]]></title>
            <link>https://medium.com/yavar/how-to-compare-columns-from-the-same-table-in-prisma-4ef1aac54850?source=rss-fad26f02d8f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ef1aac54850</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gnanabillian]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 06:07:36 GMT</pubDate>
            <atom:updated>2022-12-08T11:02:41.774Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, In this post, I am explaining how to compare columns from the same table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*Tud-vHjTKyyCDf2M" /></figure><p>we can compare the columns from the same table directly while using only non-unique filters</p><p>In the following steps, we must use raw queries:</p><ul><li>version earlier than 4.3.0</li><li>unique filters, such as <strong>findUnique</strong> or <strong>findUniqueOrThrow</strong></li><li>compare a field with a unique constraint</li></ul><p>To enable column comparisons in the same table, add the <strong>fieldReference</strong> feature flag to the <strong>generator</strong> block of your Prisma Schema as follows:</p><pre>// This is your Prisma schema file,<br>// learn more about it in the docs: https://pris.ly/d/prisma-schema<br><br>generator client {<br>  provider        = &quot;prisma-client-js&quot;<br>  previewFeatures = [&quot;fieldReference&quot;]<br>}<br><br>datasource db {<br>  provider = &quot;postgresql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>model User {<br>  id                           Int       @id @unique @default(autoincrement())<br>  first_name                   String    @db.VarChar(100)<br>  last_name                    String    @db.VarChar(100)<br>  email                        String    @db.VarChar(100)<br>  role                         Role      @default(VENDOR)<br>  User                         User?     @relation(name: &quot;user&quot;, fields: [created_by], references: [id])<br>  created_by                   Int?      @db.Integer()<br>  created_at                   DateTime  @default(now())<br>  updated_at                   DateTime  @updatedAt<br>  deleted_at                   DateTime? @default(null)<br>  user                         User[]    @relation(&quot;user&quot;)<br><br>  @@map(&quot;users&quot;)<br>}</pre><p>To compare columns in the same table, use the &lt;model&gt;.fields property. In the following example, the query returns all records where the value in the prisma.user.first_name field is equal to the prisma.user.last_name field.</p><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br>const prisma= new PrismaClient();<br><br>const userData= await prisma.user.findMany({<br>      where: {<br>        first_name: { equals: prisma.user.fields.last_name }<br>      })</pre><p><strong>fields</strong> is a special property of every model. It contains the list of that model’s fields.</p><p><strong>Note:</strong></p><ul><li>we could only compare fields of the same type. For example, the following causes an error:</li></ul><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br>const prisma= new PrismaClient();<br><br>const userData= await prisma.user.findMany({<br>      where: {<br>        first_name: { equals: prisma.user.fields.created_by } //Type &quot;String&quot; is not assignable to type &quot;Int&quot;<br>      }<br>})</pre><ul><li>If you use the <em>groupBy</em> model query with the having option, then you must put our referenced fields in the by argument.</li></ul><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br>const prisma= new PrismaClient();<br><br>const userData= await prisma.user.groupBy({<br>      by:[ &#39;id&#39;, &#39;first_name&#39; ],<br>      having: {<br>        id: { equals: prisma.user.fields.first_name } <br>      }<br>})</pre><ul><li>The following example does not work, because name is not in the by argument:</li></ul><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br>const prisma= new PrismaClient();<br><br>const userData= await prisma.user.groupBy({<br>      by:[ &#39;id&#39; ],<br>      having: {<br>        id: { equals: prisma.user.fields.first_name } <br>      }<br>})</pre><p><strong>Conclusion</strong></p><p>I hope, In this post, we have learned about comparing columns from the same table, Thank you for reading this post, See you soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef1aac54850" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yavar/how-to-compare-columns-from-the-same-table-in-prisma-4ef1aac54850">How to compare columns from the same table in Prisma</a> was originally published in <a href="https://medium.com/yavar">YavarTechWorks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>