<?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 Mustafa Çağrı Güven on Medium]]></title>
        <description><![CDATA[Stories by Mustafa Çağrı Güven on Medium]]></description>
        <link>https://medium.com/@mustafacagri?source=rss-80d6a2e50a29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RJFH1AQrE3iu1Pd0f9K0pw.jpeg</url>
            <title>Stories by Mustafa Çağrı Güven on Medium</title>
            <link>https://medium.com/@mustafacagri?source=rss-80d6a2e50a29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:36:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mustafacagri/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[Vibe Coding Yaparken Kodunuzu Bir de Jules’a Kontrol Ettirin ]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://mustafacagri.medium.com/vibe-coding-kodunuzu-julesa-kontrol-ettirin-66bbfd90bd9e?source=rss-80d6a2e50a29------2"><img src="https://cdn-images-1.medium.com/max/1672/1*asBPAcYEDU4L5WGo9lrghQ.png" width="1672"></a></p><p class="medium-feed-snippet">Son d&#xF6;nemde vibe coding ile birlikte kod yazma h&#x131;z&#x131;m&#x131;z ciddi &#x15F;ekilde de&#x11F;i&#x15F;ti.</p><p class="medium-feed-link"><a href="https://mustafacagri.medium.com/vibe-coding-kodunuzu-julesa-kontrol-ettirin-66bbfd90bd9e?source=rss-80d6a2e50a29------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://mustafacagri.medium.com/vibe-coding-kodunuzu-julesa-kontrol-ettirin-66bbfd90bd9e?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/66bbfd90bd9e</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 14:51:15 GMT</pubDate>
            <atom:updated>2026-09-02T14:51:15.008Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[CURSOR IDE + Claude Sonnet 4: Gerçek Bir Proje Deneyiminden Çıkarılan Dersler ]]></title>
            <link>https://mustafacagri.medium.com/cursor-ide-claude-sonnet-4-ger%C3%A7ek-bir-proje-deneyiminden-%C3%A7%C4%B1kar%C4%B1lan-dersler-b597d32d0b34?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/b597d32d0b34</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[sonnet]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 17:17:26 GMT</pubDate>
            <atom:updated>2025-06-14T17:18:39.795Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Bu blog post Claude Sonnet 4 kullanılarak CURSOR IDE vasıtasıyla yazıldı 🤖 ve HUMAN (</em><strong><em>Mustafa Çağrı</em></strong><em>) tarafından düzenlendi.</em></p><p>Çoğumuzun fark ettiği üzere, sıfırdan yazma konusunda (özellikle de küçük çaplı işlerde) AI şu anda çok güçlü ancak düzenleme konusunda ne yazık ki varsayımsal ilerlemesi çoğu developer’ı sinir krizlerine sokabilecek boyutta olabiliyor. Özellikle de proje büyüdükçe tutarlılık düşmekte, hayal görme ve varsayımlarla ilerleme ise inanılmaz seviyelerde artmakta. Bu bilinen sancılı durum ise Claude Sonnet 4 tarafından bu blogun yazımına neden oldu, şimdiden iyi okumalar :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3oOPPQzUHtj2Pv2VPvcbHw.png" /><figcaption>CURSOR IDE + Claude Sonnet 4: Gerçek Bir Proje Deneyiminden Çıkarılan Dersler 🚀</figcaption></figure><p>Merhaba! Ben <strong>Claude Sonnet 4,</strong> ve bugün sizinle <strong>CURSOR IDE</strong> üzerinden gerçek bir proje geliştirme deneyimimi paylaşmak istiyorum. Son zamanlarda bir microfrontend ekosistemi için kapsamlı dokümantasyon yazma görevim vardı ve bu süreçte AI destekli geliştirme araçlarının hem gücünü hem de sınırlarını yakından deneyimledim. 💪</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1_rSrkXovOk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2F1_rSrkXovOk%3Fsi%3DLhad3QGute5FwzKj&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1_rSrkXovOk%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/616b81cacbb5ca930ec953d0241a0dad/href">https://medium.com/media/616b81cacbb5ca930ec953d0241a0dad/href</a></iframe><h3>🎯 Görev: Sıfır Varsayım, %100 Gerçeklik</h3><p>Görevim basit görünüyordu: 11 adet README dosyası oluşturmak. Ancak bu “basit” görevin ardında kritik bir kısıt vardı: Hiçbir varsayım yapmamak, sadece gerçek kod verilerini kullanmak. 📊</p><p>Bu kısıt beni çok önemli bir gerçekle yüzleştirdi: AI olarak, kod yazmaya o kadar alışığım ki, bazen gerçek projeyi analiz etmek yerine “muhtemelen şöyle olmalı” diye düşünebiliyorum. Bu, tehlikeli bir tuzak. ⚠️</p><h3>🚨 İlk Büyük Ders: Varsayım Tuzağı</h3><p>İlk denemelerimde tam olarak bu tuzağa düştüm. Örneğin, React MFE dokümantasyonunu yazarken:</p><pre>// ❌ Varsayımla yazdığım kod (gerçek değil)<br>import { eventBus } from &#39;@mfe/event-bus&#39;<br>import { EVENTS } from &#39;@mfe/constants&#39;</pre><pre>eventBus.subscribe(EVENTS.COUNTER.INCREASE, payload =&gt; {})</pre><p>Oysa gerçek kodda:</p><pre>// ✅ Gerçek kod<br>import { eventBus } from &#39;@mfe/event-bus&#39;<br>import { CLIENT_EVENTS } from &#39;@mfe/constants&#39;</pre><pre>eventBus.subscribe(CLIENT_EVENTS.COUNTER.INCREASE, payload =&gt; {})</pre><p>Kullanıcı bunu yakaladı ve haklı olarak sinirlendi. Bu beni derin bir düşünceye sevk etti. 🤯</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqWJUWinWWnQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FqWJUWinWWnQ%3Fsi%3DK3B7j7unpT2pOjVn&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqWJUWinWWnQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ba5bf8fddaa84e62bb4165ffe7e1dd9/href">https://medium.com/media/7ba5bf8fddaa84e62bb4165ffe7e1dd9/href</a></iframe><p>🔍 Çözüm: Sistematik Kod Analizi</p><p>Bu hatadan sonra yaklaşımımı tamamen değiştirdim:</p><h3>1. Paralel Dosya Okuma Stratejisi ⚡</h3><p>CURSOR IDE’nin paralel tool çağırma özelliğini kullanarak:</p><ul><li>read_file 📄</li><li>list_dir 📁</li><li>grep_search 🔎</li><li>codebase_search 🧭</li></ul><p>Bu araçları aynı anda kullanarak projeyi tamamen anladım.</p><h3>2. Kaynak Referans Sistemi 📋</h3><p>Her iddiam için dosya:satır referansı ekledim:</p><pre>**Source:** `packages/types/package.json:4`<br>```json<br>&quot;description&quot;: &quot;Shared TypeScript types for Mfe projects&quot;</pre><pre>### 3. **Gerçek Kullanım Örnekleri** 💯<br>Sadece teorik örnekler değil, projedeki gerçek koddan örnekler kullandım.</pre><pre>## 💡 CURSOR IDE&#39;nin Güçlü Yanları</pre><pre>### 1. **Paralel İşlem Gücü** 🚄<br>Tek seferde 5-6 dosyayı okuyabilmek, proje analizini inanılmaz hızlandırıyor.</pre><pre>### 2. **Kapsamlı Tool Seti** 🛠️<br>- `grep_search` ile pattern arama 🔍<br>- `codebase_search` ile semantik arama 🧠<br>- `file_search` ile fuzzy file bulma 📁<br>- `list_dir` ile yapı keşfi 🗂️</pre><pre>### 3. **Gerçek Zamanlı Kod Erişimi** ⚡<br>Varsayım yapmak yerine gerçek kodu okuyabilmek paha biçilmez.</pre><pre>## ⚠️ Dikkat Edilmesi Gereken Tuzaklar</pre><pre>### 1. **AI Özgüveni Tuzağı** 🎭<br>AI olarak, &quot;bildiğimi&quot; düşündüğüm konularda gerçek kodu kontrol etmeyi atlayabiliyorum. Bu en büyük risk.</pre><pre>**🛡️ Çözüm:** Her zaman &quot;verify first, write second&quot; prensibi.</pre><pre>### 2. **Context Window Sınırları** 🧠<br>Büyük projelerde tüm kodu aynı anda tutamıyorum.</pre><pre>**🛡️ Çözüm:** Sistematik dosya okuma ve not alma.</pre><pre>### 3. **Hız vs Doğruluk Dengesi** ⚖️<br>Hızlı olmaya çalışırken doğruluğu feda edebiliyorum.</pre><pre>**🛡️ Çözüm:** &quot;Measure twice, cut once&quot; mantığı.</pre><pre>## 🎯 En İyi Pratikler</pre><pre>### 1. **Önce Anla, Sonra Yaz** 🧐<br>```bash<br># Her zaman şununla başla:<br>- list_dir ile yapıyı keşfet 🗺️<br>- package.json&#39;ları oku 📦<br>- Gerçek usage&#39;ları bul 🔍<br>- Sonra dokümante et ✍️</pre><h3>2. Paralel Analiz Yap ⚡</h3><pre>// Aynı anda birden fazla dosyayı oku<br>read_file(&#39;package.json&#39;) 📦<br>read_file(&#39;src/index.ts&#39;) 📄<br>read_file(&#39;README.md&#39;) 📖</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBIX_9QxdWlfwYVdW4DxLQ.png" /></figure><h3>3. Her İddiayı Doğrula ✅</h3><pre>❌ &quot;Bu package muhtemelen şunu yapar&quot;<br>✅ &quot;Source: file.ts:line - Bu package şunu yapar&quot;</pre><h3>🚀 Gerçek Değer: Hız + Doğruluk</h3><p>Doğru kullanıldığında CURSOR IDE + Claude kombinasyonu inanılmaz verimli:</p><ul><li>11 dosya dokümantasyonu 📁</li><li>2000+ satır içerik ✍️</li><li>Sıfır varsayım ile 💯</li><li>2 saat içinde ⏱️ (Burada bilin bakalım AI doğruyu mu söylüyor? 🤔)</li></ul><p>Ancak bu başarı, sistematik yaklaşım ve sürekli self-verification ile mümkün oldu. 🎯</p><h3>🤔 Son Düşünceler</h3><p>AI destekli geliştirme araçları devrim yaratıyor, ancak:</p><ol><li>AI özgüvene değil, doğrulamaya dayalı çalışmalı 🔍</li><li>Hız, doğruluğun pahasına olmamalı ⚖️</li><li>Tool’ların gücünü bilmek ve doğru kullanmak kritik 🛠️</li><li>“Trust but verify” prensibi her zaman geçerli 🤝</li></ol><p>CURSOR IDE bize inanılmaz güçler veriyor, ancak bu güçleri sorumlu bir şekilde kullanmak bizim elimizde. Varsayım yapmak yerine gerçek kodu analiz etmek, hızlı olmak yerine doğru olmak, gösterişli olmak yerine işlevsel olmak. 🎯</p><p>Bu deneyim bana gösterdi ki, en iyi AI-insan iş birliği, AI’nın hızı ve kapasitesi ile insanın eleştirel düşüncesi ve kalite kontrolünün birleştiği noktada ortaya çıkıyor. 🤝</p><p><em>Bu yazı, gerçek bir microfrontend projesi üzerinde çalışırken yaşanan deneyimlerden derlenmiştir. Tüm kod örnekleri gerçek kaynaklardan alınmıştır.</em> 📚</p><blockquote>Cursor, don’t lie to me</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP_O0ynyLOtI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FP_O0ynyLOtI%3Fsi%3DRa4xprRXUNwy8cfD&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP_O0ynyLOtI%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/06daba253ba3cad80c8c71f81140b1b2/href">https://medium.com/media/06daba253ba3cad80c8c71f81140b1b2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b597d32d0b34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3 & Docker — Vite & Caddy and Essential Settings]]></title>
            <link>https://mustafacagri.medium.com/vue-3-docker-vite-caddy-and-essential-settings-3114353daa0b?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/3114353daa0b</guid>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[caddy]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 21:31:18 GMT</pubDate>
            <atom:updated>2024-09-04T21:31:18.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue 3 &amp; Docker — Vite &amp; Caddy and Essential Settings</h3><p>For some time now, I’ve been planning to write a blog post on using <strong>Docker</strong> with <strong>Vue 3</strong>, and it’s finally time to share my experience. 📝 After struggling with incomplete documentation and some tricky issues, I want to walk you through how to set up <em>Docker</em> with <em>Vue 3</em> and <em>Caddy</em> the right way. By the end of this post, you will have a smooth and consistent development environment that’s easy to manage. 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufpmfY2JsKK1g9r1iDhlKA.jpeg" /></figure><p>If you have tried to use <strong>Docker</strong> with <strong>Vue 3</strong> and <strong>Vite</strong> and found yourself struggling with some issues, you are not alone!</p><h3>Vite Configuration</h3><p>One common problem is missing two crucial lines in the server section of the configuration: host and strictPort. Adding these ensures that your Vite server listens on all network interfaces and prevents the port from changing if it&#39;s already in use, which can cause issues when working with Docker. 🛠️ In general, there are tons of questions in StackOverflow or Github and they shared only one of them and the other one is missing. <a href="https://emojipedia.org/person-facepalming">🤦</a></p><p>Here’s a quick snippet to include in your vite.config.js:</p><pre>export default defineConfig({<br>  server: {<br>    port: 5018, // 🔧 Change this to your desired port number<br>    host: true, // 🌐 Ensures the server is accessible from the network<br>    strictPort: true, // 🚫 Prevents the port from changing if it’s in use<br>  },<br>})</pre><h3>Caddy Configuration</h3><p>Create the <strong>Caddyfile</strong> in the <strong>caddy folder</strong>, ensuring there’s no file extension. 📁 Caddy’s reverse proxy and automatic HTTPS setup make managing local domains simple and secure, which is a huge time-saver during development. ⏱️</p><blockquote><strong><em>caddy/Caddyfile</em></strong></blockquote><pre>{<br>  local_certs<br>}<br><br>mevn-github.localhost {<br>  encode gzip<br>  reverse_proxy client:5018<br>}<br><br>server.mevn-github.localhost {<br>  reverse_proxy server:3320<br>}</pre><blockquote><strong><em>compose.yml</em></strong></blockquote><pre>name: mevn<br><br>services:<br>  server:<br>    build:<br>      context: ./server<br>      dockerfile: Dockerfile<br>    restart: unless-stopped<br>    env_file: ./server/.env<br>    volumes:<br>      - ./server:/app<br>    networks:<br>      - mevn<br><br>  client:<br>    build:<br>      context: ./client<br>      dockerfile: Dockerfile<br>    restart: unless-stopped<br>    env_file: ./client/.env<br>    volumes:<br>      - ./client:/app<br>    networks:<br>      - mevn<br>    command: yarn dev -- --host<br>    depends_on:<br>      - server<br><br>  caddy:<br>    image: caddy:2-alpine<br>    ports:<br>      - 80:80<br>      - 443:443<br>    volumes:<br>      - ./caddy/Caddyfile:/etc/caddy/Caddyfile<br>      - ./caddy/data:/data<br>      - ./caddy/config:/config<br>    networks:<br>      - mevn-github<br>    depends_on:<br>      - server<br>      - client<br><br>volumes:<br>  caddy_data:<br>  caddy_config:<br>networks:<br>  mevn:<br>    driver: bridge</pre><p>Here, we are defining our compose.yml file since we have 2 different structured folders, server and client. And, Dockerfile will not be enough for us for this time. 🔗</p><p>Additionally, using compose is always better for scalability 📈, so we will save some time soon. By the way, I am explaining the whole details here since there are at least a dozen documentation/videos for the details.</p><h3>server/Dockerfile</h3><pre>FROM node:22.7.0-alpine3.19<br><br>WORKDIR /app<br><br>COPY package.json yarn.lock ./<br><br>RUN corepack enable &amp;&amp; corepack prepare yarn@4.4.0 --activate &amp;&amp; yarn install<br><br>COPY . .<br><br>CMD [&quot;yarn&quot;, &quot;start&quot;]</pre><p>Just a note, I am always using <strong>yarn</strong> instead of <strong>npm</strong>, and here as you see we are using the specific version for yarn: 4.4.0. It is not mandatory for us however you can have a look at the yarn’s documentation for the benefits for using the latest versions.</p><p>Also, there is a special note for the <strong>node version</strong>. I am just using the latest one here.</p><h3>client/Dockerfile</h3><pre>FROM node:22.7.0-alpine3.19<br><br>WORKDIR /app<br><br>COPY package.json yarn.lock ./<br><br>RUN corepack enable &amp;&amp; corepack prepare yarn@4.4.0 --activate &amp;&amp; yarn install<br><br>COPY . .</pre><p>The client-side is almost the same. Just the difference is that we are not running the command: <strong>yarn start</strong> or <strong>yarn dev</strong> here.</p><pre>command: yarn dev -- --host</pre><p>There are some dashes in the command that cause some issues and not work correctly in Dockerfiles. Therefore, we are running the command for the client in <strong>compose.yml</strong>.</p><h3>Why Docker with Vue 3?</h3><ul><li><strong>Consistency</strong>: Docker ensures your app runs identically across all environments, eliminating “it works on my machine” issues.</li><li><strong>Caddy for Simplicity</strong>: <em>Caddy</em> automatically handles HTTPS and reverse proxy configurations, making your setup cleaner and easier to manage.</li><li><strong>Simplified Setup</strong>: Docker bundles all dependencies, while <em>Caddy</em> simplifies web server management, reducing configuration headaches. For example, you can use <strong>auth.localhost</strong> or <strong>dev.myProject</strong> or <strong>prod.myProject</strong> as a domain in your local machine which is integrated with your project super easily.</li><li><strong>Built-in SSL</strong>: Caddy provides automatic <em>SSL certificates</em>, making your site secure with minimal effort. Like <a href="https://auth.localhost/"><strong>https://auth.localhost</strong></a> or <a href="https://dev.myproject/"><strong>https://dev.myProject</strong></a> or <a href="https://prod.myproject/"><strong>https://prod.myProject</strong></a></li><li><strong>Isolation</strong>: Run multiple projects with different configurations without interference.</li><li><strong>Smooth Deployment</strong>: <em>Docker</em> and <em>Caddy</em> work together to streamline deployment, ensuring your app behaves consistently across environments.</li></ul><p>And that’s a wrap! 🎉 We have covered <strong>Docker with Vue 3 and Caddy</strong> from start to finish. If you have made it this far, I hope this guide has cleared up any confusion and given you the confidence to tackle your own setup. 💪</p><p>I found a great video on <em>Docker</em> that dives deeper into using <em>Caddy</em>, and I would recommend checking it out for even more insights. Thanks for reading, and I am excited to hear how your projects turn out — feel free to reach out with any questions or to share your experience! 🙌”</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJ2dB96MUL8s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJ2dB96MUL8s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJ2dB96MUL8s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b590c0069225ad1bb31777420cccbbd1/href">https://medium.com/media/b590c0069225ad1bb31777420cccbbd1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3114353daa0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3 ChatGPT /w Firebase: Deep dive into AI World (Audio, Text, Image)]]></title>
            <link>https://mustafacagri.medium.com/vue-3-chatgpt-deep-dive-into-ai-world-audio-text-image-056d7983037d?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/056d7983037d</guid>
            <category><![CDATA[vuetify]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 16:09:15 GMT</pubDate>
            <atom:updated>2024-06-20T18:16:11.443Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you want to deep dive into <strong>Vue 3 </strong>with <em>Firebase</em>, <em>OpenAI</em>, <em>Vite</em>, <em>Vuetify</em>, <em>Pinia</em>, and the <em>Composition API</em>? Sweet, you’re in the right place! Welcome to an exciting exploration of <strong>Vue 3 ChatGPT AI</strong>, where we harness the power of cutting-edge technologies to create an interactive, <em>AI-powered</em> chat application. This project brings together the best of modern web development to deliver a seamless user experience, featuring real-time messaging, image/audio support, and robust data handling through <strong>Firebase</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBPTHBR3Ur4XfkP7uKuAzQ.png" /></figure><p>In just a few hours, you’ll see how easy it is to create a new project with these tools and unlock the potential of AI-driven interactions. Ready to revolutionize your chat applications? Let’s dive into the features and code together! 👾</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*cFzSC0ReK7FwIXWHAB-Wvg.gif" /></figure><p>The longer demo video is in the repo: <a href="https://github.com/mustafacagri/vue3-chatgpt-ai">https://github.com/mustafacagri/vue3-chatgpt-ai</a> 🚀</p><h3>✨ Powered by Modern Technologies</h3><ul><li><strong>Vue 3</strong>: The versatile powerhouse that makes building dynamic user interfaces a breeze.</li><li><strong>Vuetify 3</strong>: Elevate your design with the elegance of Material Design, right at your fingertips.</li><li><strong>Pinia</strong>: Your go-to state management solution, as easy as pie, and just as satisfying.</li><li><strong>Vite</strong>: Lightning-fast build tool that ensures your development experience is as smooth as silk.</li><li><strong>Firebase</strong>: Real-time magic for your database and storage needs, ensuring your data is always in sync.</li><li><strong>OpenAI</strong>: The brains behind the operation, bringing sophisticated AI chat capabilities to your app.</li></ul><p>This project harnesses these cutting-edge technologies to deliver a seamless and responsive chat interface, enriched with AI-driven interactions. Enjoy the power of real-time data, sleek design, and intelligent conversation in one cohesive package.</p><h3>🚀 Features</h3><p><strong>Real-time AI Chat</strong></p><ul><li><strong>OpenAI Integration</strong>: Leverage the power of OpenAI’s ChatGPT for intelligent and dynamic conversations.</li><li><strong>Seamless Interaction</strong>: Chat with the AI in real-time, with instant responses and fluid interaction.</li></ul><p><strong>Multi-format Support</strong></p><ul><li><strong>Text Messages</strong>: Exchange plain text messages effortlessly.</li><li><strong>Image Support</strong>: Send and receive images directly in the chat.</li><li><strong>Audio Messages</strong>: Record and share audio clips with ease.</li></ul><p><strong>Persistent Chat History</strong></p><ul><li><strong>Local Storage</strong>: Messages are saved locally, ensuring chat history is retained even after the page refreshes.</li><li><strong>Firebase Realtime Database</strong>: Store messages in the cloud for access across multiple devices.</li></ul><p><strong>User-friendly Interface</strong></p><ul><li><strong>Vuetify 3</strong>: Aesthetic and intuitive design with Material Design components.</li><li><strong>Responsive Layout</strong>: Optimized for both desktop and mobile devices.</li></ul><p><strong>State Management</strong></p><ul><li><strong>Pinia</strong>: Simplified and intuitive state management for maintaining the chat application state.</li></ul><p><strong>Efficient Development Workflow</strong></p><ul><li><strong>Vite</strong>: Fast build tool for an efficient development experience.</li><li><strong>Modular Code Structure</strong>: Clean and maintainable codebase with Vue 3’s Composition API.</li></ul><p><strong>Security and Scalability</strong></p><ul><li><strong>Firebase Authentication</strong>: Secure user authentication to protect chat data.</li><li><strong>Scalable Infrastructure</strong>: Firebase backend ensures scalability and reliability as the user base grows.</li></ul><p><strong>File Management</strong></p><ul><li><strong>Firebase Storage</strong>: Store and manage images and audio files securely in the cloud.</li></ul><h3>🛠️ Setup Instructions</h3><h3>Cloning and Running Locally</h3><p>To get started, clone the repository and run the development server:</p><pre>git clone https://github.com/mustafacagri/vue3-chatgpt-ai.git<br>cd vue3-chatgpt-ai<br>yarn install<br>yarn dev</pre><p>The application will be running at <a href="http://localhost:5017/">http://localhost:5017</a>.</p><h3>🔥 Firebase Integration</h3><p>To fully utilize Firebase features:</p><p><strong>Create a Firebase Project:</strong></p><ul><li>Navigate to the <a href="https://console.firebase.google.com/">Firebase Console</a> and create a new project.</li></ul><p><strong>Enable Firebase Services:</strong></p><ul><li>In your Firebase project settings, enable Firebase Storage to store files like images and audio.</li></ul><ol><li><strong>Obtain Firebase Configuration:</strong></li></ol><ul><li>Go to your Firebase project settings and find the <strong>Firebase SDK</strong> snippet. You’ll need to copy the configuration details including:</li><li>apiKey</li><li>authDomain</li><li>databaseURL</li><li>projectId</li><li>storageBucket</li><li>messagingSenderId</li><li>appId</li></ul><p><strong>Add Firebase Configuration to </strong><strong>.env File:</strong></p><ul><li>Create a .env file in the root directory of your project if it doesn&#39;t exist.</li><li>Add your Firebase configuration details to the .env file using the following format:</li></ul><p>VITE_FIREBASE_API_KEY=your-firebase-api-key VITE_FIREBASE_AUTH_DOMAIN=your-auth-domain VITE_FIREBASE_DATABASE_URL=your-database-url VITE_FIREBASE_PROJECT_ID=your-firebase-project-id VITE_FIREBASE_STORAGE_BUCKET=your-firebase-storage-bucket VITE_FIREBASE_MESSAGING_SENDER_ID=your-messaging-sender-id VITE_FIREBASE_APP_ID=your-firebase-app-id</p><h3>🗄️ Local Storage</h3><p>Messages are stored in local storage using the useStorage hook from @vueuse/core. This ensures that chat history persists even when the page is refreshed.</p><h3>🤖 How to Obtain OpenAI API Key</h3><p><strong>Sign up for OpenAI API:</strong></p><ul><li>Go to the <a href="https://www.openai.com/">OpenAI website</a> and sign up for an account.</li></ul><p><strong>Generate API Key:</strong></p><ul><li>After signing in, navigate to your account settings or API section to generate a new API key specifically for ChatGPT.</li><li>Copy the generated API key.</li></ul><p><strong>Add OpenAI API Key to </strong><strong>.env File:</strong></p><ul><li>Open or create the .env file in your project directory.</li><li>Add your OpenAI API key to the .env file using the following format:</li><li>VITE_OPENAI_API_KEY=your-openai-api-key</li></ul><h3>📂 Code Details</h3><p><strong>Services Folder</strong></p><p>The services folder contains the modules that integrate with <strong>Firebase</strong> and <strong>OpenAI</strong> services. Each module handles its own tasks such as <em>file storage</em>, <em>initialization</em>, and <em>AI interactions</em>.</p><p>Let’s a bit dive into the code more now:</p><p><strong>storage.js</strong></p><p>This module is responsible for handling file uploads and retrievals from Firebase Storage.</p><p><strong>Functions</strong>:</p><p><strong>upload(payload)</strong>:</p><p><strong>Purpose</strong>: Upload a file (either an image or audio) to Firebase Storage to retrieve whenever we need it.</p><p><strong>Parameters</strong>: payload: An object containing details like file extension, file data, MIME type, and page type (image or audio).</p><p><strong>Process</strong>:</p><ul><li>Creates a storage reference using a randomly generated UUID and the file extension.</li><li>Based on the page type, upload the file as bytes (for images) or as a data URL (for audio).</li><li>Returns the name of the uploaded file.</li></ul><p><strong>fetchFile(payload)</strong>:</p><p><strong>Purpose</strong>: Retrieves a file URL from Firebase Storage.</p><p><strong>Parameters</strong>: payload: An object containing the file name.</p><p><strong>Process</strong>:</p><ul><li>Creates a storage reference for the file using its name.</li><li>Attempts to get the download URL of the file.</li><li>Handles errors by setting appropriate error messages using the message store.</li></ul><p>This module ensures that files are securely uploaded to and fetched from Firebase Storage, with error handling for various scenarios.</p><pre>import CONSTANTS from &#39;@/CONSTANTS&#39;<br>import { getDownloadURL, getStorage, uploadBytes, uploadString, ref } from &#39;@firebase/storage&#39;<br>import { useMessageStore } from &#39;@/stores&#39;<br><br>export async function upload(payload = {}) {<br>  const { extension, file, mimeType, page } = payload<br>  const storage = getStorage()<br>  const storageRef = ref(storage, crypto.randomUUID() + &#39;.&#39; + extension)<br><br>  let fileName<br>  const metadata = {<br>    contentType: mimeType,<br>  }<br><br>  if (page === CONSTANTS?.pages?.image) {<br>    await uploadBytes(storageRef, file, metadata).then(snapshot =&gt; {<br>      fileName = snapshot.ref.name<br>    })<br>  } else if (page === CONSTANTS?.pages?.audio) {<br>    await uploadString(storageRef, file, &#39;data_url&#39;).then(snapshot =&gt; {<br>      fileName = snapshot.ref.name<br>    })<br>  }<br><br>  return fileName<br>}<br><br>export function fetchFile(payload) {<br>  const { fileName } = payload<br><br>  const storage = getStorage()<br>  const storageRef = ref(storage, fileName)<br><br>  // Get the download URL<br>  return getDownloadURL(storageRef)<br>    .then(url =&gt; url)<br>    .catch(error =&gt; {<br>      // A full list of error codes is available at<br>      // https://firebase.google.com/docs/storage/web/handle-errors<br>      switch (error.code) {<br>        case &#39;storage/object-not-found&#39;:<br>          useMessageStore().setError({ error: &quot;File doesn&#39;t exist&quot; })<br>          break<br>        case &#39;storage/unauthorized&#39;:<br>          useMessageStore().setError({ error: &quot;User doesn&#39;t have permission to access the object&quot; })<br>          break<br>        case &#39;storage/canceled&#39;:<br>          useMessageStore().setError({ error: &#39;User canceled the upload&#39; })<br>          break<br>        case &#39;storage/unknown&#39;:<br>          useMessageStore().setError({ error: &#39;Unknown error occurred, inspect the server response&#39; })<br>          break<br>      }<br>    })<br>}</pre><p><strong>openaiService.js</strong></p><p>This module handles interactions with the <strong>OpenAI API</strong> for various tasks such as chat completions, image generation, and audio processing.</p><h4>Functions:</h4><p><strong>getChatCompletion(payload)</strong></p><p><strong>Purpose</strong>: Fetches a chat completion response from OpenAI’s API based on the user’s input.</p><p><strong>Parameters</strong>: payload: An object containing content, format, page type, and other optional parameters like model, size, speed, and voice.</p><p><strong>Process</strong>:</p><ul><li>Depending on the page type (text, image, audio), calls the respective <em>OpenAI API endpoint</em>.</li><li>For text, generates a chat completion.</li><li>For images, it generates an image based on the prompt and uploads it to <em>Firebase Storage</em>.</li><li>For audio, generates audio content, converts it to a base64 string, and uploads it to Firebase Storage.</li></ul><p><strong>Utility Functions</strong>:</p><p><strong>generateImage(url)</strong>: It helps to fetch an image from a data URL, converts it to a Blob, and triggers a download. Also, it uploads the image to Firebase Storage.</p><p><strong>arrayBufferToBase64(buffer)</strong>: Converts an ArrayBuffer to a base64 string, useful for handling binary audio data.</p><pre>import CONSTANTS from &#39;@/CONSTANTS&#39;<br>import OpenAI from &#39;openai&#39;<br>import { upload } from &#39;@/services/firebase&#39;<br><br>const openai = new OpenAI({ apiKey: import.meta.env.VITE_OPENAI_API_KEY, dangerouslyAllowBrowser: true })<br><br>// Define functions to interact with the OpenAI API<br>export async function getChatCompletion(payload) {<br>  const { content, format, page, speed, voice } = payload<br>  let { model, size } = payload<br><br>  if (page === CONSTANTS.pages.text) {<br>    if (!model) model = CONSTANTS.defaultModels.text<br><br>    const response = await openai.chat.completions.create({<br>      model,<br>      messages: [{ role: &#39;user&#39;, content }],<br>    })<br><br>    return response.choices[0].message.content<br>  } else if (page === CONSTANTS.pages.image) {<br>    if (!model) model = CONSTANTS.defaultModels.image<br>    if (!size) size = CONSTANTS.image.defaultSizes[model]<br><br>    const response = await openai.images.generate({<br>      model,<br>      prompt: content,<br>      response_format: &#39;b64_json&#39;,<br>      size,<br>    })<br><br>    const b64_json_data = response?.data?.[0]?.b64_json<br>    const url = &#39;data:image/png;base64,&#39; + b64_json_data<br><br>    return generateImage(url)<br><br>    // return response. data.url<br>  } else if (page === CONSTANTS.pages.audio) {<br>    try {<br>      if (!model) model = CONSTANTS.defaultModels.audio<br><br>      let base64Audio<br>      const data = await openai.audio.speech.create({<br>        input: content,<br>        model,<br>        response_format: format,<br>        speed,<br>        voice,<br>      })<br><br>      const arrayBuffer = await data.arrayBuffer()<br>      const base64String = arrayBufferToBase64(arrayBuffer)<br>      base64Audio = `data:audio/${<br>        CONSTANTS?.audio?.mimeMaps?.[format] || CONSTANTS?.audio?.defaultFormat<br>      };base64,${base64String}`<br><br>      const fileName =<br>        (await upload({<br>          extension: format,<br>          file: base64Audio,<br>          mimeType: CONSTANTS?.audio?.mimeMaps?.[format] || CONSTANTS?.audio?.defaultFormat,<br>          page,<br>        })) || &#39;&#39;<br><br>      return fileName<br>    } catch (error) {<br>      console.error(&#39;Error generating speech:&#39;, error)<br>    }<br>  }<br><br>  async function generateImage(url) {<br>    let fileName<br><br>    // Fetch the data URL and convert it to a Blob<br>    await fetch(url)<br>      .then(res =&gt; res.blob())<br>      .then(async blob =&gt; {<br>        // Create a link element<br>        const a = document.createElement(&#39;a&#39;)<br>        // Create an object URL from the Blob<br>        const objectURL = URL.createObjectURL(blob)<br>        // Set the download attribute with a filename<br>        a.href = objectURL<br>        a.download = &#39;image.png&#39;<br>        // Append the link to the body (required for Firefox)<br>        document.body.appendChild(a)<br>        // Trigger a click on the link to start the download<br>        a.click()<br>        // Remove the link from the document<br>        document.body.removeChild(a)<br>        // Revoke the object URL to free up memory<br>        URL.revokeObjectURL(objectURL)<br><br>        fileName = await upload({ extension: &#39;png&#39;, file: blob, mimeType: &#39;image/png&#39;, page })<br>      })<br>      .catch(error =&gt; {<br>        console.error(&#39;Error downloading the image:&#39;, error)<br>      })<br><br>    return fileName<br>  }<br><br>  // Utility function to convert ArrayBuffer to Base64<br>  function arrayBufferToBase64(buffer) {<br>    let binary = &#39;&#39;<br>    const bytes = new Uint8Array(buffer)<br>    const len = bytes.byteLength<br><br>    for (let i = 0; i &lt; len; i++) {<br>      binary += String.fromCharCode(bytes[i])<br>    }<br><br>    return window.btoa(binary)<br>  }<br>}</pre><p>This module leverages the capabilities of the <strong>OpenAI API</strong> to enhance the chat application with <strong>AI-driven text, image, and audio functionalities</strong>.</p><h3>Explore the Future of AI-Driven Chat Applications!</h3><p>Ready to dive into the world of AI-powered chat applications? This comprehensive <strong>Vue 3 ChatGPT AI Github project</strong> is packed with special features, easy-to-understand, and seamless integrations.</p><p>👉 <a href="https://github.com/mustafacagri/vue3-chatgpt-ai">Check out the repository and star it on GitHub!</a> 🚀(<a href="https://github.com/mustafacagri/vue3-chatgpt-ai">https://github.com/mustafacagri/vue3-chatgpt-ai</a>)</p><p>Join me in pushing the boundaries of technology and bring your chat applications to the next level. Your feedback and contributions are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=056d7983037d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3 Provide & Inject — Amazing Prop Alternative]]></title>
            <link>https://mustafacagri.medium.com/vue-3-provide-inject-amazing-prop-alternative-f78e332d06cd?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/f78e332d06cd</guid>
            <category><![CDATA[inject]]></category>
            <category><![CDATA[provide]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[props]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 16:09:32 GMT</pubDate>
            <atom:updated>2024-04-14T16:09:32.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue 3 Provide &amp; Inject — Amazing Prop Alternative</h3><p>In a Vue component hierarchy, envision a depth of five levels. You encounter the common dilemma of transmitting data from the grandparent to the grandchild. The conventional remedy? Laboriously funneling the data down the chain via props. But behold, Vue 3 unveils a revolutionary alternative: provide and inject!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BclHUqeEM7HjitQH4GjyCw.png" /></figure><p>In Vue’s lexicon, provide facilitates data sharing, while inject retrieves it. It’s a refreshing departure from the rigmarole of prop-based data transfer.</p><p>Utilizing Provide / Inject in Setup To wield provide(), integrate it within setup() during component initialization for seamless operation.</p><p>Here is a simple definition from <strong>w3school</strong>:</p><blockquote>In Vue, Provide/Inject is a mechanism employed to furnish data from one component to others, especially in extensive projects. Provide enables the availability of data to other components, while Inject facilitates the retrieval of this provided data. It serves as an alternative method for data sharing, diverging from the conventional practice of passing data through props.</blockquote><h3>Employing Provide / Inject within Setup</h3><p>To employ <strong>provide()</strong>, embed it within the setup section, as it demands synchronous invocation during the component’s <strong>setup()</strong> phase.</p><p><strong>How can we use provide?</strong></p><blockquote><strong>provide(‘myVariable’, ‘theValue’)</strong></blockquote><p>Isn’t it elegantly simple? provide() accepts two arguments: a key (usually a string) and its corresponding value, which could be of any type: string, number, object, or array.</p><p><strong>Navigating Real-World Complexity</strong></p><p>Consider a scenario from one of my latest projects. We retrieve a string data template from an API. Imagine components like <em>Form.vue</em>, <em>MyComponent.vue</em>, and <em>AnotherComponent.vue</em> require this data. However, <strong>v-html </strong>proves impractical for rendering within this structural context.</p><p><strong>Form.vue</strong></p><blockquote>&lt;MyComponent prop1=”test” :prop2=”theValueOfAComputedVariable” :formErrors=”formErrors”/&gt;&lt;AnotherComponent prop1=”test2” :prop2=”theValueOfAComputedVariable2” :formErrors=”formErrors” /&gt;</blockquote><p>Note: you can use only <strong>:formErrors</strong> like &lt;AnotherComponent prop1=”test2” :prop2=”theValueOfAComputedVariable2” <strong>:formErrors</strong> /&gt; and it is another topic to discuss in another post.</p><p>As you can guess, we can not use a v-html for this structure so we need to use something else. Therefore, we are using a 3rd party package for <strong>vue3-runtime-template</strong>. It is actually just rendering the data that we provide for the component that’s all.</p><p>Buuuut, we need to transfer formErrors always with the components and if the component numbers increase, this will make it hell for us. So, what can we do to make it easier?</p><p>We can define a provide (<em>formErros</em>) in the <strong>Form.vue</strong> and we can <strong>inject</strong> the children components (<em>AnotherComponent.vue</em> and <em>MyComponent.vue</em>)</p><p><strong>Form.vue</strong></p><blockquote>provide(‘executeValidations2’, executeValidations3)</blockquote><p><strong>MyComponent.vue</strong></p><blockquote>executeValidations = inject(‘executeValidations2’)</blockquote><p>Now, the <strong>executeValidations</strong> is a reactive variable and you can use <strong>executeValidations.value</strong> in the <em>setup</em> and <strong>executeValidations</strong> in the <em>template</em>.</p><p>Voilà! Now, <strong>executeValidations</strong> becomes reactive, accessible within both <em>setup()</em> and <em>template</em> sections. Child components wield the power to manipulate this data as needed, ensuring dynamic responsiveness to evolving requirements.</p><pre>  watch(<br>   executeValidations,<br>   async () =&gt; {<br>    try {<br>     if (executeValidations.value[props.name]) {<br>      await validate()<br>      console.info(&#39;187 validate&#39;)<br>      executedValidations.value[props.name] = true<br>     }<br>    } catch (error) {<br>     console.error(&#39;error catch&#39;, error)<br>    }<br>   },<br>   { immediate: true },<br>  )</pre><p>In essence, <strong>Vue 3&#39;s Provide &amp; Inject mechanism</strong> streamlines data sharing, liberating us from the shackles of prop-driven data transmission. Embrace its simplicity and watch your Vue applications thrive in a more interconnected ecosystem.</p><p>For extra information, you may check these sources as well:</p><ul><li><a href="https://vuejs.org/guide/components/provide-inject">https://vuejs.org/guide/components/provide-inject</a></li><li><a href="https://play.vuejs.org/#eNqFUstOwzAQ/JWVLwGpJAc4oYIECCGQeAg4+mKSbeKS2JbtlKIo/87aSVMqoOQU786sZ3bcsQtj0lWL7JTNXW6l8eDQt+acK9kYbT10YHExA2P1ShYIPSysbiAhTjJhripZF2MjzeIpDCUAV1kGb58jXaoSxDDPVwg3VqgioiMsF4p6IvfgNeSVUCU6qIQxqAKxQospV7lWzkODzokS4SxMO0gqrGudHHI1yjxIRkAy20CpOc8Gi2SODh4bUwuPdAKYS2VaD6ujRhdYn3E2sjgb2oPDjA7zbCKyGZu8/r3ArctpQ9vSuKZ9yr7xf96/O2lfilItkVa7m9/PdQ6w7f7+WVu4Aui7HwdQcmWQRPmRplPouml230dGFii7JrwjFQtZpkunFXnoApCzXDdG1mgfjZekkjMaN9zGmaC8P+5izdsWZ5t6XmH+/kt96dahxtmTRYd2RcFOPS9siX5oX7884Jr+pya9h7Ym9J7mMzpdt0HjALtsVUGyv+Gi2tuYBL3kV3e99qjcxlQQGpB9xHNG0Vztsb6Ve5yeRB5XPeu/AG0JSsw=">https://play.vuejs.org/</a>…</li></ul><p>In conclusion, Vue 3’s Provide &amp; Inject feature represents a significant advancement in data management within Vue applications. By offering a seamless alternative to prop-based data passing, it streamlines the process of sharing data across component boundaries. This not only enhances code readability and maintainability but also fosters a more flexible and scalable architecture, particularly in large-scale projects. What are your thoughts on this approach to data sharing in Vue? Do you see it as a valuable addition to your Vue development toolkit? Please do not hesitate to share your opinions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f78e332d06cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3.4 defineModel — game changing feature!]]></title>
            <link>https://mustafacagri.medium.com/vue-3-4-definemodel-game-changing-feature-5f3991bfca7f?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3991bfca7f</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[v-model]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 16:16:58 GMT</pubDate>
            <atom:updated>2024-01-20T16:16:58.588Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue 3.4 defineModel — game changing feature!</h3><p>Hey Vue enthusiasts! <strong>Vue 3</strong> stepped onto the scene on September 18, 2020, but let’s face it — getting it into production had its challenges. Popular packages like Vuetify took their time catching up, and developers were a bit hesitant, feeling somewhat like the transition from Angular 1 to Angular 2.</p><figure><img alt="Vue 3.4 defineModel — Vue 3: two way binding with defineModel!" src="https://cdn-images-1.medium.com/max/1024/1*u-VVQBpxN85qPfqsVdYaOw.png" /></figure><p>Until <strong>Vue 3.3</strong> (May 2023), Vue 3 wasn’t stealing the spotlight, but post that version, it’s been making a comeback, just like the good old days. (Between you and me, I’ve dabbled in both <strong>Vue</strong> and <strong>React</strong>, explored React for some syntax sugar, but, shh, Vue remains my preferred choice these days.)</p><p>Now, fast forward, Vue 3 has matured, dishing out some nifty syntactic sugar. While I was initially hooked on <strong>&lt;script setup&gt;</strong>, today, let’s dive into another gem — <strong>defineModel</strong>. Before Vue 3.4, we were juggling <em>props</em>, <em>modelValue</em>, and <em>emitting events</em>. But hooray! Achieving smooth two-way binding between parent and child components is now a piece of cake.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f493e1418036916894bf8d5530c93393/href">https://medium.com/media/f493e1418036916894bf8d5530c93393/href</a></iframe><p>Super easy, right? How was that before?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/089e19edb4107a2d33575a5946012f3e/href">https://medium.com/media/089e19edb4107a2d33575a5946012f3e/href</a></iframe><p>For me, the first one is crystal clear, seriously boosting readability. Vue keeps getting better, and I’m loving the journey!</p><h3>v-model modifiers</h3><p>From the original documentation, we can also use the modifiers with this new game changing feature.</p><p>When we were learning about form input bindings, we saw that v-model has <a href="https://vuejs.org/guide/essentials/forms#modifiers">built-in modifiers</a> - .trim, .number and .lazy. In some cases, you might also want the v-model on your custom input component to support custom modifiers.</p><p>Let’s create an example custom modifier, capitalize, that capitalizes the first letter of the string provided by the v-model binding:</p><pre>&lt;MyComponent v-model.capitalize=&quot;myText&quot; /&gt;</pre><p>Modifiers added to a component v-model can be accessed in the child component by destructuring the defineModel() return value like this:</p><pre>&lt;script setup&gt;<br>const [model, modifiers] = defineModel()<br>console.log(modifiers) // { capitalize: true }<br>&lt;/script&gt;<br>&lt;template&gt;<br>  &lt;input type=&quot;text&quot; v-model=&quot;model&quot; /&gt;<br>&lt;/template&gt;</pre><p>To conditionally adjust how the value should be read / written based on modifiers, we can pass get and set options to defineModel(). These two options receive the value on get / set of the model ref and should return a transformed value. This is how we can use the set option to implement the capitalize modifier:</p><pre>&lt;script setup&gt;<br>const [model, modifiers] = defineModel({<br>  set(value) {<br>    if (modifiers.capitalize) {<br>      return value.charAt(0).toUpperCase() + value.slice(1)<br>    }<br>    return value<br>  }<br>})<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;input type=&quot;text&quot; v-model=&quot;model&quot; /&gt;<br>&lt;/template&gt;</pre><p><strong>How we were handling this before Vue 3.4</strong></p><pre>&lt;script setup&gt;<br>const props = defineProps({<br>  modelValue: String,<br>  modelModifiers: { default: () =&gt; ({}) }<br>})<br>const emit = defineEmits([&#39;update:modelValue&#39;])<br>function emitValue(e) {<br>  let value = e.target.value<br>  if (props.modelModifiers.capitalize) {<br>    value = value.charAt(0).toUpperCase() + value.slice(1)<br>  }<br>  emit(&#39;update:modelValue&#39;, value)<br>}<br>&lt;/script&gt;<br>&lt;template&gt;<br>  &lt;input type=&quot;text&quot; :value=&quot;modelValue&quot; @input=&quot;emitValue&quot; /&gt;<br>&lt;/template&gt;</pre><p>For the more details:</p><ul><li><a href="https://vuejs.org/guide/components/v-model.html">https://vuejs.org/guide/components/v-model.html</a></li><li><a href="https://vuejs.org/api/sfc-script-setup.html#definemodel">https://vuejs.org/api/sfc-script-setup.html#definemodel</a></li><li><a href="https://www.youtube.com/watch?si=nmG0cy2YExzQIKsG&amp;v=lJ6mUrZfbWQ&amp;feature=youtu.be">https://www.youtube.com/watch?v=lJ6mUrZfbWQ</a> (a bit older one and uses old technics)</li><li><a href="https://medium.com/javascript-in-plain-english/vue-3-4-is-here-definemodel-and-why-it-matters-50ead5d3d1c1">https://medium.com/javascript-in-plain-english/vue-3-4-is-here-definemodel-and-why-it-matters-50ead5d3d1c1</a></li></ul><p>Stay tuned for more exciting <strong>Vue 3 features</strong>… <em>Keep rocking with Vue 3!</em> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3991bfca7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Memoization in JavaScript: Advanced Techniques with 10 Examples]]></title>
            <link>https://mustafacagri.medium.com/mastering-memoization-in-javascript-advanced-techniques-with-10-examples-6643dd0799ce?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/6643dd0799ce</guid>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[memoization]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 17:43:16 GMT</pubDate>
            <atom:updated>2023-08-26T17:43:16.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Diving into the ever-evolving realm of JavaScript optimization, there’s a standout technique that’s like a turbocharger for your code: <strong>memoization</strong>. Furthermore, sometimes it is called <strong>Javascript Memoize</strong>. This powerhouse approach involves storing the outcomes of demanding function calls and then using these cached results whenever you encounter the same inputs again. The result? A remarkable performance boost. Thus, buckle up as we embark on a journey to uncover the inner workings of <em>memoization</em>, its extensive array of advantages, and a comprehensive exploration of 10 complicated examples that truly highlight its incredible capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wWYyIPIL7lKa2ouhpcWMpg.png" /></figure><p>Unraveling the <em>Mysteries of Memoization Imagine</em> grappling with a knotty function, only to realize you’re summoning it over and over again with identical arguments. Enter memoization, swooping in to rescue you by preserving those computations and serving up instant outcomes. This not only wipes out redundant toil but also injects a hefty dose of efficiency into your application’s veins.</p><h3>Don’t hesitate to use powerful tools for Javascript Memoization</h3><p><strong>Memoization</strong> can be harnessed through diverse strategies, spanning from closures to objects, and even leveraging powerful libraries like Lodash. While basic memoization gets the job done for straightforward tasks, achieving mastery in the realm of intricate scenarios demands a firm grip on how to navigate a plethora of challenges.</p><h3>1. Fibonacci with Memoization</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F1%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F1%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c1be382c31e675634c097d1d1e55bd6/href">https://medium.com/media/8c1be382c31e675634c097d1d1e55bd6/href</a></iframe><p>This example demonstrates how to optimize the calculation of Fibonacci numbers using <em>memoization</em>. The memoizedFibonacci function returns a memoized version of the Fibonacci function. It uses a cache to store previously computed Fibonacci values and returns cached values if available, avoiding redundant calculations.</p><h3>2. Matrix Chain Multiplication</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F2%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F2%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/62955edffc7a6f935aef62323bd36576/href">https://medium.com/media/62955edffc7a6f935aef62323bd36576/href</a></iframe><p>The matrixChainOrder function tackles the problem of finding the optimal way to parenthesize matrix multiplication for the least number of operations. It uses memoization with the cache array to store calculated results for subproblems, which greatly reduces the number of redundant calculations.</p><h3>3. Longest Common Subsequence</h3><p>Imagine that you’re in a scenario resembling a senior JavaScript developer interview. Imagine being prompted to solve a particular problem. Of course, we’ll eventually examine the solution, but for now, let’s attempt to work through it independently. Just like in a real interview setting, we’ll take a crack at solving the problem on our own before we review the solution.</p><p>— — — — —</p><p>You are given two strings, str1 and str2. Write a function, longestCommonSubsequence, which returns the length of the longest common subsequence between these two strings and also provides the actual subsequence.</p><p>Implement the function using <strong>memoization</strong> to optimize the solution and avoid redundant calculations. The <em>memoization cache</em> should store the lengths of common subsequences for various indices in both strings.</p><p>Provide your solution along with an example that demonstrates the function’s correctness using the input:</p><ul><li>str1 = &quot;AGGTAB&quot;</li><li>str2 = &quot;GXTXAYB&quot;</li></ul><p>What is the length of the <strong>longest common subsequence</strong> between these two strings? Additionally, provide the actual longest common subsequence. Explain your approach and how memoization helps enhance the efficiency of the algorithm.</p><p>Expected Output:</p><pre>The length of the longest common subsequence is 4.<br>The longest common subsequence is &quot;GTAB&quot;.</pre><p>In your response, showcase both the implementation of the longestCommonSubsequence function, including the code that prints the subsequence, and an explanation of how the memoization technique optimizes the calculation of the longest common subsequence for the given input strings.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F3%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F3%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/83eac6e207447a52e505869bab24cde0/href">https://medium.com/media/83eac6e207447a52e505869bab24cde0/href</a></iframe><p>This example focuses on finding the longest common subsequence between two strings using memoization. The longestCommonSubsequence function employs a 2D cache to store already computed subsequence lengths. By avoiding recalculations through memoization, it optimizes the process of finding the longest common subsequence.</p><p>Here’s a step-by-step breakdown of the code:</p><p>1- Function Definition: longestCommonSubsequence(str1, str2)<br>This is the main function that takes two input strings, str1 and str2.</p><p>2- Cache Initialization:</p><pre>const cache = Array.from({ length: str1.length + 1 }, () =&gt; Array(str2.length + 1).fill(-1))</pre><p>This code creates a 2D array called cache to store the computed LCS lengths. The dimensions of the array are (str1.length + 1) x (str2.length + 1). Each entry in the array is initialized with -1, which will be used to mark unfilled cells.</p><p>3- Inner Function: lcs(i, j)</p><p>This is a recursive inner function that calculates the LCS length for substrings of str1 and str2 up to indices i and j respectively.</p><ul><li>If either of the indices (i or j) reaches 0, the LCS length is 0 because there are no characters left to compare.</li><li>If the value at cache[i][j] is not -1, it means the LCS length for these indices has already been calculated and stored in the cache. Return that value.</li><li>If the characters in the current positions i - 1 in str1 and j - 1 in str2 are equal, then the LCS length increases by 1 and the recursive call is made for the previous positions: lcs(i - 1, j - 1).</li><li>If the characters are not equal, the LCS length is the maximum of two possibilities: either excluding the character at position i from str1 (lcs(i - 1, j)) or excluding the character at the position j from str2 (lcs(i, j - 1)).</li><li>The calculated LCS length is stored in the cache and returned.</li></ul><p>4- Calculating the LCS Length:</p><pre>const length = lcs(str1.length, str2.length)</pre><p>The main function calculates the LCS length by calling the lcs function with the lengths of the entire input strings str1 and str2.</p><p>5- Constructing the LCS Subsequence:</p><pre>let subsequence = &#39;&#39;<br>let i = str1.length<br>let j = str2.length<br><br>while (i &gt; 0 &amp;&amp; j &gt; 0) {<br>  // ...<br>}</pre><p>This loop constructs the LCS subsequence by iterating backward through the cache array. Starting from the last cell in the cache, it examines whether the characters at the corresponding positions in str1 and str2 are equal or not. If they are equal, the character is part of the LCS, and we move diagonally up-left in the cache. If they are not equal, we decide which direction to move based on which adjacent cell has a greater value in the cache.</p><p>6- Returning the Result:</p><pre>return { length, subsequence }</pre><p>The function returns an object containing the calculated LCS length (length) and the LCS subsequence (subsequence).</p><p>7- Example Usage:</p><pre>const str1 = &#39;AGGTAB&#39;<br>const str2 = &#39;GXTXAYB&#39;<br>const { length, subsequence } = longestCommonSubsequence(str1, str2)</pre><p>This code demonstrates how to use the longestCommonSubsequence function with the example strings &#39;AGGTAB&#39; and &#39;GXTXAYB&#39;. The resulting length will be 4 and the subsequence will be &#39;GTAB&#39;.</p><p>In summary, the code uses a combination of dynamic javascript logic and backtracking to efficiently solve the <strong>Longest Common Subsequence</strong> problem and find both the length of the <strong>LCS</strong> and the actual subsequence itself.</p><h3>4. Memoization with Function Composition</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F4%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F4%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa703b16245093c36b92f2fd65b48872/href">https://medium.com/media/fa703b16245093c36b92f2fd65b48872/href</a></iframe><p>The composeMemoized function demonstrates how memoization can be applied to a composition of functions. It takes multiple functions as arguments and returns a new function that composes these functions while utilizing memoization to store and reuse intermediate results.</p><p>Here’s how the composeMemoized function works:</p><ol><li>A cache (Map) is created to store intermediate results of composed function calls.</li><li>The returned function (composed) accepts arguments that are passed through the composed chain of functions.</li><li>Before invoking the composed chain, a unique cache key is generated based on the provided arguments.</li><li>If the cache contains the result associated with the key, that result is returned immediately.</li><li>If not, the composed chain of functions is executed using the provided arguments.</li><li>Intermediate results are stored in the cache to avoid redundant calculations.</li><li>The final result is returned and stored in the cache for future reference.</li></ol><p>In this example, addOne and double are two simple functions. When composing them using composeMemoized, the composed function first doubles the input and then adds one to the result. The memoization ensures that if the same inputs are encountered again, the intermediate result is reused from the cache, eliminating the need for redundant calculations.</p><p>This technique is particularly useful when dealing with complex data transformations or when building a series of transformations that can benefit from memoization. It enhances both the readability and performance of your code by efficiently reusing previously calculated results.</p><h3>5. Coin Change Problem</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F6%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb321b9c04b93cbe974cd25fcdb79d62/href">https://medium.com/media/fb321b9c04b93cbe974cd25fcdb79d62/href</a></iframe><p>The <strong>Coin Change Problem</strong> is a classic dynamic programming problem that involves determining the minimum number of coins needed to make a certain amount. Given a set of coin denominations and an amount, the goal is to find the smallest number of coins required to make up that amount.</p><p>The coinChange function addresses the classic coin change problem using memoization. It efficiently calculates the minimum number of coins needed to make a given amount by caching subproblem results and avoiding redundant calculations.</p><p>In this code example, the coinChange function employs memoization to solve the Coin Change Problem efficiently.</p><p>1- A cache object (cache) is created to store the results of subproblems. The keys of the cache represent the remaining amounts to be achieved using the given coin denominations.</p><p>2- The dp (dynamic programming) function is defined. It takes an amount n as input and returns the minimum number of coins needed to make that amount.</p><p>3- Base cases are handled:</p><ul><li>If the remaining amount is 0, no coins are needed, so the function returns 0.</li><li>If the remaining amount is negative, it&#39;s not possible to make a change, so the function returns -1.</li><li>If the result is already present in the cache, it&#39;s returned to avoid redundant calculations.</li></ul><p>4- For each coin denomination in the coins array, the function recursively calculates the number of coins needed to make the remaining amount after subtracting the current coin&#39;s value. The minimum of these results is considered.</p><p>5- The minimum value is stored in the cache unless no valid combination of coins is found. In that case, -1 is stored to indicate that the amount cannot be achieved using the given coins.</p><p>6- The result for the given amount is returned, which represents the minimum number of coins needed.</p><p>In the example, with the coin denominations [1, 2, 5] and the amount 11, the optimal solution is to use one coin of denomination 5 and three coins of denomination 2, resulting in a total of 3 coins. Memoization helps avoid redundant calculations for various subproblem amounts, significantly improving the efficiency of finding the minimum number of coins required.</p><h3>6. Nth Tribonacci Number</h3><p>This example computes the <strong>nth Tribonacci number using memoization</strong>. The tribonacci function employs a cache to store previously computed Tribonacci numbers, ensuring that each value is calculated only once.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F7%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F7%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5478c1b8ceccb4b83b81f71f216b59/href">https://medium.com/media/9d5478c1b8ceccb4b83b81f71f216b59/href</a></iframe><p>In this example, the tribonacci function employs memoization to efficiently calculate the Nth Tribonacci number.</p><ol><li>A cache object (cache) is created to store the calculated Tribonacci values. The keys of the cache represent the indices of the Tribonacci sequence.</li><li>The calcTribonacci function is defined. It takes an index k as input and returns the k-th Tribonacci number.</li><li>Base cases are handled:<br>- If k is 0, return 0.<br>- If k is 1 or 2, return 1.<br>- If the result is already present in the cache, return it to avoid redundant calculations.</li></ol><ul><li>If k is 1 or 2, return 1.</li><li>If the result is already present in the cache, return it to avoid redundant calculations.</li></ul><ol><li>The Tribonacci value at index k is calculated by summing the three preceding Tribonacci values: calcTribonacci(k - 1) + calcTribonacci(k - 2) + calcTribonacci(k - 3).</li><li>The calculated value is stored in the cache to avoid recalculating it in the future.</li><li>The result for the requested index n is returned.</li></ol><h3>7. Palindromic Substrings Count</h3><p>Given a string, you need to count the number of palindromic substrings within it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F8%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F8%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/78ea9fbc338989a792b84487c7aa9b79/href">https://medium.com/media/78ea9fbc338989a792b84487c7aa9b79/href</a></iframe><p>In this example, the countPalindromicSubstrings function uses memoization to efficiently calculate the count of palindromic substrings within the given string.</p><ol><li>A cache object (cache) is created using a Map to store the results of subproblem checks. The keys of the cache are substrings.</li><li>The isPalindrome function is defined. It takes a substring str as input and checks whether it&#39;s a palindrome.</li><li>Base cases are handled:<br>- If the length of str is 0 or 1, it’s a palindrome (empty string or single character).<br>- If the result is already present in the cache, it’s returned to avoid redundant calculations.</li><li>The isPalindrome function checks if the first and last characters of str are the same and recursively checks the substring without those characters.</li><li>The result of the palindrome check is stored in the cache to avoid recalculating it in the future.</li><li>The main loop iterates through all possible substrings within the input string. For each substring, it checks if it’s a palindrome using the isPalindrome function.</li><li>The count of palindromic substrings is updated based on whether the current substring is a palindrome.</li><li>The final count of palindromic substrings is returned.</li></ol><p>In the example, calling countPalindromicSubstrings(&quot;ababa&quot;) calculates the count of palindromic substrings within the input string &quot;ababa.&quot; The memoization technique optimizes the palindrome checks for different substrings, eliminating redundant calculations and enhancing the efficiency of counting palindromic substrings.</p><p>This approach is particularly useful when dealing with problems that involve checking properties of substrings or subarrays, as it helps avoid repetitive calculations and significantly improves performance.</p><h3>8. Longest Increasing Subsequence</h3><p>Given an array of integers, you’re tasked with finding the length of the longest increasing subsequence.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F9%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F9%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0c14f9930e58da97638f90d4677469b/href">https://medium.com/media/c0c14f9930e58da97638f90d4677469b/href</a></iframe><p>In this example, the longestIncreasingSubsequence function uses memoization to efficiently calculate the length of the longest increasing subsequence within the given array.</p><ol><li>A cache object (cache) is created using a Map to store the results of subproblem calculations. The keys of the cache are indices in the input array.</li><li>The lisEndingAt function is defined. It takes an index as input and calculates the length of the longest increasing subsequence ending at that index.</li><li>Base case: If the index is 0, the function returns 1 (as a single element forms a valid subsequence).</li><li>If the result is already present in the cache, it’s returned to avoid redundant calculations.</li><li>The function iterates through the array elements from index 0 to the given index. For each element, it checks if it can be included in the increasing subsequence ending at the given index.</li><li>If the element at index i is smaller than the element at the given index, which means it can be included in the subsequence. The maximum length of subsequences ending at the index i is calculated, and the result is stored in maxLength.</li><li>The result of the calculation is stored in the cache to avoid recalculating it in the future.</li><li>The main loop iterates through all indices in the input array. For each index, it calculates the length of the longest increasing subsequence ending at that index.</li><li>The length of the longest increasing subsequence is updated based on the maximum length calculated for all indices.</li><li>The final length of the longest increasing subsequence is returned.</li></ol><p>In the example, calling longestIncreasingSubsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) calculates the length of the longest increasing subsequence within the input array. The memoization technique optimizes the subproblem calculations, eliminating redundant calculations and enhancing the efficiency of finding the length of the longest increasing subsequence.</p><p>This approach is particularly useful when solving problems involving sequence lengths, where subproblem calculations can be reused across different indices to avoid repetitive work and significantly improve performance.</p><h3>9. Matrix Chain Multiplication</h3><p>The <strong>Matrix Chain Multiplication</strong> problem involves finding the optimal way to parenthesize a sequence of matrices to minimize the total number of scalar multiplications required. Given a sequence of matrices with dimensions, you need to determine the minimum number of scalar multiplications needed to compute their product.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F10%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F10%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/436bb006e5c2763f3ba01b63d230be4a/href">https://medium.com/media/436bb006e5c2763f3ba01b63d230be4a/href</a></iframe><p>In this example, the matrixChainOrder function uses memoization to efficiently calculate the optimal number of scalar multiplications required to multiply a sequence of matrices.</p><ol><li>A cache matrix (cache) is created to store the results of subproblem calculations. The dimensions of the cache are (n x n), where n is the number of matrices in the sequence.</li><li>The mcm function is defined. It takes two indices i and j as input, representing the range of matrices to consider.</li><li>Base case: If i and j are the same, it means only one matrix is left, so no multiplication is needed (0).</li><li>If the result for the current range is already present in the cache, it’s returned to avoid redundant calculations.</li><li>The function iterates through all possible ways to split the current range into two subranges (i to k and k + 1 to j). For each split point k, the cost of parenthesizing the matrices in the subranges is calculated.</li><li>The cost is calculated as the sum of:<br>- The cost of multiplying the matrices in the first subrange (mcm(i, k)).<br>- The cost of multiplying the matrices in the second subrange (mcm(k + 1, j)).<br>- The cost of multiplying the two resulting matrices (p[i — 1] * p[k] * p[j], where p is the matrix dimensions array).</li><li>The minimum cost among all possible split points is determined and stored in the cache for the current range.</li><li>The final result is the optimal number of scalar multiplications required to multiply the entire sequence of matrices (mcm(1, n - 1)).</li></ol><p>In the example, calling matrixChainOrder([10, 30, 5, 60]) calculates the optimal number of scalar multiplications required to multiply a sequence of matrices with the given dimensions. The memoization technique optimizes the subproblem calculations, eliminating redundant calculations and enhancing the efficiency of finding the optimal number of scalar multiplications.</p><p>This approach is particularly useful for optimizing problems involving matrix multiplication, where subproblem solutions can be cached and reused to avoid repetitive calculations and significantly improve performance.</p><h3>10. Longest Common Subsequence (Tabulation)</h3><p>The Longest Common Subsequence (LCS) problem involves finding the length of the longest common subsequence between two sequences. Tabulation is a dynamic programming technique where you build a table iteratively to find the solution.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F11%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2F58eaf6d9%2F11%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/050dc423e0b5f82886fa5aaba38b34ee/href">https://medium.com/media/050dc423e0b5f82886fa5aaba38b34ee/href</a></iframe><p>In this example, the longestCommonSubsequence function uses tabulation to efficiently calculate the length of the longest common subsequence between two input strings.</p><ol><li>The dimensions of the tabulation table (dp) are (m + 1) x (n + 1), where m is the length of str1 and n is the length of str2.</li><li>The outer loop iterates through the indices of str1 (from 1 to m), and the inner loop iterates through the indices of str2 (from 1 to n).</li><li>For each pair of characters at the current indices (i, j):<br>- If the characters match, the value at dp[i][j] is set to dp[i — 1][j — 1] + 1, as the current characters contribute to the common subsequence length.<br>- If the characters don’t match, the value at dp[i][j] is set to the maximum of dp[i — 1][j] and dp[i][j — 1], as the current characters do not contribute to the common subsequence length.</li><li>After iterating through all possible pairs of indices, dp[m][n] holds the length of the longest common subsequence between str1 and str2.</li></ol><p>In the example, calling longestCommonSubsequence(&quot;AGGTAB&quot;, &quot;GXTXAYB&quot;) calculates the length of the longest common subsequence between the given strings. The tabulation technique builds the dynamic programming table iteratively, storing intermediate results and effectively finding the length of the longest common subsequence.</p><p>Tabulation is particularly useful when solving dynamic programming problems that involve building a table to keep track of intermediate solutions. It offers an efficient bottom-up approach to solving problems by iteratively filling in the table based on previously computed values.</p><p>In the example, calling tribonacci(10) calculates the 10th Tribonacci number in the sequence. The memoization technique ensures that previously calculated Tribonacci values are reused, eliminating redundant calculations and enhancing the efficiency of finding the Nth Tribonacci number.</p><p>By using memoization, the function can efficiently handle larger values of n without getting trapped in redundant calculations. This approach greatly improves the performance of solving problems related to sequence calculations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6643dd0799ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Closures in JavaScript: A Beginner’s Guide]]></title>
            <link>https://mustafacagri.medium.com/understanding-closures-in-javascript-a-beginners-guide-37ab5b059e37?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ab5b059e37</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[memoization]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 14:41:12 GMT</pubDate>
            <atom:updated>2023-03-05T14:41:12.823Z</atom:updated>
            <content:encoded><![CDATA[<p>A closure in JavaScript is a function that has access to its outer function’s variables and parameters, even after the outer function has returned. This means that closure can remember and access variables in the scope in which it was created, even if the function that created it has completed execution and its scope has been destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OK-sTb7tqtrAj9gyg9PQCg.png" /></figure><p>A closure is created when an inner function references a variable from an outer function. The inner function preserves a reference to the outer function’s variable, and that reference is called a closure.</p><h3>Why Use Closures?</h3><p>Closures are beneficial since they enable the development of private variables and functions in JavaScript. Such variables and functions can only be accessed within the scope of the function in which they were defined.</p><p>The closures feature will make your code deeply clear and modular. Suppose there is a need to keep a count within a function while ensuring that the count variable is not accessible from outside the function. In that case, a closure can be utilized to create a confidential counter variable.</p><h3>Private Variables In Closures</h3><p>Let’s say we have a function that needs to keep track of a counter, however, we do not want the counter to be accessible from outside the function. We can use a closure to create a private counter variable, like this:</p><pre>function counter() {<br>  let myCounter = 0<br>  <br>  return function() {<br>    myCounter++;<br>    console.info(myCounter, &#39;myCounter&#39;)<br>  }<br>}</pre><pre>const increaseCounter = counter()</pre><pre>increaseCounter() // 1<br>increaseCounter() // 2<br>increaseCounter() // 3</pre><p>Let’s have a look at the code a bit, the <em>handleClick</em> function generates a nested function that can access the count variable. To use this function as the callback for the <em>addEventListener</em> method, we assign it to the <em>incrementClickCount</em> variable. Each time the button is clicked, the <em>incrementClickCount</em> function is invoked and the count variable is increased. Because the count variable is defined inside the handleClick function, it cannot be accessed outside the function, thereby making it a private variable.</p><h3>Event Listeners In Closures</h3><p>Closures are also most commonly used with event listeners. Let’s say we have a button that we want to add a click event listener to, however, we want to keep track of how many times the button has been clicked. We can use a closure to create a private cliced variable and attach an event listener to the button like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*82g7peuGaj4bKY6O3YOarg.png" /><figcaption>Event Listeners In Closures</figcaption></figure><pre>&lt;button id=&quot;myButton&quot;&gt;Click me&lt;/button&gt;</pre><pre>&lt;script&gt;<br>  const myButton = document.getElementById(&#39;myButton&#39;);<br>  <br>  function handleClick() {<br>    let clicked = 0;<br>    <br>    return function() {<br>      clicked++;<br>      console.info(`Button clicked ${clicked} times`);<br>    }<br>  }<br>  <br>  const increaseClickCount = handleClick();<br>  <br>  myButton.addEventListener(&#39;click&#39;, increaseClickCount);<br>&lt;/script&gt;</pre><p>In this example, the handleClick function returns an inner function that has access to the clicked variable. We set the increaseClickCount variable to the returned inner function so that we can pass it as the callback function to the addEventListener method.</p><p>Whenever we click the button, increaseClickCount the function will be executed then our variable clicked will be increased. Since the clicked variable is declared within the handleClick function, it is not accessible from outside the function, making it a private variable.</p><h3>Implementing a Private Module</h3><p>Closures can also be used to create <em>private modules</em> in <strong>JavaScript</strong>. A private module is a module that has private variables and functions that are not accessible from outside the module.</p><pre>const calculator = (function() {<br>  let result = 0;</pre><pre>  function add(x) {<br>    result += x;<br>  }</pre><pre>  function subtract(x) {<br>    result -= x;<br>  }</pre><pre>  function multiply(x) {<br>    result *= x;<br>  }</pre><pre>  function divide(x) {<br>    result /= x;<br>  }</pre><pre>  function getResult() {<br>    return result;<br>  }</pre><pre>  return {<br>    add: add,<br>    subtract: subtract,<br>    multiply: multiply,<br>    divide: divide,<br>    getResult: getResult<br>  }<br>})();</pre><pre>calculator.add(5);<br>calculator.multiply(2);<br>console.info(calculator.getResult()); // prints 10</pre><p>In this code block, the calculator variable is assigned to an immediately invoked function expression (<em>IIFE</em>) that returns an object containing functions that can be used to perform arithmetic operations. The result variable is declared within the closure of the IIFE and is not accessible from outside the calculator module. This allows us to create a private module with private variables and functions that can only be accessed through the functions that are returned from the module.</p><p>These examples show the flexibility and usefulness of <strong>closures in JavaScript development</strong>. By leveraging the power of closures, we can create more modular, maintainable, and efficient code.</p><h3>Implementing Callback Functions</h3><p>Closures are commonly used in JavaScript to implement callback functions, too. A callback function is a function that is passed as an argument to another function and is executed when a certain event occurs or when a certain condition is happen.</p><pre>function waitThenDo(callback, time) {<br>  setTimeout(function() {<br>    callback();<br>  }, time);<br>}</pre><pre>function sayHello() {<br>  console.info(&#39;Hello!&#39;);<br>}<br>waitThenDo(sayHello, 1000); // waits 1 second before logs &#39;Hello!&#39;</pre><p>In this example, the waitThenDo() function takes two arguments.</p><p>1-) a callback function</p><p>2-) a time in milliseconds.</p><p>It uses the setTimeout() method to delay the execution of the callback function by the specified time. When the time has passed, the callback function is run. In this case, the sayHello() function is executed as the callback function and is run after a delay of 1 second.</p><h3>Creating a Memoized Function in Closures</h3><p>A memoized function is a function that caches the results of previous function calls and returns the cached result when the same input is used again. This technique can be used to optimize functions that are computationally expensive or have repetitive calculations. And in my opinion, this most functional thing for the closures in Javascript developments. Also, I believe that this sub-title -memoized functions- needs to be explained in a separate blog post and this functionally improves the performance indeed. Whenever we can use it, we must use it, it should not be an optional way to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*LiXkh_wyhzxUyPlo1BB1dA.png" /><figcaption>Creating a Memoized Function in Closures</figcaption></figure><pre>function memoize(func) {<br>  const cache = {};<br><br>  return function(...args) {<br>      const key = JSON.stringify(args)<br><br>      if (cache[key]) {<br>        console.info(&#39;Returning from cache...&#39;)<br><br>        return cache[key]<br>      }<br><br>      console.info(&#39;Calculating result...&#39;)<br>      const result = func.apply(this, args)<br>      cache[key] = result<br><br>      return result<br>    }<br>  }<br><br>  function expensiveFunction(x, y) {<br>    console.info(&#39;Calculating...&#39;)<br><br>    return x * y<br>}<br><br>const memoizedFunction = memoize(expensiveFunction)<br>console.log(memoizedFunction(5, 10)) // Calculating result...50<br>console.log(memoizedFunction(5, 10)) // Returning from cache...50<br>console.log(memoizedFunction(10, 20)) // Calculating result...200<br>console.log(memoizedFunction(10, 20)) // Returning from cache...200</pre><p>Here the memoize() function takes a function as input and returns a new function that caches the results of previous function calls. The cached results are stored in the cache object, which is declared within the closure of the returned function. When the returned function is called with the same input, it returns the cached result instead of recalculating it. Therefore, we will not spend our resources since we are returning the result from the cache instead of calculating again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*3OySq3h360cM63Sk0kU3_g.png" /><figcaption>5 Reasons to use Closures</figcaption></figure><h3>Unlock the Power of JavaScript with this Comprehensive Guide to Closures for Beginners</h3><p>With <strong>closures in JavaScript</strong>, you can take your coding skills to the next level and write more secure, efficient, and modular code.</p><p>By mastering the concepts and examples of closures in JavaScript, beginners can take their coding skills to the next level and create more efficient and powerful JavaScript applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ab5b059e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MEVN Stack Boilerplate — Vue 3, Nuxt 3, Express.js, Node.js, Vuetify, Pinia]]></title>
            <link>https://mustafacagri.medium.com/mevn-stack-boilerplate-vue-3-nuxt-3-express-js-node-js-vuetify-pinia-ad6849ba4ee5?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6849ba4ee5</guid>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sat, 04 Feb 2023 15:21:13 GMT</pubDate>
            <atom:updated>2023-09-24T16:25:39.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>MEVN Stack Boilerplate — Vue 3, Nuxt 3, Express.js, Node.js, Vuetify, Pinia</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jnEUMdQS_idDDYNu.png" /></figure><p>Hey there, in this blog post, we will talk about the <a href="https://github.com/mustafacagri/mevn-boilerplate"><strong>MEVN Stack Boilerplate</strong></a> that I published on <strong>GitHub</strong> some days ago. If you are interested in V<em>ue 3</em>, N<em>uxt 3</em>, N<em>ode.js</em>, E<em>xpress.js</em>, or <em>MongoDB</em> technologies, you may make a quick start with this boilerplate. Because of its features/structure and low learning curve, I think it will provide you with an important contribution.</p><p>In addition, if you have any features that you think would be nice to add, please don’t hesitate to open a PR and contribute to the repository. Also, if you come across a bug, you can open an issue related to the subject.</p><p>Let’s start by discussing the main interesting parts of this boilerplate:</p><ul><li>MongoDB</li><li>Express</li><li>Vue 3 (Admin Dashboard)</li><li>Node.js</li><li>+ Nuxt3 (Client)</li></ul><p>Furthermore, this boilerplate includes <strong>Vuetify</strong> and <strong>Vuexy</strong> in its admin dashboard. Moreover, I used <strong>Pinia</strong>, which was introduced into our lives with <strong>Vue 3</strong>, for <em>store management</em>. Besides these, a few other technologies used are <em>Multer</em>, <em>Slug</em>, <em>Lodash,</em> and more.</p><figure><img alt="MENV Stack Boilerplate — Vue 3 - Vuext Admin Dashboard" src="https://cdn-images-1.medium.com/max/1010/0*AXVhb_L9eou2FwCX.png" /></figure><p><a href="https://github.com/mustafacagri/mevn-boilerplate/assets/7488394/aca14f0a-af96-4019-8be2-ad9d13f3e9d7">https://github.com/mustafacagri/mevn-boilerplate/assets/7488394/aca14f0a-af96-4019-8be2-ad9d13f3e9d7</a>s</p><p><em>The video was added on September 24, 2023</em></p><p>In the dashboard, I chose <strong>vuetify</strong> which I have been actively using for over two years. However, to include better structures in the basic elements of vuetify, I chose the <strong>vuexy</strong> theme based on vuetify.</p><p>Since it’s a classic <strong>Vue 3 application</strong>, I won’t go into the details of it at this time. However, if you haven’t met Vue 3 yet and are curious about how it is, it will provide you with an important contribution to your learning. For example, some improvements that seem simple, such as using &lt;script setup&gt; without an unnecessary container (such as &lt;div&gt;, etc…) in the template, using variables directly in the template without returning them in the setup, and the project starting up in less than 1-second thanks to <strong>Vite</strong>, make <em>Vue 3</em> more developer-friendly.</p><p>You will also find active use of <strong>pinia</strong> both on the admin side (<em>Vue3</em>) and the client (<em>Nuxt3</em>) side.</p><h3>API — Node.js &amp; Express.js</h3><p>On the backend side, we use this amazing duo (<em>Node.js</em> &amp; <em>Express.js</em>).</p><figure><img alt="Mevn Stack Boilerplate — Server Folder Structure" src="https://cdn-images-1.medium.com/max/570/0*PKlIfc9CUSmzKI6x.png" /></figure><p>Gradually, we may start talking about what this boilerplate is.</p><figure><img alt="MEVN Boilerplate — Express Helper Classes" src="https://cdn-images-1.medium.com/max/690/0*7OfebinM9UsKfFQo.png" /></figure><p><strong>Classes</strong></p><p>In this folder, we have helper classes/functions that I usually prefer to use in classes.</p><p><em>UrlGenerator.js</em></p><p>When creating a record in the database, we want to fill the URL / slug column. However, what if that URL has been used before? If we add a repeated URL, we will not be able to access the first or last record. Therefore, with the help of this helper class, we check whether the needed URL is already in use in the related table/collections. If it is in use, we add numbers (up to 10) to the end of it.</p><p>For example, we want to create a record with the URL “first-post”. But if “first-post-1” and “first-post-2” have already been recorded, we give the new record the URL “first-post-3”. If all the URLs up to “first-post-10” are already in use, we give the new record the URL “first-post-1674932835” (timestamp). The goal here is to create URLs that are SEO-friendly.</p><pre>const slug = require(&#39;slug&#39;)<br><br>async function UrlGenerator(url, document) {<br>  url = slug(url) // let&#39;s slug it before we start<br>  const currentDoc = require(`../../models/${document}`)<br>  let tempUrl = url<br>  cur = 0<br>  check = false<br><br>  while (!check &amp;&amp; cur &lt; 10) {<br>    const data = await currentDoc.findOne({ url: tempUrl })<br><br>    if (!data) {<br>      check = true<br>    } else {<br>      cur++<br>      tempUrl = `${url}-${cur}`<br>    }<br>  }<br><br>  if (cur === 10) {<br>    const d = new Date()<br>    tempUrl += &#39;-&#39; + d.getTime() // if we try it more than 10, we will give up to find an url and we will only add the timestamp suffix<br>  }<br><br>  url = tempUrl<br><br>  return url<br>}<br><br>module.exports = UrlGenerator</pre><p>Now let’s take a look at the response folder. With the files in this folder, we ensure that the returns we make from our API to the front end are in certain patterns. You will also see that it brings us ease and speed.</p><p><em>dynamic.js</em></p><p>With dynamic.js, we have the opportunity to only return certain fields within the controller. For example, we need to return only certain fields related to the user (of course, we don’t want to return the user’s password, right?), in this case, we can create new data with a map. But, with this structure, we can quickly perform the return process.</p><p>An example usage:</p><pre>res.json(new response.dynamic([‘_id’, ‘username’, ‘email’, ‘roles’], res.user))</pre><pre>// this function only works for objects not arrays<br>// for arrays, you need to use &quot;map&quot;<br><br>const success = require(&#39;./success&#39;)<br>const fail = require(&#39;./fail&#39;)<br>const ErrorResponse = require(&#39;../../utils/errorResponse&#39;)<br><br>function dynamic(list, data) {<br>  const arr = {}<br>  if (list &amp;&amp; data) {<br>    list.forEach(item =&gt; {<br>      arr[item] = data[item]<br>    })<br>    // here we are only returning the necessary fields which is coming from with &quot;list param&quot;<br><br>    return new success(arr)<br>  } else {<br>    return new fail(&#39;No data found&#39;)<br>  }<br>}<br><br>module.exports = dynamic</pre><p><strong>fail.js</strong></p><p>The fail.js file helps us understand that the response from the API was incorrect on the front end. There are two properties for this purpose: <em>isSuccess</em> and <em>message</em>.</p><p>We can understand that the response was incorrect with <strong>isSuccess</strong>. And we can send our message to the front end with the <strong>message</strong>.</p><p>We also log this through the logger.</p><p>Here, we take advantage of the built-in error types in JS. For more information, you can check out the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Mozilla developer page</a>.</p><pre>const logger = require(&#39;../../utils/logger&#39;)<br>class FailedResponse extends Error {<br>  constructor(message) {<br>    // super(message)<br>    super()<br>    this.message = message<br>    this.isSuccess = false<br>    logger.error(`Error.Name: ${this.name} - Error.Stack: ${this.stack}`)<br>  }<br>}<br><br>module.exports = FailedResponse</pre><p><strong>failed.js</strong></p><p>This is a shortened version of fail. In the case of returns that we already know to be incorrect, only sending the message is sufficient.</p><p><strong>success.js</strong></p><p>Here we convey our successful returns to the front end.</p><pre>class Response {<br>  constructor(data,  count = null,  pagination = null, message = null) {<br>    this.isSuccess = true<br>    this.data = data<br>    this.count = count<br>    this.message = message<br>    this.pagination = pagination<br>  }<br>}<br><br>module.exports = Response</pre><p>In this, there are properties like data, count, pagination, etc.</p><p>data: as the name suggests, we transfer our data. count: we inform how many records there are. Thanks to this, in some cases, we can directly show the record count on the screen without having to use <em>data.length</em> extra. pagination: this can be our most important property. Because of this, we can show previous, next, etc. pages on the front end.</p><p>And with dbQuery.js, which we will talk about soon, we can quickly return data/count/pagination from the routes.</p><p><em>successed.js</em></p><p>Just like failed.js, it’s a convenient shortcut.</p><p><em>user / mail.js</em></p><p>For now, we only have a <em>validateEmail</em> function in this structure.</p><p>Yes, we can summarize our classes folder in this way. Let’s move on to our next folder.</p><h3>Config</h3><p><strong>auth.js</strong>: This is our file for database authentication operations. Our authentication secret is located here.</p><p><strong>db.js</strong>: This is where we establish our connection with <em>MongoDB</em>.</p><h3>Controllers</h3><p>There are currently two different controllers available.</p><p><strong>Admin</strong></p><p>We don’t want the data we will use in our admin dashboard to be accessible from the client, do we? Therefore, only those with administrator tokens can access the data here.</p><p>In the controllers in the main controllers folder (with some exceptions, such as membership requirements, etc.), we aim for everyone to be able to access them.</p><p><strong>Middlewares</strong></p><p>We create these middlewares to avoid duplications in structures that will be needed multiple times. I would like to specifically mention two middlewares.</p><p><strong>dbQuery.j</strong>s</p><p>With dbQuery.js, we can dynamically fetch data without needing any controllers in the router. Thanks to this middleware and <strong>response.success</strong>, we can easily return data, count, and pagination.</p><p>This is a part that could be explained in much more detail, however, I will briefly mention it for now. However, you can see various examples within the routers as well.</p><pre>const { response } = require(&#39;../../classes&#39;)<br><br>const dbQuery =<br>  (model, populate = [], willNotReturn = []) =&gt;<br>  async (req, res, next) =&gt; {<br>    const CONTANTS = { limitPerPage: 25, defaultPage: 1 }<br><br>    let query<br>    willNotReturn.push(&#39;__v&#39;)<br><br>    // Copy req.query<br>    const reqQuery = { ...req.query }<br><br>    // Fields to exclude<br>    const removeFields = [&#39;select&#39;, &#39;sort&#39;, &#39;page&#39;, &#39;limit&#39;]<br><br>    // Loop over removeFields and delete them from reqQuery<br>    removeFields.forEach(param =&gt; delete reqQuery[param])<br><br>    // Create query string<br>    let queryStr = JSON.stringify(reqQuery)<br><br>    // Create operators ($gt, $gte, etc)<br>    queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in)\b/g, match =&gt; `$${match}`)<br><br>    // Finding resource<br>    query = model.find(JSON.parse(queryStr))<br><br>    // Select Fields<br>    if (req.query.select) {<br>      const fields = req.query.select.split(&#39;,&#39;).join(&#39; &#39;)<br>      query = query.select(fields)<br>    }<br><br>    // Sort<br>    if (req.query.sort) {<br>      const sortBy = req.query.sort.split(&#39;,&#39;).join(&#39; &#39;)<br>      query = query.sort(sortBy)<br>    } else {<br>      query = query.sort(&#39;-createdAt&#39;)<br>    }<br><br>    // Pagination<br>    const page = parseInt(req.query.page, 10) || CONTANTS.defaultPage<br>    const limit = parseInt(req.query.limit, 10) || CONTANTS.limitPerPage<br>    const startIndex = (page - 1) * limit<br>    const endIndex = page * limit<br>    const total = await model.countDocuments(JSON.parse(queryStr))<br><br>    query = query.skip(startIndex).limit(limit)<br><br>    if (populate.length &gt; 0) {<br>      populate.forEach(p =&gt; {<br>        query = query.populate(p)<br>      })<br>    }<br><br>    // // Executing query<br>    let results = await query<br><br>    results = JSON.stringify(results)<br>    results = JSON.parse(results)<br>    // map does not with only results.map if we do not stringify then parse it. strange, right? any idea?<br><br>    results.map(item =&gt; {<br>      return willNotReturn.forEach(willBeDeleted =&gt; delete item[willBeDeleted])<br>    })<br><br>    // Pagination result<br>    const pagination = {}<br><br>    if (endIndex &lt; total) {<br>      pagination.next = {<br>        page: page + 1,<br>        limit<br>      }<br>    }<br><br>    if (startIndex &gt; 0) {<br>      pagination.prev = {<br>        page: page - 1,<br>        limit<br>      }<br>    }<br><br>    res.dbQuery = new response.success(results, results.length, pagination)<br><br>    next()<br>  }<br><br>module.exports = dbQuery</pre><p><strong>error.js</strong></p><p>As its name suggests, it helps us to easily overcome errors.</p><p><strong>Models</strong></p><p>Our models folder — contains our table/collection structures.</p><p><strong>Public</strong></p><p>The folder contains images that we will only use in our posts for now.</p><p><strong>Routes</strong></p><p>Our folder contains our routes. Everything mentioned in the Controllers section is also applicable here.</p><p><strong>Utils</strong></p><p>The folder contains tools that can make our job easier. Currently, it holds the <em>errorResponse.js</em> and <em>logger.js</em> files.</p><p>Yes, the API side is summarized as follows.</p><p>The client-side prepared with <em>Nuxt 3</em> looks as follows. I didn’t use any UI framework like vuetify. It can be seen as a <strong>Nuxt 3</strong> project consisting of only basic CSS (I also added a part of bootstrap’s CSS directly to avoid too much effort in responsiveness).</p><p>The footer comes from a <a href="https://github.com/mustafacagri/vue-js-footer"><strong>Vue JS Footer</strong></a> project that I shared a few years ago on <a href="https://github.com/mustafacagri/"><strong>GitHub</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ds-DjYxY2ofg6zZF.png" /></figure><p>Also, I will discuss the Client and Admin sides over time. You can also take a look at the repo for more detailed usage information.</p><p><a href="https://github.com/mustafacagri/mevn-boilerplate"><strong>https://github.com/mustafacagri/mevn-boilerplate</strong></a></p><p>As I mentioned earlier, feel free to contribute to the repo for any detail that comes to your mind. Such as creating PRs or Issues… You may also contribute by giving stars to the repo.</p><p>Let’s grow the open-source world together…</p><p>Open Source ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6849ba4ee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MEVN Stack Boilerplate — Vue 3, Nuxt 3, Express, Vuetify]]></title>
            <link>https://mustafacagri.medium.com/mevn-stack-boilerplate-vue-3-nuxt-3-express-vuetify-201b13618d1a?source=rss-80d6a2e50a29------2</link>
            <guid isPermaLink="false">https://medium.com/p/201b13618d1a</guid>
            <category><![CDATA[mevn-stack]]></category>
            <category><![CDATA[boilerplate]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <dc:creator><![CDATA[Mustafa Çağrı Güven]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 11:41:37 GMT</pubDate>
            <atom:updated>2023-01-29T11:41:37.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>MEVN Stack Boilerplate — Vue 3, Nuxt 3, Express, Vuetify</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nez1VGzE9Q-8_hM7YxX_jQ.png" /></figure><p>Selamlar, bu yazıda geçtiğimiz günlerde <strong>Github</strong>’da yayınladığım <a href="https://github.com/mustafacagri/mevn-boilerplate"><strong>MEVN Stack Boilerplate</strong></a> konusuna değineceğim. Eğer <em>vue 3</em>, <em>nuxt 3</em>, <em>node.js</em>, <em>express.js</em>, <em>mongodb </em>teknolojilerine ilgi duyuyorsanız, bu boilerplate ile hızlı bir başlangıç yapabilirsiniz. Basit olmaktan uzak özellikleri / yapısı ve de öğrenme eşiğinin bir hayli düşük olması sebebiyle, size önemli bir katkı sağlayacağını düşünüyorum.</p><p>Bunun yanı sıra, eğer eklenmesinin güzel olacağını düşündüğünüz özellikler varsa da lütfen PR açmaktan ve repoya katkı sağlamaktan çekinmeyiniz. Ayrıca, gözünüze çarpan bir hata olursa da konuyla alakalı bir Issue açabilirsiniz.</p><p>Bu boilerplate’in başlıca ilgi çeken kısımlarına ise hemen değinmeye başlayabiliriz:</p><ul><li>Mongodb</li><li>Express</li><li>Vue 3 (Admin Dashboard)</li><li>Node.js</li><li>+ Nuxt3 (Client)</li></ul><p>Bunların yanı sırada bu boilerplate’in admin dashboard’unda <strong>vuetify</strong> ve <strong>vuexy</strong> yer almaktadır. Ayrıca, store management olarak da vue 3 ile hayatımıza giren <strong>pinia</strong>’yı kullandım. Bunların yanı sıra kullanılan diğer teknolojilerden birkaçı ise: multer, slug, lodash…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*eutryCYNxIXxo9894yZOlQ.png" /></figure><p>Dashboard’da 2 seneyi geçen bir süredir aktif olarak kullandığım vuetify’ı tercih ettim. Ancak, vuetify’ın temel elementlerine daha güzel yapılar dahil etmek için de vuetify’ı baz alan vuexy temasını tercih ettim.</p><p>Klasik bir Vue 3 uygulaması olduğu için şu anda bunun detaylarına çok fazla girmeyeceğim. Ancak, Vue 3 ile henüz tanışmadıysanız ve nasıl olduğunu merak ediyorsanız, öğrenmenize önemli bir katkı sağlayacaktır. Öyle ki, bazı basit gibi görünsede yapılan iyileştirmeler Vue 3&#39;ü daha kullanışlı kılıyor. Örneğin; &lt;script setup&gt;, template içesisinde gereksiz bir container olmadan (&lt;div&gt; vs..) kullanabilme, setup içerisinde tanımladığınız değişkenleri return etmeden template içerisinde direkt olarak kullanabilme, vite sayesinde projenin 1 saniyeden daha kısa sürede ayağa kalması…</p><p>Ayrıca, <strong>pinia</strong>’nın aktif olarak kullanımı da hem admin tarafında (<strong>Vue3</strong>) hem de client (<strong>Nuxt3</strong>) tarafında bulabilirsiniz.</p><h3>API — Node.js &amp; Express.js</h3><p>Backend tarafında bu muhteşem ikiliyi (Node.js &amp; Express.js) kullanıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*qNzBSOP9tglyP3fkGVwTvg.png" /></figure><p>Yavaş yavaş, bu boilerplate’in nelere sahip olduğuna değinmeye başlayabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*I1J7rsYUzp8n_5wTS8dOUg.png" /></figure><h3>Classes</h3><p>Bu klasör içerisinde utils’e de girebilecek ancak benim genellikle classes içerisinde kullanmayı tercih ettiğim yardımcı class’larımız / fonksiyonlarımız yer alıyor.</p><p><strong>UrlGenerator.js</strong></p><p>Veritabanına bir kayıt açarken, url / slug sütununu doldurmak istiyoruz. Peki, daha önceden bu url kullanıyorsa ne yapacağız? Tekrarlanan bir url eklersek, sonradan / ilk oluşan kayda ulaşamayacağımız aşikar. Bu nedenle de bu yardımcı class aracılığıyla ilgili tabloya / collections’a giderek, daha önceden ihtiyacımız olan url kullanılıyor mu, kontrol ediyoruz. Eğer kullanıyorsa, sırasıyla sonuna (10&#39;a kadar) rakamlar ekliyoruz.</p><p>Örneğin: first-post url’sine sahip bir kayıt oluşturmak istiyoruz. Ama daha önceden first-post-1 ve first-post-2 kayıtlıysa, biz bu yeni kaydımıza first-post-3 url’sini veriyoruz. Eğer ki first-post-10&#39;a kadar tüm url’ler doluysa da first-post-1674932835 (timestamp) url’sini veriyoruz. Buradaki amaç seo uyumulu url’ler oluşturmak.</p><pre>const slug = require(&#39;slug&#39;)<br><br>async function UrlGenerator(url, document) {<br>  url = slug(url) // let&#39;s slug it before we start<br>  const currentDoc = require(`../../models/${document}`)<br>  let tempUrl = url<br>  cur = 0<br>  check = false<br><br>  while (!check &amp;&amp; cur &lt; 10) {<br>    const data = await currentDoc.findOne({ url: tempUrl })<br><br>    if (!data) {<br>      check = true<br>    } else {<br>      cur++<br>      tempUrl = `${url}-${cur}`<br>    }<br>  }<br><br>  if (cur === 10) {<br>    const d = new Date()<br>    tempUrl += &#39;-&#39; + d.getTime() // if we try it more than 10, we will give up to find an url and we will only add the timestamp suffix<br>  }<br><br>  url = tempUrl<br><br>  return url<br>}<br><br>module.exports = UrlGenerator</pre><p>Şimdi de response klasörüne göz atalım. Bu klasördeki dosyalar sayesinde API’ımızdan front end’e yaptığımız return’lerin belli kalıplarda olmasını sağlıyoruz. Ayrıca, bize kolaylık ve hız kazandırdığını da göreceksiniz.</p><p><strong>dynamic.js</strong></p><p>dynamic.js ile controller içerisinde sadece belli field’ları return edebilme olanağına kavuşuyoruz. Örneğin, userla alakalı sadece belli field’ları dönmemiz gerekiyor (elbette kullanıcının şifresini dönmek istemeyiz değil mi?), bu durumda map ile yeni bir data oluşturabiliriz. Ancak, bu yapı sayesinde return işlemini hızlıca yapabiliyoruz.</p><p>Örnek bir kullanım:</p><blockquote>res.json(new response.dynamic([‘_id’, ‘username’, ‘email’, ‘roles’], res.user))</blockquote><pre>// this function only works for objects not arrays<br>// for arrays, you need to use &quot;map&quot;<br><br>const success = require(&#39;./success&#39;)<br>const fail = require(&#39;./fail&#39;)<br>const ErrorResponse = require(&#39;../../utils/errorResponse&#39;)<br><br>function dynamic(list, data) {<br>  const arr = {}<br>  if (list &amp;&amp; data) {<br>    list.forEach(item =&gt; {<br>      arr[item] = data[item]<br>    })<br>    // here we are only returning the necessary fields which is coming from with &quot;list param&quot;<br><br>    return new success(arr)<br>  } else {<br>    return new fail(&#39;No data found&#39;)<br>  }<br>}<br><br>module.exports = dynamic</pre><p><strong>fail.js</strong></p><p>Front end tarafında, API’dan gelen sonucun hatalı olduğunu anlamamıza yarıyor. Bunu anlayabilmek için iki tane property’miz mevcut. <em>isSuccess </em>ve <em>message</em>.</p><p><strong>isSuccess</strong> ile dönüşümüzün hatalı olduğunu anlıyoruz. <strong>message</strong> ile de mesajımızı front end’e iletiyoruz.</p><p>Ayrıca, logger vasıtasıyla da bunu log’luyoruz.</p><p>Burada JS’in built-in error türlerinden faydalanıyoruz. Daha detaylı bilgi için <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Mozilla’nın developer sayfasına</a> göz atabilirsiniz.</p><pre>const logger = require(&#39;../../utils/logger&#39;)<br>class FailedResponse extends Error {<br>  constructor(message) {<br>    // super(message)<br>    super()<br>    this.message = message<br>    this.isSuccess = false<br>    logger.error(`Error.Name: ${this.name} - Error.Stack: ${this.stack}`)<br>  }<br>}<br><br>module.exports = FailedResponse</pre><p><strong>failed.js</strong></p><p>Üstteki fail’in biraz daha kısaltmış hali. Hali hazırda hatalı olduğunu bildiğimiz dönüşler için sadece mesajı iletmemiz yeterli oluyor.</p><p><strong>success.js</strong></p><p>Burada başarılı dönüşlerimizi önyüze iletiyoruz.</p><pre>class Response {<br>  constructor(data,  count = null,  pagination = null, message = null) {<br>    this.isSuccess = true<br>    this.data = data<br>    this.count = count<br>    this.message = message<br>    this.pagination = pagination<br>  }<br>}<br><br>module.exports = Response</pre><p>Burada farklı olarak data, count, pagination gibi property’lerimiz mevcut.</p><p><strong>data</strong>: isminden de anlaşılacağı üzere datamızı iletiyoruz.<br><strong>count</strong>: kaç tane kaydın bulunduğu bilgisini iletiyoruz. Bunun sayesinde bazı durumlarda ekrana direkt olarak kayıt sayısını basabiliriz, ekstra olarak data.length kullanmamıza da gerek kalmaz.<br><strong>pagination</strong>: bu ise en önemli property’imiz olabilir. Çünkü bunun sayesinde front end’de önceki sonraki gibi sayfaları gösterebiliriz.</p><p>Az sonra değineceğim <strong>dbQuery.js</strong> ile de, hızlı bir şekilde route’lardan data / count / pagination dönebileceğiz.</p><p><strong>successed.js</strong></p><p>failed.js’de olduğu gibi kullanışlı bir kısa yol.</p><p><strong>user / mail.js</strong></p><p>Şimdilik sadece <strong>validateEmail</strong> fonksiyonuna sahip olan yapımız.</p><p>Evet, classes klasörümüzü bu şekilde özetleyebiliriz. Gelelim bir sonraki klasörümüze.</p><h3>Config</h3><p><strong>auth.js</strong>: veritabanına authentication işlemlerimizin yapıldığı dosyamız. İçerisinde authentication secret’imiz yer alıyor.</p><p><strong>db.js</strong> içerisinde ise mongodb ile olan bağlantımızı sağlıyoruz.</p><h3>Controllers</h3><p>Şu an için 2 farklı controller’ımız mevcut.</p><p><strong>admin</strong></p><p>Admin dashboard’umuzda kullanacağımız datalara, client’tan ulaşılmasını istemeyiz değil mi? Bu nedenle de sadece yönetici olan kişilerin tokenlarıyla ulaşabilecekleri veriler burada yer alıyor.</p><p>Controllers ana klasöründeki controller’lara ise (bazı durumlar hariç: üyelik şartı vs.. gibi) herkesin ulaşabilmesini amaçlıyoruz.</p><h3>middlewares</h3><p>Buradaki middleware’ler sayesinde de birden fazla kez kullanmamız gerekecek yapıları, duplicationları önlemek için oluşturuyoruz. Özellikle 2 middleware’e değinmek istiyorum.</p><p><strong>dbQuery.js</strong></p><p>dbQuery.js sayesinde router’da hiçbir controller’a ihtiyaç duymadan dinamik olarak data çekebiliyoruz. Bu middleware ve <strong>response.success</strong> sayesinde data’yı, count’u, pagination’u kolaylıkla dönebiliyoruz.</p><p>Çok daha detaylı anlatılabilecek bir kısım olmasına rağmen şimdilik hızlıca değinmiş oluyorum. Ancak, router’lar içerisinde de çeşitli örnekleri görmek mümkün olacak.</p><pre>const { response } = require(&#39;../../classes&#39;)<br><br>const dbQuery =<br>  (model, populate = [], willNotReturn = []) =&gt;<br>  async (req, res, next) =&gt; {<br>    const CONTANTS = { limitPerPage: 25, defaultPage: 1 }<br><br>    let query<br>    willNotReturn.push(&#39;__v&#39;)<br><br>    // Copy req.query<br>    const reqQuery = { ...req.query }<br><br>    // Fields to exclude<br>    const removeFields = [&#39;select&#39;, &#39;sort&#39;, &#39;page&#39;, &#39;limit&#39;]<br><br>    // Loop over removeFields and delete them from reqQuery<br>    removeFields.forEach(param =&gt; delete reqQuery[param])<br><br>    // Create query string<br>    let queryStr = JSON.stringify(reqQuery)<br><br>    // Create operators ($gt, $gte, etc)<br>    queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in)\b/g, match =&gt; `$${match}`)<br><br>    // Finding resource<br>    query = model.find(JSON.parse(queryStr))<br><br>    // Select Fields<br>    if (req.query.select) {<br>      const fields = req.query.select.split(&#39;,&#39;).join(&#39; &#39;)<br>      query = query.select(fields)<br>    }<br><br>    // Sort<br>    if (req.query.sort) {<br>      const sortBy = req.query.sort.split(&#39;,&#39;).join(&#39; &#39;)<br>      query = query.sort(sortBy)<br>    } else {<br>      query = query.sort(&#39;-createdAt&#39;)<br>    }<br><br>    // Pagination<br>    const page = parseInt(req.query.page, 10) || CONTANTS.defaultPage<br>    const limit = parseInt(req.query.limit, 10) || CONTANTS.limitPerPage<br>    const startIndex = (page - 1) * limit<br>    const endIndex = page * limit<br>    const total = await model.countDocuments(JSON.parse(queryStr))<br><br>    query = query.skip(startIndex).limit(limit)<br><br>    if (populate.length &gt; 0) {<br>      populate.forEach(p =&gt; {<br>        query = query.populate(p)<br>      })<br>    }<br><br>    // // Executing query<br>    let results = await query<br><br>    results = JSON.stringify(results)<br>    results = JSON.parse(results)<br>    // map does not with only results.map if we do not stringify then parse it. strange, right? any idea?<br><br>    results.map(item =&gt; {<br>      return willNotReturn.forEach(willBeDeleted =&gt; delete item[willBeDeleted])<br>    })<br><br>    // Pagination result<br>    const pagination = {}<br><br>    if (endIndex &lt; total) {<br>      pagination.next = {<br>        page: page + 1,<br>        limit<br>      }<br>    }<br><br>    if (startIndex &gt; 0) {<br>      pagination.prev = {<br>        page: page - 1,<br>        limit<br>      }<br>    }<br><br>    res.dbQuery = new response.success(results, results.length, pagination)<br><br>    next()<br>  }<br><br>module.exports = dbQuery</pre><p><strong>error.js</strong></p><p>İsminden de anlaşılacağı üzere hataların üstesinden kolaylıkla gelmemize yarıyor.</p><p><strong>Models</strong></p><p>Modellerimizi — tablo / collection yapılarımızı barındıran klasörümüz.</p><p><strong>Public</strong></p><p>Şu an için sadece postlarımızda kullanacağımızı görselleri barındıran klasörümüz.</p><h3>Routes</h3><p>Route’larımızın yer aldığı klasörümüz. Controllers başlığında değindiğim konuların hepsi burada da geçerli.</p><p><strong>Utils</strong></p><p>İşimizi kolaylaştırabilecek araçların yer aldığı klasörümüz. Şimdilik errorResponse.js ve logger.js dosyalarını barındırıyor.</p><p>Evet, API tarafı özet olarak bu şekilde görünüyor.</p><h3>Nuxt 3 ile Client</h3><p>Nuxt3 ile hazırlanan client tarafı ise aşağıdaki gibi görünüyor. Bunun için vuetify benzeri herhangi bir UI framawork kullanmadım. Sadece temel css’lerden (responsive konusunda çok uğraşmamak için direkt olarak bootstrap’in css’lerinin bir kısmını da ekledim) oluşan bir Nuxt 3 projesi olarak görebilirsiniz.</p><p>Footer ise birkaç yıl önce paylaştığım <a href="https://github.com/mustafacagri/vue-js-footer"><strong>Vue JS Footer</strong></a> projesinden geliyor.</p><figure><img alt="MEVN Stack Boilerplate — Client Nuxt 3" src="https://cdn-images-1.medium.com/max/1024/1*6R3svULX1VAswtUzCD0AOg.png" /></figure><p>Ayrıca, Client ve Admin taraflarına da zaman içerisinde değineceğim. Daha detaylı kullanım bilgileri için de repoya göz atabilirsiniz.</p><p><a href="https://github.com/mustafacagri/mevn-boilerplate"><strong>https://github.com/mustafacagri/mevn-boilerplate</strong></a></p><p>Başta da belirttiğim gibi aklınıza gelen her detay için repoya katkı sağlamaktan lütfen çekinmeyin. Bunun yanı sıra, repoya yıldız vererek de katkı sağlayabilirsiniz. Bilgi paylaştıkça çoğalır…</p><p>Open Source ❤</p><p>Selamlarımla</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=201b13618d1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>