<?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 janlin002 on Medium]]></title>
        <description><![CDATA[Stories by janlin002 on Medium]]></description>
        <link>https://medium.com/@123davidbill?source=rss-e86c029131cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NDe3tAe62l7hikcMDjebEw.png</url>
            <title>Stories by janlin002 on Medium</title>
            <link>https://medium.com/@123davidbill?source=rss-e86c029131cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:16:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@123davidbill/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[2024 年度回顧]]></title>
            <link>https://123davidbill.medium.com/2024-%E5%B9%B4%E5%BA%A6%E5%9B%9E%E9%A1%A7-bda0cd0672e9?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bda0cd0672e9</guid>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 14:19:23 GMT</pubDate>
            <atom:updated>2024-12-28T14:19:23.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5eRdovpnpqXktEHT" /><figcaption>Photo by <a href="https://unsplash.com/@boliviainteligente?utm_source=medium&amp;utm_medium=referral">BoliviaInteligente</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>一扎眼馬上就要2025了，今年雖然或許在工作上沒有升遷，或是帳戶沒有大筆金錢流入，不過今年是我認為這幾年來最認真為自己活著的一年…</p><p>在過去幾年都為了想在工作上擁有一些不一樣的成就，常常沒日沒夜的去研究一些程式相關的東西、或是各種無償加班只為了讓公司能看到我的努力，反而失去了跟家人朋友相處的時間，甚至是把身體搞得很差，不過經歷了一些所謂的辦公室政治以後，我突然覺得我應該去思考自己想要的是什麼，而不是一位的去當一個隨時可棄的棋子(共勉之)</p><p>現在就來回顧今年我做了哪些事吧</p><ol><li><strong>參加了讀書會，並且自己也主講了兩次</strong></li><li><strong>對 Facebook 的專案發了一個PR，並且被合併進去</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*n8qtnDn1jAFiYv1GVCxTuA.png" /></figure><p>雖然這是一個非常小的改動，不過我覺得在這次PR中，見識到了大公司的嚴謹程度根本不是一般公司能夠比擬的，也讓我更加嚮往能夠在充滿大神的團隊裡面工作</p><p><strong>3. 參加了臺北市政府舉辦的黑客松活動，並且奪得佳績</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OUssT-pZCNwPpyyNcb9ww.jpeg" /></figure><p>參加這次的黑客松活動絕對是個偶然，哪天不知道從哪裡獲得了台北市政府黑客松的資訊，然後傳到朋友的群組裡面，沒想到大家都說有興趣，只好硬著頭皮參加，當然也因為是我主動提起的，所以理所當然的我就成為了這次活動的隊長，從前期的說明會到後期的獎金發放都需要自己去洽談，說真的雖然很辛苦，不過也學到了很多</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoC1HIBuP38ke2qQDwOUBw.jpeg" /></figure><p>當然最後也很幸運的拿到了佳作的成績，這邊要特別感謝各位參與的同仁，特別是 Oscar, Scott, Wei 沒有他們就沒有今天的成績</p><p><strong>4. 參加了企業舉辦的在職專班</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkUtKv8196lk8_rQ_zeX3Q.jpeg" /></figure><p>近幾年一直聽到比特幣、加密貨幣這些名詞，不過感覺離我們的生活很遙遠，剛好在網路上看到 XREX 推出了免費的在職專班，只需要投遞履歷就可參與面試篩選，心想反正也沒有損失就投遞了，最後也很幸運的錄取了，並且在裡面認識了很多很有趣的人</p><p><strong>5. 給自己放了為期一個禮拜的假 — 泰國</strong></p><p>這是第一次挑戰自己出國，從機票到房間都需要自己包辦，不過旅途的過程是美好的，放慢角度以後會發現一些平常沒有注意到的細節</p><blockquote><em>獨旅是與自己的和解</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22URdT7CKqwnY8wIJW4K-A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odNGyMXqFY1j5GofUl6QGg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLnf40u0xPPGkT1w5Z45zg.jpeg" /></figure><p><strong>6. 報名了菲律賓的語言學校</strong></p><p>今年因為年中就離開前公司了，然後又不想要馬上就投入工作，所以就報名了為期兩個月的語言學校</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NvNJA7XVbUvqx53StLzjRA.jpeg" /><figcaption>學校環境很好，跟度假村一樣</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaG6NJ1Z4cB8bhDg0jsKJw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIskBhsQcxwzPN7C1m5-TA.jpeg" /><figcaption>菲律賓雖然髒了一點，不過我覺得還算安全</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHrEgB3BF1QJmvBZne-wRQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX0fQd5tJ7hYzeIzMZIJrg.jpeg" /><figcaption>體驗了一些在台灣沒機會體驗的事</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bda0cd0672e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Vue] Computed]]></title>
            <link>https://123davidbill.medium.com/vue-computed-2dd046a4ef57?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dd046a4ef57</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 07:17:04 GMT</pubDate>
            <atom:updated>2024-04-08T07:17:04.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wHVR6edUkGXJhdZ1.png" /></figure><h4>Computed</h4><p>Computed 是 Vue 原生提供的計算屬性，他解決的問題是為了避免讓我們在 Template 中，使用過多的邏輯計算，以官網的例子為例：</p><pre>const author = reactive({<br>  name: &#39;John Doe&#39;,<br>  books: [<br>    &#39;Vue 2 - Advanced Guide&#39;,<br>    &#39;Vue 3 - Basic Guide&#39;,<br>    &#39;Vue 4 - The Mystery&#39;<br>  ]<br>})<br><br>&lt;p&gt;Has published books:&lt;/p&gt;<br>&lt;span&gt;{{ author.books.length &gt; 0 ? &#39;Yes&#39; : &#39;No&#39; }}&lt;/span&gt;</pre><p>在過去，我們習慣把邏輯寫在 Template 中，上面的程式碼雖然還算方便易懂，但考慮到實務上邏輯會更複雜，屆時會看到 Template 中，充斥著各個邏輯，所以我們可以考慮使用 Computed ，把邏輯獨立出來</p><pre>&lt;script setup&gt;<br>import { reactive, computed } from &#39;vue&#39;<br><br>const author = reactive({<br>  name: &#39;John Doe&#39;,<br>  books: [<br>    &#39;Vue 2 - Advanced Guide&#39;,<br>    &#39;Vue 3 - Basic Guide&#39;,<br>    &#39;Vue 4 - The Mystery&#39;<br>  ]<br>})<br><br>// 使用 Computed 將邏輯獨立出來，如果之後需要復用也很方便<br>const publishedBooksMessage = computed(() =&gt; {<br>  return author.books.length &gt; 0 ? &#39;Yes&#39; : &#39;No&#39;<br>})<br><br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;p&gt;Has published books:&lt;/p&gt;<br>  &lt;span&gt;{{ publishedBooksMessage }}&lt;/span&gt;<br>&lt;/template&gt;</pre><p>不過需特別注意的是：透過 Computed 宣告的變數，會以 Ref 的方式呈現，這部分等一下源碼的地方會帶到</p><blockquote>如果對於 Ref 跟 Reactive 不清楚的讀者，可以參考我之前的<a href="https://medium.com/@123davidbill/vue-ref-vs-reactive-d197ca9f20ff">文章</a></blockquote><h4>Computed &amp; TypeScript</h4><p>以下為 Computed 的原始碼，可以看到 Computed 可以接受任何型別的參數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*V1virHCQt5x2eLfiCGGrCg.png" /></figure><p>以官網為例</p><pre>import { ref, computed } from &#39;vue&#39;<br><br>const count = ref(0)<br><br>// 正常情況會推導出型別：ComputedRef&lt;number&gt;<br>const double = computed(() =&gt; count.value * 2)<br><br>// TS Error: Property &#39;split&#39; does not exist on type &#39;number&#39;<br>// 因為 number 沒有 split 的方法，所以報錯<br>const result = double.value.split(&#39;&#39;)<br><br>// 也可以自己手動定義型別<br>const double = computed&lt;number&gt;(() =&gt; {<br>  // 若返回值不是 number 則會報錯<br>})<br></pre><h4>源碼解析</h4><p>我們將第一個範例的 publishedBooksMessage 打印出來，看會長什麼樣子</p><pre>&lt;script setup&gt;<br>import { computed, reactive } from &#39;vue&#39;<br><br>const author = reactive({<br>  name: &#39;John Doe&#39;,<br>  books: [<br>    &#39;Vue 2 - Advanced Guide&#39;,<br>    &#39;Vue 3 - Basic Guide&#39;,<br>    &#39;Vue 4 - The Mystery&#39;<br>  ]<br>})<br><br>const publishedBooksMessage = computed(() =&gt; {<br>  return author.books.length &gt; 0 ? &#39;Yes&#39; : &#39;No&#39;<br>})<br><br>console.log(publishedBooksMessage, &#39;publishedBooksMessage&#39;)<br>&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiGNoVmn5HHC2O0mZMYqKw.png" /></figure><p>console.log 出來的結果如上圖，這邊我們得到一個關鍵字ComputedRefImpl ，那麼現在來看原始碼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*GzoNfHBp-Xh2MP3R8lA0ng.png" /></figure><p>這邊我們針對 get 來做說明</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Aaiq0hnnmeVEyzC3GFe15w.png" /></figure><p>Computed 的邏輯其實就是，發現 hasChanged 如果回傳 True，就觸發 Ref 更新，這邊可以導出另一個觀念：如果 hasChanged 回傳 false 的話，Computed 將不會更新，也就是所謂的 cache</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*jpJpKVzfxNBgB_ggAV0tWQ.png" /><figcaption>hasChanged 是透過 JavaScript 中的 Object.is 來判斷是否更新</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*xTuLf96HL6itrzL0LHz8pQ.png" /><figcaption>toRaw 會根據一個 Vue 創建的代理返回其原始對象。<a href="https://cn.vuejs.org/api/reactivity-advanced.html#toraw">https://cn.vuejs.org/api/reactivity-advanced.html#toraw</a></figcaption></figure><h4>Computed vs Function</h4><p>一般來說 Computed 跟 Function 所達到的效果會是一樣的</p><pre>const publishedBooksMessage1 = computed(() =&gt; {<br>  return author.books.length &gt; 0 ? &#39;Yes&#39; : &#39;No&#39;<br>})<br><br>&lt;div&gt;{{ publishedBooksMessage1 }}&lt;div&gt;<br></pre><pre>const publishedBooksMessage2 = () =&gt; {<br>  return author.books.length &gt; 0 ? &#39;Yes&#39; : &#39;No&#39;<br>}<br><br>&lt;div&gt;{{ publishedBooksMessage2() }}&lt;div&gt;</pre><p>他們唯一的差別在於，有沒有 cache<br>以 Computed 為例，author.books 沒有更新的話，publishedBooksMessage1 就不會重新計算<br>function 版本只要 畫面出現 re-render 就會造成 publishedBooksMessage2 重新計算<br>所以如果今天有需要做到大效能計算的邏輯，可以考慮包裝成 Computed ，來減少不必要的渲染</p><h4>Computed &amp; Methods &amp; Watch</h4><ul><li>computed 最大特點是必須回傳一個值，並且會把它緩存起來，當函式裏的依賴改變時，才會重新執行和求值</li><li>watch 會偵測單一個值，當它有變化時就執行。</li><li>methods 只要呼叫它，它就會執行。通常用於點擊事件</li></ul><h4>參考文章</h4><ul><li><a href="https://vuejs.org/guide/essentials/computed.html#computed-caching-vs-methods">Vue.js</a></li><li><a href="https://github.com/vuejs/core">GitHub - vuejs/core: 🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dd046a4ef57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Vue] Ref vs Reactive]]></title>
            <link>https://123davidbill.medium.com/vue-ref-vs-reactive-d197ca9f20ff?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d197ca9f20ff</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 12:25:46 GMT</pubDate>
            <atom:updated>2024-04-02T12:25:46.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*_9cwb2GcDnE9a9a2.png" /></figure><p>前陣子為了支援公司的專案 (Vue2)，花了點時間在研究 Vue ，沒想到越陷越深，就開始研究 Vue3 ，還加入了一個 Vue 的讀書會，剛好 Ref vs Reactive 是我主講的內容，所以就把當天主講的內容整理一下，寫成這篇文章吧</p><h4>Composition API</h4><p>Vue3 時出了一個新的元件編寫方式，也就是 Composition API，Composition API 讓我們可以解決過去邏輯散落在各地的問題</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xeb0d9RCkEOjTc-p.png" /><figcaption><a href="https://fjolt.com/article/vue-composition-api-vs-options-api">https://fjolt.com/article/vue-composition-api-vs-options-api</a></figcaption></figure><p>再來就是隨著 TypeScript 的崛起，Vue3 的 Composition API 也選擇跟進，所以如果使用 Composition API 以後，會對於 TypeScript 的開發者更加友好</p><p>最重要的是 Composition API 是出了兩個語法: Ref, Reactive，也就是本篇文章的重點</p><h4>setup</h4><p>Vue 3 中如果想要使用 Composition API 的功能，須先宣告 setup ，過去在使用 setup() 時，每次都要手動 return Ref() 的變數，常會造成開發時的困擾，所以官方後續提供了 &lt;script setup&gt; 方法，也就不用擔心會忘記 return 了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Au7uxWcWUhFQi6aj" /><figcaption><a href="https://twitter.com/vuejs/status/1428350895654203409">https://twitter.com/vuejs/status/1428350895654203409</a></figcaption></figure><h4>Ref</h4><p>Ref() 是一個可以接受任何型別的參數，並且會回傳一個內部只包含一個 value 屬性的響應式物件，在使用 Ref() 時，需特別注意兩件事:</p><ol><li>直接對 Ref() 中的 value 屬性修改時，修改完的物件，同樣會具備響應式的效果</li><li>Ref 並不會對 Object 與 Array 的內部屬性做監聽，如果有需要做到對內部屬性監聽的效果，可以考慮使用 Reactive()</li></ol><h4>Ref &amp; TypeScript</h4><p>Vue 原生有提供 Ref 型別</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*jPnBJW7DS5upzFrCasi4MQ.png" /></figure><p>原始碼的部分，直接使用 TypeScript 的泛型處理，並且預設為 any ，也就應證前面所說：Ref() 是一個可以接受任何型別的參數</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_X6zAPSjv5irTf_KUd2xXg.png" /><figcaption><a href="https://github.com/vuejs/vue/blob/bed04a77e575d6c4c1d903f60087dca874f7213e/src/v3/reactivity/ref.ts#L20">https://github.com/vuejs/vue/blob/bed04a77e575d6c4c1d903f60087dca874f7213e/src/v3/reactivity/ref.ts#L20</a></figcaption></figure><h4><strong>Why Ref?</strong></h4><p>Ref() 這種寫法，每次都需要 .value() 才能取得到我們想要的值，感覺寫法很不美觀，Vue 3 會推出 Ref() 的原因，主要就是為了達到 <strong>Reactivity </strong>的效果</p><h4><strong>Reactivity</strong></h4><p>指的是 Vue 幫助你即時更新相依資料這件事</p><p><em>…it’s the concept that when x changes or updates in one location, the things that depend on the value of x are recalculated and updated in various other locations in a non-blocking fashion, without having to tie up threads sitting around just waiting for events to happen. ….</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*TmZFfIJW5rIEow7KdGts6Q.png" /></figure><p>上方程式碼，點擊按鈕以後，console.log 會持續更新，但畫面不會跟著改變，會一直停留在預設值 1 ，這是因為我們沒有達到 Reactivity 的效果，（畫面不知道資料有更新）</p><h4>Ref 怎麼實現 Reactivity？</h4><p>Ref 是使用 getter setter 來達到 Reactivity 效果的</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*bppKlsNFh_Xqc3U5kvfAEQ.png" /><figcaption><a href="https://vuejs.org/guide/essentials/reactivity-fundamentals.html#ref">https://vuejs.org/guide/essentials/reactivity-fundamentals.html#ref</a></figcaption></figure><p>上方程式碼是官網的示意圖，當觸發(trigger)到資料更改時，會同步的提醒(track)監聽對象資料有更新，需做相對應的處理</p><h4><strong>Ref &amp; Object</strong></h4><p>前面有說 Ref() 是一個可以接受任何型別的參數，不過他在處理 Object 型別這塊，還是使用 Reactive()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*OMN5F3xoJvGRJkCmLbcG3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*keep4dmAcZWKLIIuL8T8CA.png" /></figure><p>雖然還沒介紹到 Reactive()，但可以看到 msg.value 打印出來的結果是一個 Proxy，而 Reactive 就是使用 Proxy 實現的</p><p>這樣的說法有點牽強，不能看到 Proxy 就說是 Reactive()，所以來看一下原始碼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*w7bOsgGchqBxPg-g" /></figure><p>可以看到倒數第二行，有判斷是否為一般型別，如果不是的話就將 newVal 帶到 toReactive 中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*k8Zfd7Pis14RbzrqPNiUrQ.png" /></figure><h4>Reactive</h4><p>Reactive() 是一個只能接受 Object 型別的參數，並且使用時，不需要使用 .value() 就可以取到值，這點跟 Ref() 不一樣，需特別注意</p><h4>Reactive 的原理</h4><p>Reactive 是透過 Proxy 實現，不過特別的是最早之前 Vue 是透過 Object.defineProperty 去實現 Reactive()，待等到 ES6 出了 Proxy 以後，才將 Reactive() 用 Proxy 的方式去改寫</p><h4>Object.defieneProperty vs Proxy</h4><p>Object.defineProperty 是 ES5 出的語法，而 Proxy 則是 ES6 出的語法</p><p>Object.defineProperty 是用來定義對象的屬性，而 Proxy 則是用來代理對象並對其進行操作攔截和修改。兩者的應用場景不同，但都可以用來對對象的行為進行定制化。</p><p>Vue 最一開始是使用 Object.defineProperty 實作 Reactive()，不過 Object.defineProperty 卻有一些問題，例如: 無法監聽對象屬性的新增和刪除</p><pre>let num = 3<br>const cat = {<br>    name: &#39;大橘&#39;,<br>    sex: &#39;boy&#39;,<br>    age: 5<br>}<br>Object.defineProperty(cat,&#39;age&#39;,{<br>    get() {<br>        console.log(&#39;get value&#39;)<br>        return num<br>    },<br>    set(val) {<br>        console.log(&#39;set value&#39;, val)<br>        num = val<br>    }<br>})<br>cat.age = 6 // 可以被監聽到<br>cat.breed = &#39;狸花猫&#39; // 無法被監聽到</pre><p>由於 breed 不在原始的 cat 中，所以無法觸發 set function</p><p>可以看到數據無法被讀取到，從而無法實現數據的響應式，所以在 Vue2 中增加了 set、delete 等API，並且對數組的 api 也進行了重寫。並且這種響應式對深層的嵌套對象，需要進行深層的監聽，會消耗極大的性能。</p><p>所以當 Proxy 出來以後，就選擇使用 Proxy 取代 Object.defineProperty</p><blockquote>如果不熟悉 Proxy 可以看我之前的<a href="https://123davidbill.medium.com/%E9%82%A3%E4%BA%9B%E5%B9%B4-%E6%88%91%E5%80%91%E9%81%BA%E5%BF%98%E7%9A%84-proxy-reflect-eebeaca68d1b">文章</a></blockquote><h4>Reactive &amp; TypeScript</h4><p>Reactive 的型別定義方法就跟一般的 Object 一樣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*DW7gNALxS9jVc7e__vgnJw.png" /></figure><p>記得 Reactive 的型別一定要是 Object 型別，不然會出錯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*XXWZrdPW4Ca0Ymh3arSaog.png" /><figcaption><a href="https://github.com/vuejs/vue/blob/bed04a77e575d6c4c1d903f60087dca874f7213e/src/v3/reactivity/reactive.ts#L32">https://github.com/vuejs/vue/blob/bed04a77e575d6c4c1d903f60087dca874f7213e/src/v3/reactivity/reactive.ts#L32</a></figcaption></figure><p>原始碼的部分，可以看到雖然跟 Ref 一樣是使用泛型處理，不過卻繼承 (extends) 了 object 型別，所以記得不要使用 Reactive 去宣告一個普通型別的值</p><h4>Bonus: 為什麼 Reactive 接收一般型別的變數不會白畫面？</h4><p>前面提到 Reactive() 是使用 Proxy 實現的，但是為什麼 Proxy 可以接收一個非 Object 型別的變數？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*WDcgmyZaQBrBqc0eiIvo_g.png" /><figcaption>如果在 Proxy 的 target 或 handler 使用了非 object 型別的變數，就會報錯</figcaption></figure><p>原因是因為 Vue 有做一個防呆機制，透過 isObject() 方法來判斷是否為 Object 型別，確定是 Object 型別，才能夠執行 reactive()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*5uDuc2mWliw5I755-laYQw.png" /><figcaption><a href="https://github.com/vuejs/core/blob/0dea7f9a260d93eb6c39aabac8c94c2c9b2042dd/packages/reactivity/src/baseHandlers.ts#L89">https://github.com/vuejs/core/blob/0dea7f9a260d93eb6c39aabac8c94c2c9b2042dd/packages/reactivity/src/baseHandlers.ts#L89</a></figcaption></figure><h4>Ref vs Reactive 怎麼選？</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/131d9011513f13df89b9bcfc66c3aedd/href">https://medium.com/media/131d9011513f13df89b9bcfc66c3aedd/href</a></iframe><p>這邊作者之前有被訪問到，結論就是團隊溝通好就好</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe8Wlv4AGJjk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De8Wlv4AGJjk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe8Wlv4AGJjk%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/8f0e7753f789c7d224e032c078738c8d/href">https://medium.com/media/8f0e7753f789c7d224e032c078738c8d/href</a></iframe><h4>Vue 2 中如何使用 Ref &amp; Reactive</h4><p>如果你的專案還是 Vue2，並且想直接使用 Composition API ，有很多方式，下面我推薦兩個種：</p><ol><li>@vue/composition-api (官網推薦)</li><li>Vue-demi (監聽你的 package.json 內的版本，再決定要傳遞什麼版本的 Composition API，原始碼很少，推薦可以看看)</li></ol><h4>深度探討</h4><ul><li>template 中有些資料是固定不動的，還需要使用 ref/reactive 綁定嗎？</li></ul><h4>參考資料</h4><ul><li><a href="https://book.vue.tw/CH6/6-1-composition-intro.html">6-1 Composition API 簡介 | 重新認識 Vue.js | Kuro Hsu</a></li><li><a href="https://vuejs.org/guide/essentials/reactivity-fundamentals.html">Vue.js</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d197ca9f20ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[演算法筆記] Search — 搜尋]]></title>
            <link>https://123davidbill.medium.com/%E6%BC%94%E7%AE%97%E6%B3%95%E7%AD%86%E8%A8%98-search-%E6%90%9C%E5%B0%8B-7a4e6903b8b1?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a4e6903b8b1</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 07:09:34 GMT</pubDate>
            <atom:updated>2024-03-24T07:09:34.990Z</atom:updated>
            <content:encoded><![CDATA[<h3>[演算法筆記] Search — 搜尋</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kw_pomyH0g7GffVb" /><figcaption>Photo by <a href="https://unsplash.com/@rocinante_11?utm_source=medium&amp;utm_medium=referral">Mick Haupt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>Linear Search</li><li>Binary Search</li><li>BFS &amp; DFS</li></ul><h4>Linear Search — 線性搜尋法</h4><p><strong>線性搜索 </strong>是一種尋找某一特定值的搜索算法，指按一定的順序檢查數組中[<strong>每一個元素]</strong>，直到找到所要尋找的特定值為止。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*xQQW1sLauKA_OECS.png" /></figure><p><strong>程式碼</strong></p><pre>function linearSearch(arr, target) {<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (arr[i] === target) { <br>      // 如果找到目標，就回傳<br>      return i;<br>    }<br>  }<br>  // 如果目標不在 arr 中，就返回 -1<br>  return -1;<br>}<br><br>const array = [4, 2, 10, 7, 1, 9];<br>const targetElement = 7;<br>const resultIndex = linearSearch(array, targetElement);</pre><p><strong>時間複雜度</strong></p><p>O(n)</p><p>因為是檢查數組中的 [<strong>每一項]</strong>，所以複雜度為 O(n) ，雖然有可能第一項就找到目標，但我們通常只會關注最壞情況下的複雜度</p><h4>Binary Search — 二分搜尋</h4><p>二分搜尋法 是一種在 [<strong>有序陣列] </strong>中搜尋某一特定元素的搜尋演算法。搜尋過程從陣列的 [<strong>中間元素] </strong>開始，如果中間元素正好是要搜尋的元素，則搜尋過程結束。</p><p>如果某一特定元素大於或者小於中間元素，則在陣列大於或小於中間元素的那一半中搜尋</p><p>跟開始一樣從中間元素開始比較。如果在某一步驟陣列為空，則代表找不到。這種搜尋演算法 [<strong>每一次比較都使搜尋範圍縮小一半]</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*EuQn5xmPdtRJfFaD.png" /></figure><p><strong>程式碼</strong></p><pre>let iterativeFunction = function (arr, x) {<br>  let start = 0,<br>    end = arr.length - 1;<br><br>  while (start &lt;= end) {<br>    let mid = Math.floor((start + end) / 2); // 先將序列最中間的元素取出<br><br>    if (arr[mid] === x) return true;<br>    // 如果目標大於中間元素，說明會在右半邊，所以須調整 start 的位置<br>    // 然後因為中間元素跟目標不相符，所以 index 須加一 (mid + 1)<br>    // iterativeFunction([23, 38, 56, 72, 91], 23)<br>    else if (arr[mid] &lt; x) start = mid + 1; <br>    // 反之，調整 end 位置<br>    else end = mid - 1;<br>  }<br><br>  return false;<br>};<br><br>iterativeFunction([2, 5, 8, 12, 16, 23, 38, 56, 72, 92], 23)</pre><p><strong>完整程式碼</strong></p><pre>let iterativeFunction = function (arr, x) {<br>  let start = 0,<br>    end = arr.length - 1;<br><br>  while (start &lt;= end) {<br>    let mid = Math.floor((start + end) / 2);<br><br>    if (arr[mid] === x) return true;<br>    else if (arr[mid] &lt; x) start = mid + 1; <br>    else end = mid - 1;<br>  }<br><br>  return false;<br>};<br><br>iterativeFunction([2, 5, 8, 12, 16, 23, 38, 56, 72, 92], 23)</pre><p><strong>時間複雜度</strong></p><p>O(logn)</p><h4><strong>BONUS: 什麼是 log ?</strong></h4><p>log 就是所謂的對數</p><p>公式如下:</p><pre>logₐ(x) = y</pre><p>a: 底數(如果為 10 可以省略)</p><p>x: 真數</p><p>y: 對數</p><p>我們可以理解為: <strong>底數</strong>的<strong>對數</strong>次方為<strong>真數</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*DxYpcS6pZr-8aUQZ.png" /></figure><p>至於為什麼 logn 的時間複雜度較好？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*7hOT4Onvw1koSkae.png" /></figure><p>可以看到 logn 的線圖趨近於 1 ，隨著樣本數量越大會越趨近於平緩，也就是為什麼時間複雜度會越好</p><h4>BONUS: BFS &amp; DFS</h4><p><strong>深度優先搜尋</strong>(Depth-First Search,DFS) 與 <strong>廣度優先搜尋</strong>(Breadth-First Search, BFS)，是可以用來走訪或搜尋樹節點與圖頂點的演算法</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*HssaWFSQQdw5jGxt" /></figure><h4>BFS</h4><blockquote>水平搜尋</blockquote><p><strong>原理</strong></p><p>先選定一個頂點開始走訪，逐一走過此頂點相鄰未被走過的頂點，若相鄰頂點都被走過，再從走訪過的頂點中擇一為新記錄點，逐一走過新記錄點相鄰未被走過的頂點，以此類推。</p><p><strong>程式碼</strong></p><pre>const graph = {<br>  A: [&quot;B&quot;, &quot;C&quot;],<br>  B: [&quot;A&quot;, &quot;D&quot;, &quot;E&quot;],<br>  C: [&quot;A&quot;, &quot;F&quot;],<br>  D: [&quot;B&quot;],<br>  E: [&quot;B&quot;, &quot;F&quot;],<br>  F: [&quot;C&quot;, &quot;E&quot;],<br>};<br><br>function bfs(graph, start) {<br>  const queue = [start];<br>  const visited = new Set([start]);<br><br>  while (queue.length &gt; 0) {<br><br>    const vertex = queue.shift();<br>    for (const neighbor of graph[vertex]) {<br>      if (!visited.has(neighbor)) {<br>        queue.push(neighbor);<br>        visited.add(neighbor);<br>      }<br>    }<br>  }<br>}<br><br>bfs(graph, &quot;A&quot;);</pre><p><strong>影音支援</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmL5vCsLR1no%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmL5vCsLR1no&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmL5vCsLR1no%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/0a7cddad5fcf81d5fa01374974cb9764/href">https://medium.com/media/0a7cddad5fcf81d5fa01374974cb9764/href</a></iframe><h4>DFS</h4><blockquote>垂直搜尋</blockquote><p><strong>原理</strong></p><p>先選定一個頂點開始走訪，接著從此頂點相鄰未被走過的頂點中，擇一走訪標示為記錄點，以此類推，不斷從新記錄點的相鄰未被走過頂點中尋找。</p><p>若新紀錄點的相鄰頂點都被走過，則退回起點，繼續從未被走過頂點中尋找。</p><p><strong>程式碼</strong></p><pre>DFSPreOrder (){<br>    let result = []<br><br>    function traverse(currentNode){<br>        result.pish(currentNode)<br>        if(currentNode.right){<br>            traverse(currentNode.right)<br>        }<br>        if(currentNode.left){<br>            traverse(currentNode.left)<br>        }<br>    }<br><br>    traverse(this.root)<br><br>    return result<br>}</pre><p><strong>影音支援</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8ycDb59RECk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8ycDb59RECk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8ycDb59RECk%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/ef58398a1937f2b08bb3cf3c9114cd50/href">https://medium.com/media/ef58398a1937f2b08bb3cf3c9114cd50/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a4e6903b8b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[筆記]開源協作會需要知道的 Git 指令]]></title>
            <link>https://123davidbill.medium.com/%E7%AD%86%E8%A8%98-%E9%96%8B%E6%BA%90%E6%9C%83%E9%9C%80%E8%A6%81%E7%9F%A5%E9%81%93%E7%9A%84-git-%E6%8C%87%E4%BB%A4-b3807efd7336?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3807efd7336</guid>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 00:14:58 GMT</pubDate>
            <atom:updated>2024-02-22T00:16:20.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WqYUIeH3McLzZD1H" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>fork 一個專案<br>git clone fork的專案<br>git checkout -b branch-name<br><br>// ...開發<br><br>git add .<br>git commit -m &#39;xxx&#39;<br>git push <br><br>// ...發 PR<br><br>// 同步遠端<br>git remote add upstream 遠端專案<br>git fetch upstream<br>git checkout master<br>// 指定本地端 master 的上游為開源專案的 master<br>git branch --set-upstream-to upstream/master <br>git status<br><br>// 情境: 開發到一半，遠端分支更新了<br>git remote update<br>git fetch upstream master<br>git rebase upstream/master </pre><p>參考文章</p><ul><li><a href="https://github.com/gabrieldemarmiesse/getting_started_open_source">GitHub - gabrieldemarmiesse/getting_started_open_source: You want to contribute to an open-source project? You don&#39;t know how to do it? Here is how to.</a></li><li><a href="https://github.com/janlin002/docker_practice?tab=readme-ov-file">GitHub - janlin002/docker_practice: Learn and understand Docker, with real DevOps practice!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3807efd7336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma + MongoDB 部署到 Render 一次搞定]]></title>
            <link>https://123davidbill.medium.com/prisma-mongodb-%E9%83%A8%E7%BD%B2%E5%88%B0-render-%E4%B8%80%E6%AC%A1%E6%90%9E%E5%AE%9A-b1aabac304e0?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1aabac304e0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[render]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 15:07:49 GMT</pubDate>
            <atom:updated>2024-02-09T15:07:49.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*96k8WkOUnZdV6LbQ" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>這篇文章會分成兩個部分:</p><ol><li>Prisma 如何跟 MongoDB 做連線</li><li>如何將 Nestjs 專案部署到 Render</li></ol><p>首先，在文章開始，先祝大家新年快樂、新的一年都賺大錢~</p><p>順便推薦我之前的文章，在讀文章前，先去看看之前的文章，會比較清楚:</p><p>Nest 基礎介紹:</p><p><a href="https://123davidbill.medium.com/nestjs-%E5%9F%BA%E7%A4%8E%E4%BB%8B%E7%B4%B9-315cea073865">Nestjs 基礎介紹</a></p><p>Prisma 入門指南:</p><p><a href="https://123davidbill.medium.com/prisma-%E5%85%A5%E9%96%80%E6%8C%87%E5%8D%97-e130d2bfe0d8">Prisma 入門指南</a></p><h4>Prisma 如何跟 MongoDB 做連線</h4><p>首先，我們需要先將 Prisma 加入到專案中</p><pre>npm install prisma --save-dev<br>prisma init</pre><p>不意外的話，Prisma 會自動建立一個資料夾 prisma/schema.prisma ，預設是使用 PostgreSql，現在我們要改成 MongoDB</p><pre>datasource db {<br>  provider = &quot;mongodb&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}<br><br>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}</pre><p>然後我們要修改一下 .env 裡面 DATABASE_URL ，把它改成 MongoDB 的 URL</p><p>格式如下：</p><pre>mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE</pre><h4>DATABASE_URL 怎麼取得？</h4><ol><li>進入 MongoDB 官網中，建立一個專案，並且幫這個專案取得響亮的名字</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*gR9MVPWFwQo4Zcyr2ELl5Q.png" /></figure><p>2. 如果有協作人員，可以把他一起加入到專案中，沒有的話，直接按 create 即可</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*li1WtIAvFFVRAKHVqiRNmg.png" /></figure><p>3. 開好專案以後，我們現在要建立第一個 database，點擊左側選單中的 Database 然後再點擊 Build a Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8aB-gdiPUjFLxYgNDdFEg.png" /></figure><p>4. 以下是我的基本配置(畫面沒有切換到免費版)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mrEM_-dwTSAcr9xDGTEtg.png" /></figure><p>5. 建立好 database 以後，會出現 Quickstart 的畫面，這邊會有這個 database 的 使用者名稱 跟 password，很重要，要記起來</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*-PZTKFts3D6dZzQCloPioA.jpeg" /></figure><p>6. 在做到第 5 點時，其實基本的 database 就已經完成了，不過要跟我們的專案做連結，所以我們回到 Database 頁面，點擊 connect 並且選取 Drivers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-820hJJ5goUa5h8HEAcFw.png" /></figure><p>7. 下面那串聯結就是你的 DATABASE_URL，步過記得要將中間的 &lt;password&gt; 換成剛剛 第 5 步 拿到的 password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*mWLJ4C2twnMYfHyFTy4w4g.png" /></figure><h4>連結到 Nest.js</h4><p>上面講解了如何拿到 DATABASE_URL 以後，現在我們要來講如何連結到 Nestjs</p><p>其實就只需要把剛剛拿到的連結塞到 .env 裡的 DATABASE_URL 就好</p><pre>DATABASE_URL=&quot;mongodb+srv://&lt;username&gt;:&lt;password&gt;@intoolview.b9bzqyr.mongodb.net/test?retryWrites=true&amp;w=majority&quot;</pre><h4>Bonus： 同步 schema &amp; database</h4><pre>npx prisma db push</pre><p>透過上面的指令，可以將我們的 prisma/schema.prisma 跟 MongoDB 達到同步的效果</p><h4>如何將 Nestjs 專案部署到 Render</h4><ol><li>Render 提供了很多的部署服務，這邊我們選取 Web Service</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*8cHnd3qp4qUKk8_ZQ5kypw.png" /></figure><p>2. 這邊因為我的專案有 Push 到 Github ，所以我選擇 Build and deploy from a Git repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*C0HbbpRIt4Vdog22-kAaRw.png" /></figure><p>3. 選取一個 Github 裡的專案，或是使用 Github 的連結也可以</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QSglI0v0dNsAA3dtmbhMvA.png" /></figure><p>4. 幫自己的專案命名，需要特別注意的是 Build commpand<br>如果單純寫 npm run build 會報錯: nest: not found，解決方法就是在 build 之前，先 install</p><pre>npm install &amp;&amp; npm run build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Id5D3PO0iFJHoh7bC9riew.png" /></figure><p>5. 這邊我們一樣當 免費仔，環境變數的部分，需要填寫兩個欄位 DATABASE_URL 這個就是前面講的那個 DATABASE_URL，然後我們需要將 NODE_VERSION 改成 18.18.0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct3T4WeChnxyDvO5uEqpUQ.png" /></figure><p>6. 這樣就部署成功拉~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qwTlum4a18GS2mmxl4Ucg.png" /></figure><blockquote>這篇幾乎都是圖片，希望會幫助到需要的人~</blockquote><h4>推薦文章</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0Pt7Kfh78Jg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0Pt7Kfh78Jg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0Pt7Kfh78Jg%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/7bd1e31739bb143927919548b069d947/href">https://medium.com/media/7bd1e31739bb143927919548b069d947/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fu62W6XN3uD4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Du62W6XN3uD4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fu62W6XN3uD4%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/0a75d4dc1a986d7b1d901794ace83e49/href">https://medium.com/media/0a75d4dc1a986d7b1d901794ace83e49/href</a></iframe><ul><li><a href="https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/mongodb-typescript-mongodb">Start from scratch with MongoDB (15 min) : typescript-mongodb</a></li><li><a href="https://velog.io/@youngkiu/MongoDB-Using-Prisma-in-NestJS">velog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1aabac304e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma 入門指南]]></title>
            <link>https://123davidbill.medium.com/prisma-%E5%85%A5%E9%96%80%E6%8C%87%E5%8D%97-e130d2bfe0d8?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e130d2bfe0d8</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 08:42:34 GMT</pubDate>
            <atom:updated>2023-12-21T08:42:34.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*E6TRT7I9JnJPZEQ9.png" /></figure><h4><strong>什麼是 Prisma?</strong></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHExSdWnXlvk%3Fstart%3D1160%26feature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHExSdWnXlvk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHExSdWnXlvk%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e314d435d062adf078d3a409d0004292/href">https://medium.com/media/e314d435d062adf078d3a409d0004292/href</a></iframe><blockquote>蠻推薦各位可以去看這部影片，短短 50 分鐘，把 Prisma 精華都講過一遍了</blockquote><p>Nest 官網是這樣描述 Prisma 的</p><blockquote>Prisma is an open-source ORM for Node.js and TypeScript. It is used as an alternative to writing plain SQL, or using another database access tool such as SQL query builders (like knex.js) or ORMs (like TypeORM and Sequelize). Prisma currently supports PostgreSQL, MySQL, SQL Server, SQLite, MongoDB and CockroachDB (Preview).</blockquote><p>那我們用 chatGPT 來翻譯一下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*-fOvomjAS7vHjZDB.png" /></figure><blockquote>Prisma 是用於Node.js和TypeScript的開源ORM（對象-關係映射）。它被用作替代編寫純SQL或使用其他數據庫訪問工具（如knex.js）或ORM（如TypeORM和Sequelize）。Prisma目前支持PostgreSQL、MySQL、SQL Server、SQLite、MongoDB和CockroachDB。</blockquote><p>那麼新的問題來了，什麼是 ORM?</p><h4><strong>什麼是 ORM?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bRzPsfBvMjD-Djec.png" /></figure><p>在過去後端在對資料庫操作時，都需要寫一些 SQL 語言，來跟資料庫互動，不過這樣有些缺點</p><p>1. 程式碼會變得比較難以維護</p><p>2. 容易寫錯，例如:空行不對,缺少引號</p><p>3. 容易遭到 SQL Injection 攻擊</p><p>為了解決以上問題，就出現了 ORM ，ORM 不在需要自己去寫 SQL 語法，而是使用 OOP 的概念去撰寫</p><p>sql 語法</p><pre>SELECT * FROM TABLE</pre><p>ORM 語法</p><pre>this.prisma.table.findMany();</pre><p>當然 ORM 也不是沒有缺點，由於需要在背後大量的轉換 SQL 語法，導致效能上也比直接操作 SQL 來的更慢一些</p><p>對 ORM 有興趣的讀者，可以參考<a href="https://www.explainthis.io/zh-hant/swe/orm-intro">這篇文章</a></p><blockquote>總的來說 Prisma 就是一個可以讓我們用 OOP 概念去操作資料庫的套件，除了這次要介紹的 Prisma 之前我們介紹過的 TypeORM 也是在做一樣的事情</blockquote><h4>建立 Nest 專案</h4><pre>$ npm i -g @nestjs/cli<br>$ nest new [project-name]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*BMoYXZndZgqueMnjfvYo2A.png" /></figure><p>建立完專案以後，試著把專案 run 起來，確定沒有問題</p><pre>$ npm run start:dev</pre><h4>Docker + PostgreSql</h4><blockquote>這邊如果有任何錯誤，都歡迎留言給我，十分感謝</blockquote><p>首先線建立一個 docker-compose.yml 資料夾</p><pre>touch docker-compose.yml</pre><p>不知道 Docker compose 的讀者，可以看<a href="https://lufor129.medium.com/docker-%E5%85%AD-%E7%94%A8docker-compose%E5%BB%BA%E7%AB%8B%E8%88%87%E5%AF%A6%E4%BD%9Cweb%E5%B0%88%E6%A1%88-a709a1a24382">這篇文章</a></p><p>並且輸入以下程式碼</p><pre>version: &#39;3.1&#39;<br>services:<br>postgres:<br>container_name: postgres<br>image: postgres:13.5<br>restart: always<br>ports:<br>- 5432:5432<br>environment:<br>POSTGRES_USER: postgres<br>POSTGRES_PASSWORD: postgres<br>POSTGRES_DB: postgres<br>PGDATA: ./pgdata:/var/lib/postgresql/data/pgdata</pre><ul><li>image 裡面 postgres 的版本可以自己選擇，可參考 postgres 的 <a href="https://hub.docker.com/_/postgres">DockerHub</a></li><li>port 分為兩部分host_port 跟 container_port，以上方程式碼可解讀成: 你將主機的連接埠 5432 對應到 postgres 容器的連接埠 5432。 (5432 通常是 PostgreSQL 使用的連接埠)</li></ul><p>接著我們需要透過指令構建 image 並執行 container</p><pre>docker-compose up</pre><p>環境架設起來後，接著就可以到 pgAdmin 裡面做連線了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTblhMJ9YcwhVGrapY84kA.png" /></figure><p>對 docker 連線 PostgreSql 有興趣的讀者，可以參考<a href="https://blog.devcloud.com.tw/rang-kai-fa-zhe-shi-yong-docker-desktop-qi-dong-postgres-kuai-su-kai-shi-jin-xing-kai-fa/">這篇文章</a></p><h4><strong>Set up Prisma</strong></h4><blockquote>推薦大家在開發 Prisma 時，一定要下載 vscode Prisma <a href="https://marketplace.visualstudio.com/items?itemName=Prisma.prisma">套件</a></blockquote><p>資料庫架設好以後，我們接著架設我們的 ORM</p><pre>$ npm install prisma - save-dev<br>$ npx prisma init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*uu0VTWyfj8NWcqg2sU2fFA.png" /></figure><p>這時候會發先我們多了兩個資料夾:</p><p>1. prisma：database schema 會寫在這裡</p><p>2. .env：環境變數</p><p>接著我們需要將 Prisma 跟 PostgreSql 做連線</p><p>我們需要到 .env 資料夾中，更改 DATABASE_URL</p><pre>DATABASE_URL = &quot;postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public&quot;;</pre><p>這邊的寫法跟剛剛連線的寫法一樣</p><pre>postgresql://USER:PASSWORD@HOST:PORT/DATABASE</pre><p>到這邊基本的連線就已經完成</p><h4><strong>Prisma service</strong></h4><p>透過 Prisma service 可以實例化(instance) PrismaClient 並且連結到資料庫</p><pre>$ npx nest g module prisma<br>$ npx nest g service prisma</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*GKRSKFDkCPnAvhcbtK-5eQ.png" /></figure><blockquote>這邊有個小技巧: 假設你沒有寫測試的習慣，且不想要每次都自動生成一堆測試檔案，可以在指令後方加上 — no-spec</blockquote><pre>$ npx nest g module prisma - no-spec<br>$ npx nest g service prisma - no-spec</pre><pre>// src/prisma/prisma.service.ts<br>import { INestApplication, Injectable } from &quot;@nestjs/common&quot;;<br>import { PrismaClient } from &quot;@prisma/client&quot;;<br>@Injectable()<br>export class PrismaService extends PrismaClient {}</pre><pre>// src/prisma/prisma.module.ts<br>import { Module } from &quot;@nestjs/common&quot;;<br>import { PrismaService } from &quot;./prisma.service&quot;;<br>@Module({<br>providers: [PrismaService],<br>exports: [PrismaService],<br>})<br>export class PrismaModule {}</pre><h4><strong>實戰篇</strong></h4><h4><strong>Database</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*WpSJzERuTTspkcTXSKmCjw.png" /></figure><p>這是我們是以一個班級的作答情況，來設計這個 database，下面會以這個情境來說明常見的 relations</p><h4><strong>relations</strong></h4><p><strong>one-to-one</strong></p><p><strong>one-to-many</strong></p><p>一對多關係，以上面的圖片來說，一個學生會有多個測驗結果，或是說一個課堂中會有多個測驗，這個關係就是 1-n</p><p><strong>many-to-may</strong></p><p>多對多，就好像學生跟課堂間的關係</p><h4><strong>schema</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*4TJ0yBtfc1IMfZHZz3_a_g.png" /></figure><h4><strong>特殊語法</strong></h4><p><strong>@@map / @map</strong></p><p>這兩個 map 都是拿來重命名，@map 是針對 Column 重命名，而 @@map 是針對 table 重命名</p><pre>model User {<br>id Int @id<br>cardId Int @map(&quot;card_id&quot;)<br>@@map(&quot;user&quot;)<br>}</pre><p>等同於:</p><pre>model user {<br>id Int @id<br>card_id Int<br>}</pre><p><strong>@default</strong></p><p>預設值</p><pre>model User {<br>id Int @id @default(autoincrement())<br>}</pre><p>autoincrement() 代表自動生成</p><p><strong>@id / @@id</strong></p><p>@id 代表主鍵(PK)，@@id 則是一次設立多個主鍵</p><pre>model Table {<br>  id Int @id @default(autoincrement())<br>}<br>model Table {<br>  firstName String<br>  lastName String<br>  @@id([firstName, lastName])<br>}</pre><p><strong>@unique / @@unique</strong></p><p>跟 id 一樣，分為一個跟多個唯一值</p><pre>model User {<br>  id Int @id @default(autoincrement())<br>  email String? @unique<br>  name String<br>}<br>model User {<br>  id Int @id<br>  first_name Int<br>  last_name Int<br>  card Int?<br><br>  @@unique([first_name, last_name])<br>}</pre><p><strong>@relation</strong></p><p>relation 代表的是外鍵約束</p><p>寫法如下</p><pre>model User {<br>  id Int @id<br>  first_name String<br>  last_name String<br>  Post Post[]<br>}<br>model Post {<br>  id Int @id<br>  author User @relation(fields: [userId], references: [id])<br>  content String<br>  userId Int<br>}</pre><p>感覺很難懂，但是其實很間單，把他拆分一下</p><pre>author User @relation(fields: [userId], references: [id])<br>author [要連結的table] @relation(fields: [自己的哪個Column要做連線], references: [要連到目標table的哪個Column])</pre><p>這樣是不是簡單很多？</p><h4><strong>結語</strong></h4><p>花了幾天玩了一下 Prisma 個人覺得寫法比 TypeORM 更為直觀，並且 vscode prisma 套件太強大了，錯誤訓息也非常人性化，大推~</p><h4><strong>參考文章</strong></h4><ul><li><a href="https://izo.tw/prisma/">【Prisma】JavaScript 的資料庫工具 安裝 / 撰寫Schema / Migrate / Seeder ｜ iZO手札</a></li><li><a href="https://www.prisma.io/blog/nestjs-prisma-rest-api-7D056s1BmOL0">Build a REST API with NestJS, Prisma, PostgreSQL and Swagger</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-build-a-rest-api-with-prisma-and-postgresql">How To Build a REST API with Prisma and PostgreSQL | DigitalOcean</a></li></ul><p><a href="https://blog.dteam.top/posts/2022-01/prisma-introduction.html">https://blog.dteam.top/posts/2022-01/prisma-introduction.html</a></p><p><a href="https://www.prisma.io/blog/backend-prisma-typescript-orm-with-postgresql-data-modeling-tsjs1ps7kip1">TypeScript, PostgreSQL, Prisma | Data Modeling, CRUD, Aggregates</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e130d2bfe0d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2023 年回顧]]></title>
            <link>https://123davidbill.medium.com/2023-%E5%B9%B4%E5%9B%9E%E9%A1%A7-973ba9be0244?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/973ba9be0244</guid>
            <category><![CDATA[2023]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 13:01:36 GMT</pubDate>
            <atom:updated>2023-12-19T13:15:59.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZT_AXqzn9zhL-7CA" /><figcaption>Photo by <a href="https://unsplash.com/@sashafreemind?utm_source=medium&amp;utm_medium=referral">Sasha Freemind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>去年年底寫了一篇回顧的文章，今年再回頭去看，覺得自己成長了一點，所以今年一樣會把這一年所做的事情記錄下來</p><h4>健康</h4><p>今年在工作時有時候會有點容易覺得累，所以想說想要讓自己健康一點，於是開始了為期三個月的減肥計劃，也很開心能在三個月的時間內減了快 15 公斤，算是有達到預期設定的目標</p><h4>工作</h4><blockquote>「凡殺不死我的，必使我更強大」</blockquote><p>在工作上不再跟過去一樣都由我主導，在開發上面也有點綁手綁腳，工作模式變得有點像是配合團隊，在團隊內開發能力也備受質疑，不再擁有絕對的話語權，這讓我思考個人能力補強的部分，並且往各個領域去嘗試</p><p>也感謝公司近幾期工項給的比較少，讓我有很多個人時間可以去學習一些後端的東西，目標在明年過完年，可以轉成全端</p><h4>生活</h4><p>今年年初去了一趟新加坡，一個跟台北很像的地方，東西還好玩的也還好，感覺台灣更好玩</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*mrX2Y05JZIi06LwcsWVvEg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrOAaIuWf7thgzaugDIo1w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bw2-qbx4t8YRtqM4vM0YDQ.jpeg" /></figure><p>年底去了一趟台中，逃離了台北的塵囂，吃了有名的屋馬</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koB8r0-ILOBUZD5efIur0Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28_sYsp66rK9ZSd1Ms-1vg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_4hdG1L2w_XijmM8aMjqQ.jpeg" /></figure><p>今年可能是因為疫情接近尾聲，所以旅遊的機會變多了~</p><p>明年希望可以去趟泰國跟日本</p><h4>明年的期許</h4><h4>工作</h4><p>明年過年後，希望可以轉職全端，除了可以整個軟體業有更深入的了解，也可以提升自己的價值，增加談判的籌碼</p><h4>生活</h4><p>明年希望可以花多點時間給自己，去旅遊去學習程式以外的東西</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=973ba9be0244" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nestjs + TypeORM + PostgreSql 實作登入系統]]></title>
            <link>https://123davidbill.medium.com/nestjs-typeorm-postgresql-%E5%AF%A6%E4%BD%9C%E7%99%BB%E5%85%A5%E7%B3%BB%E7%B5%B1-2cf801d9b08b?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf801d9b08b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[nest]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 09:48:56 GMT</pubDate>
            <atom:updated>2023-12-12T12:36:42.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IEOWQH8Bdabdrau4" /><figcaption>Photo by <a href="https://unsplash.com/@danny144?utm_source=medium&amp;utm_medium=referral">Dan Nelson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>上一篇文章介紹過Nest後，我們今天要來時做一個登入系統</p><blockquote>老話一句: 有任何錯誤都歡迎留言給我</blockquote><p>那我們話不多說進入今天的文章</p><h4>流程</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*45Ajfh-DgdTGOpMm" /></figure><p>登入系統分為兩個部分: 1. 註冊 2. 登入</p><p><strong>註冊</strong></p><p>註冊首先會先確認是否有該使用者，確定沒有以後會將新使用者的密碼用 bcrypt 這個套件做基本的加密，然後回傳 JWT 給前端，前端之後有需要打 Api 都要拿這組 JWT 來驗證是否為該使用者</p><p><strong>登入</strong></p><p>登入步驟稍微多一點點，首先須先確認使用者的密碼正確，然後使用驗證 JWT 是否一致，確定無誤以後，才能登入成功</p><h4><strong>環境下載</strong></h4><p>先創立一個 Nest 的專案，project-name 這邊名字自己取就可以了</p><pre>$ npm i -g @nestjs/cli<br>$ nest new [project-name]</pre><p>下載完以後，我們會需要下載一些，等一下要用到的套件</p><pre>npm i @nestjs/jwt @nestjs/passport @types/passport-jwt passport passport-jwt</pre><p>以上都下載完以後，我們現在開始實作，如何連線到 PostgreSql</p><h4><strong>連線 DB </strong>PostgreSql</h4><pre>npm install --save @nestjs/typeorm typeorm pg</pre><p>這邊推薦一篇<a href="https://learningsky.io/use-postgresql-databases-with-the-pgadmin/">文章</a>，可以快速的建立本地端的 PostgreSQL server，並透過 pgAdmin 做圖形化的管理</p><blockquote>以後會專門做影片跟大家講解</blockquote><h4>開始實作</h4><pre>nest g res [資料夾名稱]<br><br>ex. nest g res user</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*xaFh7fpklngjNQsa3iggoA.png" /></figure><p>透過 nest g res [資料夾名稱] 我們可以快速的建立一個 resource ，生成的程式碼中，有兩個比較特別 dto 跟 entities:</p><p>dto: dto 我們前一篇介紹過了，這篇就不多做解釋</p><p>entities: entities 就是建立 database tables 的地方</p><h4>設計 table</h4><pre>import { Entity, Column, PrimaryGeneratedColumn } from &#39;typeorm&#39;;<br><br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn(&#39;uuid&#39;)<br>  id: string;<br><br>  @Column({ unique: true })<br>  email: string;<br><br>  @Column()<br>  password: string;<br>}</pre><p>PrimaryGeneratedColumn 是這個 table 的主鍵(primary key)</p><p>Column 代表 table 裡面的其他欄位</p><h4>在 service 中調用 db 的資料</h4><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;;<br><br>@Injectable()<br>export class UsersService {<br>  constructor(<br>    // 將 DB 注入到 service 中<br>    @InjectRepository(User)<br>    private usersRepository: Repository&lt;User&gt;,<br>  ) {}<br>  <br>  // ...CRUD functions<br>}</pre><h4><strong>註冊</strong></h4><p>controller.ts</p><pre>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br><br>import { AuthService } from &#39;./auth.service&#39;;<br>import { RegisterDto } from &#39;./dto/registerDto&#39;;<br><br>@Controller(&#39;user&#39;)<br>export class AuthController {<br>  constructor(private readonly authService: AuthService) {}<br><br>  @Post(&#39;/register&#39;)<br>  async register(@Body() registerDto: RegisterDto) {<br>    return this.authService.register(registerDto);<br>  }<br>}</pre><p>service.ts</p><pre>import { HttpException, HttpStatus, Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { JwtService } from &#39;@nestjs/jwt&#39;;<br><br>import { User } from &#39;@/entity/user.entities&#39;;<br>import { RegisterDto } from &#39;./dto/registerDto&#39;;<br><br>@Injectable()<br>export class AuthService {<br>  constructor(<br>    @InjectRepository(User)<br>    private usersRepository: Repository&lt;User&gt;,<br>    private jwtService: JwtService,<br>  ) {}<br><br>  // 註冊<br>  async register(registerDto: RegisterDto) {<br>    const { email, password } = registerDto;<br><br>    // 透過 bcrypt 幫明碼加密<br>    const salt = await bcrypt.genSalt();<br>    const passwordHash = await bcrypt.hash(password, salt);<br><br>    try {<br>      // 因為我們的 email 在 entity 有定義為 unique<br>      // 所以如果輸入 db 裡已經有的 email 會 response error<br>      this.usersRepository.save({<br>        email,<br>        password,<br>      });<br><br>      return {<br>        status: HttpStatus.OK,<br>        message: &#39;User registered successfully&#39;,<br>      };<br>    } catch (error) {<br>      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br>  }<br>}</pre><p>registerDto.ts</p><pre>import { IsEmail, IsNotEmpty, IsString } from &#39;class-validator&#39;;<br><br>export class RegisterDto {<br>  @IsEmail()<br>  @IsNotEmpty()<br>  email: string;<br><br>  @IsString()<br>  @IsNotEmpty()<br>  password: string;<br>}</pre><h4>登入</h4><p>controller.ts</p><pre>import { Controller, Post, Body } from &#39;@nestjs/common&#39;;<br><br>import { AuthService } from &#39;./auth.service&#39;;<br>import { LoginDto } from &#39;./dto/loginDto&#39;;<br><br>@Controller(&#39;user&#39;)<br>export class AuthController {<br>  constructor(private readonly authService: AuthService) {}<br><br>  @Post(&#39;/login&#39;)<br>  async login(@Body() loginDto: LoginDto) {<br>    return this.authService.login(loginDto);<br>  }<br>}</pre><p>service.ts</p><pre>import { HttpException, HttpStatus, Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { JwtService } from &#39;@nestjs/jwt&#39;;<br><br>import { User } from &#39;@/entity/user.entities&#39;;<br>import { LoginDto } from &#39;./dto/loginDto&#39;;<br><br>@Injectable()<br>export class AuthService {<br>  constructor(<br>    @InjectRepository(User)<br>    private usersRepository: Repository&lt;User&gt;,<br>    private jwtService: JwtService,<br>  ) {}<br><br>  // 登入<br>  async login(loginDto: LoginDto) {<br>    const { email, password } = loginDto;<br><br>    const user = await this.usersRepository.findOne({ where: { email } });<br><br>    // 如果沒有該使用者就回傳，找不到該使用者<br>    if (!user) {<br>      throw new HttpException(&#39;User not found&#39;, HttpStatus.NOT_FOUND);<br>    }<br><br>    // 這邊需要特別注意，compare 後方的兩個欄位不能放錯<br>    // 第一個欄位是使用者輸入的密碼(明碼)<br>    // 第二個欄位是我們儲存在 db 裡面的密碼(暗碼)<br>    const isSameUser = await bcrypt.compare(password, user.password);<br><br>    // 密碼錯誤<br>    if (!isSameUser) {<br>      throw new HttpException(&#39;Invalid credentials&#39;, HttpStatus.BAD_REQUEST);<br>    }<br><br>    // 如果確定為本人，則把 requests 包裝成 jwt 回傳給前端，作為之後 call api 的鑰匙<br>    const access_token = await this.jwtService.signAsync(loginDto);<br><br>    return {<br>      status: HttpStatus.OK,<br>      message: &#39;User logged in successfully&#39;,<br>      access_token,<br>    };<br>  }<br>}</pre><p>loginDto.ts</p><pre>import { IsEmail, IsNotEmpty, IsString } from &#39;class-validator&#39;;<br><br>export class LoginDto {<br>  @IsEmail()<br>  @IsNotEmpty()<br>  email: string;<br><br>  @IsString()<br>  @IsNotEmpty()<br>  password: string;<br>}</pre><h4>程式碼</h4><p><a href="https://github.com/janlin002/nest-login-system">GitHub - janlin002/nest-login-system</a></p><h4>參考文章</h4><ul><li><a href="https://learningsky.io/use-postgresql-databases-with-the-pgadmin/">【 Tools 】透過 pgAdmin 操作 PostgreSQL 資料庫</a></li><li><a href="https://medium.com/simform-engineering/nestjs-and-postgresql-a-crud-tutorial-32aa78778752">NestJS and PostgreSQL: A CRUD Tutorial</a></li><li><a href="https://docs.nestjs.com/">Documentation | NestJS - A progressive Node.js framework</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf801d9b08b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript 新語法 — satisfies]]></title>
            <link>https://123davidbill.medium.com/typescript-%E6%96%B0%E8%AA%9E%E6%B3%95-satisfies-28f36b4fdfc2?source=rss-e86c029131cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/28f36b4fdfc2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[janlin002]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 03:20:58 GMT</pubDate>
            <atom:updated>2023-12-11T07:19:57.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>TypeScript 新語法 — satisfies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pkTORYULS5-fRaRS" /><figcaption>Photo by <a href="https://unsplash.com/@timothycuenat?utm_source=medium&amp;utm_medium=referral">Timothy Cuenat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>其實說新語法也有點牽強，畢竟在去年 11 月份 也就是 typeScript 的 4.9 版就已經發布了，只是最近才關注到這個語法，並且解決了我很多開發時的不方便，所以就把它記錄下來</p><p>開始前，先給大家一個簡單的情境</p><pre>type Type = {<br>  amount: number | string<br>}<br><br>const record: Type = {<br>  amount: 123.11,<br>} <br><br>console.log(Math.floor(record.amount))</pre><p>這樣的寫法，邏輯感覺是行得通的，但是 TypeScript 卻會報錯</p><pre>Argument of type &#39;string | number&#39; is not assignable to parameter of type &#39;number&#39;.<br>  Type &#39;string&#39; is not assignable to type &#39;number&#39;.</pre><p>原因是因為 TypeScript 認為 amount 有可能為 string 但是你對他做一個 number 才有的操作（Math.floor()），所以就報錯了</p><p>那怎麼解決？</p><p>很簡單，就用 as !!!</p><p>如果把上面的程式碼改成用 as ，就不會報錯了</p><pre>type Type = {<br>  amount: number | string<br>}<br><br>const record: Type = {<br>  amount: 123.11,<br>}<br><br>console.log(Math.floor(record.amount as number))</pre><p>但使用 as 也有很大的缺點，除了很不直觀以外，他也讓你的 code 脫離了 TypeScript 的驗證，所以只有在你對自己所做事情非常有把握的情況下，才會使用到 as ，以我個人的開發經驗來說，當使用到 as 時，通常是開發者個人問題</p><h4>satisfies</h4><p>現在要來介紹 satisfies ，一個可以取代 as 的新語法</p><blockquote>先說一下結論: satisfies 這個語法，可以讓 TypeScript 去<strong>自適應</strong>型別</blockquote><p>一樣拿上面的例子來說</p><pre>type Type = {<br>  amount: number | string<br>}<br><br>const record= {<br>  amount: 123.11,<br>} satisfies Type<br><br>console.log(Math.floor(record.amount))</pre><p>如果改成上面這個寫法的話，就不會在報錯，並且把滑鼠滑到 record.amount 時，會發現它自動認定我們的 amount 是 number !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*CvMVpnPGBDbc3GT6TavbWA.png" /></figure><p>那現在嘗試改成 string 的寫法，看會不會一樣認定為正確的型別</p><pre>type Type = {<br>  amount: number | string<br>}<br><br>const record= {<br>  amount: &#39;Apple, Banana, Kiwi&#39;,<br>} satisfies Type<br><br>console.log(record.amount.slice(7))</pre><p>一樣把滑鼠滑到 record.amount 確認一下型別，這時候 TypeScript 會認定為 string !!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*1pd90A3O2BbeiV4TFW5I9g.png" /></figure><h4>結論</h4><p>satisfies 是一個非常好的新語法，解決了過去可能會一直使用 as 的情況，或許下次開發到需要使用 as 前，可以先考慮是否能夠替換成 satisfies</p><p>這邊附上程式碼，有興趣的話可以去玩玩看，<a href="https://www.typescriptlang.org/play?ssl=19&amp;ssc=21&amp;pln=20&amp;pc=5#code/PTAEmBzRGDUemTBC3QJJ0DTmAoZAXAngBwKagCrZ4C8oA3sqKAIYC2A9gK4B2aAXKM47QEY4BOoAD6gAzmn4BLZgHNkAX1QBjes3Gh+OFfwAmHQrlCkKVOk1YcAjACYAzADpLlgDQLQy1aPoAbHPe-0MgAUALLUaAAW9gBmAfT8QZraOvZmLGgAlBmoIDSioAgouZiGBiTkyLmmDOkcXLwCwmIS0nK5ipVgKmpoGlrxegRERhVVNDUWoDYOTq7tOV2ePn4BwWGRMXEJSQOpE73U+fV8-FmonWLhkqLRkjhH3CegSBcleGUjFGNpk8eNIuIpLILh1ct11DtdMYLtVzOwpnZHC4QZc0NdbvchrgFqBwct-IFQuEorF6PFEv1dHs4WccaIrjc7vlAa1nkUwG8seUvmBYbVOI9-s0gW0wKDFj0+slod99hwAOQAQSwWF8zlAACFqMxtdR1QBpSQAd0k8rmYtR6KZXJxeN8BOCkJSPzQ9lE3kkShwQQA7FkgA">TypeScript playground</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28f36b4fdfc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>