<?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 Peng Jie on Medium]]></title>
        <description><![CDATA[Stories by Peng Jie on Medium]]></description>
        <link>https://medium.com/@bivinity?source=rss-5f58b032caf0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mlLqFN9CLYRGX4b86T2a1Q.jpeg</url>
            <title>Stories by Peng Jie on Medium</title>
            <link>https://medium.com/@bivinity?source=rss-5f58b032caf0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:59:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bivinity/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[Deploy your Telegram Bot on zeit/now]]></title>
            <link>https://medium.com/@bivinity/deploy-your-telegram-bot-on-zeit-now-d0ecc5381bd5?source=rss-5f58b032caf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ecc5381bd5</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Peng Jie]]></dc:creator>
            <pubDate>Sat, 04 Mar 2017 14:56:04 GMT</pubDate>
            <atom:updated>2017-03-04T14:56:04.904Z</atom:updated>
            <content:encoded><![CDATA[<p>先前撰寫過一篇 <a href="https://neighborhood999.github.io/2016/07/19/Develop-telegram-bot/">Telegram Bot 開發起手式</a>主要就是簡單學習如何撰寫一個自己的 Telegram Bot，但是後來想要把 Telegram Bot 給 deploy 起來，苦無找不到比較好的空間，最初那時候就是將 Bot deploy 到 <a href="https://www.heroku.com/">Heroku</a> 上，退伍後這陣子又寫了另一個 <a href="https://github.com/neighborhood999/telegram-cafe-nomad">Cafe Nomad Bot</a>，這次找到了一個很容易 deploy Telegram Bot 的方式，請繼續往下看吧！🚀</p><h3>𝚫 now — realtime global deployments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*j12GygKXuapiZVz0-jpkyg.png" /></figure><p>zeit <a href="https://zeit.co/now">now</a> 主要是可以讓你很即時的部屬你的 Nodejs 應用程式，首先你必須要去<a href="https://zeit.co/login">註冊一個帳號</a>，接著你只要現在你的環境下安裝好 now 這個 CLI 一切都非常簡單，也支援 <a href="https://zeit.co/blog/now-dockerfile">Dockerfile</a>。</p><p><a href="https://zeit.co/now">now</a> 的官方網站也有提供一個<a href="https://zeit.co/now#get-started">入門教學</a>，你可以很快明白到如何使用 now，這邊就不多說明如何使用了。</p><pre>$ npm install now -g</pre><p>完成 now CLI 的安裝後，文章後面就會提到如何 deploy 到 now 了！</p><h3>Telegram Bot 設定</h3><p>由於要把 Telegram Bot deploy 到網路上，所以我們必須要先設定 <a href="https://core.telegram.org/bots/api#setwebhook">webHook</a>，文件裡有詳細說明如何去設定 webHook，但因為當初開發有使用他人撰寫好的 <a href="https://github.com/yagop/node-telegram-bot-api">library</a>，所以只要簡單的去呼叫 method 做設定就可以了。</p><pre>const token = &#39;Your token.&#39;;</pre><pre>let bot;</pre><pre>if (env === &#39;production&#39;) {</pre><pre>  const webHook = { port: process.env.PORT || 443 };</pre><pre>  const url = process.env.APP_URL || &#39;Your App URL.&#39;;</pre><pre>  bot = new TelegramBot(token, { webHook });</pre><pre>  bot.setWebHook(`${url}/bot${token}`); // In here for setting webHook</pre><pre>} else {</pre><pre>  bot = new TelegramBot(token, { polling: true }); // On devlopment mode</pre><pre>}</pre><p>以上程式碼主要示意在 production 和 development 要如何去設定，首先我先設定了 webHook 以及 url，最後<strong>第八行</strong>中完成設定 webHook。</p><blockquote><em>目前支援的 WebHooks Port 有： </em><strong><em>443, 80, 88, 8443</em></strong><em>。</em></blockquote><p>這邊囉嗦一下，process.env 除了可以在 npm script 中可以直接設定：</p><pre>{</pre><pre>  &quot;name&quot;: &quot;deploy-telegram-bot&quot;,</pre><pre>  &quot;main&quot;: &quot;index.js&quot;,</pre><pre>  &quot;scripts&quot;: {</pre><pre>      &quot;start&quot;: &quot;NODE_ENV=production node index.js&quot;</pre><pre>  }</pre><pre>}</pre><p>或者你可以選擇使用 <a href="https://github.com/motdotla/dotenv">dotenv</a> 也是很方便的呢！我在開發 <a href="https://github.com/neighborhood999/telegram-cafe-nomad">Cafe Nomad Bot</a> 就是使用它，後面就會知道使用它的好處囉！</p><p>前面都是透過很簡單的方式說明如何設定 Telegram Bot，接下來我們回到 now。</p><h3>Deploy on 𝚫 now</h3><p>我們使用 now 做 deploy 時，會產生像這樣的網址：</p><pre>&gt; <a href="https://package-name-random.now.sh/">https://package-name-random.now.sh</a></pre><p>什麼意思呢？也就是說 now 會利用你的 package-name 作為前綴，後面在一組英文亂數，最後是 .now.sh。 在你每次下 now 做 deploy 時，每次都會產生不同的網址，這其實挺麻煩的，但 now 提供了一個便利的方式，有興趣可以<a href="https://zeit.co/blog/easy-aliasing">讀這篇文章</a>。</p><p>簡單來說就是你可以在 package.json 加入一個 alias property，或者是另外建立一個 now.json。</p><p>延伸閱讀：</p><ul><li><a href="https://zeit.co/blog/easy-aliasing">An Easier Way to Alias</a></li><li><a href="https://zeit.co/blog/now-json">Customizing Now using now.json</a></li></ul><pre>{</pre><pre>  &quot;alias&quot;: &quot;zeit.chat&quot;</pre><pre>}</pre><p>所以當你下完 now deploy 完後：</p><pre>⚓️  ~/P/telegram-cafe-nomad  deploy-now ⚑  now</pre><pre>&gt; Deploying ~/Peng-Jie/telegram-cafe-nomad</pre><pre>&gt; Using Node.js 7.6.0 (default)</pre><pre>&gt; Ready! https://telegram-cafe-nomad-hjdcmlroud.now.sh (copied to clipboard) [2s]</pre><pre>&gt; Upload [====================] 100% 0.0s</pre><pre>&gt; Sync complete (174B) [1s]</pre><pre>&gt; Initializing…</pre><pre>&gt; Building</pre><pre>&gt; ▲ npm install</pre><pre>&gt;  ‣ babel-preset-env@^1.1.8</pre><pre>&gt;  ‣ babel-register@^6.22.0</pre><pre>&gt;  ‣ fetch-mock@^5.9.3</pre><pre>&gt;  ‣ nyc@^10.1.2</pre><pre>&gt;  ‣ @google/maps@^0.3.1</pre><pre>&gt; ⧗ Installing:</pre><pre>&gt;  ‣ dotenv@^4.0.0</pre><pre>&gt;  ‣ isomorphic-fetch@^2.2.1</pre><pre>&gt;  ‣ node-telegram-bot-api@^0.27.0</pre><pre>&gt; ✓ Installed 564 modules [12s]</pre><pre>&gt; ▲ npm start</pre><pre>&gt; &gt; telegram-cafe-nomad@1.0.0 start /home/nowuser/src</pre><pre>&gt; &gt; node index.js</pre><pre>&gt; Deployment complete!</pre><p>再下 now alias，這樣你就會有固定的 URL 囉：</p><pre>&gt; Assigning alias tg-cafe-nomad to deployment...</pre><pre>&gt; Success! Alias created (ccxNJdmWYN6bXW1Ok6FQzSZw):</pre><pre>https://your-new-alias.now.sh now points to https://telegram-cafe-nomad-hjdcmlroud.now.sh (cfxel1qm7xDQ32XuhDw3zHAH) [copied to clipboard]</pre><p><em>溫馨小提醒： now 對於 Free 用戶有它存在的方案：</em></p><ul><li><strong>每個月只能 deploy 20 次</strong></li><li><strong>每個月有 1GB 的頻寬</strong></li><li><strong>免費備份</strong></li><li><strong>每個檔案最大為 1 MB</strong></li><li><strong>沒有自訂的 domain</strong></li><li>_src <strong>頁面是公開的</strong></li><li><a href="https://zeit.co/now#pricing"><em>更多參考 Pricing</em></a></li></ul><p>前面提到使用 <a href="https://github.com/motdotla/dotenv">dotenv</a> 來載入你的一些 nodejs 的環境變數，now 本身也支援變數的設定，你可以使用 now --help 找到說明。</p><pre>$ now -e NODE_ENV=production -e BOT_TOKEN=123456789</pre><p>但是我覺得這樣還要額外去設定這些太麻煩了，所以就直接使用 <a href="https://github.com/motdotla/dotenv">dotenv</a> 省下這些額外的設定，詳細的使用方式可以參考 dotenv 的 <a href="https://github.com/motdotla/dotenv/blob/master/README.md">README</a>。</p><h3>總結</h3><p>now 真的對於 nodejs 應用程式部署相當的方便容易 ✌️，而且我覺得相對於 Heroku 感覺快很多 😕（錯覺嗎？），而且在設定上也相當的簡易，透過 CLI 進行設定等等。</p><p><em>以下是一個簡單的 Telegram Bot Example：</em></p><pre>const token = &#39;Your token.&#39;;</pre><pre>let bot;</pre><pre>if (env === &#39;production&#39;) {</pre><pre>  const webHook = { port: process.env.PORT || 443 };</pre><pre>  const url = process.env.APP_URL || &#39;Your App URL.&#39;;</pre><pre>  bot = new TelegramBot(token, { webHook });</pre><pre>  bot.setWebHook(`${url}/bot${token}`);</pre><pre>} else {</pre><pre>  bot = new TelegramBot(token, { polling: true });</pre><pre>}</pre><pre>bot.on(&#39;message&#39;, message =&gt; {</pre><pre>bot.sendMessage(message.chat.id, &#39;Telegram Bot deployed on zeit/now.&#39;);</pre><pre>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ecc5381bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 Ubuntu上自動更新 Atom Editor]]></title>
            <link>https://medium.com/@bivinity/%E5%9C%A8-linux-%E4%B8%8A%E8%87%AA%E5%8B%95%E6%9B%B4%E6%96%B0-atom-editor-2eca1f39dec8?source=rss-5f58b032caf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eca1f39dec8</guid>
            <category><![CDATA[atom-text-editor]]></category>
            <dc:creator><![CDATA[Peng Jie]]></dc:creator>
            <pubDate>Tue, 21 Feb 2017 02:19:01 GMT</pubDate>
            <atom:updated>2017-02-25T23:59:03.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VRt2Aj8H2azT-NVfpaZUSQ.png" /></figure><p>自從從 <a href="https://www.sublimetext.com/">Sublime Text</a> 跳到 <a href="https://atom.io/">Atom</a> 之後，對於使用 Atom 一直覺得蠻順手的，相關的 package 也很多，在寫程式的時候也相當方便，雖然現在很多人都很推 <a href="https://code.visualstudio.com/">Visual Studio Code</a>，但是目前來說 Atom 的功能就可以滿足我了，所以也就沒特別換到 Visual Studio Code；Atom 是基於 <a href="http://electron.atom.io/">Electron</a> 所打造的，不過在先前比較令人詬病的地方就是<strong>開啟的速度相當的慢</strong>！不過前陣子在 <a href="https://github.com/atom/atom/releases/tag/v1.14.0"><strong>1.14.0</strong></a><strong> </strong>版本中對於這部份有做了改進，實際更新後我覺得開啟速度的確有改善許多。</p><p>我自己本身有兩台電腦，都是使用 Atom Editor，一台 Windows、一台 Ubuntu，今天的主題就是<strong>在 Ubuntu上如何自動去更新 Atom Editor</strong>，Windows 的部份其實都會自動幫你下載更新，只是記得到 AppData 下把舊版的 Atom 移除，不然蠻佔空間的；在 Ubuntu 上，安裝 Atom 通常可以透過加入 <strong>PPA</strong> 來進行安裝，或者是到 Atom 的 <a href="https://github.com/atom/atom/releases">GitHub Release Page</a> 來安裝。</p><ol><li>使用 PPA 進行安裝，首先要加入 respository，再進行安裝：</li></ol><pre>$ sudo add-apt-repository ppa:webupd8team/atom</pre><pre>$ sudo apt update; sudo apt install atom</pre><p>PPA 的部份安裝很容易，但是這篇文章主要是透過 GitHub Release Page 下載回來的 .deb 來進行安裝說明。</p><p>2. 下載 .deb 檔案回來進行安裝：</p><p>我們到 GitHub Release Page 下載安裝檔案<em>（這裡以 .deb 作為範例）</em>，透過以下指令就可以進行安裝了：</p><pre>$ dpkg -i atom-amd64.deb</pre><p>但是透過這種方式安裝有個<strong>缺點</strong>就是，當 atom 版本更新時需要<strong>自己手動進行更新！</strong>因為這幾天發現相關 package 無法更新到最新版本，才發現自己的 Atom 版本很久沒更新了，但是覺得每次要這樣手動來更新 Atom Editor 太累人，於是上網找了方法來解決。</p><h3>透過 shell script 來解決</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a2295a4594878e31e9564d3fdce4eb7/href">https://medium.com/media/2a2295a4594878e31e9564d3fdce4eb7/href</a></iframe><p>大概解釋一下這個 shell script 的原理：</p><p>第一行：就是透過 wget 把 Atom Release HTML 頁面給下載回來，存放到 /tmp 下名稱為 latest 的檔案。</p><p>第二行： $(cat /tmp/latest | grep -o -E &#39;href ...) 這裡就是從你的上面 wget 下來的頁面，找到下載連結的 URL，接著一樣下載存到 /tmp 資料夾下，名為 atom-amd64.deb 的檔案。</p><p>第三行：安裝 .deb 檔案。</p><p>可以把這個 shell script 放到 /usr/local/bin 下，並修改檔案的屬性成執行，之後就可以從 CLI 通過指令來更新 Atom 囉！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eca1f39dec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 Promise.all() 解決多次的 API Callback]]></title>
            <link>https://medium.com/@bivinity/%E4%BD%BF%E7%94%A8-promise-all-%E8%A7%A3%E6%B1%BA%E5%A4%9A%E6%AC%A1%E7%9A%84-api-callback-b4feb817ad76?source=rss-5f58b032caf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4feb817ad76</guid>
            <dc:creator><![CDATA[Peng Jie]]></dc:creator>
            <pubDate>Sun, 29 Jan 2017 13:34:01 GMT</pubDate>
            <atom:updated>2017-01-29T23:29:47.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>Callback Hell</h3><p>在 JavaScript 中蠻容易遇見像這樣 callback hell 的程式碼：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cj9r0yBqp85jpJttkKxcnQ.png" /><figcaption><a href="http://thecodebarbarian.com/2015/03/20/callback-hell-is-a-myth">http://thecodebarbarian.com/2015/03/20/callback-hell-is-a-myth</a></figcaption></figure><p>像這樣巢狀非同步的程式碼，對人腦來說真的很不友善，再後來學會了 Promise、Async / Await 來避免這樣寫出這樣過度巢狀化的程式碼。</p><h3>Google Maps Service</h3><p>這陣子正在寫一個 telegram bot，用到了 Google Maps 的服務，主要是為了用來計算兩點之間的距離，要使用這個服務，首先你需要到 Google API Console 去建立一個新專案：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*q4vERvOSFXxXVrMbtqltog.png" /></figure><p>接著點擊<strong>資料庫</strong>去選擇你需要的 API 服務：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjxTBc3eo1Bk7gBsyqwAYg.png" /></figure><p>完成後再點擊<strong>憑證</strong>的地方去複製你的 API 金鑰就可以使用 Google 提供的 API 服務了。</p><h3>API 的 Callback</h3><p>我們在 Node.js 中，使用 <strong>fs </strong>來讀取檔案時，會看到如下的程式碼：</p><pre>fs.readFile(file, [options], callback);</pre><p>在 Node.js 的核心模組，通常在 callback 的部份我們都會優先處理錯誤：</p><pre>fs.readFile(&#39;someFile.md&#39;, (err, data) =&gt; {<br>  if (err) throw err;</pre><pre>  console.log(data);<br>});</pre><p>這次開發 telegram bot 因為使用了 Google Maps 服務因此選了一個 <a href="https://github.com/googlemaps/google-maps-services-js">google-maps-service-js</a> 的 library 來處理 Google Maps 相關的計算，因為要計算兩點的距離，根據<a href="http://googlemaps.github.io/google-maps-services-js/docs/GoogleMapsClient.html">官方的文件</a>，我們必須使用 distanceMatrix 這個方法來計算：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75389f35fe78a0370ad3e68b49709763/href">https://medium.com/media/75389f35fe78a0370ad3e68b49709763/href</a></iframe><p>這個部份我們可以得到兩點計算後的距離，然後把 response.json 解構賦值，我們可以得到兩點之間的距離到底是多少<em>（text 是一個 String，ex: 5.0 km)</em>。</p><p>這樣看起來好像順利可以取得距離了，但是像在 JavaScript 會有 scope 的問題，有些值你無法把他 return 出來時，就會用到 <strong>callback</strong> 了，上方的程式碼在 callback 的地方是一個 <strong>Anonymous Function</strong>，所以就算 return 了值，也無法取得，如果透過 callback 方式：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c7319a6179e3bf9e30cf6db011e4eb6/href">https://medium.com/media/0c7319a6179e3bf9e30cf6db011e4eb6/href</a></iframe><p>這裡的 callback 遵循了 Node.js 的 callback function style 優先處理錯誤，但是後來我發現透過 callback 的方式來取得值的方式無法滿足我的需求，今天假設我對這個 distanceMatrix 做了多次的 request，然後得到多個值儲存成陣列再做計算的話呢？callback 好像讓事情變得更難處理呢！</p><h3>嘗試使用 Promise</h3><p>因為以上的問題，我後來嘗試使用了 <strong>Promise</strong>，這也讓程式看起來像是同步的感覺。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f37a4c6ab7ca4a533fd51b3efc1b25ee/href">https://medium.com/media/f37a4c6ab7ca4a533fd51b3efc1b25ee/href</a></iframe><p>我們可以透過這樣的方式來取得距離：</p><pre>promiseDistance(somePoint).then(res =&gt; console.log(res)）;</pre><p>乾淨！相對於 callback 讓人感覺舒服多了，接下來我們來處理多筆資料：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8bcefd0b72f4474d28788d7f54b7614/href">https://medium.com/media/b8bcefd0b72f4474d28788d7f54b7614/href</a></iframe><p>這時候我們有一個 stores 含有多筆經緯度的資料，而我們有個原點，把原點跟每個經緯度來做計算得到距離，在 stores.map 的部份可以看到我每次回傳的都是一個 <strong>Promise</strong>，promiseDistance(point) 把我們的點傳入進去，接著會得到 API 會傳回來的結果，這個地方是<strong>非同步，</strong>可以透過 <strong>console.log(newStores)</strong> 知道這個回傳陣列內的值都是一個 <strong>Promise {&lt;pending&gt;}</strong> 的狀態。</p><h3>使用 Promise.all() 處理 […Promise { &lt;pending&gt; }]</h3><p>在這個部份我本來也不知道該如何解決的，於是在 MDN 翻了 Promise 相關的文件找到了這個方法法 — <strong>Promise.all()</strong>。</p><p>Promise.all(<strong>iterable</strong>) 傳入的值要是一個 iterable object，像是陣列就是一個 iterable object<em>（更多 iterable 請參考 — </em><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/iterable"><em>MDN iterable</em></a><em>）</em>，當你傳入的 iterable 內的 Promise 都為 resolved ，Promise.all 的 狀態就會轉為 resolved，反之假設其中一個為 rejected 的狀態，Promise.all 則會轉為 rejected 的狀態。</p><p>剛剛 nextStores 都是狀態在 pending 的 Promise，接著我們把它放入 Promsie.all()，來等待這些 pending 的狀態轉為 resolved or rejected，這樣我們就可以對 API 做多次的呼叫，Promise.all 會等待所有個 Promise 都完成狀態轉化後才會在繼續執行 <strong>.then</strong> 或 <strong>.catch</strong>，感覺就像在寫同步的程式碼，感覺超棒的！</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df4410079d2975bcf79f0bd6349faa62/href">https://medium.com/media/df4410079d2975bcf79f0bd6349faa62/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4feb817ad76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[初識 GraphQL]]></title>
            <link>https://medium.com/@bivinity/%E5%88%9D%E8%AD%98-graphql-1533032c1121?source=rss-5f58b032caf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1533032c1121</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Peng Jie]]></dc:creator>
            <pubDate>Thu, 12 Jan 2017 07:05:34 GMT</pubDate>
            <atom:updated>2017-01-13T09:47:16.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DBjZcMPPTNPEaq_l46EQsQ.png" /></figure><p>第一次聽到 GraphQL 是在 Facebook 使用 React Native 做了一個 <a href="https://github.com/fbsamples/f8app">F8 App</a> ，但那時候都把精神都花再學習 Reactjs 上，所以後來也沒有特別去了解。</p><p>最近這陣子剛退伍，整理一下了 <a href="https://www.instapaper.com/">Instapaper</a>，發現了好幾篇跟 GraphQL 相關的文章<em>（雖然還沒仔細閱讀 </em>😛<em>）</em>，GraphQL 真的慢慢變成趨勢了，所以想趁這段空窗期好好學習一下 GraphQL，順便記錄一下學習的過程，希望可以幫助對於 GraphQL 沒有概念的朋友可以對 GraphQL 有多一點認識！</p><h3>GraphQL 是什麼</h3><p>GraphQL 是一個 “query language”，是由 Facebook 所提出的，GraphQL 主要是為了解決在 REST 上所遇到的一些問題，待會在下面文章我們會繼續討論到，對於 GraphQL 想要更深入的了解請參考以下連結：</p><ul><li>facebook/graphql — <a href="https://github.com/facebook/graphql">https://github.com/facebook/graphql</a></li><li>GraphQl — <a href="https://facebook.github.io/graphql/">https://facebook.github.io/graphql/</a></li></ul><pre>// 假想取得一篇文章的資訊，包含文章作者、時間、日期、留言。<br>{<br>  posts {<br>    id<br>    author<br>    title<br>    date<br>    comments {<br>      commentId<br>      user<br>      timestamp<br>    }<br>  }<br>}</pre><p>GraphQL 不是一個程式語言或是框架，它是一個概念和規範，就像 REST 那樣，每個不同的程式語言都有實作自己的 GraphQL，更多請參閱：<a href="http://graphql.org/code/">Code | GraphQL</a>。</p><h3>GraphQL 解決了哪些問題</h3><p>當我們在設計 API 的時候，通常都會遵循 REST 的風格來設計，在 REST 中，我們把這些不同的資源利用四個動詞：<strong>GET、POST、UPDATE、DELETE </strong>來做不同的 <strong>state transfer</strong>，這些不同的搭配產生的 URI 讓我們來作為 API，例如：</p><pre>GET /posts &lt;- 取得所有文章<br>POST /posts/ &lt;- 新增文章<br>UPDATE /posts/1 &lt;- 更新 id 為 1 的文章<br>DELETE /posts/1 &lt;- 刪除 id 為 1 的文章</pre><p>上面例子是很簡單的 RESTful API，但是當需求變得比較複雜的時候，可能會<strong>用到多個 API</strong>，或者是透過 Model 關聯拿回需要的資料，在這個部份有可能會<strong>回傳多餘的欄位資料</strong>，造成網路資源的浪費；又或者在處理巢狀的 Route 不是這麼的容易，當應用程式越來越複雜時，會發現 Endpoints 會變得非常龐大。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RapSQHY4a5TWqDaKpxUe-A.png" /><figcaption>比較 REST 和 GraphQL fetch 資料的差別。photo via <a href="https://goo.gl/GbTY9R">https://goo.gl/GbTY9R</a></figcaption></figure><p>從上圖來比較 REST 和 GraphQL，當我們透過 REST 來取得 album 的資料和評論時，我們<strong>需要透過兩次的 GET 來取得</strong>；透過 GraphQL 我們可以明確的告訴 Server 我們需要回傳哪些欄位，<strong>一次</strong>就可以拿回全部的資料，相較於 REST 更加靈活。</p><p>就我對 REST 的了解，和現在目前對 GraphQL 的認識，我的想法是：</p><blockquote>RESTful 所有的 resource 都是圍繞著被定義的 route 在進行，而 GraphQL 則是透過定義不同的 Type，然後建立一個 Schema，如 <strong>Graph</strong>QL 其名，由每個不同的 Type 內的欄位來組織成不同的資料。</blockquote><blockquote>以下內容的相關程式碼在：<a href="https://github.com/neighborhood999/graphql-emoji-for-learning">graphql-emoji-for-learning</a></blockquote><h3>建立 GraphQL Server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i22Tks0jUrcchEy_5Aj0-g.jpeg" /></figure><p>前面大概解釋了一下 GraphQL 解決了在 REST 上所遇到的一些問題，接下來還是透過實作簡單的範例來感受一下 GraphQL 所帶來的好處，我將使用 JavaScript 來實做並利用一個 emoji.json 來作為假想的 Database，再透過 GraphQL 來取得 emoji 的資料。</p><p>首先，我們先完成前置的準備，先建立一個 GraphQL 的 Server：</p><pre>// 安裝 Koa<br>npm install koa@2 koa-convert koa-mount koa-graphql --save-dev</pre><pre>// or use yarn</pre><pre>yarn add -D koa@^2.0.0 koa-convert koa-mount koa-graphql</pre><p>接著，我們安裝由 JavaScript 實作 GraphQL 核心的 package — <a href="https://github.com/graphql/graphql-js">graphql</a></p><pre>npm install graphql --save</pre><pre>// or use yarn</pre><pre>yarn add graphql</pre><p>完成 package 安裝後，我們來建立一個 schema.js 和 server.js 來測試 GraphQL Server：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f104bdfbbb88f008c05f2c2bf2035b39/href">https://medium.com/media/f104bdfbbb88f008c05f2c2bf2035b39/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d51ae44a5bd086f6c4313b5b0bc5061/href">https://medium.com/media/8d51ae44a5bd086f6c4313b5b0bc5061/href</a></iframe><p>執行 node server.js，接著打開http://localhost:3000/graphql確認； <a href="https://github.com/graphql/graphiql">Graph<em>i</em>QL</a> 可以讓你很方便執行 query、mutation，並可以在右邊馬上看到你的執行結果，有助於你在 Debug 時找到問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qn8K44bFuNfIn9pzMBPOBw.png" /><figcaption>如果執行結果如上圖，就代表你的 GraphQL Server 沒問題了！</figcaption></figure><h3>如何定義 Type</h3><p><strong>Type System</strong> 是 GraphQL 的核心之一，用來定義你的資料類型，在 query 後該回傳什麼類型的資料回來，我們將這些所有 Type 組合起來就是變成了一個 Schema 了！</p><p>在 Schema 中，我們都會有一個最基本的 <strong>Query Type</strong>，它是一個 <strong>Key-Value</strong> 的形式，<strong>每個 Key 會對應到一個 Type</strong>；GraphQL 本身內建了五種 Scalar Type，你可以在你的 Schema 內直接使用它們：</p><ul><li><strong>String</strong></li><li><strong>Int</strong></li><li><strong>Float</strong></li><li><strong>Boolean</strong></li><li><strong>ID</strong></li></ul><p>預設上，每個 GraphQL Type 都可以是 <strong>null</strong>，可以透過加入 ! 來表示該欄位不可以為 null：</p><pre>// 以 schema.js 為範例<br>type Query {<br>  hello: String!<br>}</pre><p>如果需要使用回傳的並不是單一的值，我們可以使用 <strong>List </strong>這個，只要把 Type 加入 [] 就可以了：</p><pre>type Query {<br>  hello: [String!]! // hello 是 String List，且該欄位和回傳值不能為 null<br>}</pre><h3>定義 Object Type</h3><p>這個範例使用了 <a href="https://unpkg.com/emoji.json@1.2.0/emoji.json">emoji.json</a>，裡面有一些 Emoji 相關資訊，透過 fetch 將資料抓回來後，做一些處理，並以前面幾筆作為範例 data。</p><pre>// 處理完成後的資料結構如下：<br>{<br>    1: {<br>        &quot;no&quot;: 1,<br>        &quot;code&quot;: &quot;1F600&quot;,<br>        &quot;char&quot;: &quot;😀&quot;,<br>        &quot;name&quot;: &quot;GRINNING FACE&quot;,<br>        &quot;date&quot;: &quot;2012ˣ&quot;,<br>        &quot;keywords&quot;: [&quot;face&quot;, &quot;grin&quot;]<br>    },<br>    2: {<br>        &quot;no&quot;: 2,<br>        &quot;code&quot;: &quot;1F601&quot;,<br>        &quot;char&quot;: &quot;😁&quot;,<br>        &quot;name&quot;: &quot;GRINNING FACE WITH SMILING EYES&quot;,<br>        &quot;date&quot;: &quot;2010ʲ&quot;,<br>        &quot;keywords&quot;: [&quot;eye&quot;, &quot;face&quot;, &quot;grin&quot;, &quot;smile&quot;]<br>    },<br>    3: {<br>        &quot;no&quot;: 3,<br>        &quot;code&quot;: &quot;1F602&quot;,<br>        &quot;char&quot;: &quot;😂&quot;,<br>        &quot;name&quot;: &quot;FACE WITH TEARS OF JOY&quot;,<br>        &quot;date&quot;: &quot;2010ʲ&quot;,<br>        &quot;keywords&quot;: [&quot;face&quot;, &quot;joy&quot;, &quot;laugh&quot;, &quot;tear&quot;]<br>    }<br>}</pre><p>很多時候我們需要用到的 Type 可能不是單純只有上面的 Scalar Type，所以<strong>我們可以定義自己所需的 Type</strong>，定義新的 <strong>Object Type</strong> 就像在定義 type Query 一樣，將你需要的欄位寫上，並給定型別（ex：String、ID ...etc)，<strong>Type 中的<em>欄位型別</em>也可以是其他你所定義的 Type</strong>，並不拘限內建的 Type。</p><p>依據整理後的 JSON 結構，新增 <strong>type Emoji</strong> 並更新我們前面的 schema.js：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74d2d4ca9447ce25e4e4cad2208cd25/href">https://medium.com/media/d74d2d4ca9447ce25e4e4cad2208cd25/href</a></iframe><p>接著打開 Graph<em>i</em>QL 輸入以下 query，確認執行結果：</p><pre>query {<br>  emojis {<br>    no<br>    code<br>    char<br>    name<br>    date<br>    keywords<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXxcOlnMXk3YWhgxRKznRQ.png" /><figcaption>Query 後所產生的 emoji 資料。</figcaption></figure><p>在前面提到了：「Type 中的欄位型別也可以是其他你所定義的 Type」，聽起來有點繞，讓我們看一下是怎麼回事，假設我們今天有另外一個 data 是長成這樣的：</p><pre>{<br>  1: {<br>    &quot;name&quot;: &quot;face&quot;,<br>    &quot;ids&quot;: [1, 3],<br>    <strong>&quot;list&quot;</strong>: [{<br>        &quot;no&quot;: 1,<br>        &quot;code&quot;: &quot;1F600&quot;,<br>        &quot;char&quot;: &quot;😀&quot;,<br>        &quot;name&quot;: &quot;GRINNING FACE&quot;,<br>        &quot;date&quot;: &quot;2012ˣ&quot;,<br>        &quot;keywords&quot;: [&quot;face&quot;, &quot;grin&quot;]<br>    }, {<br>        &quot;no&quot;: 3,<br>        &quot;code&quot;: &quot;1F602&quot;,<br>        &quot;char&quot;: &quot;😂&quot;,<br>        &quot;name&quot;: &quot;FACE WITH TEARS OF JOY&quot;,<br>        &quot;date&quot;: &quot;2010ʲ&quot;,<br>        &quot;keywords&quot;: [&quot;face&quot;, &quot;joy&quot;, &quot;laugh&quot;, &quot;tear&quot;]<br>    }]<br>  },<br>  2: {<br>    &quot;name&quot;: &quot;grin&quot;,<br>    &quot;ids&quot;: [1, 2],<br>    <strong>&quot;list&quot;</strong>: [{<br>        &quot;no&quot;: 1,<br>        &quot;code&quot;: &quot;1F600&quot;,<br>        &quot;char&quot;: &quot;😀&quot;,<br>        &quot;name&quot;: &quot;GRINNING FACE&quot;,<br>        &quot;date&quot;: &quot;2012ˣ&quot;,<br>        &quot;keywords&quot;: [&quot;face&quot;, &quot;grin&quot;]<br>    }, {<br>        &quot;no&quot;: 2,<br>        &quot;code&quot;: &quot;1F601&quot;,<br>        &quot;char&quot;: &quot;😁&quot;,<br>        &quot;name&quot;: &quot;GRINNING FACE WITH SMILING EYES&quot;,<br>        &quot;date&quot;: &quot;2010ʲ&quot;,<br>        &quot;keywords&quot;: [&quot;eye&quot;, &quot;face&quot;, &quot;grin&quot;, &quot;smile&quot;]<br>    }]<br>  }<br>}</pre><p>有注意到 <strong>list </strong>這個 key 嗎？是否和我們所定義的 type Emoji 相似，沒錯！所以我們可以這樣去定義這個資料的 type：</p><pre>type XXX {<br>  name: String!<br>  ids: [Int!]!<br>  <strong>list: [Emoji!]!</strong><br>}</pre><h3>傳入參數</h3><p>在 GraphQL 也可以使用傳入<strong>參數</strong>的搜尋方式，我們利用上面的範例再做一些小改進，首先我們在 type Query 的部份再新增一個 relatedEmoji(keyword: String!)：</p><pre>type Query {<br>  emojis: [Emoji!]!<br>  <strong>relatedEmoji(keyword: String!): [Emoji!]!</strong><br>}</pre><p>我們將 keyword 傳給 Resolver Function，讓 Resolver Function 去作應對的處理：</p><pre>exports.rootValue = {<br>  emojis: () =&gt; { ... },<br>  <strong>relatedEmoji: ({ keyword }) =&gt; Object.keys(data)<br>    .map(id =&gt; data[id])<br>    .filter(emoji =&gt; emoji[&#39;keywords&#39;].includes(keyword) ? emoji : null)</strong>,<br>};</pre><blockquote><strong>What’s resolver function?</strong> resolver function 就是當我們這個 field（ex：relatedEmoji） 在執行時，所對應到的 f unction 來處理並產生結果。</blockquote><p>我們再透過下面的方式在 query 一次，確認 query 的結果：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NCJqzQB-RDah0t3DZ2s0w.png" /><figcaption>透過傳送參數到 keyword 來進行 query，我們可以找到所 keywords 內有 grin 的資料。</figcaption></figure><h3>Mutation</h3><p>Mutation 翻譯過來的意思是：突變、變化；當我們在<strong>新增</strong>、<strong>修改</strong>、<strong>刪除</strong>資料時，我們在這都稱這個動作為為 <strong>Mutate</strong>，而在 GraphQL 主要的動作就是 <strong>Query</strong> 和 <strong>Mutation</strong>，在這個部份簡單介紹如何使用 Mutation。</p><p>首先，我們必須在 buildSchema 新增另一個 Top-Level Type — <strong>Mutation</strong>：</p><pre>exports.schema = buildSchema(`<br>  type Emoji { ... }<br>  type Query { ... }<br>  <strong>type Mutation { ... }</strong><br>`)</pre><h4>新增 Emoji</h4><p>這裡我們先來實作新增（Create）資料的部份，在 SQL 中也就是所謂的 Insert，我們更新 type Mutation 的內容：</p><pre>type Mutation {<br>  <strong>createNewEmoji(input: EmojiInput): Emoji</strong><br>}</pre><p>在 createEmoji(input: EmojiInput) 的地方這裡有個<strong>小細節</strong>，這裡的 EmojiInput 是定義一個 input 的 type<em>（</em><a href="http://graphql.org/learn/schema/#input-types"><em> input-types</em></a><em>）</em>，我們可以預期得到一個我們所要的輸入 type：</p><pre>input Emoji {<br>  code: String!<br>  char: String!<br>  name: String!<br>  date: String!<br>  keywords: [String!]!<br>}</pre><p>所以在新增一筆新的 Emoji 之後，回傳的 Type 是 Emoji，在這裡可以很明顯感受到 GraphQL 的 Type System 所帶來的好處；接著我們來實作 createNewEmoji 的 Resolver Function：</p><pre>exports.rootValue = {<br>  emojis: () =&gt; { ... },<br>  relatedEmoji: ({ keyword }) =&gt; { ... },<br>  <strong>createNewEmoji: ({ input }) =&gt; {<br>    const newEmoji = data[Object.keys(data).length + 1] = input;<br>    const id = Object.keys(data).length;<br>    newEmoji[&#39;no&#39;] = id;</strong></pre><pre><strong>    return newEmoji;<br>  },</strong><br>};</pre><p>打開 Graph<em>i</em>QL 輸入以下來新增一筆資料，並確認執行結果：</p><pre>mutation {<br>  createNewEmoji(input: {<br>    code: &quot;1F61C&quot;,<br>    char: &quot;😜&quot;,<br>    name: &quot;FACE WITH STUCK-OUT TONGUE AND WINKING EYE\n≊ face with stuck-out tongue &amp; winking eye&quot;,<br>    date: &quot;2010ʲ&quot;,<br>    keywords: [&quot;eye&quot;,&quot;face&quot;,&quot;joke&quot;,&quot;tongue&quot;, &quot;wink&quot;]<br>  }) {<br>    no<br>    code<br>    char<br>    name<br>    keywords<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSAgnlUieEOGgz53XmHPTg.png" /><figcaption>新增一筆 Emoji 資料。</figcaption></figure><p>看起來是新增成功了，我們透過 query 確認是否正確：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZY_Tf0b7n7o6D5miEvPvMg.png" /><figcaption>成功新增第四筆 Emoji 的資料！</figcaption></figure><h4>更新 Emoji</h4><p>寫到這發現篇幅有點長了😮，這邊就繼續延續上面的部份，直接實作更新（Update）資料的部份。</p><p>我們要在 type Mutation 再新增一個 updateEmoji(id, input)，給定我們要更新資料的 id 和所要更新的資料：</p><pre>type Mutation {<br>  createNewEmoji(input: EmojiInput): Emoji<br>  <strong>updateEmoji(id: ID!, input: EmojiInput): Emoji</strong><br>}</pre><p>在 exports.rootValue 新增 updateEmoji 的 Resolver Function：</p><pre>exports.rootValue = {<br>  emojis: () =&gt; { ... },<br>  relatedEmoji: { ... },<br>  createNewEmoji: { ... },<br>  <strong>updateEmoji: ({ id, input }) =&gt; {<br>    data[id] = input;<br>    data[id][&#39;no&#39;] = id;</strong></pre><pre><strong>    return data[id];<br>  },</strong><br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXEI8no_pQ-RmDsB4SbAGw.png" /><figcaption>修改剛剛新增的第四筆 Emoji 資料。</figcaption></figure><p>再使用 query 來確認第四筆的 Emoji 資訊是否被更新了：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3IvdeiHUJ_un-A8NALC8w.png" /></figure><h4>刪除 Emoji</h4><p>最後就是刪除（Delete）資料了，我們在 type Mutation 新增一個 deleteEmoji(id) ，結果回傳的是刪除後其他的資料：</p><pre>type Mutation {<br>  createNewEmoji(input: EmojiInput): Emoji<br>  updateEmoji(id: ID!, input: EmojiInput): Emoji<br>  <strong>deleteEmoji(id: ID!): [Emoji]</strong><br>}</pre><p>更新 exports.rootValue，新增 deleteEmoji 的 Resolver Function：</p><pre>exports.rootValue = {<br>  emojis: () =&gt; { ... },<br>  relatedEmoji: ({ keyword }) =&gt; { ... },<br>  createNewEmoji: ({ input }) =&gt; { ... },<br>  updateEmoji: ({ id, input }) =&gt; { ... },<br>  <strong>deleteEmoji: ({ id }) =&gt; {<br>    delete data[id];</strong></pre><pre><strong>    return Object.keys(data).map(id =&gt; data[id]);<br>  }</strong><br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdXr6Nz0yXB3c03esTcDEg.png" /><figcaption>刪除 id 為 4 的 Emoji 資料前。</figcaption></figure><p>執行刪除資料後的回傳結果如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omkd0zjvsnztbygSJWdo1A.png" /><figcaption>可以發現第四筆資料已經被我們刪除了！</figcaption></figure><p>介紹 GraphQL 大概就到這裡了，把我們最常使用的 CRUD 給走過了一遍，當然 GraphQL 的功能還不只這樣，還有一些像是：<a href="http://graphql.org/learn/queries/#fragments">Fragments</a>、<a href="http://graphql.org/learn/schema/#interfaces">Interfaces</a>…etc，當然更多相關的資料還是到 GraphQL 官方網站去學習囉！</p><p>這次對 GraphQL 的學習算是相當的淺的，還有許多沒有 touch 到的地方希望有時間再來學習，這篇文章是一個 GraphQL 初學者所寫的，我想內容應該會有不少錯誤（笑），如果有任何表達或是思考上的錯誤，歡迎糾正我，感謝你（妳）的閱讀！</p><h3>Reference</h3><ul><li><a href="http://ithelp.ithome.com.tw/articles/10188294">GraphQL 入門（iTHome 鐵人賽）</a></li><li><a href="http://graphql.org/learn/">Introduction to GraphQL</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1533032c1121" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>