การ validate ข้อมูลใน fastify

Teerayut Hiruntaraporn
2 min readJun 15, 2021

--

Fastify ถือว่าเป็น Web Framework ที่น่าสนใจอีกตัวหนึ่งในช่วงปีที่ผ่านมาด้วยจุดเด่นอย่างหนึ่งคือ ความเร็วในการทำงานของมันที่ดุกว่า express ขณะที่ฟังก์ชันการใช้งานก็ดูคล้ายๆ adoption ไม่ได้ วุ่นวายมาก

ทีนี้ในเวลาที่เราจะรับข้อมูลจาก REST API ปัญหาที่มักจะพบเจอกันก็คือการที่เราต้องมา validate ข้อมูลที่ได้รับมา ว่ามันโอเคที่จะ process ต่อไหม, หรือมีใครจะแอบมาเล่นอะไรแผลงๆ เรา

ผู้พัฒนาก็เลยต้องเสียเวลาในระดับหนึ่งในการทำการตรวจสอบปัญหาพวกนี้

สำหรับ Fastify นั้นได้ใช้ประโยชน์จากการมีอยู่ของ JSON Schema โดยจะเอา definition ที่เราต้องการสร้างเป็น JSON Schema แล้ว มาตรวจสอบให้เมื่อมีการ ทำ REST Request เข้ามาที่ระบบ

เช่น ถ้าเรากำหนดข้อมูล JSON Schema สำหรับ validate body JSON ในลักษณะนี้

const schema = {
body: {
title: "Example schema",
description: "This is example Schema",
type: "object",
properties: {
id: {
description: "id",
type: "integer",
},
documents: {
description: "Documents name list",
type: "array",
items: {
type: "string",
},
minItems: 2,
uniqueItems: true,
},
},
required: ["id", "documents"],
},
};

ในที่นี้คือ เราจะรับ JSON มาเป็น hash ที่ประกอบด้วย

  • id (integer)
  • documents (array ของ string ที่มีขนาดอย่างน้อย 2 ตัว และไม่ซ้ำกัน)

เมื่อเราเอามาเข้ากับ ตัวรับ request ก็จะอยู่ในรูปแบบนี้

fastify.post("/merge", { schema }, async (req, resp) => {
const data = req.body
.
.
.
}

สิ่งที่เกิดขึ้นคือ เมื่อมัน parse ถูก มันก็เข้ามาทำงานภายใน block

แต่ถ้ามันผิดโครงสร้าง ก็จะโวยวาย และบอกด้วยว่า ปัญหาคืออะไร เช่น

❯ curl -X POST --header 'content-type: application/json' \
-d '{"id":1, "documents": null}' \
http://localhost:4000/merge
{"statusCode":400,"error":"Bad Request","message":"body.documents should be array"}

หรือ

> curl -X POST --header 'content-type: application/json' \
-d '{"id":1, "documents": ["test1"]}' \
http://localhost:4000/merge
{"statusCode":400,"error":"Bad Request","message":"body.documents should NOT have fewer than 2 items"}

ก็ถือว่าเป็นเทคนิคที่ช่วยให้ชีวิตสบายขึ้น ไม่ต้องมี logic ของ Code validation ท่วม แต่ก็ต้องแลกมาด้วยการไป กำหนด schema ที่เหมาะสมครับ

แหล่งอ้างอิง

  1. Fastify, https://www.fastify.io/
  2. JSON Schema, https://json-schema.org/learn/getting-started-step-by-step.html

--

--

Teerayut Hiruntaraporn
Teerayut Hiruntaraporn

No responses yet