<?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 Atilla Taha Kördüğüm on Medium]]></title>
        <description><![CDATA[Stories by Atilla Taha Kördüğüm on Medium]]></description>
        <link>https://medium.com/@atillataha?source=rss-755eb80c350d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZjHhf3e64p-0yrfYxnjtIw.jpeg</url>
            <title>Stories by Atilla Taha Kördüğüm on Medium</title>
            <link>https://medium.com/@atillataha?source=rss-755eb80c350d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:17:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atillataha/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[Senkron Bloklamadan Asenkron Batch İşlemeye: Node.js Performansını İyileştirmek]]></title>
            <link>https://medium.com/@atillataha/senkron-bloklamadan-asenkron-batch-i%CC%87%C5%9Flemeye-node-js-performans%C4%B1n%C4%B1-i%CC%87yile%C5%9Ftirmek-5d02deafb6ac?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d02deafb6ac</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 20:26:02 GMT</pubDate>
            <atom:updated>2026-06-07T20:26:02.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UXFRHRWv8y9ttw05.png" /></figure><p>Node.js geliştiricisi olarak çoğumuz en az bir kez şu hatayı yapmıştır: Büyük bir veri dizisini (array) basit bir for veya forEach döngüsüyle tek tek işlemek. İlk bakışta sorun yok gibi görünse de, veri miktarı arttıkça bu yaklaşım uygulamanızın tamamen kilitlenmesine (freeze) yol açabilir.</p><p>Peki bu sorun neden ortaya çıkıyor ve nasıl çözülür? Gelin, backend mülakatlarında da çokça karşımıza çıkan bu önemli konuyu inceleyelim.</p><h3>Temel Sorun: Event Loop’u Tıkamak</h3><p>Node.js, single-threaded bir yapıya sahiptir. I/O işlemleri asenkron yapılırken, CPU yoğun senkron işlemler Event Loop’u tamamen meşgul eder.</p><p>Örneğin aşağıdaki gibi senkron bir döngü yazdığınızda:</p><p>JavaScript</p><pre>// Yanlış Yaklaşım: Event Loop’u kilitleyen kod<br>const processItemsSync = (items) =&gt; {<br>  for (const item of items) {<br>    handleTaskSync(item); // Ağır senkron işlem<br>  }<br>};</pre><p>Döngü bitene kadar Node.js gelen hiçbir HTTP isteğine cevap veremez, veritabanı sorguları çalışmaz. Uygulama resmen felç olur.</p><h3>Çözüm: Asenkron Batch (Yığın) İşleme</h3><p>Çözüm oldukça basit: İş yükünü küçük parçalara bölmek ve Event Loop’un nefes almasını sağlamak. Bunun için JavaScript’in asenkron yapısını kullanarak işlemleri paralel veya kontrollü yığınlar hâlinde yönetebiliriz.</p><pre>// Doğru Yaklaşım: Asenkron Paralelleştirme<br>const processItemsAsync = async (items) =&gt; {<br>  return Promise.all(items.map(item =&gt; handleTaskAsync(item)));<br>};</pre><blockquote>Not: Eğer veri seti çok büyükse Promise.all bellek kullanımını aşırı artırabilir. Bu durumda veriyi 100’lü veya 200’lü chunk’lara bölüp, p-limit gibi kütüphanelerle eşzamanlı işlem sayısını sınırlamak (concurrency control) çok daha sağlıklı bir yaklaşımdır.</blockquote><h3>Mülakatlarda Karşınıza Çıkarsa</h3><p>Bu konu, özellikle mid-level ve senior pozisyonlardaki teknik mülakatlarda sıkça test edilir. Size bloklayan bir kod verip “Bunu Event Loop’u kilitlemeyecek şekilde refactor et” diyebilirler.</p><p><strong>Örnek problem</strong>, aşağıdaki linkteki problemi çözebilirsiniz.</p><p><a href="https://mockpair.com/tr/shared-questions/8263cbfd-7599-40d8-96d0-b385e941ad3a">Mock Interview Platform</a></p><h3>Özetle</h3><ul><li>Event Loop’u uzun süren senkron işlemlerle asla meşgul etmeyin.</li><li>İş yükünü asenkron parçalara bölün.</li><li>Büyük verilerde kontrollü batching ve concurrency limiti kullanarak uygulamanızın performansını ve throughput’unu yüksek tutun.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d02deafb6ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Güvenilir Kod: AI’dan Gelen Kod Nasıl Refactor Edilmeli]]></title>
            <link>https://medium.com/@atillataha/g%C3%BCvenilir-kod-aidan-gelen-kod-nas%C4%B1l-refactor-edilmeli-1a413ee48f93?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a413ee48f93</guid>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Sun, 24 May 2026 08:21:19 GMT</pubDate>
            <atom:updated>2026-05-24T08:21:19.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*s2LRp4IUzoIKasdO.jpeg" /></figure><h3>İsimlendirme ve Davranışsal Düzeltmeler</h3><p>AI destekli araçlar artık sıradan kod parçaları üretmemize yardımcı oluyor. Ancak bu kodlar genelde işlevsel olsa da, ekip içinde güven ve sürdürülebilirlik açısından sorunlu isimlendirme, yanlış veri yapısı seçimleri veya anlaşılması zor yapılar barındırır. Bu makalede “AI’dan gelen kodu” gerçek projeye güvenle sokmak için uygulanabilir refactor adımlarını, örnekleri ve pratik bir kontrol listesini paylaşıyorum.</p><p><strong>Neden refactor etmeliyiz?</strong></p><p>AI, kısa sürede geçerli-sintakslı kod üretir; fakat niyeti, sınırları veya kullanım modellerini her zaman açıkça ifade etmez.</p><p>Yanıltıcı isimlendirme (ör. `list` ama aslında `map`) geliştirme sırasında gizli hatalara ve yanlış varsayımlara yol açar.</p><p>Refactor, okunabilirliği, test edilebilirliği ve bakım maliyetini azaltır.</p><p><strong>AI Kodunun Yaygın Sorunları</strong></p><p>Yanıltıcı Veri Yapısı İsimlendirmeleri: `items` ama veri bir nesne/map.</p><p>Uzun, farklı ama otomatik tamamlama hatalarına açık sınıf/fonksiyon isimleri.</p><p>Kısaltmalar ve encoded-meaning (kullanıcıya gerçek niyeti söylemeyen isimler).</p><p>Görsel karışıklık yaratan tek karakterli isimler (`l`, `I`, `0`, `O`, `1`).</p><p>Tropik yapılar: Tek fonksiyon içinde birden fazla sorumluluk (AI bazen tek parçada fazla şey yazar).</p><p><strong>Refaktör İçin Genel Strateji</strong></p><p>1. <strong>Önce anlayın</strong>: Kodu çalıştırmadan önce hızlı bir statik inceleme yapın — hangi veri yapıları kullanılmış, hangi fonksiyonlar dışarıya API sunuyor ve hangi taraf etkileri (side effect) mevcut?</p><p>2.<strong> Davranışı testle güvence altına alın:</strong> Refaktöre başlamadan önce mevcut davranışı doğrulayan basit birim testleri yazın veya mevcut testleri çalıştırın; bu, değişikliklerden sonra oluşabilecek gerilemeleri (regression) yakalamanızı sağlar.</p><p>3. <strong>Küçük adımlarla ilerleyin</strong>: Tek seferde büyük değişiklikler yapmak yerine, her değişiklik küçük ve geri alınabilir olsun; her adımda testleri çalıştırın.</p><p>4. <strong>İsimlendirmede niyeti gösterin: </strong>Değişken veya yapı adında veri tipini ve kullanım niyetini belirtin (ör. `usersById`, `userList`, `countUsers` gibi). Kısa standart önekler (`ById`, `Map`, `Array`, `Count`) yardımcı olur.</p><p>5. <strong>Otomasyonu kullanın: </strong>ESLint, tip denetimi ve CI pipeline’ına eklenen statik analizlerle isim ve stil kurallarını zorunlu hale getirin; otomatik kontroller refaktör sırasında hataları azaltır.</p><p><strong>Adım Adım Uygulamalı Örnek</strong></p><pre>const list = {<br>  u1: { name: &#39;Alice&#39; },<br>  u2: { name: &#39;Bob&#39; },<br>};<br><br>function getUserByIndex(idx) {<br>  return list[idx];<br>}<br><br>function ABCManagerForEfficientProcessingOfUsers(users) {<br>  return Object.keys(users).length;<br>}<br><br>module.exports = { list, getUserByIndex, ABCManagerForEfficientProcessingOfUsers };</pre><p><strong>Problemler (hızlı tespit):</strong></p><p>- `list` aslında bir nesne/map; isim yanıltıcı.</p><p>- `getUserByIndex` map’ten index ile erişmeye çalışıyor, bu hata üretir.</p><p>- `ABCManagerForEfficientProcessingOfUsers` gereksiz uzun ve belirsiz.</p><pre>const usersMap = new Map([<br>  [&#39;u1&#39;, { name: &#39;Alice&#39; }],<br>  [&#39;u2&#39;, { name: &#39;Bob&#39; }],<br>]);<br><br>function getUserById(id) {<br>  return usersMap.get(id) || null;<br>}<br><br>function countUsers(usersMap) {<br>  return usersMap.size;<br>}<br><br>module.exports = { usersMap, getUserById, countUsers };</pre><p>Açıklama:</p><p>- `usersMap` ismi, bunun bir `Map` olduğunu açıkça anlatır.</p><p>- `getUserById` `Map.get()` kullanır ve sonuç yoksa `null` döndürür.</p><p>- `countUsers` burada `Object.keys` yerine `Map.size` kullanır.</p><p>AI üretimi kodlar üretkenliği artırıyor ama insan denetimi ve küçük refactor alışkanlıkları olmadan kod tabanınızı tehlikeye atabilir. İyi bir refactor süreci anlayış, test, küçük adımlar, ve net isimlendirme kuralları AI’nın ürettiği kodu güvenle üretime sokmanızı sağlar.</p><h4><strong>Kendinizi burada deneyebilirsiniz:</strong></h4><p><a href="https://mockpair.com/tr/shared-sessions/4dfaaef0-a6d9-497f-b51d-33804f5258be">https://mockpair.com/tr/shared-sessions/4dfaaef0-a6d9–497f-b51d-33804f5258be</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a413ee48f93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gmail’de Bir E-posta Sildiğinizde Geri Alma Butonu Nasıl Çalışır?]]></title>
            <link>https://medium.com/@atillataha/gmailde-bir-e-posta-sildi%C4%9Finizde-geri-alma-butonu-nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r-teknik-a%C3%A7%C4%B1klama-c2b2d5517bc3?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2b2d5517bc3</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Tue, 19 May 2026 09:52:51 GMT</pubDate>
            <atom:updated>2026-05-19T09:54:33.080Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jsYKIuno3_TJLG6P.png" /></figure><p>Gmail’i kullandığınızda bir e-postayı sildiğiniz anda ekran hemen temizlenir ve altta “E-posta silindi • Geri al” bildirimi çıkar. Bu küçük detay, Gmail’i rakiplerinden ayıran o kusursuz kullanıcı deneyimini yaratır.</p><p>Peki bu özellik teknik olarak nasıl implemente ediliyor? Gerçek bir uygulamada bunu nasıl yaparsınız?</p><h3>Optimizm UI + Undo Pattern</h3><p>Gmail bu özelliği klasik <strong>Optimistic UI</strong> yaklaşımıyla birleştirerek çözüyor. Yani kullanıcı “Sil” butonuna bastığı anda:</p><ol><li>E-posta listeden <strong>hemen</strong> kaldırılıyor (kullanıcı gecikme hissetmiyor).</li><li>Gerçek silme işlemi (backend’e istek) 5 saniye geciktiriliyor.</li><li>Kullanıcıya bu 5 saniye içinde işlemi geri alma şansı veriliyor.</li></ol><p>Bu yaklaşım hem hızlı hissettiriyor hem de kullanıcı hatalarına karşı koruma sağlıyor.</p><h3>Adım Adım Nasıl Uygulanır?</h3><p><strong>1. Geçici Silme (UI tarafında)</strong> Kullanıcı sil butonuna bastığında e-postayı diziden hemen çıkarıyoruz ama henüz sunucudan silmiyoruz. Silinen e-postayı bir değişkende (veya state’te) saklıyoruz.</p><p><strong>2. Undo Banner / Snackbar Gösterme</strong> E-posta listeden kalktıktan hemen sonra ekranın altında bir banner gösteriyoruz. Bu banner’da hem bilgi veriliyor hem de “Geri Al” butonu yer alıyor.</p><p><strong>3. Timer Mekanizması</strong> Banner göründüğü anda 5 saniyelik (genellikle 5000ms) bir timer başlatıyoruz. Bu timer’ın ID’sini saklamak çok önemli, çünkü kullanıcı Undo’ya basarsa timer’ı iptal edebileceğiz.</p><p><strong>4. Kullanıcı Undo’ya Basarsa</strong></p><ul><li>Timer iptal edilir.</li><li>Saklanan e-posta tekrar listeye (genellikle en üste) eklenir.</li><li>Banner gizlenir.</li><li>Backend silme işlemi hiç tetiklenmez.</li></ul><p><strong>5. Timer Biterse</strong> Timer tamamlandığında backend’e gerçek silme isteği gönderilir ve silme kalıcı hale gelir.</p><p>Bu örneği kendin denemek istersen, aşağıdaki linkten örnek soruya gidebilirsin.<br><a href="https://mockpair.com/tr/shared-sessions/808fd37b-7466-4052-981a-2f79c844be9a">https://mockpair.com/tr/shared-sessions/808fd37b-7466-4052-981a-2f79c844be9a</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2b2d5517bc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dissecting an API Monitoring Tool: A Technical Deep Dive into]]></title>
            <link>https://medium.com/@atillataha/dissecting-an-api-monitoring-tool-a-technical-deep-dive-into-da4d489f8f9b?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/da4d489f8f9b</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[data-logger]]></category>
            <category><![CDATA[npm-package]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 19:24:51 GMT</pubDate>
            <atom:updated>2025-07-15T19:24:51.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*98f8DNeGbTLnWDOQ.jpg" /></figure><p>In any software system, what you can’t measure, you can’t improve. For APIs, this means understanding not just which endpoints are being used, but also which are slow, which are error-prone, and — most critically — which have been forgotten. Standard logging is reactive; we wanted to build a proactive, intelligent system.</p><p>This article is a technical deep-dive into the architecture and implementation of endpoint-usage-tracker, an open-source NPM package for Express.js and NestJS. We’ll explore the engineering decisions behind its core components, from data ingestion to the mechanics of its route discovery engine.</p><h3>High-Level Architecture</h3><p>The system is composed of five major components that work in concert:</p><ol><li><strong>Data Ingestion (Middleware/Interceptor):</strong> The entry point for all request data, living inside the host application.</li><li><strong>The Tracker Core:</strong> The central brain that handles data normalization, processing, and communication with the data store.</li><li><strong>Data Store (Redis):</strong> A high-performance, persistent store for all usage, performance, and route metadata.</li><li><strong>Route Discovery Engine:</strong> A specialized module that programmatically inspects the application at startup to find all defined routes.</li><li><strong>Automatic Reporter:</strong> An asynchronous job scheduler that analyzes the data and pushes insights to developers.</li></ol><p>Let’s dissect each one.</p><h3>1. Data Ingestion: The Art of Interception</h3><p>The first challenge is to capture every request without impacting performance. We leveraged framework-native patterns for this.</p><ul><li><strong>For Express.js</strong>, we use a standard middleware. However, to accurately measure responseTime, we can’t simply time the middleware function, as it yields control to the next handler before the response is sent. The solution is to listen for the finish event on the response object. This ensures we capture the final status code and total duration right as the response is completed.</li></ul><pre>// Simplified Express Middleware Logic<br>function expressMiddleware(req, res, next) {<br>  const start = process.hrtime();<br><br>  res.on(&#39;finish&#39;, () =&gt; {<br>    const diff = process.hrtime(start);<br>    const responseTime = (diff[0] * 1e3) + (diff[1] * 1e-6);<br>    <br>    tracker.track({<br>      method: req.method,<br>      path: req.originalUrl,<br>      statusCode: res.statusCode,<br>      responseTime,<br>    });<br>  });<br><br>  next();<br>}</pre><ul><li><strong>For NestJS</strong>, we use an <strong>Interceptor</strong>. Interceptors are more powerful, wrapping the entire request/response stream in an RxJS Observable. This allows us to use the tap operator on the stream&#39;s return path, which functions similarly to the finish event listener, giving us a clean, framework-idiomatic way to capture the final state.</li></ul><h3>2. Data Persistence: Choosing the Right Redis Structures</h3><p>We chose Redis as our data store for its speed, versatility, and atomic operations, which are critical for handling concurrent requests. The key to our Redis implementation is a carefully designed schema using different data structures for different needs.</p><p>Our Redis key schema follows the pattern: &lt;prefix&gt;:&lt;type&gt;:&lt;endpoint_name&gt;.</p><p><strong>Hashes for Aggregation:</strong> We use Redis Hashes to store aggregated statistics for each endpoint. Hashes are memory-efficient and allow for atomic increments of fields.</p><p><strong>Key:</strong> my-app:global:GET:/api/users/:id</p><p><strong>Fields:</strong></p><ul><li>count: Total requests (updated with HINCRBY).</li><li>status_200, status_404, etc.: Status code counts (HINCRBY).</li><li>total_response_time: A running sum of response times (HINCRBYFLOAT).</li><li>response_count: The number of responses with a recorded time (HINCRBY).</li><li>first_accessed, last_accessed: Timestamps (HSETNX and HSET).</li></ul><p><strong>Why Hashes?</strong> This structure allows us to update multiple metrics for an endpoint in a single, efficient operation, avoiding read-modify-write race conditions.</p><p><strong>Lists for Raw Performance Data:</strong> To calculate accurate percentiles (P50, P95, P99), we need the raw response time values, not just an average.</p><p><strong>Key:</strong> my-app:raw:GET:/api/users/:id</p><p><strong>Operation:</strong> We LPUSH every new responseTime to a list.</p><p><strong>Memory Management:</strong> To prevent unbounded memory growth, this list is capped and expired. We only keep the last N values (e.g., 1000) or expire the key after a set time (e.g., 24 hours). This gives us a rolling window of data for percentile calculation.</p><h3>3. The Core Challenge: The Route Discovery Engine</h3><p>Tracking existing traffic is standard. The real innovation is in finding endpoints with <strong>zero traffic</strong>. This required us to inspect the application’s internals.</p><ul><li><strong>The Express.js Approach:</strong> We traverse the (undocumented) _router.stack property of the main Express app object. This property is an array containing all middleware and routers. We recursively iterate through this stack, looking for layers that have a route property. This route object contains the HTTP methods and path. We also have to handle nested Routers, which requires a recursive traversal strategy.</li><li><strong>The NestJS Approach:</strong> Since NestJS is built on top of a platform like Express by default, the same technique works. However, a more robust, future-proof implementation would leverage the @nestjs/discovery module to query for all controllers and @Get, @Post, etc., decorators, reading the path metadata directly from them.</li></ul><p>The list of all discovered routes is stored in Redis, creating a master manifest of the application’s entire API surface.</p><h3>4. From Data to Insights: The Automatic Reporter</h3><p>The AutomaticReporter is a scheduled job that runs independently of the request cycle. On its schedule, it executes the following logic:</p><p><strong>Fetch All Routes:</strong> It gets the complete list of <em>defined</em> routes from our manifest in Redis.</p><p><strong>Fetch All Usage Stats:</strong> It gets all the <em>used</em> endpoint statistics from the aggregated Hashes.</p><p><strong>Perform a “Diff”:</strong> It compares the two sets. Any route in the “defined” set but not in the “used” set (or with a last_accessed timestamp older than the threshold) is marked as unused.</p><p><strong>Calculate Performance Metrics:</strong> For each used endpoint, it calculates:</p><p>1. <strong>Error Rate:</strong> (status_4xx_count + status_5xx_count) / total_count.</p><p><strong>2. Percentiles:</strong> It fetches the raw data from the Redis List, sorts it, and calculates the P50, P95, and P99 response times.</p><p><strong>3. Average Response Time:</strong> total_response_time / response_count.</p><p><strong>Push Notifications:</strong> It formats this report and sends it to configured channels like Slack or a generic webhook.</p><h3>Challenges and Future Directions</h3><ul><li><strong>Reliance on Undocumented APIs:</strong> Using _router.stack in Express is powerful but brittle. Future versions of Express could change this, requiring updates.</li><li><strong>KEYS vs. </strong><strong>SCAN:</strong> In our code, we use KEYS to fetch all tracker-related keys. In a production Redis instance with millions of keys, KEYS is a blocking operation and should be avoided. The more robust solution, which we plan to implement, is to use SCAN for iterative, non-blocking key retrieval.</li><li><strong>GraphQL Support:</strong> The current implementation is REST-focused. Supporting GraphQL would require a different approach, likely by inspecting operation names within the request body rather than just the URL path.</li></ul><h3>Conclusion</h3><p>Building endpoint-usage-tracker was an exercise in moving from passive data collection to active, intelligent monitoring. By combining framework-native interception patterns, carefully chosen Redis data structures, and a novel route discovery engine, we created a tool that provides actionable insights to help developers fight technical debt and improve API health.</p><p>The project is open-source, and we are actively looking for contributors. If these technical challenges sound interesting to you, we invite you to check out the repository, try it out, and help us build the future of API observability.</p><h3>How to Contribute</h3><p>This project was born from a real-world need, and I believe it can benefit many others. It’s open-source under the MIT license, and we welcome contributions of all kinds.</p><p>Whether you want to add support for a new framework, suggest a new feature, or help improve the documentation, your input is valuable. Check out our CONTRIBUTING.md file on GitHub to get started.</p><ul><li><strong>GitHub Repository: </strong><a href="https://github.com/AtillaTahak/endpoint-usage-tracker">https://github.com/AtillaTahak/endpoint-usage-tracker</a></li><li><strong>NPM Package:</strong><a href="https://www.npmjs.com/package/endpoint-usage-tracker"> </a><a href="https://www.npmjs.com/package/endpoint-usage-tracker">https://www.npmjs.com/package/endpoint-usage-tracker</a></li></ul><p>Let’s work together to build smarter, cleaner, and more maintainable APIs. Give it a try and let us know what you think</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4d489f8f9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeORM Entity Middleware: Implementing Lifecycle Hooks and Event Subscribers in NestJS]]></title>
            <link>https://medium.com/@atillataha/typeorm-entity-middleware-implementing-lifecycle-hooks-and-event-subscribers-in-nestjs-60d4ee98eeac?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/60d4ee98eeac</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 07:05:40 GMT</pubDate>
            <atom:updated>2025-07-08T07:05:40.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*e1l0WOqIg2yBOSML" /></figure><p><em>Learn how to implement middleware-like functionality in TypeORM entities with practical examples and best practices</em></p><p>When building enterprise applications with NestJS and TypeORM, you often need to perform additional operations when entities are created, updated, or deleted. Whether it’s sending notifications, updating caches, or triggering business logic, TypeORM provides several powerful mechanisms to implement middleware-like functionality.</p><p>In this comprehensive guide, we’ll explore entity lifecycle hooks and event subscribers, comparing their advantages and disadvantages with real-world examples.</p><h3>🎯 What Are TypeORM Lifecycle Hooks?</h3><p>TypeORM offers built-in decorators that allow you to hook into the entity lifecycle at specific points:</p><ul><li>@BeforeInsert() — Executed before entity insertion</li><li>@AfterInsert() — Executed after entity insertion</li><li>@BeforeUpdate() — Executed before entity update</li><li>@AfterUpdate() — Executed after entity update</li><li>@BeforeRemove() — Executed before entity removal</li><li>@AfterRemove() — Executed after entity removal</li></ul><h3>📝 Method 1: Direct Entity Lifecycle Hooks</h3><p>The simplest approach is to add lifecycle hooks directly to your entity:</p><pre>import { Entity, Column, BeforeInsert, AfterInsert, BeforeUpdate } from &#39;typeorm&#39;;<br>import { BaseEntity } from &#39;./base.entity&#39;;<br><br>@Entity()<br>export class User extends BaseEntity {<br>  @Column()<br>  firstName: string;<br><br>  @Column()<br>  lastName: string;<br><br>  @Column({ unique: true })<br>  email: string;<br><br>  @Column({ nullable: true })<br>  fullName: string;<br><br>  @Column({ default: true })<br>  isActive: boolean;<br><br>  @Column({ type: &#39;timestamp&#39;, nullable: true })<br>  lastLoginAt: Date;<br><br>  @BeforeInsert()<br>  beforeCreateActions() {<br>    // Generate full name before insertion<br>    this.fullName = `${this.firstName} ${this.lastName}`;<br>    <br>    // Normalize email<br>    this.email = this.email.toLowerCase().trim();<br>    <br>    // Log the action<br>    console.log(`About to create user: ${this.email}`);<br>    <br>    // Validate data<br>    if (!this.email.includes(&#39;@&#39;)) {<br>      throw new Error(&#39;Invalid email format&#39;);<br>    }<br>  }<br><br>  @BeforeUpdate()<br>  beforeUpdateActions() {<br>    // Update full name when names change<br>    if (this.firstName || this.lastName) {<br>      this.fullName = `${this.firstName} ${this.lastName}`;<br>    }<br>    <br>    console.log(`About to update user: ${this.id}`);<br>  }<br><br>  @AfterInsert()<br>  afterCreateActions() {<br>    console.log(`User created successfully with ID: ${this.id}`);<br>  }<br>}</pre><h3>✅ Advantages:</h3><ul><li><strong>Simple and straightforward</strong> — Easy to understand and implement</li><li><strong>Direct entity control</strong> — Logic is co-located with entity definition</li><li><strong>Automatic execution</strong> — No need to remember to call hooks manually</li><li><strong>Type safety</strong> — Full TypeScript support within entity context</li></ul><h3>❌ Disadvantages:</h3><ul><li><strong>Limited to synchronous operations</strong> — Cannot handle async operations properly</li><li><strong>Business logic in entity</strong> — Violates separation of concerns</li><li><strong>Hard to test in isolation</strong> — Tightly coupled with entity</li><li><strong>No dependency injection</strong> — Cannot inject services</li><li><strong>Performance impact</strong> — Executes on every operation</li></ul><h3>🚀 Method 2: Event Subscribers (Recommended)</h3><p>For more complex scenarios, especially when you need to perform async operations or inject services, use EventSubscriber:</p><pre>import {<br>  EntitySubscriberInterface,<br>  EventSubscriber,<br>  InsertEvent,<br>  UpdateEvent,<br>  RemoveEvent,<br>} from &#39;typeorm&#39;;<br>import { User } from &#39;../entities/user.entity&#39;;<br>import { Injectable, Logger, Inject } from &#39;@nestjs/common&#39;;<br>import { EmailService } from &#39;../services/email.service&#39;;<br>import { AuditService } from &#39;../services/audit.service&#39;;<br>import { CacheService } from &#39;../services/cache.service&#39;;<br><br>@Injectable()<br>@EventSubscriber()<br>export class UserSubscriber implements EntitySubscriberInterface&lt;User&gt; {<br>  private readonly logger = new Logger(UserSubscriber.name);<br><br>  constructor(<br>    @Inject(EmailService)<br>    private readonly emailService: EmailService,<br>    @Inject(AuditService)<br>    private readonly auditService: AuditService,<br>    @Inject(CacheService)<br>    private readonly cacheService: CacheService,<br>  ) {}<br><br>  /**<br>   * Indicates that this subscriber only listens to User entity events<br>   */<br>  listenTo() {<br>    return User;<br>  }<br><br>  /**<br>   * Called before user insertion<br>   */<br>  beforeInsert(event: InsertEvent&lt;User&gt;) {<br>    const user = event.entity;<br>    <br>    this.logger.log(`Preparing to create user: ${user.email}`);<br>    <br>    // Set default values<br>    if (!user.fullName) {<br>      user.fullName = `${user.firstName} ${user.lastName}`;<br>    }<br>    <br>    // Normalize email<br>    user.email = user.email.toLowerCase().trim();<br>    <br>    // Validate required fields<br>    this.validateUserData(user);<br>  }<br><br>  /**<br>   * Called after user insertion - can handle async operations<br>   */<br>  async afterInsert(event: InsertEvent&lt;User&gt;) {<br>    const user = event.entity;<br>    <br>    this.logger.log(`User created with ID: ${user.id}, Email: ${user.email}`);<br>    <br>    try {<br>      // Perform async post-creation tasks<br>      await Promise.all([<br>        this.sendWelcomeEmail(user),<br>        this.createUserProfile(user),<br>        this.updateUserCache(user),<br>        this.logUserCreation(user),<br>      ]);<br>      <br>      this.logger.log(`Post-creation tasks completed for user ${user.id}`);<br>    } catch (error) {<br>      this.logger.error(`Error in post-creation tasks for user ${user.id}:`, error);<br>      // Don&#39;t throw here to avoid affecting the main transaction<br>    }<br>  }<br><br>  /**<br>   * Called after user update<br>   */<br>  async afterUpdate(event: UpdateEvent&lt;User&gt;) {<br>    if (!event.entity) return;<br>    <br>    const user = event.entity as User;<br>    const updatedColumns = event.updatedColumns;<br>    <br>    this.logger.log(`User updated: ${user.id}`);<br>    <br>    // Check specific field updates<br>    const emailUpdated = updatedColumns.some(<br>      column =&gt; column.propertyName === &#39;email&#39;<br>    );<br>    <br>    const nameUpdated = updatedColumns.some(<br>      column =&gt; [&#39;firstName&#39;, &#39;lastName&#39;].includes(column.propertyName)<br>    );<br>    <br>    if (emailUpdated) {<br>      await this.handleEmailChange(user, event.databaseEntity);<br>    }<br>    <br>    if (nameUpdated) {<br>      await this.handleNameChange(user);<br>    }<br>    <br>    // Always update cache<br>    await this.updateUserCache(user);<br>  }<br><br>  private validateUserData(user: User) {<br>    if (!user.email || !user.email.includes(&#39;@&#39;)) {<br>      throw new Error(&#39;Valid email is required for user creation&#39;);<br>    }<br>    <br>    if (!user.firstName || !user.lastName) {<br>      throw new Error(&#39;First name and last name are required&#39;);<br>    }<br>  }<br><br>  private async sendWelcomeEmail(user: User) {<br>    try {<br>      await this.emailService.sendWelcomeEmail(user.email, user.firstName);<br>      this.logger.log(`Welcome email sent to ${user.email}`);<br>    } catch (error) {<br>      this.logger.error(`Failed to send welcome email to ${user.email}:`, error);<br>    }<br>  }<br><br>  private async createUserProfile(user: User) {<br>    try {<br>      // Create additional user profile data<br>      this.logger.log(`Creating user profile for ${user.id}`);<br>      // Implementation here...<br>    } catch (error) {<br>      this.logger.error(`Failed to create user profile for ${user.id}:`, error);<br>    }<br>  }<br><br>  private async updateUserCache(user: User) {<br>    try {<br>      await this.cacheService.setUser(user.id, user);<br>      this.logger.log(`User cache updated for ${user.id}`);<br>    } catch (error) {<br>      this.logger.error(`Failed to update cache for user ${user.id}:`, error);<br>    }<br>  }<br><br>  private async logUserCreation(user: User) {<br>    try {<br>      await this.auditService.logEvent(&#39;USER_CREATED&#39;, {<br>        userId: user.id,<br>        email: user.email,<br>        timestamp: new Date(),<br>      });<br>    } catch (error) {<br>      this.logger.error(`Failed to log user creation for ${user.id}:`, error);<br>    }<br>  }<br><br>  private async handleEmailChange(newUser: User, oldUser: User) {<br>    const oldEmail = oldUser?.email;<br>    const newEmail = newUser.email;<br>    <br>    if (oldEmail !== newEmail) {<br>      await Promise.all([<br>        this.emailService.sendEmailChangeNotification(oldEmail, newEmail),<br>        this.auditService.logEvent(&#39;EMAIL_CHANGED&#39;, {<br>          userId: newUser.id,<br>          oldEmail,<br>          newEmail,<br>          timestamp: new Date(),<br>        }),<br>      ]);<br>    }<br>  }<br><br>  private async handleNameChange(user: User) {<br>    this.logger.log(`Name changed for user ${user.id}`);<br>    // Handle name change logic here<br>  }<br>}</pre><h3>✅ Advantages:</h3><ul><li><strong>Full async support</strong> — Can handle complex async operations</li><li><strong>Dependency injection</strong> — Access to services and other dependencies</li><li><strong>Separation of concerns</strong> — Business logic separated from entity</li><li><strong>Testable</strong> — Easy to unit test in isolation</li><li><strong>Flexible</strong> — Can handle multiple entities with one subscriber</li><li><strong>Error handling</strong> — Better error management without affecting main transaction</li></ul><h3>❌ Disadvantages:</h3><ul><li><strong>More complex setup</strong> — Requires additional configuration</li><li><strong>Potential performance overhead</strong> — Additional processing on every operation</li><li><strong>Memory usage</strong> — Subscribers stay in memory</li><li><strong>Debugging complexity</strong> — Harder to trace execution flow</li><li><strong>Circular dependency risk</strong> — Must be careful with service injection</li></ul><h3>🔧 Registering the Event Subscriber</h3><p>To use the event subscriber, register it in your module:</p><pre>    TypeOrmModule.forRootAsync({<br>      useFactory: () =&gt; ({<br>        type: &#39;postgres&#39;,<br>        host: process.env.DB_HOST,<br>        username: process.env.DB_USERNAME,<br>        password: process.env.DB_PASSWORD,<br>        database: process.env.DB_NAME,<br>        autoLoadEntities: true,<br>        poolSize: 30,<br>        extra: {<br>          max: 30,<br>          min: 10,<br>          idleTimeoutMillis: 10000,<br>          connectionTimeoutMillis: 30000,<br>          acquireTimeoutMillis: 60000,<br>          createTimeoutMillis: 30000,<br>          destroyTimeoutMillis: 5000,<br>          reapIntervalMillis: 1000,<br>          createRetryIntervalMillis: 200,<br>        },<br>        connectTimeoutMS: 30000,<br>        socketTimeoutMS: 60000,<br>        subscribers: [UserSubscriber],<br>      }),<br>    }),</pre><h3>🎯 Advanced Use Cases</h3><h3>1. Product Inventory Management</h3><pre>@Injectable()<br>@EventSubscriber()<br>export class ProductSubscriber implements EntitySubscriberInterface&lt;Product&gt; {<br>  constructor(<br>    private readonly inventoryService: InventoryService,<br>    private readonly notificationService: NotificationService,<br>  ) {}<br><br>  listenTo() {<br>    return Product;<br>  }<br><br>  async afterUpdate(event: UpdateEvent&lt;Product&gt;) {<br>    if (!event.entity) return;<br>    <br>    const product = event.entity as Product;<br>    const updatedColumns = event.updatedColumns.map(col =&gt; col.propertyName);<br>    <br>    // Handle stock level changes<br>    if (updatedColumns.includes(&#39;stockLevel&#39;)) {<br>      await this.handleStockLevelChange(product, event.databaseEntity);<br>    }<br>    <br>    // Handle price changes<br>    if (updatedColumns.includes(&#39;price&#39;)) {<br>      await this.handlePriceChange(product, event.databaseEntity);<br>    }<br>  }<br><br>  private async handleStockLevelChange(newProduct: Product, oldProduct: Product) {<br>    const oldStock = oldProduct?.stockLevel || 0;<br>    const newStock = newProduct.stockLevel;<br>    <br>    // Low stock alert<br>    if (newStock &lt;= newProduct.lowStockThreshold &amp;&amp; oldStock &gt; newProduct.lowStockThreshold) {<br>      await this.notificationService.sendLowStockAlert(newProduct);<br>    }<br>    <br>    // Out of stock alert<br>    if (newStock === 0 &amp;&amp; oldStock &gt; 0) {<br>      await this.notificationService.sendOutOfStockAlert(newProduct);<br>    }<br>    <br>    // Update inventory cache<br>    await this.inventoryService.updateProductCache(newProduct);<br>  }<br>}</pre><h3>2. Order Processing</h3><pre>@Injectable()<br>@EventSubscriber()<br>export class OrderSubscriber implements EntitySubscriberInterface&lt;Order&gt; {<br>  constructor(<br>    private readonly paymentService: PaymentService,<br>    private readonly inventoryService: InventoryService,<br>    private readonly emailService: EmailService,<br>  ) {}<br><br>  listenTo() {<br>    return Order;<br>  }<br><br>  async afterInsert(event: InsertEvent&lt;Order&gt;) {<br>    const order = event.entity;<br>    <br>    try {<br>      await Promise.all([<br>        this.reserveInventory(order),<br>        this.sendOrderConfirmation(order),<br>        this.updateCustomerStats(order),<br>      ]);<br>    } catch (error) {<br>      // Handle gracefully - order is already created<br>      console.error(&#39;Post-order creation error:&#39;, error);<br>    }<br>  }<br><br>  async afterUpdate(event: UpdateEvent&lt;Order&gt;) {<br>    if (!event.entity) return;<br>    <br>    const order = event.entity as Order;<br>    const updatedColumns = event.updatedColumns.map(col =&gt; col.propertyName);<br>    <br>    if (updatedColumns.includes(&#39;status&#39;)) {<br>      await this.handleStatusChange(order, event.databaseEntity);<br>    }<br>  }<br><br>  private async handleStatusChange(newOrder: Order, oldOrder: Order) {<br>    const oldStatus = oldOrder?.status;<br>    const newStatus = newOrder.status;<br>    <br>    switch (newStatus) {<br>      case OrderStatus.PAID:<br>        await this.processPayment(newOrder);<br>        break;<br>      case OrderStatus.SHIPPED:<br>        await this.handleShipment(newOrder);<br>        break;<br>      case OrderStatus.CANCELLED:<br>        await this.handleCancellation(newOrder);<br>        break;<br>    }<br>  }<br>}</pre><h3>🛡️ Best Practices and Performance Considerations</h3><h3>1. Keep Operations Lightweight</h3><pre>// ✅ Good: Quick operations<br>async afterInsert(event: InsertEvent&lt;User&gt;) {<br>  const user = event.entity;<br>  <br>  await this.cacheService.setUser(user.id, user);<br>  await this.auditService.logQuickEvent(&#39;USER_CREATED&#39;, user.id);<br>}<br><br>// ❌ Bad: Heavy operations<br>async afterInsert(event: InsertEvent&lt;User&gt;) {<br>  const user = event.entity;<br>  <br>  // These should be queued instead<br>  await this.generateComplexReport(user);<br>  await this.processLargeDataSet(user);<br>  await this.callSlowExternalAPI(user);<br>}<br><br>// ✅ Better: Queue heavy operations<br>async afterInsert(event: InsertEvent&lt;User&gt;) {<br>  const user = event.entity;<br>  <br>  await this.queueService.add(&#39;user-onboarding&#39;, {<br>    userId: user.id,<br>    tasks: [&#39;generate-report&#39;, &#39;process-data&#39;, &#39;call-external-api&#39;]<br>  });<br>}</pre><h3>2. Error Handling and Resilience</h3><pre>@Injectable()<br>@EventSubscriber()<br>export class ResilientSubscriber implements EntitySubscriberInterface&lt;User&gt; {<br>  private readonly logger = new Logger(ResilientSubscriber.name);<br><br>  async afterInsert(event: InsertEvent&lt;User&gt;) {<br>    const user = event.entity;<br>    <br>    const tasks = [<br>      { name: &#39;EMAIL_WELCOME&#39;, fn: () =&gt; this.sendWelcomeEmail(user), critical: false },<br>      { name: &#39;CREATE_PROFILE&#39;, fn: () =&gt; this.createProfile(user), critical: true },<br>      { name: &#39;UPDATE_CACHE&#39;, fn: () =&gt; this.updateCache(user), critical: false },<br>      { name: &#39;LOG_CREATION&#39;, fn: () =&gt; this.logCreation(user), critical: false },<br>    ];<br><br>    const results = await Promise.allSettled(<br>      tasks.map(task =&gt; this.executeTask(task, user.id))<br>    );<br><br>    const failedCriticalTasks = results<br>      .map((result, index) =&gt; ({ result, task: tasks[index] }))<br>      .filter(({ result, task }) =&gt; result.status === &#39;rejected&#39; &amp;&amp; task.critical);<br><br>    if (failedCriticalTasks.length &gt; 0) {<br>      this.logger.error(`Critical post-creation tasks failed for user ${user.id}`);<br>      // Optionally trigger compensation logic<br>    }<br>  }<br><br>  private async executeTask(task: any, userId: string) {<br>    try {<br>      await task.fn();<br>      this.logger.log(`✅ ${task.name} completed for user ${userId}`);<br>    } catch (error) {<br>      this.logger.error(`❌ ${task.name} failed for user ${userId}:`, error);<br>      throw error;<br>    }<br>  }<br>}</pre><h3>3. Transaction Management</h3><pre>async afterInsert(event: InsertEvent&lt;User&gt;) {<br>  const user = event.entity;<br>  const entityManager = event.manager;<br>  <br>  try {<br>    // This will be part of the same transaction<br>    await entityManager.save(UserProfile, {<br>      user_id: user.id,<br>      created_at: new Date(),<br>    });<br>  } catch (error) {<br>    // This will rollback the entire transaction including user creation<br>    throw error;<br>  }<br>}</pre><h3>🧪 Testing Event Subscribers</h3><h3>Unit Testing</h3><pre>describe(&#39;UserSubscriber&#39;, () =&gt; {<br>  let subscriber: UserSubscriber;<br>  let emailService: jest.Mocked&lt;EmailService&gt;;<br>  let auditService: jest.Mocked&lt;AuditService&gt;;<br><br>  beforeEach(async () =&gt; {<br>    const module = await Test.createTestingModule({<br>      providers: [<br>        UserSubscriber,<br>        {<br>          provide: EmailService,<br>          useValue: {<br>            sendWelcomeEmail: jest.fn(),<br>            sendEmailChangeNotification: jest.fn(),<br>          },<br>        },<br>        {<br>          provide: AuditService,<br>          useValue: {<br>            logEvent: jest.fn(),<br>          },<br>        },<br>      ],<br>    }).compile();<br><br>    subscriber = module.get&lt;UserSubscriber&gt;(UserSubscriber);<br>    emailService = module.get(EmailService);<br>    auditService = module.get(AuditService);<br>  });<br><br>  describe(&#39;beforeInsert&#39;, () =&gt; {<br>    it(&#39;should normalize email and set full name&#39;, () =&gt; {<br>      const user = new User();<br>      user.firstName = &#39;John&#39;;<br>      user.lastName = &#39;Doe&#39;;<br>      user.email = &#39;JOHN.DOE@EXAMPLE.COM&#39;;<br>      <br>      const mockEvent = { entity: user } as InsertEvent&lt;User&gt;;<br><br>      subscriber.beforeInsert(mockEvent);<br><br>      expect(user.email).toBe(&#39;john.doe@example.com&#39;);<br>      expect(user.fullName).toBe(&#39;John Doe&#39;);<br>    });<br><br>    it(&#39;should throw error for invalid email&#39;, () =&gt; {<br>      const user = new User();<br>      user.firstName = &#39;John&#39;;<br>      user.lastName = &#39;Doe&#39;;<br>      user.email = &#39;invalid-email&#39;;<br>      <br>      const mockEvent = { entity: user } as InsertEvent&lt;User&gt;;<br><br>      expect(() =&gt; subscriber.beforeInsert(mockEvent)).toThrow(&#39;Valid email is required&#39;);<br>    });<br>  });<br>});</pre><h3>🎯 When to Use Which Approach</h3><h3>Use Entity Lifecycle Hooks when:</h3><ul><li>Simple synchronous operations</li><li>Data validation and transformation</li><li>Default value assignment</li><li>Basic logging</li></ul><h3>Use Event Subscribers when:</h3><ul><li>Complex async operations</li><li>Service integration required</li><li>Separation of concerns important</li><li>Advanced error handling needed</li></ul><h3>📊 Performance Comparison</h3><p>AspectLifecycle HooksEvent Subscribers<strong>Setup Complexity</strong>LowMedium<strong>Performance Impact</strong>LowMedium<strong>Async Support</strong>❌✅<strong>Dependency Injection</strong>❌✅<strong>Testability</strong>LowHigh<strong>Maintainability</strong>LowHigh</p><h3>🚀 Conclusion</h3><p>TypeORM’s lifecycle hooks and event subscribers provide powerful mechanisms for implementing middleware-like functionality in NestJS applications. The choice between these approaches depends on your specific requirements:</p><p><strong>Key Takeaways:</strong></p><ul><li><strong>Performance</strong>: Keep operations lightweight, queue heavy processing</li><li><strong>Error handling</strong>: Don’t let subscriber errors affect main operations</li><li><strong>Testing</strong>: Ensure comprehensive test coverage</li><li><strong>Maintainability</strong>: Choose the approach that best fits your architecture</li></ul><p>By following these patterns and best practices, you can build robust, maintainable applications that respond intelligently to entity lifecycle events while maintaining good performance and reliability.</p><p><em>What’s your experience with TypeORM lifecycle hooks? Have you used event subscribers in your projects? Share your thoughts in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60d4ee98eeac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS 11: New Features and Examples]]></title>
            <link>https://medium.com/@atillataha/nestjs-11-new-features-and-examples-fb648ab797dc?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb648ab797dc</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 09:15:30 GMT</pubDate>
            <atom:updated>2025-02-12T09:15:30.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OP3ztp6pirJmWrpG.png" /></figure><p>NestJS, a progressive Node.js framework for building efficient and scalable server-side applications, has released its highly anticipated version 11. This update brings a host of new features, performance improvements, and bug fixes.</p><h3>1. IntrinsicException: Silent Error Handling</h3><p>NestJS 11 introduces the IntrinsicException class, which allows developers to throw exceptions that bypass the framework’s automatic logging mechanism. This is particularly useful for sensitive errors or cases where logging is unnecessary.</p><p><strong>Example</strong>:</p><pre>import { IntrinsicException } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class UserService {<br>  async findUser(id: string) {<br>    const user = await this.userRepository.findOne(id);<br>    if (!user) {<br>      throw new IntrinsicException(&#39;User not found&#39;); // This won&#39;t be auto-logged<br>    }<br>    return user;<br>  }<br>}</pre><p>By using IntrinsicException, you can prevent sensitive information from being logged, ensuring better security and cleaner logs.</p><h3>2. CacheModule: Enhanced Caching with Keyv</h3><p>The CacheModule in NestJS 11 has been updated to use cache-manager v6, which leverages <strong>Keyv</strong> for a unified key-value storage interface. This update supports a variety of storage backends, including Redis, MongoDB, and in-memory storage.</p><pre>import { CacheModule } from &#39;@nestjs/cache-manager&#39;;<br>import * as redisStore from &#39;cache-manager-redis-store&#39;;<br><br>@Module({<br>  imports: [<br>    CacheModule.register({<br>      store: redisStore,<br>      host: &#39;localhost&#39;,<br>      port: 6379,<br>      ttl: 60, // Time-to-live in seconds<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><p><strong>Using the Cache</strong>:</p><pre>import { Injectable, Cache } from &#39;@nestjs/common&#39;;<br>import { InjectCache } from &#39;@nestjs/cache-manager&#39;;<br><br>@Injectable()<br>export class UserService {<br>  constructor(@InjectCache() private readonly cacheManager: Cache) {}<br><br>  async getUser(id: string) {<br>    const cachedUser = await this.cacheManager.get(`user_${id}`);<br>    if (cachedUser) {<br>      return cachedUser;<br>    }<br><br>    const user = await this.userRepository.findOne(id);<br>    await this.cacheManager.set(`user_${id}`, user, 60); // Cache for 60 seconds<br>    return user;<br>  }<br>}</pre><p>This update makes caching more flexible and efficient, especially for distributed systems.</p><h3>3. ConfigService: Improved Configuration Management</h3><p>The ConfigService in NestJS 11 now allows developers to override process.env values with custom configuration factories. Additionally, the new skipProcessEnv option simplifies testing by skipping environment variable loading.</p><p><strong>Example Configuration</strong>:</p><pre>import { ConfigModule, ConfigService } from &#39;@nestjs/config&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      skipProcessEnv: true, // Skip loading process.env<br>      load: [() =&gt; ({ database: { host: &#39;localhost&#39;, port: 5432 } })],<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><p><strong>Using ConfigService</strong>:</p><pre>@Injectable()<br>export class DatabaseService {<br>  constructor(private readonly configService: ConfigService) {}<br><br>  getDatabaseConfig() {<br>    return {<br>      host: this.configService.get&lt;string&gt;(&#39;database.host&#39;),<br>      port: this.configService.get&lt;number&gt;(&#39;database.port&#39;),<br>    };<br>  }<br>}</pre><p>This update provides greater flexibility in managing configuration values, especially in testing environments.</p><h3>4. JSON Logging with ConsoleLogger</h3><p>NestJS 11 enhances the default ConsoleLogger with built-in JSON logging support, making it easier to integrate with log aggregation tools.</p><p><strong>Example</strong>:</p><pre>const app = await NestFactory.create(AppModule, {<br>  logger: new ConsoleLogger({<br>    json: true,<br>    colors: process.env.NODE_ENV === &#39;development&#39;, // Enable colors for local development<br>  }),<br>});</pre><p>This outputs logs in JSON format, which is ideal for containerized environments:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2025-02-12T12:34:56.789Z&quot;,<br>  &quot;level&quot;: &quot;INFO&quot;,<br>  &quot;message&quot;: &quot;UserService initialized&quot;,<br>  &quot;context&quot;: &quot;UserService&quot;<br>}</pre><h3>5. Microservices: Advanced Control with unwrap()</h3><p>NestJS 11 introduces the unwrap() method for microservice transporters, allowing direct access to the underlying client instance.</p><p><strong>Example</strong>:</p><pre>const serviceRef = app.connectMicroservice({<br>  transport: Transport.NATS,<br>  options: { servers: [&#39;nats://localhost:4222&#39;] },<br>});<br>const natsConnection = serviceRef.unwrap&lt;NatsConnection&gt;();<br>console.log(natsConnection.info); // Access NATS connection details</pre><p>This feature enables advanced use cases, such as inspecting connection details or performing low-level configurations.</p><h3>6. New ParseDatePipe for Date Validation</h3><p>The ParseDatePipe simplifies date validation in requests, ensuring that incoming date values are properly formatted.</p><pre>@Get()<br>async find(@Query(&#39;date&#39;, ParseDatePipe) date: Date) {<br>  return { date };<br>}</pre><p>This pipe automatically validates and transforms date strings into Date objects, reducing boilerplate code.</p><h3>7. Express v5 and Fastify v5 Support</h3><p>NestJS now aligns with the latest versions of Express and Fastify. While Fastify v5 upgrades are seamless, Express v5 introduces breaking route syntax changes:</p><p><strong>Deprecated Route Syntax</strong>:</p><pre>@Get(&#39;users/*&#39;) // Invalid in Express v5<br>findAll() { ... }</pre><p><strong>Updated Syntax</strong>:</p><pre>@Get(&#39;users/*splat&#39;) // Named wildcard<br>findAll() { ... }</pre><p>Wildcards must now be named (e.g., *splat), and optional parameters require braces (e.g., /:file{.:ext}). Developers should audit existing routes to ensure compatibility</p><h3>8. Faster Application Startup</h3><p>Dynamic module initialization has been optimized by replacing hash-based opaque keys with object references. This reduces startup times significantly for applications with large dynamic modules (e.g., those loading extensive configurations)</p><p><strong>Note</strong>: If your app imports the same dynamic module with identical configurations multiple times, NestJS 11 treats them as separate instances. To retain singleton behavior, assign the module to a variable:</p><pre>const sharedModule = DynamicModule.forRoot({});<br>@Module({ imports: [sharedModule, sharedModule] })<br>export class AppModule {}</pre><h3>9. Updates to GraphQL</h3><p>NestJS 11 brought a major update to the GraphQL module, adding support for Apollo Server v4. This release includes major changes, especially in plugins and federation. For example, the @nestjs/graphql package now supports different drivers like Apollo and Mercurius</p><p><strong>Example:</strong></p><pre>GraphQLModule.forRoot&lt;ApolloDriverConfig&gt;({<br>  driver: ApolloDriver,<br>  autoSchemaFile: &#39;schema.gql&#39;,<br>});</pre><p>This update makes GraphQL-based applications more modular and flexible</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb648ab797dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the React Render Props Design Pattern: A Comprehensive Guide]]></title>
            <link>https://medium.com/@atillataha/exploring-the-react-render-props-design-pattern-a-comprehensive-guide-1033cd57d92c?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1033cd57d92c</guid>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Sun, 08 Oct 2023 17:23:40 GMT</pubDate>
            <atom:updated>2023-10-08T17:23:40.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1LVlRsI20y-vkEw" /></figure><p><strong>Introduction:</strong></p><p>React, a popular JavaScript library for building user interfaces, offers developers various patterns and techniques to create flexible and reusable components. One such pattern is the “Render Props” pattern. In this comprehensive guide, we’ll take an in-depth look at Render Props in React, understanding its core concepts, real-world applications, and advantages over other patterns.</p><p><strong>Chapter 1: Understanding the Render Props Pattern</strong></p><p>The Render Props pattern is a powerful technique that allows components to share data, behavior, and rendering logic. In this chapter, we’ll dissect the fundamental concepts behind Render Props, including how it works and why it’s a valuable tool for React developers.</p><p><strong>Chapter 2: Configuring Components with Render Props</strong></p><p>One of the key advantages of the Render Props pattern is its ability to configure components dynamically. We’ll explore how to create highly customizable components using Render Props, allowing developers to pass configuration options and tailor component behavior as needed.</p><p>Example: Configuring a Button Component with Render Props</p><pre>// Customizable Button Component using Render Props<br>const CustomizableButton = ({ render }) =&gt; {<br>  const buttonConfig = { size: &#39;medium&#39;, color: &#39;blue&#39; };<br>  return &lt;button&gt;{render(buttonConfig)}&lt;/button&gt;;<br>};<br><br>// Usage of the CustomizableButton component<br>&lt;CustomizableButton<br>  render={(config) =&gt; (<br>    &lt;IconComponent size={config.size} color={config.color} /&gt;<br>  )}<br>/&gt;</pre><p><strong>Chapter 3: Sensible State Sharing with Render Props</strong></p><p>Render Props excel at sharing state and logic between components. We’ll delve into practical examples of how to share stateful data efficiently using Render Props, avoiding common pitfalls and making your components more maintainable.</p><p>Example: Sharing Counter State using Render Props</p><pre>// State Sharing Component with Render Props<br>const StateSharingComponent = ({ render }) =&gt; {<br>  const [count, setCount] = useState(0);<br>  return &lt;div&gt;{render(count, setCount)}&lt;/div&gt;;<br>};<br><br>// Utilizing the StateSharingComponent to share counter state<br>&lt;StateSharingComponent<br>  render={(count, setCount) =&gt; (<br>    &lt;div&gt;<br>      Count: {count}<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  )}<br>/&gt;</pre><p><strong>Chapter 4: Optimizing Performance with Render Props</strong></p><p>Render Props can be optimized to prevent unnecessary re-renders and enhance application performance. We’ll explore strategies for optimizing Render Props components, including memoization and controlled updates.</p><p>Example: Optimizing Performance with Memoization</p><pre>// Performance-Optimized Component using Render Props<br>const PerformanceOptimization = ({ render }) =&gt; {<br>  const [data, setData] = useState([]);<br><br>  useEffect(() =&gt; {<br>    // Fetch and update data<br>  }, []);<br><br>  return &lt;div&gt;{render(data)}&lt;/div&gt;;<br>};<br><br>// Applying memoization to the PerformanceOptimization component<br>&lt;PerformanceOptimization<br>  render={useMemo((data) =&gt; &lt;DataComponent data={data} /&gt;, [data])}<br>/&gt;</pre><p><strong>Chapter 5: Render Props vs. React Hooks</strong></p><p>In this chapter, we’ll compare the Render Props pattern to React Hooks, another popular feature for sharing logic in React components. We’ll discuss when to choose Render Props over Hooks and the unique advantages Render Props offer.</p><p><strong>Things to consider with render props</strong></p><p>Render props can make it easier to implement complex interactions and configurations, but they also have some disadvantages.</p><ul><li>Render props can make components dependent on each other. This can make it difficult to develop components independently of each other.</li><li>Render props can make code more difficult to read and understand.</li></ul><p><strong>When to use render props</strong></p><p>Render props are useful in the following situations:</p><ul><li>To make it easier to implement complex interactions or configurations between components</li><li>To ensure that components can be developed independently of each other</li><li>To share the state of components</li></ul><p><strong>Alternatives to render props</strong></p><p>The following alternatives can be used instead of render props:</p><ul><li>Hooks: Hooks are a more modern way to share state and behavior between components.</li><li>Stateless functional components (SFCs): SFCs can be used to implement components that do not need state.</li></ul><p><strong>Conclusion</strong></p><p>By the end of this guide, you’ll have a comprehensive understanding of the React Render Props pattern and its versatile applications. You’ll be equipped to leverage Render Props to create more flexible, reusable, and performant React components in your projects.</p><p>This comprehensive guide provides practical insights, code examples, and best practices to help you master the Render Props pattern and enhance your React development skills.</p><p><strong>Additional details</strong></p><p>Here are some additional details about render props:</p><ul><li>Render props are implemented by passing a function as a prop to another component.</li><li>The function passed as a prop is called the render prop.</li><li>The render prop function returns a React element.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1033cd57d92c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced React“Components as Props Design Pattern” in React with Performance Comparisons]]></title>
            <link>https://medium.com/@atillataha/advanced-react-components-as-props-design-pattern-in-react-with-performance-comparisons-6be44080855c?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6be44080855c</guid>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 17:12:17 GMT</pubDate>
            <atom:updated>2023-10-05T17:12:17.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*u-drWzqMmGQtA25V.png" /></figure><p>React is all about building applications using components, and these components often need to communicate with each other. One way to facilitate this communication and maintain good performance is by using the “Components as Props” pattern. In this article, we’ll delve into this pattern, its advantages, and demonstrate its usage with performance comparisons.</p><h3>What is “Components as Props”?</h3><p>“Components as Props” is a design pattern in React where one component is embedded inside another and used as a prop. This pattern simplifies communication between components, especially in complex applications where different components need to work together.</p><h3>Why Use “Components as Props”?</h3><p>To understand the benefits of “Components as Props,” let’s start with an example and compare it to an alternative approach.</p><h4>Scenario: A Modal Component</h4><p>Imagine you have a modal component, Modal, that can display various content inside it. You want to reuse this modal for different purposes, such as displaying login forms, product details, and notifications.</p><h4>Approach 1: Without “Components as Props”</h4><p>In the first approach, you create a separate Modal component for each use case. Here&#39;s an example of using this approach:</p><pre>// Separate Modal Components<br>function LoginFormModal() {<br>  return (<br>    &lt;Modal&gt;<br>      {/* Login Form Content */}<br>    &lt;/Modal&gt;<br>  );<br>}<br><br>function ProductDetailsModal() {<br>  return (<br>    &lt;Modal&gt;<br>      {/* Product Details Content */}<br>    &lt;/Modal&gt;<br>  );<br>}<br><br>// Usage<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;LoginFormModal /&gt;<br>      &lt;ProductDetailsModal /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>While this approach works, it can lead to code duplication and maintainability issues, especially if you have many modals with similar structures. Each modal component is tightly coupled with its specific content.</p><h4>Approach 2: Using “Components as Props”</h4><p>In the second approach, you create a single, flexible Modal component that accepts its content as a prop. This allows you to reuse the same Modal component for different purposes:</p><pre>// Reusable Modal Component<br>function Modal({ children }) {<br>  return (<br>    &lt;div className=&quot;modal&quot;&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Usage<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Modal&gt;<br>        {/* Login Form Content */}<br>      &lt;/Modal&gt;<br>      &lt;Modal&gt;<br>        {/* Product Details Content */}<br>      &lt;/Modal&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now, you have a single Modal component that can adapt to various use cases by passing different content components as props (children). This reduces code duplication and simplifies maintenance.</p><h3>Performance Comparison</h3><p>You might wonder whether the “Components as Props” pattern affects performance. Let’s analyze the performance differences between the two approaches.</p><p>In Approach 1 (Without “Components as Props”), each modal component creates a new instance of the Modal component. When rendering multiple modals, this can lead to more component instances and potentially affect performance.</p><p>In Approach 2 (Using “Components as Props”), you reuse the same Modal component for different content. Since React is efficient in managing components, the performance impact of rendering multiple modals is minimal.</p><h3>Example: Shopping Cart Application</h3><p>In this example, we’ll create a shopping cart application and demonstrate how to use the “Components as Props” pattern to optimize the shopping cart’s content.</p><h3>Step 1: Basic Shopping Cart</h3><p>First, let’s create a basic shopping cart component:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function ShoppingCart() {<br>  const [cartItems, setCartItems] = useState([]);<br><br>  const addItemToCart = (item) =&gt; {<br>    setCartItems([...cartItems, item]);<br>  };<br><br>  return (<br>    &lt;div className=&quot;shopping-cart&quot;&gt;<br>      &lt;h2&gt;Shopping Cart&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {cartItems.map((item, index) =&gt; (<br>          &lt;li key={index}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;button onClick={() =&gt; addItemToCart(`Item ${cartItems.length + 1}`)}&gt;Add Item&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ShoppingCart;</pre><p>This component represents a shopping cart and allows us to add items to it.</p><h3>Step 2: Adding Slow Components</h3><p>Now, let’s introduce slow components within the cart:</p><pre>import React, { useState } from &#39;react&#39;;<br>import { SlowProductComponent, AnotherSlowProductComponent } from &#39;./components&#39;;<br><br>function ShoppingCart() {<br>  const [cartItems, setCartItems] = useState([]);<br><br>  const addItemToCart = (item) =&gt; {<br>    setCartItems([...cartItems, item]);<br>  };<br><br>  return (<br>    &lt;div className=&quot;shopping-cart&quot;&gt;<br>      &lt;h2&gt;Shopping Cart&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {cartItems.map((item, index) =&gt; (<br>          &lt;li key={index}&gt;<br>            {item}<br>            &lt;SlowProductComponent /&gt;<br>            &lt;AnotherSlowProductComponent /&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;button onClick={() =&gt; addItemToCart(`Item ${cartItems.length + 1}`)}&gt;Add Item&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ShoppingCart;</pre><p>In this step, we render slow components like SlowProductComponent and AnotherSlowProductComponent within each cart item. As new items are added, these slow components also re-render, potentially affecting performance.</p><h3>Step 3: Optimizing with Components as Props</h3><p>Now, let’s optimize our cart using the “Components as Props” pattern. We’ll create a new component called ShoppingCartItem and pass it as a prop to the ShoppingCart component.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function ShoppingCartItem({ children }) {<br>  return (<br>    &lt;li&gt;<br>      {children}<br>    &lt;/li&gt;<br>  );<br>}<br><br>function ShoppingCart() {<br>  const [cartItems, setCartItems] = useState([]);<br><br>  const addItemToCart = (item) =&gt; {<br>    setCartItems([...cartItems, item]);<br>  };<br><br>  return (<br>    &lt;div className=&quot;shopping-cart&quot;&gt;<br>      &lt;h2&gt;Shopping Cart&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {cartItems.map((item, index) =&gt; (<br>          &lt;ShoppingCartItem key={index}&gt;<br>            {item}<br>            &lt;SlowProductComponent /&gt;<br>            &lt;AnotherSlowProductComponent /&gt;<br>          &lt;/ShoppingCartItem&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;button onClick={() =&gt; addItemToCart(`Item ${cartItems.length + 1}`)}&gt;Add Item&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ShoppingCart;</pre><p>Now, we’ve encapsulated the slow components within the ShoppingCartItem component. As new items are added, only the ShoppingCartItem components re-render, not the slow components. This significantly improves the performance of our shopping cart application.</p><p>In this example, we used the “Components as Props” pattern to efficiently manage the rendering of slow components within the shopping cart, optimizing the application’s performance.</p><h3>Conclusion</h3><p>The “Components as Props” pattern in React offers a more modular and efficient way to manage component communication. It promotes code reusability and maintainability by allowing you to pass components as props, adapting to different use cases with ease.</p><p>When choosing between creating separate components and using “Components as Props,” consider the benefits of code organization, reusability, and performance. In most cases, the latter approach will result in cleaner, more efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6be44080855c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Singelton — Sync.Once]]></title>
            <link>https://medium.com/@atillataha/golang-singelton-sync-once-9a237326c8e3?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a237326c8e3</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[golan]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 13:13:07 GMT</pubDate>
            <atom:updated>2023-08-13T13:13:07.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>Golang Singelton — Sync.Once</h3><p>Merhabalar bu arada desing pattern kavramı üzerine çalışmaktayım.Singleton tasarım deseni, bir sınıfın yalnızca bir örneğini oluşturmasını ve bu örneğe genel bir erişim noktası sağlamasını amaçlar. Bu, kaynak kullanımını optimize etmek veya nesnelerin tek bir örneğini paylaşmak gibi durumlar için kullanışlıdır. Bunuda öğrendiğim dillerde farklı kullanımları üzerine düşünüyorum. Go dilinde ilk başta kendi fonsiyonlarını kullanmadan ufak bir singleton tasarım desenini kullanarak bir proje oluşturdum. Arada ki farkı daha iyi anlamak için</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>type Singleton struct{<br> name []string<br>}<br><br>func (s *Singleton) addName( name string){<br> s.name = append(s.name, name)<br>}<br>var instance *Singleton<br><br>func GetInstance() *Singleton{<br> if instance == nil{<br>  instance = &amp;Singleton{<br>   name: []string{},<br>  }<br><br> }<br> return instance<br>}<br><br>func (s Singleton) printSingleton(){<br> fmt.Println(&quot;Singleton&quot;)<br>}<br><br>func main(){<br> singleton := GetInstance()<br> singleton.addName(&quot;John&quot;)<br> singleton.addName(&quot;Doe&quot;)<br> singleton2 := GetInstance()<br> singleton2.addName(&quot;Jane&quot;)<br> singleton2.addName(&quot;Doe&quot;)<br> singleton.printSingleton()<br> fmt.Println(singleton.name)<br>}</pre><p>Burada Singleton adında bir struct oluşturdum ve addName diye bir fonksiyon tanımladım. Dışarı da bir instance oluşturdum bu nesnemin tekrar oluşturulup oluşturulmamasını kontrol etmek için kullanacağım. GetInstance diye oluşturduğum fonksiyon geriye pointer tipinde Singleton nesnesini dönecek ama ondan önce kontrol edecek olşturuduğum instance eğer nil ise yeni Örneği gönderecek. Peki bunu go dilinde sync.once kullanarak naıl yaparız ?</p><p>Go dilinde singleton tasarım deseni, sync.Once paketi ile oldukça kolay bir şekilde uygulanabilir. sync.Once tipi, sadece bir kez çalışacak bir işlevi (fonksiyonu) senkronize bir şekilde çağırmak için kullanılır.</p><p>Örnek bir singleton yapısının ve GetInstance() fonksiyonunun nasıl oluşturulabileceğine dair basit bir örnek:</p><pre>package singleton<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>type Singleton struct {<br> Name string<br>}<br><br>var instance *Singleton<br>var once sync.Once<br><br>func GetInstance() *Singleton {<br> once.Do(func() {<br>  instance = &amp;Singleton{Name: &quot;Instance&quot;}<br> })<br> return instance<br>}<br><br>func (s *Singleton) SayHello() {<br> fmt.Printf(&quot;Hello from %s!\n&quot;, s.Name)<br>}</pre><p>Bu basit örnekte, Singleton adlı bir struct tanımlanmış ve bu struct&#39;ın tek bir örneği oluşturulması amaçlanmıştır. GetInstance() fonksiyonu, sync.Once yardımıyla yalnızca bir kez çağrılarak bu örneği oluşturur. SayHello() fonksiyonu ise örneğin işlevini gösterir.</p><p>Bunu kullanan bir örnek:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;singleton&quot;<br>)<br><br>func main() {<br> instance1 := singleton.GetInstance()<br> instance1.SayHello()<br><br> instance2 := singleton.GetInstance()<br> instance2.Name = &quot;Modified Instance&quot;<br> instance2.SayHello()<br><br> instance1.SayHello()<br>}</pre><p>Bu örnekte GetInstace fonksiyonu once.Do ile sadece bir kere çalışacaktır.</p><p>Evet bu yazımızda Singleton Örneğini hem sync.Once kullanarak hemde kullanmadan yaptık.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a237326c8e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basit olarak Go Dilinde Pointer]]></title>
            <link>https://medium.com/@atillataha/basit-olarak-go-dilinde-pointer-e29617b2fa34?source=rss-755eb80c350d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e29617b2fa34</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[pointer-in-golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Atilla Taha Kördüğüm]]></dc:creator>
            <pubDate>Mon, 29 May 2023 21:59:46 GMT</pubDate>
            <atom:updated>2023-05-29T21:59:46.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Pointerlar, bellekteki bir değerin adresini tutan değişkenlerdir. Bir başka deyişle, bir değişkenin bellek adresini gösteren bir pointer oluşturarak, o bellek adresindeki değeri işaret edebilirsiniz.</p><p>Pointerların kullanılması bazı durumlarda oldukça faydalı olabilir. İşte pointerların neden ve nasıl kullanıldığına dair basit bir örnek:</p><p>Örneğin, bir fonksiyon içerisinde bir değişkenin değerini değiştirmek istediğinizi düşünelim. Ancak fonksiyonlar, genellikle kendi kopyalarını oluşturarak çalışırlar ve parametre olarak geçirilen değişkenler, fonksiyon dışındaki orijinal değişkeni etkilemez. Bu durumda, pointerlar kullanarak değişkenin bellek adresini geçirebilir ve orijinal değişkeni işaret edebilirsiniz.</p><pre>func changeValue(x *int) {<br> *x = 42<br>}<br><br>func main() {<br> var num int = 10<br> fmt.Println(&quot;Before:&quot;, num) // Before: 10<br><br> changeValue(&amp;num)<br> fmt.Println(&quot;After:&quot;, num) // After: 42<br>}</pre><p>Yukarıdaki örnekte, changeValue fonksiyonuna bir pointer geçiriyoruz (*int türünde). Fonksiyon içinde, pointer üzerinden bellekteki orijinal num değişkenine erişiyoruz ve değerini değiştiriyoruz. Bu şekilde, changeValue fonksiyonunun orijinal num değişkenini güncelleyebilmesini sağlıyoruz.</p><p>Pointerlar, aynı zamanda bellek yönetimi ve veri yapılarının oluşturulması gibi ileri seviye konularda da kullanılır. Ancak bu, daha karmaşık bir konudur ve basit bir açıklamayı aşar. Pointerları anlamak için pratik yapmanız ve daha fazla örnek incelemeniz önemlidir.</p><p>Özetle, pointerlar, bellekteki bir değeri işaret etmek ve değişkenler arasında bellek adresleri üzerinden veri aktarımı yapmak için kullanılır. İhtiyaç durumuna göre pointerlar faydalı olabilir, ancak dikkatli bir şekilde kullanılması gereken bir konudur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e29617b2fa34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>