What are SSE, Server-Sent Events? Example with Express.js

Recently I have been using Server-Sent Events (SSE) to develop a feature where the server can notify the client at specific points in time. This article will provide an easy explaintion of what SSE is, when to use it, and how to implement it on both the client and server sides. 1. Introduction Imagine you need real-time updates on your website, such as displaying live stats from the server. While WebSocket might come to mind for creating bidirectional connection, that could be overkill if you only need one-way communication from server to client....

September 22, 2024 · 636 words · HSIAO, YI-HUSAN

Implement 5 common sorting algorithms with JavaScript

We’ll explore five of the most common sorting algorithms: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort and Quick Sort. Each will be implemented in JavaScript, with an analysis of their time and space complexities. 1. Bubble Sort function bubbleSort(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 1; j < arr.length; j++) { if (arr[j - 1] > arr[j]) { [arr[j - 1], arr[j]] = [arr[j], arr[j - 1]]; } } } return arr; } This code can be optimized by ruducing the numbers of iteration in the inner loop and exiting early if the array is already sorted....

August 18, 2024 · 668 words · HSIAO, YI-HUSAN

How to Dockerize NestJS

This article provide a straightforward guide to dockerizing NestJS application for both develpoment and production environments. Dockerfile for Development First, let’s create a Dockerfile.dev for the development environment within our NestJS repository: # Dockerfile.dev FROM node:20-alpine WORKDIR /usr/src/app EXPOSE 3000 CMD ["npm", "run", "start:dev"] COPY package*.json ./ RUN npm install COPY . . In this Dockerfile, we specify the Node.js version along with the Alpine Linux distribution to minimize the image size....

May 14, 2024 · 359 words · HSIAO, YI-HUSAN

Laravel 關聯 Model

Laravel 關聯性Model基礎操作:belongs_to, has_one, has_many, many to many 1. 一對一關係 has_one 假設兩個Model:店主Owner、商店Store,店主擁有一間商店(Owner has one Store),商店屬於一位店主(Store belongs to Owner)。 Owner: - id - name Store: - id - name - owner_id 首先要為Store創建欄位owner_id,在migration中可以使用$table->foreignId('owner_id')建立欄位(foreignId等同於unsignedBigInt)。 Owner.php中寫入hasOne: // app/Models/Owner.php public function store() { return $this->hasOne(Store::class); } Store.php中寫入belonsTo: // app/Models/Store.php public function owner() { return $this->belongsTo(Owner::class); } 使用方法: // 從Owner角度建立Store // 方法一:使用create $o1 = Owner::find(1); $o1->store()->create(['name'=>'store1']); // 方法二:使用save $o1 = Owner::find(1); $s2 = new Store(['name'=?'store2']); $o1->store()->save($s2); // 從Store角度建立Owner $o2 = Owner::find(2); $s3 = new Store(['name'=>'store3']); $s3->owner()->associate($o2); $s3->save(); // 撈取該Owner的Store $o1->store; $o1->store->name; // 撈取該Store的Owner $s1->owner; $s1->owner->name; hasOne與belongsTo都可以獨立設置foreign key或owner key:...

January 19, 2024 · 295 words · HSIAO, YI-HUSAN

PHP 使用筆記

PHP (Hypertext Prepocessor) 超文字預處理器,為直譯式的程式語言,可嵌入在HTML中使用。這裡記錄了PHP基礎語法與常見的函數。 1. 環境安裝與設定 下載PHP的方式: MAMP(適合Wordpress) Homebrew(適合Laravel等框架) 常見的web server: Apache Nginx(需要處理fpm) PHP自帶的web server(不是很好用) PHP設定檔為php.ini,位在/opt/homebrew/etc/php/8.1/ 1.1 Homebrew 安裝 PHP $ brew install php $ brew install [email protected] # reopen terminal $ which php # /opt/homebrew/bin/php $ ls -al "php安裝的路徑" $ brew link php $ brew unlink php $ echo $PATH # 前面的指令優先級較高 $ php -S 127.0.0.1:8000 # 運行index.php 2. PHP基礎語法 PHP使用<?php、?>作為開頭與結尾: <?php // php code ?> 2.1 註解 Comment // 單行註解,較常使用 # linux風格的單行註解 /* 這是 多行縮排 */ 2....

January 19, 2024 · 1340 words · HSIAO, YI-HUSAN

Rails Polymorphic

如何使用 Polymorphic Associations 多型關聯。 1. 使用情境 想像你正在設計「評論」功能的資料庫架構,使用者可以在幾乎任何地方留下評論,例如產品、貼文、活動等,此時你會想到使用一對多關係,為這三個 Model 設計出ProductComment、PostComment、EventComment,但此時你發現這三個資料表的欄位幾乎一模一樣,如果分成三個 Model 顯得相當冗餘,此種情景就相當適合使用Polymorphic 多型關聯來簡化資料庫的設計,使用Polymophic可以使模型在同一個關聯上屬於多個模型。 2. 使用方法 同樣以Comment這個model舉例,建立Polymorphic model的指令: rails g model Comment content:text commentable:references{polymorphic} 觀察一下產生的 migration 檔: # 產生的migration檔案,references版本 class CreateComments < ActiveRecord::Migration[7.0] def change create_table :comments do |t| t.text :content t.references :commentable, polymorphic: true, null: false t.timestamps end end end # 產生的migration檔案,較複雜的版本 class CreateComments < ActiveRecord::Migration[7.0] def change create_table :comments do |t| t.string :name t.bigint :commentable_id t.string :commentable_type t.timestamps end add_index :comments, [:commentable_type, :commentable_id] end end 接著執行rails db:migrate在資料庫產生資料表與更新schema。...

October 12, 2023 · 249 words · HSIAO, YI-HUSAN

Rails N+1問題 with joins, includes, preload and eager_load

資料庫的操作是影響網站效能的重要因素,而在存取資料時幾乎一定會遇到 N+1 問題。本篇文章將簡要探討 includes 的使用時機,以及與其相似的 preload 和 eager_load 方法。此外,我們還會介紹在處理多表格操作時常用的 joins。 1. 造成 N+1 問題的原因 我們先想像一個情境,你正在開發商家的訂單系統,其中有兩個 Model,分別是Customer與Order,Customer記載顧客資料,並且每個顧客擁有多筆訂單Order # customer.rb class Customer < ApplicationRecord has_many :orders end # order.rb class Order < ApplicationRecord belongs_to :customer end 現在我們想要呈現4位顧客的個人資訊以及他們各自的所有訂單,你可能會這樣寫: Customer.limit(4).each{|customer| puts customer.orders} Rails ORM 產生的 SQL 指令如下: SELECT 'customers'.* FROM 'customers' LIMIT 4 SELECT 'orders'.* FROM 'orders' WHERE 'orders'.'customer_id'=1 SELECT 'orders'.* FROM 'orders' WHERE 'orders'.'customer_id'=2 SELECT 'orders'.* FROM 'orders' WHERE 'orders'.'customer_id'=3 SELECT 'orders'.* FROM 'orders' WHERE 'orders'....

June 8, 2023 · 291 words · HSIAO, YI-HUSAN

Rails 基礎 ORM 的 SQL 語法

儘管Rails開發者可以透過 ActiveRecord 簡單地操作資料庫資源,但仍然需要了解基本的 SQL 語法。以下是常見 ORM 指令的翻譯,可以幫助你真正理解背後的運作原理。 較複雜的資料庫關係語法(例如:includes、join)將不在條列於本文中,我們將在另一篇文章中探討這些內容。 Create create: 使用 create 創建資料,或透過 new 產生物件之後再使用 save,以上狀況所產生的SQL語法如下。 Book.create(name: "學習Rails", author: "Eddie", intro: "學習Rails好幫手", price: 100) or Book.new(name: "學習Rails", author: "Eddie", intro: "學習Rails好幫手", price: 100) Book.save INSERT INTO books(name, author, intro, price, updated_at) VALUES ('學習Rails', 'Eddie', '學習Rails好幫手', 100, '2023...') Read all: Book.all SELECT * FROM books select or pluck: select 和 pluck 最終得到的資料形式不同,這裡不多做討論,只要知道Rails進一步的處理是在從資料庫抓取資料後,兩者前期的SQL語法沒有不同 Book.select("name") Book.pluck("name") SELECT name FROM books limit or offset: Book....

June 4, 2023 · 510 words · HSIAO, YI-HUSAN