guest@websec ~ % man r01-rails-api-app
แอป Rails แบบ API
backend ของเราเป็น Rails โหมด API-only ไม่มีหน้า HTML รับ JSON เข้าและส่ง JSON ออกเท่านั้น บทนี้อธิบายว่าโหมดนี้เก็บอะไรไว้ ตัดอะไรออก และโค้ดแต่ละส่วนอยู่ตรงไหนในโปรเจกต์ของเรา
rails new myapp --api ให้ Rails ที่เบากว่า controller สืบทอดจาก ActionController::API ไม่มี view, asset, session หรือ flash ส่วนอื่น (routing, Active Record, job, mailer, test) ใช้งานได้เหมือนเดิมสร้างแอปแบบ API-only
เพิ่ม flag เดียวก็เปลี่ยนสิ่งที่ generator สร้างให้ เราใช้ PostgreSQL เสมอ เพราะเราใช้ key แบบ uuid, คอลัมน์ jsonb และคอลัมน์แบบ array
โหมด API เก็บอะไรไว้ และตัดอะไรออก
| ยังมี | ตัดออก (เพิ่มกลับเฉพาะเมื่อจำเป็น) |
|---|---|
routing, params, strong parameters | view, layout, helper, asset pipeline |
render json:, head, status codes | cookie (ActionController::Cookies) |
before_action, rescue_from | session store และ flash message |
| Active Record, Active Job, Action Mailer | การป้องกัน CSRF (protect_from_forgery) |
| caching, logging, instrumentation | middleware สำหรับเบราว์เซอร์ (method override, flash) |
Api::AppController คือ include ActionController::Cookies ให้เพิ่มกลับทีละ module เฉพาะที่ต้องใช้ อย่าเปลี่ยนไปใช้ ActionController::Baseหนึ่ง request ตั้งแต่ต้นจนจบ
ทุกบทใน track นี้จะขยายดูกล่องใดกล่องหนึ่งในภาพนี้
สำรวจโปรเจกต์ของเรา
คลิกที่โฟลเดอร์เพื่อดูว่าอะไรควรอยู่ในนั้น และอะไรไม่ควร
ข้อตกลงที่ตั้งไว้ตอนบูต
initializer ไม่กี่ไฟล์กำหนดรูปแบบของทั้ง codebase คุณจะเห็นผลของมันในทุกบทต่อจากนี้
primary key แบบ UUID
# config/initializers/generator.rb Rails.application.config.generators do |g| g.orm :active_record, primary_key_type: :uuid end # every create_table(id: :uuid) defaults to uuidv7(), which sorts by time ActiveSupport.on_load(:active_record) do require "active_record/connection_adapters/postgresql_adapter" module PostgresUUIDv7Default def create_table(table_name, **options, &block) if options[:id] == :uuid && !options.key?(:default) options[:default] = -> { "uuidv7()" } end super(table_name, **options, &block) end end ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend(PostgresUUIDv7Default) end
ID เดาไม่ได้ด้วยการนับ (/users/2, /users/3…) และ UUID v7 ยังเรียงตามเวลาที่สร้างโดยประมาณ ทำให้ index ทำงานได้ดี
class error ของเรา
# config/initializers/app_error.rb Rails.configuration.to_prepare do class AppError < StandardError; end # 400 bad request class AppAuthenticationError < StandardError; end # 401 not logged in class AppPermissionDenied < StandardError; end # 403 logged in, not allowed class AppSoftDeleteError < StandardError; end # misuse of soft delete end
model และ service จะ raise error เหล่านี้ แล้ว Api::AppController แปลงแต่ละ class เป็น HTTP status ในที่เดียว (บท r06) ส่วน to_prepare จะรัน block ใหม่ทุกครั้งที่โค้ด reload ตอน development ทำให้ class ไม่ค้างเป็นเวอร์ชันเก่า
App สิ่งสำคัญคือรูปแบบ: มี exception ไม่กี่ตัวที่ตั้งชื่อชัดเจน และแปลงเป็น status ในที่เดียวส่วนขยายเล็กๆ ของ core
params[:info].to_bool # "true" / "yes" => true, "false" / "no" => false, nil => false
"some text".mask # "so***ext"
ENV.fetch("DEBUG", false).to_boolค่าใน query string เป็น string เสมอ to_bool (ซึ่งนิยามไว้บน String, NilClass, TrueClass, FalseClass) ทำให้ controller อ่านค่า flag ได้โดยไม่ต้องเขียน == "true" ทุกที่
# frozen_string_literal: true string literal จะแก้ไขไม่ได้ ช่วยลดการจองหน่วยความจำและจับการแก้ค่าโดยไม่ตั้งใจทดสอบความเข้าใจ
ข้อใดไม่มีใน ActionController::API ตั้งแต่แรก?
cookie เป็นเรื่องของเบราว์เซอร์ โหมด API จึงตัดออก เราเพิ่ม ActionController::Cookies กลับใน Api::AppController สำหรับ cookie login ของ admin
ต้องเขียน class ใหม่สำหรับคุยกับ directory ขององค์กร จะวางไว้ที่ไหน?
มันคุยกับระบบภายนอกและไม่มีตาราง จึงเป็น service