<?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 Giorbis Miguel Lorié Montalvo on Medium]]></title>
        <description><![CDATA[Stories by Giorbis Miguel Lorié Montalvo on Medium]]></description>
        <link>https://medium.com/@giorbismiguel?source=rss-e0c58a6f2f87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mwiPCiIOuVe_xO-Npga0ag.jpeg</url>
            <title>Stories by Giorbis Miguel Lorié Montalvo on Medium</title>
            <link>https://medium.com/@giorbismiguel?source=rss-e0c58a6f2f87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:21:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giorbismiguel/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[Building an E-Commerce Store From Scratch While Driving for Lyft]]></title>
            <link>https://medium.com/@giorbismiguel/building-an-e-commerce-store-from-scratch-while-driving-for-lyft-629e3a3016fe?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/629e3a3016fe</guid>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[small-business]]></category>
            <category><![CDATA[side-hustle]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ecommerce]]></category>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 03:48:13 GMT</pubDate>
            <atom:updated>2026-08-01T03:48:13.263Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I launched Smartly Saves — a bulk candy and snacks store — with no prior e-commerce experience, funded entirely by rideshare shifts.</h3><p>A few months ago, I made a decision that most people would call impractical: I started building an online store while working as a Lyft driver to pay the bills.</p><p>No investors. No business partner. No prior e-commerce experience.</p><p>Just a laptop, a wholesale supplier in Tampa, and a clear goal: build something real, step by step, without waiting for the “perfect moment.”</p><p>That store is <strong>Smartly Saves</strong> (<a href="https://smartlysaves.com/">smartlysaves.com</a>) — an online wholesale store selling bulk name-brand candy and snacks like M&amp;Ms, Nerds, Laffy Taffy, and more.</p><p>Here’s what that journey has looked like so far.</p><h3>Why Candy and Snacks?</h3><p>The idea came from a simple observation: name-brand snacks are everywhere, but buying them in bulk online at a fair price is surprisingly hard. Most wholesale options either require a business license, have high minimums, or charge prices that aren’t much better than retail.</p><p>I saw an opportunity to be that middle layer — sourcing from local wholesale distributors in Tampa (primarily Branex Wholesale) and making those products accessible to anyone who wants to stock up without the hassle.</p><p>The demand-driven model was intentional: I don’t pre-buy massive inventory. I source based on what’s moving, which keeps my risk low as I learn the business.</p><h3>The Tech Stack I Built — Without a Developer</h3><p>One of the things I’m most proud of is that I built the entire store infrastructure myself, learning as I went:</p><ul><li><strong>WordPress + WooCommerce</strong> on Hostinger for the store</li><li><strong>Martfury</strong> theme for the storefront design</li><li><strong>Stripe</strong> for payment processing</li><li><strong>Brevo (SureMail SMTP)</strong> for transactional emails with full domain authentication</li><li><strong>MailerLite</strong> for email marketing and automated welcome sequences</li><li><strong>SureRank SEO</strong> for on-page optimization</li><li><strong>Google Merchant Center</strong> for product sync to Google Shopping</li><li><strong>USPS dynamic shipping rates</strong> with free shipping at $40+</li><li><strong>LiteSpeed Cache</strong> for site performance</li></ul><p>None of this was plug-and-play. Each piece required research, troubleshooting, and iteration. But building it myself meant I understood every layer of the business — and kept costs near zero.</p><h3>Where We Stand Today</h3><p>A few months in, here’s the honest scorecard:</p><ul><li>✅ WooCommerce store live on a custom domain</li><li>✅ 48+ pages indexed by Google</li><li>✅ 1,310+ impressions in Google Search Console (trending upward)</li><li>✅ Products syncing to Google Merchant Center (3.88K successful API calls)</li><li>✅ Automated email capture with 10% welcome discount (SAVE10)</li><li>✅ USPS dynamic shipping rates configured</li><li>✅ First real Stripe payouts received</li><li>✅ Domain authenticated for professional email sending</li></ul><p>Is this a hockey-stick growth story? No. But it’s real, it’s growing, and every metric is trending in the right direction.</p><h3>What “Funded by Lyft” Actually Means</h3><p>I want to be transparent about this because I think it matters.</p><p>Building a business while working another job is not glamorous. It means coding product descriptions at midnight after a long shift. It means making decisions about wholesale pricing in parking lots between rides. It means delayed gratification — a lot of it.</p><p>But it also means I’m not desperate. I don’t need Smartly Saves to make money next week to survive. That removes a huge amount of pressure and lets me build it the right way, with a long-term mindset.</p><p>The Lyft income covers living expenses. Smartly Saves is being built to last.</p><h3>What’s Coming Next</h3><p>The foundation is in place. Now it’s time to build on top of it:</p><ul><li><strong>Google Shopping ads</strong> — the organic traffic is growing, but paid ads will accelerate it</li><li><strong>Expanding the product catalog</strong> — more categories, more variety, more reasons to come back</li><li><strong>Physical presence at local flea markets</strong> — starting with Oldsmar or Big Top Flea Market in Tampa to drive both in-person sales and online traffic</li><li><strong>Content on TikTok and Facebook</strong> — organic content showing products, deals, and behind-the-scenes of running the store</li></ul><h3>The Bigger Picture</h3><p>Smartly Saves is one piece of a larger vision. Under my company <strong>Smartly Digital LLC</strong>, I’m documenting this build as a case study in what’s possible when you combine the right tools, consistent effort, and a willingness to figure things out as you go.</p><p>If you’re a small business owner thinking about launching an e-commerce channel — or if you’re curious about what it really takes to go from zero to a functioning online store — I’d love to connect.</p><p>This is exactly the kind of journey Smartly Digital was built to support.</p><p><em>Follow along as I continue building in public. Next update coming soon.</em></p><p><em>— Giorbis, Founder of Smartly Saves &amp; Smartly Digital LLC</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629e3a3016fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed a Mysterious AWS 503 Error (And You Can Too)]]></title>
            <link>https://medium.com/@giorbismiguel/how-i-fixed-a-mysterious-aws-503-error-and-you-can-too-136fefd121dd?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/136fefd121dd</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 18:05:54 GMT</pubDate>
            <atom:updated>2025-09-27T18:05:54.817Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A detective story about infrastructure debugging that every developer should know</em></p><h3>The Mystery Begins</h3><p>It was just another Tuesday when my API suddenly started throwing 503 errors. One moment everything was working fine, the next moment — complete radio silence. The dreaded “Service Unavailable” message stared back at me from my terminal.</p><pre>curl -X POST https://api.mycompany.com/api/auth/login<br># HTTP 503 Service Unavailable</pre><p>As any developer knows, 503 errors are particularly frustrating because they often point to infrastructure issues rather than your code. But where do you even start debugging when your entire AWS stack seems to be the problem?</p><h3>The Investigation: Following the Digital Breadcrumbs</h3><h3>Clue #1: The DNS Trail</h3><p>My first instinct was to understand the request path. Where was my traffic actually going?</p><pre>nslookup api.mycompany.com</pre><p><strong>Bingo!</strong> The DNS revealed the first piece of the puzzle:</p><pre>api.mycompany.com canonical name = <br>my-api-load-balancer-12345.us-east-1.elb.amazonaws.com<br>Name: my-api-load-balancer-12345.us-east-1.elb.amazonaws.com<br>Address: 203.0.113.45<br>Address: 203.0.113.78</pre><p>So my domain was pointing to an AWS Application Load Balancer (ALB) in us-east-1. The plot thickens.</p><h3>Clue #2: The Timeout That Told a Story</h3><p>Next, I tried connecting directly to the load balancer’s IP addresses:</p><pre>curl -v -X POST http://203.0.113.45/api/auth/login</pre><p>Result: <strong>Connection timeout after 75 seconds.</strong></p><p>This was telling. The load balancer wasn’t even responding, which meant the problem was likely between the ALB and my backend instances, not with external connectivity.</p><h3>Going Behind Enemy Lines: EC2 Investigation</h3><p>Since I had access to the AWS console, I decided to investigate from the inside. I SSH’d into my EC2 instance to check if my application was actually running.</p><h3>The Plot Twist: Everything Was Working</h3><p>Here’s where it got interesting. My application was running perfectly:</p><pre># Nginx status<br>sudo systemctl status nginx<br># ✅ Active (running)</pre><pre># Node.js application<br>ps aux | grep node<br># ✅ Process running: node dist/main.js</pre><pre># Direct application test<br>curl -X POST <a href="http://localhost:3000/api/auth/login">http://localhost:3000/api/auth/login</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;username&quot;:&quot;test&quot;,&quot;password&quot;:&quot;test&quot;}&#39;</pre><p><strong>Response:</strong></p><pre>{<br>  &quot;statusCode&quot;: 400,<br>  &quot;message&quot;: [&quot;email should not be empty&quot;, &quot;email must be an email&quot;]<br>}</pre><p>Wait… my application was responding perfectly! It was correctly validating input and returning proper error messages. So why was the load balancer returning 503 errors?</p><h3>The Sherlock Holmes Moment: AWS Console Deep Dive</h3><p>This is where the real detective work began. I navigated to the AWS console to examine the load balancer configuration.</p><h3>Target Group Investigation</h3><p>In the ALB target group (my-api-target-group), I found something alarming:</p><ul><li><strong>Total targets:</strong> 1</li><li><strong>Healthy targets:</strong> 0 ❌</li><li><strong>Unhealthy targets:</strong> 0</li><li><strong>Unused targets:</strong> 1 ❌</li></ul><p>My instance (i-1234567890abcdef0) was marked as &quot;<strong>Unused</strong>&quot; with the cryptic message: <em>&quot;Target is in an Availability Zone that is not enabled for the load balancer&quot;</em></p><h3>The Eureka Moment: Availability Zone Mismatch</h3><p>Finally, the pieces of the puzzle came together. I checked the load balancer’s network mapping:</p><p><strong>Load Balancer Configuration:</strong></p><ul><li>✅ us-east-1a (subnet-abc123def456) - enabled</li><li>✅ us-east-1b (subnet-def456ghi789) - enabled</li><li>❌ us-east-1c - not enabled</li></ul><p><strong>My EC2 Instance Location:</strong></p><ul><li>📍 us-east-1c</li></ul><p><strong>There it was!</strong> My EC2 instance was sitting in an Availability Zone that my load balancer couldn’t reach. It’s like having a perfectly working restaurant in a city where your delivery service doesn’t operate.</p><h3>The Fix: One Click to Save the Day</h3><p>The solution was surprisingly simple:</p><ol><li><strong>Navigate to Load Balancer → Network mapping</strong></li><li><strong>Click “Edit subnets”</strong></li><li><strong>Enable </strong><strong>us-east-1c</strong> and select subnet subnet-ghi789jkl012</li><li><strong>Save changes</strong></li></ol><p>Within 2–3 minutes, the magic happened:</p><ul><li><strong>Unused targets:</strong> 0 ✅</li><li><strong>Healthy targets:</strong> 1 ✅</li></ul><p>The target group showed my instance with <strong>Protocol: HTTP:3000</strong>, confirming the ALB was now routing traffic directly to my Node.js application.</p><h3>Testing the Victory</h3><pre>curl -X POST https://api.mycompany.com/api/auth/login \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;email&quot;:&quot;test@test.com&quot;,&quot;password&quot;:&quot;test123&quot;}&#39;</pre><p><strong>Result:</strong></p><pre>{<br>  &quot;statusCode&quot;: 400,<br>  &quot;message&quot;: [&quot;password must be longer than or equal to 6 characters&quot;]<br>}</pre><p><strong>Success!</strong> No more 503 errors. My API was back online and properly validating requests.</p><h3>Lessons Learned: The Developer’s Toolkit</h3><h3>1. Always Check the Full Request Path</h3><p>Don’t assume the problem is in your code. Use tools like nslookup and curl to trace the entire request journey:</p><pre># Understand your infrastructure<br>nslookup your-domain.com</pre><pre># Test direct connectivity<br>curl -v <a href="http://direct-ip-address/endpoint">http://direct-ip-address/endpoint</a></pre><h3>2. Test Locally First</h3><p>Before diving into complex infrastructure debugging, verify your application works locally:</p><pre># SSH into your instance<br>ssh ubuntu@ec2-instance-ip</pre><pre># Test your application directly<br>curl <a href="http://localhost:3000/endpoint">http://localhost:3000/endpoint</a></pre><h3>3. Use AWS Console Methodically</h3><p>When debugging ALB issues, check these in order:</p><ol><li><strong>Load Balancer status</strong> (Active/Provisioning/Failed)</li><li><strong>Target Group health</strong> (Healthy/Unhealthy/Unused)</li><li><strong>Network mapping</strong> (Availability Zones and subnets)</li><li><strong>Security Groups</strong> (Inbound/outbound rules)</li></ol><h3>4. Understand AWS Availability Zones</h3><p>Remember that ALBs can only route traffic to instances in Availability Zones where they have subnets configured. This is a common gotcha that can leave perfectly healthy instances unreachable.</p><h3>The Bigger Picture: Why This Matters</h3><p>This incident highlights a crucial aspect of cloud infrastructure: <strong>the complexity of modern distributed systems</strong>. Your application might be running perfectly, but a simple configuration mismatch in the networking layer can make it completely inaccessible.</p><p>As developers, we need to think beyond our code and understand the entire stack:</p><ul><li><strong>DNS resolution</strong></li><li><strong>Load balancer configuration</strong></li><li><strong>Network topology</strong></li><li><strong>Security groups and firewalls</strong></li><li><strong>Target health checks</strong></li></ul><h3>Prevention: Avoiding Future Headaches</h3><p>To prevent similar issues:</p><ol><li><strong>Document your infrastructure topology</strong></li><li><strong>Use Infrastructure as Code</strong> (Terraform, CloudFormation)</li><li><strong>Set up proper monitoring</strong> for target group health</li><li><strong>Create runbooks</strong> for common debugging scenarios</li><li><strong>Test your disaster recovery procedures</strong></li></ol><h3>Real-World Debugging Commands</h3><p>Here’s a quick reference of the commands that saved the day:</p><pre># DNS investigation<br>nslookup api.mycompany.com</pre><pre># Connectivity testing<br>curl -v -X POST <a href="http://203.0.113.45/endpoint">http://203.0.113.45/endpoint</a></pre><pre># Instance debugging<br>ssh ubuntu@instance-ip<br>sudo systemctl status nginx<br>ps aux | grep node<br>sudo netstat -tlnp | grep 3000</pre><pre># Local application testing<br>curl -X POST <a href="http://localhost:3000/api/auth/login">http://localhost:3000/api/auth/login</a> \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;email&quot;:&quot;test@example.com&quot;,&quot;password&quot;:&quot;testpass&quot;}&#39;</pre><h3>Conclusion</h3><p>What started as a mysterious 503 error turned into a valuable lesson about AWS networking fundamentals. The fix was simple — just enabling the correct Availability Zone — but finding the root cause required systematic debugging and understanding of the entire request path.</p><p>Remember: when your application is working but your users can’t reach it, the problem is usually in the middle. Don’t panic, follow the trail, and debug methodically.</p><p><strong>The key takeaway?</strong> Always verify that your load balancer can actually reach your instances. A perfectly healthy application is useless if your ALB can’t find it.</p><p><strong>Have you encountered similar AWS mysteries?</strong> Share your war stories in the comments — we all learn from each other’s debugging adventures!</p><p><em>🔧 If this helped you solve a similar problem, give it a clap and follow for more real-world DevOps debugging stories.</em></p><p><strong>Tags:</strong> #AWS #DevOps #Debugging #LoadBalancer #Infrastructure #503Error #CloudComputing #TechnicalTroubleshooting</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=136fefd121dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Cómo resolver el error de despliegue en Vercel cuando trabajas con otros programadores (sin…]]></title>
            <link>https://medium.com/@giorbismiguel/c%C3%B3mo-resolver-el-error-de-despliegue-en-vercel-cuando-trabajas-con-otros-programadores-sin-17fa1bc75c2d?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/17fa1bc75c2d</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 19:18:29 GMT</pubDate>
            <atom:updated>2025-08-25T19:18:29.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Cómo resolver el error de despliegue en Vercel cuando trabajas con otros programadores (sin pagar $20 extra)</h3><p>Si trabajas con <strong>Vercel</strong> y <strong>GitHub</strong>, seguramente disfrutas lo fácil que es desplegar un proyecto con un simple <em>push</em>.<br> Pero todo cambia cuando no eres el único programador del equipo…</p><p>Un día uno de tus colaboradores hace un commit y, al intentar desplegar, aparece este error:</p><blockquote><strong><em>Deployment request did not have a git author with access to the project on Vercel</em></strong></blockquote><p>😱 ¿Qué significa? ¿Cómo lo soluciono sin tener que pagar $20 por cada miembro adicional en Vercel?</p><p>En este tutorial te voy a mostrar <strong>3 formas de resolverlo gratis</strong>, para que tu proyecto siga desplegando sin problemas.</p><h3>🔍 ¿Por qué pasa este error?</h3><p>Vercel valida que el autor de cada commit tenga permisos dentro del proyecto.<br> Cuando otro programador hace un git push, el commit lleva su nombre y correo de GitHub.<br> Como él no está registrado en tu Vercel, la plataforma bloquea el despliegue.</p><p>👉 Básicamente, Vercel dice: <em>“Si no pagas por este colaborador, no puedo desplegar sus commits”</em>.</p><h3>✅ Solución 1: Crear un commit vacío con tu usuario</h3><p>La forma más rápida (y la que salva cuando estás apurado) es crear un commit vacío con tu cuenta.</p><pre>git checkout main<br>git pull origin main   # asegúrate de tener la última versión<br>git commit --allow-empty -m &quot;Trigger deploy from my account&quot;<br>git push origin main</pre><p>Ese commit queda a tu nombre, y Vercel lo reconoce como válido.<br> En segundos, tu proyecto se desplegará 🚀.</p><h3>✅ Solución 2: Cambiar el autor de los commits</h3><p>Si quieres que los commits recientes se registren como tuyos:</p><pre>git checkout main<br>git pull origin main<br>git commit --amend --reset-author<br>git push origin main --force</pre><p>Esto cambia el autor del último commit por el usuario configurado en tu Git (git config user.name y git config user.email).</p><p>⚠️ Importante: esto <strong>reescribe la historia</strong>, así que úsalo solo si controlas la rama principal (main).</p><h3>✅ Solución 3: Usar Pull Requests en GitHub (la mejor práctica)</h3><p>Si quieres un flujo más profesional y ordenado, usa ramas y Pull Requests:</p><ol><li>El programador trabaja en su rama, por ejemplo:</li></ol><pre>git checkout -b feature-login <br>git push origin feature-login</pre><p>2. Abre un <strong>Pull Request</strong> en GitHub.</p><p>3. Tú haces el <strong>merge a </strong><strong>main</strong> desde tu cuenta.</p><p>👉 Como el commit de merge es tuyo, Vercel lo toma sin problemas.</p><p>De esta manera, mantienes la trazabilidad (ves quién hizo qué) y sigues desplegando sin pagar extra.</p><h3>🎯 ¿Qué opción elegir?</h3><ul><li>⚡ <strong>Necesito desplegar ya</strong> → commit vacío.</li><li>🔧 <strong>Quiero que el commit aparezca con mi usuario</strong> → reescribir autor.</li><li>🏆 <strong>Trabajo en equipo organizado</strong> → flujo con Pull Requests.</li></ul><h3>🚀 Conclusión</h3><p>El error de Vercel no es un bug, es una limitación de su sistema de permisos.<br> Pero no significa que tengas que pagar obligatoriamente por cada colaborador.</p><p>Con un poco de estrategia en Git puedes:</p><ul><li>Forzar el despliegue con un commit vacío.</li><li>Cambiar el autor de un commit.</li><li>O implementar un flujo profesional con Pull Requests.</li></ul><p>Así, tu equipo colabora libremente en GitHub y tú mantienes el control de los despliegues en Vercel sin costos adicionales 💡.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17fa1bc75c2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Configure HTTPS for NestJS with AWS ALB and ACM: Complete Guide 2025]]></title>
            <link>https://medium.com/@giorbismiguel/how-to-configure-https-for-nestjs-with-aws-alb-and-acm-complete-guide-2025-02c0b33b20b8?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/02c0b33b20b8</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 23:11:42 GMT</pubDate>
            <atom:updated>2025-07-25T23:11:42.847Z</atom:updated>
            <content:encoded><![CDATA[<h3>The problem every developer faces</h3><p>Have you ever deployed your frontend on Vercel (HTTPS) and your API on AWS (HTTP), only to find that when you try to make a call from your web application, the browser blocks the request with a <strong>Mixed Content</strong> error?</p><p>This is one of the most common problems when separating frontend and backend across different platforms. Today I’m going to show you <strong>step by step</strong> how to solve it by configuring HTTPS for your NestJS API using AWS Application Load Balancer and free SSL certificates.</p><h3>Why you need HTTPS for your API</h3><p>When your frontend is on HTTPS (like on Vercel), <strong>browsers automatically block</strong> any requests to APIs that are on HTTP for security reasons. This is known as <strong>Mixed Content Policy</strong>.</p><pre>// ❌ This DOESN&#39;T work<br>Frontend: https://my-app.vercel.app → API: http://api.my-domain.com<br>// Error: Mixed Content blocked</pre><pre>// ✅ This WORKS  <br>Frontend: <a href="https://my-app.vercel.app/">https://my-app.vercel.app</a> → API: <a href="https://api.my-domain.com/">https://api.my-domain.com</a></pre><h3>Architecture we’re going to implement</h3><p>By the end of this guide, you’ll have this architecture working:</p><pre>User → https://api.your-domain.com → ALB (SSL) → NestJS (Internal HTTP)</pre><p><strong>Benefits of this configuration:</strong></p><ul><li>✅ <strong>Free</strong> SSL certificates with automatic renewal</li><li>✅ High availability with Load Balancer</li><li>✅ Your NestJS application stays simple (internal HTTP)</li><li>✅ Scalability for multiple instances</li></ul><h3>Prerequisites</h3><p>Before starting, make sure you have:</p><ol><li><strong>Your own domain</strong> (example: my-domain.com)</li><li><strong>DNS managed</strong> on Vercel, Cloudflare, or similar</li><li><strong>NestJS application</strong> running on EC2</li><li><strong>AWS Console access</strong> with permissions for ACM, ALB, and EC2</li></ol><h3>Step 1: Request SSL certificate in AWS Certificate Manager</h3><h3>1.1 Go to Certificate Manager</h3><pre>AWS Console → Certificate Manager → Request certificate</pre><h3>1.2 Configure the certificate</h3><pre>Domain name: api.your-domain.com<br>Validation method: DNS validation</pre><p><strong>Why DNS validation?</strong> It’s more secure and renews automatically.</p><h3>1.3 Get validation records</h3><p>AWS will give you something like this:</p><pre>Name: _abc123.api.your-domain.com<br>Value: _xyz789.acm-validations.aws.</pre><h3>Step 2: Configure DNS validation</h3><h3>2.1 If you have issues with CAA records</h3><p>If you see an error like “Certificate Authority Authorization (CAA) error”, you need to add these records to your DNS:</p><pre>Type: CAA<br>Name: @ (root domain)<br>Value: 0 issue &quot;amazon.com&quot;</pre><pre>Type: CAA  <br>Name: @ (root domain)<br>Value: 0 issue &quot;amazontrust.com&quot;</pre><h3>2.2 Add validation record</h3><p>In your DNS panel (Vercel, Cloudflare, etc.), add:</p><pre>Type: CNAME<br>Name: _abc123.api  (without the full domain)<br>Value: _xyz789.acm-validations.aws.  (with trailing dot)</pre><p>⚠️ <strong>Important:</strong> In the Name field, only put the subdomain part, your DNS provider will automatically add the main domain.</p><h3>2.3 Wait for validation</h3><p>The certificate will change from “Pending validation” to <strong>“Issued”</strong> in 5–30 minutes.</p><h3>Step 3: Prepare your NestJS application</h3><h3>3.1 Add health check endpoint</h3><p>Your ALB needs to verify that your application is working:</p><pre>// main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;</pre><pre>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  <br>  app.enableCors();<br>  <br>  // 🚨 CRITICAL: Health check for ALB<br>  app.get(&#39;/health&#39;, (req, res) =&gt; {<br>    res.status(200).json({ <br>      status: &#39;OK&#39;, <br>      timestamp: new Date().toISOString() <br>    });<br>  });<br>  <br>  // Your application continues running on internal HTTP<br>  await app.listen(3000, &#39;0.0.0.0&#39;);<br>  console.log(&#39;API running on <a href="http://0.0.0.0:3000&#39;);">http://0.0.0.0:3000&#39;);</a><br>}<br>bootstrap();</pre><h3>3.2 Verify it works</h3><pre>curl http://localhost:3000/health<br># Should respond: {&quot;status&quot;:&quot;OK&quot;,&quot;timestamp&quot;:&quot;...&quot;}</pre><h3>Step 4: Configure Security Groups</h3><p>You need two Security Groups: one for the ALB and modify your EC2&#39;s.</p><h3>4.1 Security Group for ALB</h3><pre>AWS Console → EC2 → Security Groups → Create</pre><pre>Name: ALB-API-SG<br>Description: Security group for API Load Balancer<br>VPC: [Same VPC as your EC2]</pre><pre>Inbound rules:<br>- Type: HTTPS, Port: 443, Source: 0.0.0.0/0</pre><pre>Outbound rules:  <br>- Type: Custom TCP, Port: 3000, Destination: [EC2 Security Group]</pre><h3>4.2 Modify EC2 Security Group</h3><pre>EC2 → Security Groups → [Your EC2 Security Group] → Edit inbound rules</pre><pre>Add rule:<br>- Type: Custom TCP, Port: 3000, Source: [ALB Security Group]</pre><h3>Step 5: Create Target Group</h3><h3>5.1 Basic configuration</h3><pre>AWS Console → EC2 → Target Groups → Create</pre><pre>Target group name: api-target-group<br>Target type: Instances<br>Protocol: HTTP<br>Port: 3000<br>VPC: [Your VPC]</pre><h3>5.2 Health checks</h3><pre>Health check protocol: HTTP<br>Health check path: /health<br>Healthy threshold: 2<br>Unhealthy threshold: 2<br>Timeout: 5 seconds<br>Interval: 30 seconds<br>Success codes: 200</pre><h3>5.3 Register your EC2 instance</h3><pre>Available instances: [Select your EC2]<br>Port: 3000<br>→ Include as pending below<br>→ Create target group</pre><h3>Step 6: Create Application Load Balancer</h3><h3>6.1 Basic configuration</h3><pre>AWS Console → EC2 → Load Balancers → Create → Application Load Balancer</pre><pre>Name: api-load-balancer<br>Scheme: Internet-facing<br>IP address type: IPv4</pre><h3>6.2 Network mapping</h3><pre>VPC: [Your VPC]<br>Availability Zones: [Select AT LEAST 2 AZs]</pre><p>⚠️ <strong>Critical:</strong> Make sure the ALB includes the <strong>same Availability Zone</strong> where your EC2 is located.</p><h3>6.3 Security groups</h3><pre>Security groups: ALB-API-SG (the one you created in step 4)</pre><h3>6.4 Listeners and routing (MOST IMPORTANT)</h3><pre>Protocol: HTTPS<br>Port: 443<br>Default action: Forward to target group<br>Target group: api-target-group<br>SSL Certificate: [Your validated ACM certificate]</pre><p>🚨 <strong>Common mistake:</strong> Not selecting the SSL certificate. Without this, HTTPS won’t work.</p><h3>Step 7: Configure final DNS</h3><h3>7.1 Get ALB DNS</h3><p>Once the ALB is created, you get something like:</p><pre>api-load-balancer-123456789.us-east-1.elb.amazonaws.com</pre><h3>7.2 Configure CNAME in your DNS</h3><pre>Type: CNAME<br>Name: api<br>Value: api-load-balancer-123456789.us-east-1.elb.amazonaws.com</pre><p>⚠️ <strong>Important:</strong> If you already have A records for api, you must <strong>delete them</strong> before adding the CNAME.</p><h3>Step 8: Verification and troubleshooting</h3><h3>8.1 Verify everything works</h3><pre># 1. Verify DNS<br>nslookup api.your-domain.com</pre><pre># 2. Test HTTPS<br>curl -I <a href="https://api.your-domain.com/health">https://api.your-domain.com/health</a><br># Should respond: HTTP/2 200 OK</pre><h3>8.2 Common problems and solutions</h3><p><strong>503 Service Unavailable:</strong></p><ul><li>✅ Verify that the Target Group is “Healthy”</li><li>✅ Confirm that the /health endpoint responds on your EC2</li><li>✅ Check that Security Groups allow traffic</li></ul><p><strong>Certificate errors:</strong></p><ul><li>✅ Verify that the certificate is “Issued” in ACM</li><li>✅ Confirm that the ALB is using the correct certificate</li></ul><p><strong>Target “Unused”:</strong></p><ul><li>✅ Make sure the ALB includes your EC2’s AZ</li><li>✅ Verify that the Target Group is associated with the ALB</li></ul><h3>Expected timeline</h3><p>Step Estimated time Certificate validation 5–30 minutes ALB creation 5–10 minutes Target Group “Healthy” 2–5 minutes DNS propagation 2–10 minutes <strong>Total</strong> <strong>15–55 minutes</strong></p><h3>Final result</h3><p>Congratulations! You now have:</p><pre>// In your frontend<br>const response = await fetch(&#39;https://api.your-domain.com/users&#39;);<br>// ✅ Works perfectly without Mixed Content errors</pre><p><strong>Benefits achieved:</strong></p><ul><li>🔐 HTTPS working with free certificates</li><li>⚖️ Load Balancer for high availability</li><li>🔄 Automatic certificate renewal</li><li>📈 Scalability for multiple instances</li><li>🛡️ Optimized Security Groups</li></ul><h3>Recommended next steps</h3><ol><li><strong>Configure WAF</strong> for additional protection</li><li><strong>Implement CloudWatch</strong> for monitoring</li><li><strong>Set up Auto Scaling</strong> to handle more traffic</li><li><strong>Add CloudFront</strong> for global CDN</li></ol><h3>Conclusion</h3><p>Configuring HTTPS for your NestJS API might seem complex at first, but by following these steps you’ll have a robust and professional infrastructure.</p><p>The combination of ALB + ACM is the most efficient and economical way to handle SSL on AWS, especially since the certificates are <strong>completely free</strong> and renew automatically.</p><p>Did this guide help you? Did you encounter any problems during implementation? Let me know in the comments.</p><p><strong>Did you like this article?</strong> 👏 Give it a clap and follow me for more content about backend development and DevOps with AWS.</p><h3>Tags</h3><p>#AWS #NestJS #HTTPS #SSL #DevOps #ApplicationLoadBalancer #CertificateManager #Backend #NodeJS #API #WebDevelopment #CloudComputing #Tutorial #Guide2025</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02c0b33b20b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cómo Configurar HTTPS en NestJS con AWS ALB y ACM: Guía Completa 2025]]></title>
            <link>https://medium.com/@giorbismiguel/c%C3%B3mo-configurar-https-en-nestjs-con-aws-alb-y-acm-gu%C3%ADa-completa-2025-0dff8c33196b?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dff8c33196b</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 23:07:08 GMT</pubDate>
            <atom:updated>2025-07-25T23:07:08.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>El problema que todos enfrentamos como desarrolladores</h3><p>¿Te ha pasado que tienes tu frontend desplegado en Vercel (HTTPS) y tu API en AWS (HTTP), pero cuando intentas hacer una llamada desde tu aplicación web, el navegador te bloquea la petición con un error de <strong>Mixed Content</strong>?</p><p>Este es uno de los problemas más comunes al separar frontend y backend en diferentes plataformas. Hoy te voy a mostrar <strong>paso a paso</strong> cómo solucionarlo configurando HTTPS para tu API de NestJS usando AWS Application Load Balancer y certificados SSL gratuitos.</p><h3>¿Por qué necesitas HTTPS en tu API?</h3><p>Cuando tu frontend está en HTTPS (como en Vercel), <strong>los navegadores bloquean automáticamente</strong> cualquier petición a APIs que estén en HTTP por motivos de seguridad. Esto se conoce como <strong>Mixed Content Policy</strong>.</p><pre>// ❌ Esto NO funciona<br>Frontend: https://mi-app.vercel.app → API: http://api.mi-dominio.com<br>// Error: Mixed Content blocked</pre><pre>// ✅ Esto SÍ funciona  <br>Frontend: <a href="https://mi-app.vercel.app/">https://mi-app.vercel.app</a> → API: <a href="https://api.mi-dominio.com/">https://api.mi-dominio.com</a></pre><h3>Arquitectura que vamos a implementar</h3><p>Al final de esta guía tendrás esta arquitectura funcionando:</p><pre>Usuario → https://api.tu-dominio.com → ALB (SSL) → NestJS (HTTP interno)</pre><p><strong>Beneficios de esta configuración:</strong></p><ul><li>✅ Certificados SSL <strong>gratuitos</strong> con renovación automática</li><li>✅ Alta disponibilidad con Load Balancer</li><li>✅ Tu aplicación NestJS sigue siendo simple (HTTP interno)</li><li>✅ Escalabilidad para múltiples instancias</li></ul><h3>Requisitos previos</h3><p>Antes de empezar, asegúrate de tener:</p><ol><li><strong>Dominio propio</strong> (ejemplo: mi-dominio.com)</li><li><strong>DNS gestionado</strong> en Vercel, Cloudflare, o similar</li><li><strong>Aplicación NestJS</strong> corriendo en EC2</li><li><strong>Acceso a AWS Console</strong> con permisos para ACM, ALB, y EC2</li></ol><h3>Paso 1: Solicitar certificado SSL en AWS Certificate Manager</h3><h3>1.1 Ir a Certificate Manager</h3><pre>AWS Console → Certificate Manager → Request certificate</pre><h3>1.2 Configurar el certificado</h3><pre>Domain name: api.tu-dominio.com<br>Validation method: DNS validation</pre><p><strong>¿Por qué DNS validation?</strong> Es más seguro y se renueva automáticamente.</p><h3>1.3 Obtener registros de validación</h3><p>AWS te dará algo como esto:</p><pre>Name: _abc123.api.tu-dominio.com<br>Value: _xyz789.acm-validations.aws.</pre><h3>Paso 2: Configurar validación DNS</h3><h3>2.1 Si tienes problemas con CAA records</h3><p>Si ves un error como “Certificate Authority Authorization (CAA) error”, necesitas agregar estos registros en tu DNS:</p><pre>Type: CAA<br>Name: @ (dominio raíz)<br>Value: 0 issue &quot;amazon.com&quot;</pre><pre>Type: CAA  <br>Name: @ (dominio raíz)<br>Value: 0 issue &quot;amazontrust.com&quot;</pre><h3>2.2 Agregar registro de validación</h3><p>En tu panel DNS (Vercel, Cloudflare, etc.), agrega:</p><pre>Type: CNAME<br>Name: _abc123.api  (sin el dominio completo)<br>Value: _xyz789.acm-validations.aws.  (con punto al final)</pre><p>⚠️ <strong>Importante:</strong> En el campo Name solo pongas la parte del subdominio, tu proveedor DNS agregará automáticamente el dominio principal.</p><h3>2.3 Esperar validación</h3><p>El certificado cambiará de “Pending validation” a <strong>“Issued”</strong> en 5–30 minutos.</p><h3>Paso 3: Preparar tu aplicación NestJS</h3><h3>3.1 Agregar endpoint de health check</h3><p>Tu ALB necesita verificar que tu aplicación esté funcionando:</p><pre>// main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;</pre><pre>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  <br>  app.enableCors();<br>  <br>  // 🚨 CRITICAL: Health check para ALB<br>  app.get(&#39;/health&#39;, (req, res) =&gt; {<br>    res.status(200).json({ <br>      status: &#39;OK&#39;, <br>      timestamp: new Date().toISOString() <br>    });<br>  });<br>  <br>  // Tu aplicación sigue corriendo en HTTP interno<br>  await app.listen(3000, &#39;0.0.0.0&#39;);<br>  console.log(&#39;API running on <a href="http://0.0.0.0:3000&#39;);">http://0.0.0.0:3000&#39;);</a><br>}<br>bootstrap();</pre><h3>3.2 Verificar que funciona</h3><pre>curl http://localhost:3000/health<br># Debe responder: {&quot;status&quot;:&quot;OK&quot;,&quot;timestamp&quot;:&quot;...&quot;}</pre><h3>Paso 4: Configurar Security Groups</h3><p>Necesitas dos Security Groups: uno para el ALB y modificar el de tu EC2.</p><h3>4.1 Security Group para ALB</h3><pre>AWS Console → EC2 → Security Groups → Create</pre><pre>Name: ALB-API-SG<br>Description: Security group for API Load Balancer<br>VPC: [El mismo VPC de tu EC2]</pre><pre>Inbound rules:<br>- Type: HTTPS, Port: 443, Source: 0.0.0.0/0</pre><pre>Outbound rules:  <br>- Type: Custom TCP, Port: 3000, Destination: [EC2 Security Group]</pre><h3>4.2 Modificar Security Group de EC2</h3><pre>EC2 → Security Groups → [Tu EC2 Security Group] → Edit inbound rules</pre><pre>Agregar regla:<br>- Type: Custom TCP, Port: 3000, Source: [ALB Security Group]</pre><h3>Paso 5: Crear Target Group</h3><h3>5.1 Configuración básica</h3><pre>AWS Console → EC2 → Target Groups → Create</pre><pre>Target group name: api-target-group<br>Target type: Instances<br>Protocol: HTTP<br>Port: 3000<br>VPC: [Tu VPC]</pre><h3>5.2 Health checks</h3><pre>Health check protocol: HTTP<br>Health check path: /health<br>Healthy threshold: 2<br>Unhealthy threshold: 2<br>Timeout: 5 seconds<br>Interval: 30 seconds<br>Success codes: 200</pre><h3>5.3 Registrar tu instancia EC2</h3><pre>Available instances: [Selecciona tu EC2]<br>Port: 3000<br>→ Include as pending below<br>→ Create target group</pre><h3>Paso 6: Crear Application Load Balancer</h3><h3>6.1 Configuración básica</h3><pre>AWS Console → EC2 → Load Balancers → Create → Application Load Balancer</pre><pre>Name: api-load-balancer<br>Scheme: Internet-facing<br>IP address type: IPv4</pre><h3>6.2 Network mapping</h3><pre>VPC: [Tu VPC]<br>Availability Zones: [Selecciona AL MENOS 2 AZ]</pre><p>⚠️ <strong>Crítico:</strong> Asegúrate de que el ALB incluya la <strong>misma Availability Zone</strong> donde está tu EC2.</p><h3>6.3 Security groups</h3><pre>Security groups: ALB-API-SG (el que creaste en el paso 4)</pre><h3>6.4 Listeners and routing (LO MÁS IMPORTANTE)</h3><pre>Protocol: HTTPS<br>Port: 443<br>Default action: Forward to target group<br>Target group: api-target-group<br>SSL Certificate: [Tu certificado ACM validado]</pre><p>🚨 <strong>Error común:</strong> No seleccionar el certificado SSL. Sin esto, HTTPS no funcionará.</p><h3>Paso 7: Configurar DNS final</h3><h3>7.1 Obtener DNS del ALB</h3><p>Una vez creado el ALB, obtienes algo como:</p><pre>api-load-balancer-123456789.us-east-1.elb.amazonaws.com</pre><h3>7.2 Configurar CNAME en tu DNS</h3><pre>Type: CNAME<br>Name: api<br>Value: api-load-balancer-123456789.us-east-1.elb.amazonaws.com</pre><p>⚠️ <strong>Importante:</strong> Si ya tienes registros A para api, debes <strong>eliminarlos</strong> antes de agregar el CNAME.</p><h3>Paso 8: Verificación y troubleshooting</h3><h3>8.1 Verificar que todo funciona</h3><pre># 1. Verificar DNS<br>nslookup api.tu-dominio.com</pre><pre># 2. Probar HTTPS<br>curl -I <a href="https://api.tu-dominio.com/health">https://api.tu-dominio.com/health</a><br># Debe responder: HTTP/2 200 OK</pre><h3>8.2 Problemas comunes y soluciones</h3><p><strong>503 Service Unavailable:</strong></p><ul><li>✅ Verifica que el Target Group esté “Healthy”</li><li>✅ Confirma que el endpoint /health responda en tu EC2</li><li>✅ Revisa que los Security Groups permitan el tráfico</li></ul><p><strong>Certificate errors:</strong></p><ul><li>✅ Verifica que el certificado esté “Issued” en ACM</li><li>✅ Confirma que el ALB esté usando el certificado correcto</li></ul><p><strong>Target “Unused”:</strong></p><ul><li>✅ Asegúrate de que el ALB incluya la AZ de tu EC2</li><li>✅ Verifica que el Target Group esté asociado al ALB</li></ul><h3>Timeline esperado</h3><p>Paso Tiempo estimado Validación certificado 5–30 minutos Creación ALB 5–10 minutos Target Group “Healthy” 2–5 minutos Propagación DNS 2–10 minutos <strong>Total</strong> <strong>15–55 minutos</strong></p><h3>Resultado final</h3><p>¡Felicidades! Ahora tienes:</p><pre>// En tu frontend<br>const response = await fetch(&#39;https://api.tu-dominio.com/users&#39;);<br>// ✅ Funciona perfectamente sin errores de Mixed Content</pre><p><strong>Beneficios obtenidos:</strong></p><ul><li>🔐 HTTPS funcionando con certificados gratuitos</li><li>⚖️ Load Balancer para alta disponibilidad</li><li>🔄 Renovación automática de certificados</li><li>📈 Escalabilidad para múltiples instancias</li><li>🛡️ Security Groups optimizados</li></ul><h3>Próximos pasos recomendados</h3><ol><li><strong>Configurar WAF</strong> para protección adicional</li><li><strong>Implementar CloudWatch</strong> para monitoreo</li><li><strong>Configurar Auto Scaling</strong> para manejar más tráfico</li><li><strong>Agregar CloudFront</strong> para CDN global</li></ol><h3>Conclusión</h3><p>Configurar HTTPS para tu API de NestJS puede parecer complejo al principio, pero siguiendo estos pasos tendrás una infraestructura robusta y profesional.</p><p>La combinación de ALB + ACM es la forma más eficiente y económica de manejar SSL en AWS, especialmente porque los certificados son <strong>completamente gratuitos</strong> y se renuevan automáticamente.</p><p>¿Te ha servido esta guía? ¿Has encontrado algún problema durante la implementación? Déjamelo saber en los comentarios.</p><p><strong>¿Te gustó este artículo?</strong> 👏 Dale clap y sígueme para más contenido sobre desarrollo backend y DevOps con AWS.</p><h3>Tags</h3><p>#AWS #NestJS #HTTPS #SSL #DevOps #ApplicationLoadBalancer #CertificateManager #Backend #NodeJS #API</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dff8c33196b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Safe Boolean Handling in NestJS DTOs with class-transformer]]></title>
            <link>https://medium.com/@giorbismiguel/safe-boolean-handling-in-nestjs-dtos-with-class-transformer-db4d29d41f21?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/db4d29d41f21</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 13:06:04 GMT</pubDate>
            <atom:updated>2025-07-11T13:06:04.125Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In <strong>NestJS</strong> applications, handling boolean values in <strong>DTOs</strong> (Data Transfer Objects) can lead to unexpected errors, especially when data arrives as strings from the frontend (e.g., &#39;true&#39;, &#39;false&#39;, &#39;1&#39;, &#39;0&#39;). This issue often arises when using the <strong>ValidationPipe</strong> with enableImplicitConversion: true, as <strong>class-transformer</strong> may misinterpret strings like &#39;false&#39; as true. In this article, we explore the problem, its root cause, and a robust solution to ensure safe boolean handling.</p><h3>The Problem</h3><p>When configuring a global <strong>ValidationPipe</strong> in NestJS with transform: true and enableImplicitConversion: trueBoolean fields in DTOs can be misinterpreted. For example:</p><ul><li>The frontend sends a field like isDamaged: &#39;false&#39; (string).</li><li>Due to JavaScript’s implicit conversion (Boolean(&#39;false&#39;) evaluates to trueThe value is incorrectly transformed to true in the DTO.</li><li>This can result in a value that should be false being stored as true in the database, causing critical bugs.</li></ul><p>This behavior occurs because <strong>class-transformer</strong> applies implicit conversion before any custom transformation, making it challenging to control the process.</p><h3>Root Cause</h3><p>The issue stems from the <strong>ValidationPipe</strong> configuration in the main.ts file:</p><pre>app.useGlobalPipes(<br>  new ValidationPipe({<br>    transform: true,<br>    transformOptions: { enableImplicitConversion: true },<br>  }),<br>);</pre><ul><li>transform: true enables automatic transformation of input data to the type defined in the DTO.</li><li>enableImplicitConversion: true allows <strong>class-transformer</strong> to automatically convert values to primitive types, such as booleans.</li><li>In JavaScript, any non-empty string (including &#39;false&#39;) converts to true when using Boolean(). This causes values &#39;false&#39; to be incorrectly interpreted as true.</li></ul><h3>Proposed Solution: Rule for Safe Boolean Handling</h3><p>To prevent these errors, we propose the following rule for handling boolean fields in DTOs:</p><ol><li><strong>Declare boolean fields as </strong><strong>string | boolean:</strong> This prevents implicit conversion from transforming the value prematurely.</li><li><strong>Use a custom </strong><strong>@Transform decorator:</strong> This decorator should correctly handle boolean values and strings like &#39;true&#39;, &#39;false&#39;, &#39;1&#39;, &#39;0&#39; (in any case, combination).</li><li><strong>Normalize the value in the service:</strong> Before saving to the database, ensure the field is a valid boolean (true, false, or undefined).</li></ol><h3>Example Implementation</h3><h4>DTO with Custom Transformation</h4><pre>import { IsOptional } from &#39;class-validator&#39;;<br>import { Transform } from &#39;class-transformer&#39;;</pre><pre>export class UpdateItemDto {<br>  @Transform(({ value }) =&gt; {<br>    if (typeof value === &#39;boolean&#39;) return value;<br>    if (typeof value === &#39;string&#39;) {<br>      const v = value.toLowerCase();<br>      if (v === &#39;true&#39; || v === &#39;1&#39;) return true;<br>      if (v === &#39;false&#39; || v === &#39;0&#39;) return false;<br>    }<br>    return undefined;<br>  })<br>  @IsOptional()<br>  isDamaged?: string | boolean;<br>}</pre><h4>Normalization in the Service</h4><pre>import { UpdateItemDto } from &#39;./dto/update-item.dto&#39;;</pre><pre>export class ItemService {<br>  update(id: number, dto: UpdateItemDto) {<br>    let isDamaged: boolean | undefined;<br>    if (typeof dto.isDamaged === &#39;boolean&#39;) {<br>      isDamaged = dto.isDamaged;<br>    } else if (typeof dto.isDamaged === &#39;string&#39;) {<br>      const v = dto.isDamaged.toLowerCase();<br>      if (v === &#39;true&#39; || v === &#39;1&#39;) isDamaged = true;<br>      else if (v === &#39;false&#39; || v === &#39;0&#39;) isDamaged = false;<br>      else isDamaged = undefined;<br>    }</pre><pre>    // Save to the database<br>    const entity = { id, isDamaged };<br>    // ... persistence logic<br>    return entity;<br>  }<br>}</pre><h3>Explanation of the Implementation</h3><ul><li><strong>In the DTO:</strong></li><li>The string | boolean type allows receiving values of both types without implicit conversion, and modifying them prematurely.</li><li>The The @Transform decorator converts input values to a correct boolean or undefined If the value is invalid.</li><li>@IsOptional() makes the field optional, which is common in update endpoints.</li><li><strong>In the Service:</strong></li><li>Explicit normalization ensures that the value saved to the database is a boolean (true or false) or undefined.</li><li>This ensures consistency, as databases typically expect strict types for boolean fields.</li></ul><h3>Benefits of the Solution</h3><ul><li><strong>Robustness:</strong> Correctly handles any input format (&#39;true&#39;, &#39;FALSE&#39;, &#39;1&#39;, true, etc.).</li><li><strong>Bug Prevention:</strong> Avoids issues where &#39;false&#39; is interpreted as true.</li><li><strong>Flexibility:</strong> Compatible with forms, multipart/form-data, and other input types from the frontend.</li><li><strong>Maintainability:</strong> The transformation logic is clear and reusable across other DTOs.</li></ul><h3>Conclusion</h3><p>Improper handling of booleans in DTOs is a common issue in NestJS applications using <strong>class-transformer</strong> with implicit conversion. By declaring boolean fields asstring | boolean, using a custom @Transform A decorator and normalizing values in the service ensure safe and consistent data handling. This practice not only prevents bugs but also improves code robustness and clarity.</p><p>If you’re working with NestJS, consider adopting this rule in your projects to avoid surprises with booleans. Your database and users will thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db4d29d41f21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manejo seguro de booleanos en DTOs con NestJS y class-transformer]]></title>
            <link>https://medium.com/@giorbismiguel/manejo-seguro-de-booleanos-en-dtos-con-nestjs-y-class-transformer-91d6da1d9f3e?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d6da1d9f3e</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 13:00:04 GMT</pubDate>
            <atom:updated>2025-07-11T13:00:04.452Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducción</h3><p>En aplicaciones desarrolladas con <strong>NestJS</strong>, el manejo de valores booleanos en los <strong>DTOs</strong> (Data Transfer Objects) puede generar errores inesperados, especialmente cuando los datos provienen de un frontend en forma de strings (por ejemplo, &#39;true&#39;, &#39;false&#39;, &#39;1&#39;, &#39;0&#39;). Este problema suele ocurrir cuando se usa el <strong>ValidationPipe</strong> con la opción enableImplicitConversion: true, ya que la conversión implícita de <strong>class-transformer</strong> puede malinterpretar strings como &#39;false&#39; y convertirlos a true. En este artículo, exploramos el problema, su causa raíz y una solución robusta para garantizar un manejo seguro de booleanos.</p><h3>El problema</h3><p>Cuando se configura un <strong>ValidationPipe</strong> global en NestJS con las opciones transform: true y enableImplicitConversion: true, los campos booleanos definidos en un DTO pueden ser malinterpretados. Por ejemplo:</p><ul><li>El frontend envía un campo como isDamaged: &#39;false&#39; (string).</li><li>Debido a la conversión implícita de JavaScript (Boolean(&#39;false&#39;) evalúa a true), el valor se transforma incorrectamente a true en el DTO.</li><li>Esto puede provocar que un valor que debería ser false se guarde como true en la base de datos, generando bugs críticos.</li></ul><p>Este comportamiento ocurre porque <strong>class-transformer</strong> aplica la conversión implícita antes de cualquier transformación personalizada, lo que dificulta controlar el proceso.</p><h3>Causa raíz</h3><p>El problema radica en la configuración del <strong>ValidationPipe</strong> en el archivo main.ts:</p><pre>app.useGlobalPipes(<br>  new ValidationPipe({<br>    transform: true,<br>    transformOptions: { enableImplicitConversion: true },<br>  }),<br>);</pre><ul><li>transform: true habilita la transformación automática de los datos de entrada al tipo definido en el DTO.</li><li>enableImplicitConversion: true permite que <strong>class-transformer</strong> convierta automáticamente valores a tipos primitivos, como booleanos.</li><li>En JavaScript, cualquier string no vacío (incluyendo &#39;false&#39;) se convierte a true al usar Boolean(). Esto causa que valores como &#39;false&#39; se interpreten incorrectamente como true.</li></ul><h3>Solución propuesta: Regla para manejo seguro de booleanos</h3><p>Para evitar estos errores, proponemos la siguiente regla para manejar campos booleanos en DTOs:</p><ol><li><strong>Declara los campos booleanos como </strong><strong>string | boolean:</strong> Esto evita que la conversión implícita global transforme el valor antes de que se aplique una transformación personalizada.</li><li><strong>Usa un decorador </strong><strong>@Transform personalizado:</strong> Este decorador debe manejar correctamente valores booleanos y strings como &#39;true&#39;, &#39;false&#39;, &#39;1&#39;, &#39;0&#39; (en cualquier combinación de mayúsculas/minúsculas).</li><li><strong>Normaliza el valor en el servicio:</strong> Antes de guardar el valor en la base de datos, asegúrate de que el campo sea un booleano válido (true, false o undefined).</li></ol><h3>Ejemplo de implementación</h3><h4>DTO con transformación personalizada</h4><pre>import { IsOptional } from &#39;class-validator&#39;;<br>import { Transform } from &#39;class-transformer&#39;;</pre><pre>export class UpdateItemDto {<br>  @Transform(({ value }) =&gt; {<br>    if (typeof value === &#39;boolean&#39;) return value;<br>    if (typeof value === &#39;string&#39;) {<br>      const v = value.toLowerCase();<br>      if (v === &#39;true&#39; || v === &#39;1&#39;) return true;<br>      if (v === &#39;false&#39; || v === &#39;0&#39;) return false;<br>    }<br>    return undefined;<br>  })<br>  @IsOptional()<br>  isDamaged?: string | boolean;<br>}</pre><h4>Normalización en el servicio</h4><pre>import { UpdateItemDto } from &#39;./dto/update-item.dto&#39;;</pre><pre>export class ItemService {<br>  update(id: number, dto: UpdateItemDto) {<br>    let isDamaged: boolean | undefined;<br>    if (typeof dto.isDamaged === &#39;boolean&#39;) {<br>      isDamaged = dto.isDamaged;<br>    } else if (typeof dto.isDamaged === &#39;string&#39;) {<br>      const v = dto.isDamaged.toLowerCase();<br>      if (v === &#39;true&#39; || v === &#39;1&#39;) isDamaged = true;<br>      else if (v === &#39;false&#39; || v === &#39;0&#39;) isDamaged = false;<br>      else isDamaged = undefined;<br>    }</pre><pre>    // Guardar en la base de datos<br>    const entity = { id, isDamaged };<br>    // ... lógica de persistencia<br>    return entity;<br>  }<br>}</pre><h3>Explicación de la implementación</h3><ul><li><strong>En el DTO:</strong></li><li>El tipo string | boolean permite recibir valores de ambos tipos sin que la conversión implícita los modifique prematuramente.</li><li>El decorador @Transform convierte los valores de entrada a un booleano correcto o undefined si el valor no es válido.</li><li>@IsOptional() permite que el campo sea opcional, lo que es común en endpoints de actualización.</li><li><strong>En el servicio:</strong></li><li>Se realiza una normalización explícita para garantizar que el valor guardado en la base de datos sea un booleano (true o false) o undefined.</li><li>Esto asegura consistencia, ya que las bases de datos suelen esperar tipos estrictos para los campos booleanos.</li></ul><h3>Beneficios de la solución</h3><ul><li><strong>Robustez:</strong> Maneja correctamente cualquier formato de entrada (&#39;true&#39;, &#39;FALSE&#39;, &#39;1&#39;, true, etc.).</li><li><strong>Prevención de bugs:</strong> Evita que valores como &#39;false&#39; se interpreten como true.</li><li><strong>Flexibilidad:</strong> Compatible con formularios, multipart/form-data y otros tipos de entrada desde el frontend.</li><li><strong>Mantenibilidad:</strong> La lógica de transformación es clara y reusable en otros DTOs.</li></ul><h3>Conclusión</h3><p>El manejo incorrecto de booleanos en DTOs es un problema común en aplicaciones NestJS que usan <strong>class-transformer</strong> con conversión implícita. Al declarar los campos booleanos como string | boolean, usar un decorador @Transform personalizado y normalizar los valores en el servicio, se puede garantizar un manejo seguro y consistente de los datos. Esta práctica no solo previene bugs, sino que también mejora la robustez y claridad del código.</p><p>Si trabajas con NestJS, considera implementar esta regla en tus proyectos para evitar sorpresas con los booleanos. ¡Tu base de datos y tus usuarios te lo agradecerán!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d6da1d9f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errores que debes evitar cuando tienes que desarrollar una aplicación de gran envergadura.]]></title>
            <link>https://medium.com/@giorbismiguel/errores-que-debes-evitar-cuando-tienes-que-desarrollar-una-aplicaci%C3%B3n-de-gran-envergadura-ed069f8a7176?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed069f8a7176</guid>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 16:21:38 GMT</pubDate>
            <atom:updated>2024-07-11T21:47:51.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*FELa1FEHnPPTFuf5trq6ew.png" /></figure><p>1- No planificar bien el proyecto.</p><p>Necesitas tener conocimiento previo para acercarte una propuesta decente de entrega para no crear falsas expectativas.</p><p>2- No especializar a los programadores en el negocio.</p><p>Los programadores pueden ser muy buenos pero se enfrentan a conocimientos de negocios que quizás no tengan experiencia por lo que tienes que lograr que su conocimiento avance en ese sentido, esto lo logras con especializaciones en módulos de negocio. Mientras mas tiempo tengas un programador trabajando en un modulo, tendrá mas en cuenta las implicaciones que lleva cada cambios y especificamente que lugares del código debe modificar para que no afecte otras funcionalidades.</p><p>Tener en cuenta que se te puede ir por lo que tienes que hacer ese conocimiento parte del equipo e implementar test que te cuiden cuando venga otra persona a introducir cambios.</p><p>3- Complejizar desde el inicio el desarrollo de cada funcionalidad desde el punto de vista tecnológico. Por ejemplo, tener que modificar mas de 3 micros para lograr una funcionalidad, la aplicación debe ir de los mas fácil a lo mas difícil con un seguimiento supervisado.</p><p>Puedes apoyarte en utilizar banderas(flag) para ir cambiando poco a poco pero ya tienes un producto funcionando y si utilizas buenas técnicas de CI/CD tienes la posibilidad de revertir o simplemente cambiar el valor de una bandera, logrando así se reviertan los cambios que causaron un error.</p><p>4- No tener una estrategia e implementación de test.</p><p>Es aquí cuando los test tiene mayor valor porque necesitas estar seguro que cada cambio que estas introduciendo no rompe otras funcionalidades y es inhumano revisar todo el sistema por cada nueva funcionalidad que se introduce, ojo, al pasar el tiempo suponer que algo sencillo no afecta otro lugar es algo que no debes suponer, debes tener la seguridad.</p><p>Este punto guarda mucha relación con el punto 2 pues el conocimiento sobre el negocio se suele olvidar y necesitas los test para asegurarte de que los nuevos cambios no rompen reglas de negocio.</p><p>5- Analizar los problemas con demasiados programadores.</p><p>Cuando se analizar un problema complejo desde muchos puntos de vista casi siempre termina en horas de conversaciones donde al final no hay uno solución definitiva, hay que darle la responsabilidad al menos 2 programadores e incluso uno de plantear una solución y después con ayuda de otros ir mejorándola pero partiendo de esa base, no sobre pensar las cosas.</p><p>Hay que confiar mas en los programadores pero supervisar su avance.</p><p>6- Tener al menos en un 60% claro las dependencias que existen en el proyecto para saber que va primero y que después.</p><p>Empezar por el modulo incorrecto puede traer consecuencias nefastas porque se te queden muchas cosas incompletas ya que las dependencias hace que no lo pueda terminar por lo que la sensación esperada de avanzar en algunos puntos se pierde y todos tiene la idea que nunca se avanza o se termina algo en concreto.</p><p>7- En cada equipo tiene que haber un líder, el cual debe velar por las buenas practicas de programación, estilos, organización y cuidar de la arquitectura.</p><p>Esta persona también debe especializarse poco a poco en el negocio y saber los que mas tiene conocimiento en un área para tomar decisiones, asignar tareas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed069f8a7176" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement the pop-up menus in React Native with FlatList.]]></title>
            <link>https://medium.com/@giorbismiguel/how-to-implement-the-pop-up-menus-in-react-native-with-flatlist-788243fd4d86?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/788243fd4d86</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-developers]]></category>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 23:13:23 GMT</pubDate>
            <atom:updated>2024-07-08T22:46:58.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*Q9AVITrG_Dq2UyuMOiJbDQ.png" /></figure><p>It’s common to add pop-up menus to any mobile application with lists. With this feature, the users will have the capability to apply some actions. To accomplish this task the best option that I found. It’s to use the library:</p><blockquote>The package <a href="https://www.npmjs.com/package/react-native-popup-menu">react-native-popup-menu</a></blockquote><h3>Setting up our environment</h3><p>I suppose you have a React Native project that has already created a Flatlist displaying some data and you want to add options for any items.</p><p>The first step is to install the package: <a href="https://www.npmjs.com/package/react-native-popup-menu">react-native-popup-menu</a></p><p><strong>yarn add react-native-popup-menu</strong></p><p>If you are using <strong>older RN versions</strong> check our compatibility table</p><p>Next, to begin with the pop-up menu implementation, we’ll take a look at some of the inbuilt APIs for this library:</p><ul><li>MenuProvider: This is an API that provides the methods to handle the pop-up menus imperatively</li><li>Menu: serves as the root menu component used to define menu names and other necessary events</li><li>MenuTrigger: allows us to define the position of the displaying pop-up menu</li><li>MenuOptions: encloses all the menu options</li><li>MenuOption: a wrapper component for all menu options</li></ul><h3>How to use the API components</h3><p>The first step is to set your FlatList component inside your <strong>MenuProvider:</strong></p><pre>import React, { memo, useState } from &#39;react&#39;;<br>import { FlatList, StyleSheet, View } from &#39;react-native&#39;;<br>import { MenuProvider } from &#39;react-native-popup-menu&#39;;<br>import { Items } from &#39;../../mocks&#39;;<br>import Item from &#39;../AttachmentItem/Item&#39;;<br>import { EndOfList } from &#39;~/src/components/EndOfList/EndOfList&#39;;<br>import { colors } from &#39;~/src/theme&#39;;<br><br>const OpportunityAttachmentView = () =&gt; {<br>  const [idMenu, setIdMenu] = useState(&#39;&#39;);<br>  const handleOnClear = () =&gt; {};<br><br>  return (<br>    &lt;MenuProvider&gt;<br>      &lt;View style={styles.uploadContainer}&gt;<br>        &lt;FlatList<br>          data={Items}<br>          keyExtractor={(item) =&gt; item.id}<br>          renderItem={({ item }) =&gt; (<br>            &lt;Item<br>              id={item.id}<br>              idMenu={idMenu}<br>              setIdMenu={setIdMenu}<br>              name={item.name}<br>              person={item.person}<br>              dateUploaded={item.dateUploaded}<br>            /&gt;<br>          )}<br>          ListFooterComponent={() =&gt; !loading &amp;&amp; &lt;EndOfList /&gt;}<br>        /&gt;<br>      &lt;/View&gt;<br>    &lt;/MenuProvider&gt;<br>   );<br>};<br><br>export default memo(OpportunityAttachmentView);<br>const styles = StyleSheet.create({<br>  uploadContainer: {<br>    flex: 1,<br>    margin: 8,<br>  },<br>});</pre><p>The second step is inside your property <em>renderItem </em>to pass a component. it will have all the information and one component, in this case: <em>ItemOptions.</em> that will have all the logic related to the API components provided by the package.</p><pre>import { Divider } from &#39;@rneui/themed&#39;;<br>import React, { FC, memo } from &#39;react&#39;;<br>import { Platform, StyleSheet, Text, View } from &#39;react-native&#39;;<br><br>import { Icon } from &#39;~/src/components/Icon/Icon&#39;;<br>import ItemOptions from &#39;~/src/components/ItemOptions/ItemOptions&#39;;<br>import { colors, typography } from &#39;~/src/theme&#39;;<br><br>type Props = {<br>  id: string;<br>  name: string;<br>  person: string;<br>  dateUploaded: string;<br>  idMenu: string;<br>  setIdMenu: (id: string) =&gt; void;<br>};<br><br>const Item: FC&lt;Props&gt; = ({ id, name, person, idMenu, setIdMenu }) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;View style={styles.container} id={id}&gt;<br>        &lt;View&gt;<br>          &lt;View style={styles.containerName}&gt;<br>            &lt;Text style={styles.name}&gt;{name}&lt;/Text&gt;<br>          &lt;/View&gt;<br>          &lt;View&gt;<br>            &lt;Text style={styles.personName}&gt;{person}&lt;/Text&gt;<br>          &lt;/View&gt;<br>        &lt;/View&gt;<br><br>        &lt;ItemOptions<br>          id={id}<br>          idMenu={idMenu}<br>          setIdMenu={setIdMenu}<br>          options={[<br>            {<br>              title: &#39;Share&#39;,<br>              onPress: () =&gt; {<br>                setIdMenu(&#39;&#39;);<br>              },<br>            },<br>            {<br>              title: &#39;Download&#39;,<br>              onPress: () =&gt; {<br>                setIdMenu(&#39;&#39;);<br>              },<br>            },<br>            {<br>              title: &#39;Delete&#39;,<br>              onPress: () =&gt; {<br>                setIdMenu(&#39;&#39;);<br>              },<br>            },<br>          ]}<br>        /&gt;<br>      &lt;/View&gt;<br>      &lt;Divider width={1} color={colors.neutral.grey.lightest} /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default memo(AttachmentListItem);<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flexDirection: &#39;row&#39;,<br>    justifyContent: &#39;space-between&#39;,<br>    padding: 8,<br>  },<br>  containerIcon: {<br>    marginTop: Platform.OS === &#39;ios&#39; ? 2 : 6,<br>  },<br>  containerName: {<br>    alignItems: &#39;center&#39;,<br>    flexDirection: &#39;row&#39;,<br>    marginBottom: 5,<br>  },<br>  dateUploaded: {<br>    ...typography.labels.regular,<br>    color: colors.neutral.grey.dark,<br>  },<br>  menu: {<br>    flexDirection: &#39;row&#39;,<br>    justifyContent: &#39;space-between&#39;,<br>  },<br>  name: {<br>    ...typography.headings.h5,<br>    color: colors.neutral.grey.darkest,<br>  },<br>  personName: {<br>    ...typography.bodyContent.medium,<br>    color: colors.neutral.grey.dark,<br>  },<br>});</pre><p>This component as you can see receives one property: options that represent all the options for every item.</p><p>Inside our component: <em>ItemOptions </em>you can see :</p><pre>import { Divider } from &#39;@rneui/themed&#39;;<br>import React, { FC, memo } from &#39;react&#39;;<br>import { Platform } from &#39;react-native&#39;;<br>import { Menu, MenuOptions, MenuOption, MenuTrigger } from &#39;react-native-popup-menu&#39;;<br><br>import { Icon } from &#39;../Icon/Icon&#39;;<br><br>import { colors } from &#39;~/src/theme&#39;;<br><br>type ItemsProps = {<br>  title: string;<br>  onPress: () =&gt; void;<br>};<br><br>type Props = {<br>  id: string;<br>  idMenu: string;<br>  options: ItemsProps[];<br>  setIdMenu: (id: string) =&gt; void;<br>};<br><br>const ItemOptions: FC&lt;Props&gt; = ({ id, idMenu, options, setIdMenu }) =&gt; {<br>  const handleOnPress = (id: string) =&gt; {<br>    if (id === idMenu) {<br>      setIdMenu(&#39;&#39;);<br>      return;<br>    }<br>    setIdMenu(id);<br>  };<br><br>  return (<br>    &lt;Menu onClose={() =&gt; setIdMenu(&#39;&#39;)}&gt;<br>      &lt;MenuTrigger<br>        onPress={() =&gt; handleOnPress(id)}<br>        customStyles={{<br>          triggerWrapper: {<br>            top: 25,<br>            alignItems: &#39;center&#39;,<br>            justifyContent: &#39;center&#39;,<br>            flex: 1,<br>          },<br>          triggerTouchable: {<br>            underlayColor: colors.palette.general.white,<br>          },<br>        }}<br>      &gt;<br>        &lt;Icon<br>          name={id === idMenu ? &#39;DOTS_PRESSED&#39; : &#39;DOTS&#39;}<br>          size={24}<br>          color={colors.neutral.grey.dark}<br>        /&gt;<br>      &lt;/MenuTrigger&gt;<br><br>      &lt;MenuOptions<br>        customStyles={{<br>          optionsWrapper: {<br>            position: &#39;absolute&#39;,<br>            bottom: Platform.OS === &#39;ios&#39; ? -60 : -68,<br>            left: 50,<br>            height: 100,<br>            backgroundColor: colors.neutral.white.default,<br>            borderRadius: 8,<br>            padding: 8,<br>            width: 150,<br>            shadowOffset: { width: 0, height: 3 },<br>            shadowOpacity: 0.2,<br>            shadowRadius: 4,<br>            elevation: 5,<br>          },<br>        }}<br>      &gt;<br>        {options?.map((option, index) =&gt; (<br>          &lt;&gt;<br>            &lt;MenuOption key={option.title} onSelect={option.onPress} text={option.title} /&gt;<br>            {options.length &gt; index + 1 &amp;&amp; (<br>              &lt;Divider width={1} color={colors.neutral.grey.lightest} /&gt;<br>            )}<br>          &lt;/&gt;<br>        ))}<br>      &lt;/MenuOptions&gt;<br>    &lt;/Menu&gt;<br>  );<br>};<br><br>export default memo(ItemOptions);</pre><p>Here is a little explanation about this component</p><p>The ItemOptions component utilizes the react-native-popup-menu library to display a menu of options. Here&#39;s a breakdown of its structure and functionality:</p><ul><li><strong>Imports and Dependencies</strong>: The component imports necessary modules and components from React, React Native, and external libraries. This includes UI components like Divider from @rneui/themed, and Menu, MenuOptions, MenuOption, MenuTrigger from react-native-popup-menu for creating the popup menu. It also imports an Icon component from a local directory and a colors object from the theme settings.</li><li><strong>Component Definition</strong>: ItemOptions is a functional component that takes in Props and renders a popup menu. The component:</li><li>Defines a handleOnPress function that toggles the visibility of the menu based on whether the id of the clicked menu matches the idMenu. If they match, it closes the menu by setting idMenu to an empty string; otherwise, it opens the menu by setting idMenu to the clicked menus id.</li><li>Renders a Menu the component that automatically closes when its onClose event is triggered, resetting idMenu to an empty string to indicate no menu is active.</li><li>Inside the Menu, a MenuTrigger is used to control the opening of the menu. It is configured to call handleOnPress when pressed and applies custom styles to position and align the trigger element.</li></ul><p>It’s important to highlight the property: <em>customStyles</em> in the component: <em>MenuOptions</em> because this property will modify all the behaviour and styles.</p><p>To apply the correct style takes me a lot of time to try to understand the following properties:</p><p>1- optionsContainer</p><p>2- optionText</p><p>3- optionsWrapper</p><p>4- optionWrapper</p><p>Please check more about these properties here:</p><p><a href="https://github.com/instea/react-native-popup-menu/blob/master/doc/api.md">react-native-popup-menu/doc/api.md at master · instea/react-native-popup-menu</a></p><p>In my case, I used <em>optionWrapper</em> to customize the styles and behavior for the menu.</p><h3>Conclusion</h3><p>I hope this article has given you the insight to build a menu for every item inside your FlatList component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788243fd4d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como crear un select que cada opción tenga un checkbox para poder seleccionarla y que permitiera…]]></title>
            <link>https://medium.com/@giorbismiguel/como-crear-un-select-que-cada-opci%C3%B3n-tenga-un-checkbox-para-poder-seleccionarla-y-que-permitiera-44b0c95b597e?source=rss-e0c58a6f2f87------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b0c95b597e</guid>
            <category><![CDATA[options]]></category>
            <category><![CDATA[checkbox]]></category>
            <category><![CDATA[antd]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[select]]></category>
            <dc:creator><![CDATA[Giorbis Miguel Lorié Montalvo]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 16:15:02 GMT</pubDate>
            <atom:updated>2023-09-04T16:15:02.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Como crear un select que cada opción tenga un checkbox para poder seleccionarla y que permitiera buscar las opciones con una búsqueda arriba.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ux4A2NWUWEOptAcZcL4Q6g.png" /></figure><p>Hace poco me dieron la tarea de crear un select que tuviera la posibilidad de seleccionar cada opción con un checkbox a la izquierda. Al principio parecía una tarea fácil pero después de hacer la búsqueda en <a href="https://ant.design/">Ant Design</a> me di cuenta que los componentes que tenía no los podía utilizar. Por lo que me propuse hacer una búsqueda en internet y solo encontré algunos ejemplos aislados pero nada como lo que yo quería, así que me dispuse a crearlo.</p><p>La verdad que me costo trabajo porque tuve algunos comportamientos inesperados pero al final logre hacer este componente:</p><pre>import React, { ReactNode, useEffect, useMemo, useState } from &#39;react&#39;;<br>import type { ActionType } from &#39;@rc-component/trigger/lib/interface&#39;;<br>import { Checkbox, Popover, Row, Col, Input, Empty } from &#39;antd&#39;;<br>import { CheckboxValueType } from &#39;antd/es/checkbox/Group&#39;;<br>import { TooltipPlacement } from &#39;antd/es/tooltip&#39;;<br>import { Option } from &#39;../commons/subTable/types&#39;;<br><br>type Props = {<br>  children?: ReactNode | undefined;<br>  options: Option[];<br>  optionsSelected?: string[];<br>  onCheckboxChange: (values: CheckboxValueType[]) =&gt; void;<br>  onOpenChange?: (visible: boolean) =&gt; void;<br>  trigger?: ActionType | ActionType[];<br>  placement?: TooltipPlacement;<br>};<br><br>const { Search } = Input;<br><br>const CheckboxMenu: React.FC&lt;Props&gt; = ({<br>  children,<br>  options,<br>  optionsSelected,<br>  onCheckboxChange,<br>  onOpenChange,<br>  trigger = &#39;click&#39;,<br>  placement = &#39;bottomLeft&#39;,<br>}) =&gt; {<br>  const [searchValue, setSearchValue] = useState(&#39;&#39;);<br><br>  const [selectedItems, setSelectedItems] = useState&lt;CheckboxValueType[]&gt;([]);<br>  useEffect(() =&gt; {<br>    if (optionsSelected &amp;&amp; optionsSelected.length) {<br>      setSelectedItems([...optionsSelected]);<br>    }<br>  }, [optionsSelected]);<br><br>  const handleOnChangeCheckboxGroup = (selection: CheckboxValueType[]) =&gt; {<br>    const lastElement = selection.pop(); // get last element of array<br>    selection.unshift(lastElement ?? &#39;&#39;); // add last element to the beginning of array<br><br>    setSelectedItems([...selection]);<br>    onCheckboxChange([...selection]);<br>  };<br><br>  const handleOnChangeSearch = (event: React.KeyboardEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    if (event.currentTarget.value) {<br>      setSearchValue(event.currentTarget.value);<br>    } else {<br>      setSearchValue(&#39;&#39;);<br>    }<br>  };<br><br>  const handleOnOpenChange = (visible: boolean) =&gt; {<br>    onOpenChange?.(visible);<br>  };<br><br>  const searchRender = useMemo(<br>    () =&gt; (<br>      &lt;Row key=&#39;search&#39; style={{ marginBottom: 10 }}&gt;<br>        &lt;Search<br>          placeholder=&#39;Search&#39;<br>          defaultValue={searchValue}<br>          onKeyUp={handleOnChangeSearch}<br>          style={{ width: 120 }}<br>        /&gt;<br>      &lt;/Row&gt;<br>    ),<br>    [searchValue, handleOnChangeSearch],<br>  );<br><br>  const filterOptions = useMemo(<br>    () =&gt;<br>      options.filter((option) =&gt; option.label.toLowerCase().includes(searchValue.toLowerCase())),<br>    [options, searchValue],<br>  );<br><br>  const checkboxRender = useMemo(<br>    () =&gt; (<br>      &lt;Checkbox.Group onChange={handleOnChangeCheckboxGroup} value={selectedItems}&gt;<br>        &lt;Col&gt;<br>          {searchRender}<br>          {filterOptions.map((option) =&gt; (<br>            &lt;Row key={`checkbox-group-${option.value}`}&gt;<br>              &lt;Checkbox key={option.value} value={option.value}&gt;<br>                {option.label}<br>              &lt;/Checkbox&gt;<br>            &lt;/Row&gt;<br>          ))}<br><br>          {filterOptions.length === 0 &amp;&amp; (<br>            &lt;Row key=&#39;empty-result&#39; style={{ justifyContent: &#39;center&#39; }}&gt;<br>              &lt;Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /&gt;<br>            &lt;/Row&gt;<br>          )}<br>        &lt;/Col&gt;<br>      &lt;/Checkbox.Group&gt;<br>    ),<br>    [filterOptions, searchRender, selectedItems, handleOnChangeCheckboxGroup],<br>  );<br><br>  return (<br>    &lt;Popover<br>      content={checkboxRender}<br>      onOpenChange={handleOnOpenChange}<br>      trigger={trigger}<br>      placement={placement}<br>    &gt;<br>      {children}<br>    &lt;/Popover&gt;<br>  );<br>};<br><br>export default CheckboxMenu;</pre><p>No es necesario tener conocimientos avanzados de React para entenderlo y las propiedades que recibe tienen buenos nombres. No obstante en el siguiente ejemplo te explico como utilizarlo.</p><p>El mismo se puede utilizar de la siguiente forma:</p><pre>const handleColumnsChange = (selectedValues: CheckboxValueType[]) =&gt; {<br>  if (setColumns) {<br>    const newColumns =<br>      columns?.map((column) =&gt; ({<br>        ...column,<br>        selected: selectedValues.includes(String(column.gridPreferenceKey)),<br>      })) ?? [];<br><br>    setColumns(newColumns);<br>  }<br>};<br><br>const handleOnOpenChange = (visible: boolean) =&gt; {<br>  if (!visible) {<br>    setGlobalMenuActive(&#39;&#39;);<br>  }<br>};<br><br>const columnsToSelectOption = useMemo(() =&gt; {<br>  if (!columns) {<br>    return [];<br>  }<br><br>  return columns.map((column) =&gt; ({<br>    label: column.title,<br>    value: String(column.gridPreferenceKey),<br>  }));<br>}, [columns]);<br><br>const columnsHeaderSelected = useMemo(() =&gt; {<br>  if (!columns) {<br>    return [];<br>  }<br><br>  return columns<br>    .filter((column) =&gt; column.selected !== false)<br>    .map((column) =&gt; String(column.gridPreferenceKey));<br>}, [columns]);<br><br>&lt;CheckboxMenu<br>  key=&#39;columns-menu&#39;<br>  options={columnsToSelectOption}<br>  optionsSelected={columnsHeaderSelected}<br>  onCheckboxChange={handleColumnsChange}<br>  onOpenChange={handleOnOpenChange}<br>&gt;<br>  &lt;CustomButton<br>    dataTestId=&#39;subtable-columns-button&#39;<br>    key=&#39;columns&#39;<br>    shape=&#39;circle&#39;<br>    type=&#39;text&#39;<br>    tooltipText=&#39;Columns&#39;<br>    onlyIcon<br>    danger<br>    tooltipColor=&#39;gray&#39;<br>    icon={&lt;TableOutlined /&gt;}<br>    onClick={handleColumnsIconClick}<br>    active={globalMenuActive === &#39;columns&#39;}<br>  /&gt;<br>&lt;/CheckboxMenu&gt;</pre><p>En este puedes ver que utilizamos un componente con el nombre: <strong>CustomButton</strong>, Te lo comparto por si es de ayuda:</p><p>Aquí la customización de ese botón utilizando <em>styled-components</em></p><pre>import styled from &#39;styled-components&#39;;<br>import { Button, ButtonProps } from &#39;antd&#39;;<br><br>interface StyledButtonlProps extends ButtonProps {<br>  noborder: boolean;<br>  active?: boolean;<br>}<br><br>const StyledCustomButton = styled(Button).attrs((props: StyledButtonlProps) =&gt; ({<br>  ghost: props.ghost,<br>  danger: props.danger,<br>  noborder: props.noborder,<br>  active: props.active,<br>}))`<br>  &amp;&amp;&amp; {<br>    border: ${(props) =&gt; props.noborder &amp;&amp; &#39;none !important&#39;};<br>    background-color: ${(props) =&gt; props.active &amp;&amp; &#39;#dcdffb !important&#39;};<br>    &amp;:hover {<br>      color: ${(props) =&gt; props.ghost &amp;&amp; !props.danger &amp;&amp; &#39;#0078D4 !important&#39;};<br>      background-color: ${(props) =&gt; props.ghost &amp;&amp; &#39;#dcdffb !important&#39;};<br>    }<br>  }<br>`;<br><br>export default StyledCustomButton;</pre><p>Ahora si el componente <strong>CustomButton </strong>que utiliza los estilos de arriba:</p><pre>import React, { ReactNode } from &#39;react&#39;;<br>import { QuestionCircleOutlined } from &#39;@ant-design/icons&#39;;<br>import { TooltipPlacement } from &#39;antd/es/tooltip&#39;;<br>import StyledCustomButton from &#39;./CustomButton.styles&#39;;<br>import CustomToolTip from &#39;../customPopover&#39;;<br><br>interface CustomButtonProps {<br>  title?: string | ReactNode;<br>  type?: &#39;primary&#39; | &#39;ghost&#39; | &#39;dashed&#39; | &#39;link&#39; | &#39;text&#39; | &#39;default&#39;;<br>  size?: &#39;large&#39; | &#39;middle&#39; | &#39;small&#39;;<br>  icon?: ReactNode;<br>  disabled?: boolean;<br>  shape?: &#39;default&#39; | &#39;circle&#39; | &#39;round&#39;;<br>  block?: boolean;<br>  danger?: boolean;<br>  ghost?: boolean;<br>  onlyIcon?: boolean;<br>  href?: string;<br>  loading?: boolean | { delay: number };<br>  onClick?: () =&gt; void;<br>  ClassName?: string;<br>  dataTestId?: string;<br>  style?: object;<br>  tooltipText?: unknown;<br>  tooltipColor?: string;<br>  placement?: TooltipPlacement;<br>  noborder?: boolean;<br>  id?: string;<br>  tooltipClassName?: string;<br>  active?: boolean;<br>}<br><br>const CustomButton: React.FC&lt;CustomButtonProps&gt; = ({<br>  title,<br>  type,<br>  size,<br>  onlyIcon,<br>  icon = onlyIcon &amp;&amp; &lt;QuestionCircleOutlined /&gt;,<br>  disabled,<br>  shape,<br>  block,<br>  danger,<br>  ghost,<br>  loading,<br>  ClassName,<br>  onClick,<br>  href,<br>  dataTestId,<br>  style,<br>  tooltipText,<br>  tooltipColor,<br>  placement,<br>  noborder = true,<br>  id,<br>  tooltipClassName,<br>  active = false,<br>}) =&gt; (<br>  &lt;CustomToolTip<br>    title={tooltipText as string}<br>    color={tooltipColor}<br>    placement={placement}<br>    overlayClassName={tooltipClassName}<br>  &gt;<br>    &lt;StyledCustomButton<br>      type={type || &#39;default&#39;}<br>      active={active}<br>      shape={shape || &#39;default&#39;}<br>      size={size || &#39;large&#39;}<br>      icon={icon}<br>      disabled={disabled}<br>      block={block}<br>      danger={danger}<br>      ghost={ghost}<br>      loading={loading}<br>      href={href}<br>      onClick={onClick}<br>      className={ClassName}<br>      data-testid={dataTestId || &#39;customButton&#39;}<br>      style={style}<br>      noborder={noborder}<br>      {...{ id }}<br>    &gt;<br>      {onlyIcon ? &#39;&#39; : title || &#39;unknown&#39;}<br>    &lt;/StyledCustomButton&gt;<br>  &lt;/CustomToolTip&gt;<br>);<br><br>export default CustomButton;</pre><p>Espero les sea de ayuda. Ya que tuve que dedicarle buen tiempo para lograr el resultado que quería.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b0c95b597e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>