ในการใช้งาน HTTP Server และ HTTP Client นั้น TypeScript ไม่ได้มีไลบรารี Core Library แบบรวมศูนย์เหมือน dart:io แต่การทำงานจะขึ้นอยู่กับสภาพแวดล้อมที่โค้ดรัน:
-
Client: ใช้ Fetch API (มาตรฐาน Web/Node.js)
-
Server: ใช้ Node.js
httpModule (หรือ Frameworks เช่น Express)
บทความนี้จะแสดงวิธีจัดการทั้ง Client และ Server ในบริบทของ TypeScript โดยเน้นที่ความปลอดภัยของชนิดข้อมูล (Type Safety)
1. HTTP Client: การเรียกใช้งาน API (Using fetch)
ในฐานะ Client (เช่น ในเบราว์เซอร์หรือ Node.js environment) TypeScript/JavaScript ใช้ Fetch API ซึ่งเป็น Global Function ในการส่ง HTTP Request
A. การกำหนดชนิดข้อมูล (Type Safety)
เราใช้ interface เพื่อกำหนดโครงสร้างของข้อมูลที่จะได้รับกลับมา (Response Body) ซึ่งเป็นหัวใจสำคัญของ TypeScript ในการจัดการ API
// กำหนดโครงสร้างข้อมูลที่คาดหวังจาก API
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
// กำหนด Generic Function เพื่อให้รับส่งข้อมูลที่มี Type
async function fetchApi<T>(url: string, method: string = 'GET'): Promise<T> {
const response = await fetch(url, { method });
if (!response.ok) {
throw new Error(`HTTP Error! Status: ${response.status}`);
}
// แปลง Response เป็น JSON และระบุชนิดข้อมูลด้วย <T>
return response.json() as T;
}
B. ตัวอย่างการใช้งาน GET และ POST
เราใช้ async/await ร่วมกับ fetch เพื่อให้โค้ดมีความอ่านง่ายและเป็นลำดับ
async function getPostExample() {
try {
// ใช้ <Post> เพื่อระบุชนิดข้อมูลที่คาดหวัง
const post: Post = await fetchApi<Post>('https://jsonplaceholder.typicode.com/posts/1');
console.log(`Title: ${post.title}`); // TypeScript รู้จัก post.title
} catch (error) {
console.error("Fetch failed:", error);
}
}
async function createPostExample() {
const newPost = {
title: 'New TS Post',
body: 'This is body',
userId: 1,
};
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newPost), // แปลง Object เป็น JSON String
});
const createdPost: Post = await response.json();
console.log(`Created ID: ${createdPost.id}`);
}
2. HTTP Server: การสร้าง Web Server (Using Node.js)
สำหรับการสร้าง HTTP Server ใน TypeScript จะใช้ Module หลักของ Node.js ที่ชื่อว่า node:http ซึ่งจำเป็นต้องมีการ import ก่อนใช้งาน
A. การสร้าง Server
เราใช้เมธอด http.createServer() ที่รับ Callback Function ที่มีพารามิเตอร์ req (Request) และ res (Response)
// ต้องติดตั้ง @types/node ก่อน: npm install @types/node
import * as http from 'node:http';
import { IncomingMessage, ServerResponse } from 'node:http'; // Import Types
const hostname: string = '127.0.0.1';
const port: number = 3000;
// กำหนดชนิดข้อมูลให้กับ req และ res เพื่อให้ TypeScript ช่วยตรวจสอบ
const server = http.createServer((req: IncomingMessage, res: ServerResponse) => {
// 1. การกำหนด HTTP Status Code
res.statusCode = 200;
// 2. การกำหนด Header
res.setHeader('Content-Type', 'application/json');
// 3. การจัดการ Routing (อย่างง่าย)
if (req.url === '/hello' && req.method === 'GET') {
const data = { message: 'Hello from TypeScript Node.js Server!' };
res.end(JSON.stringify(data)); // ส่ง Response กลับ
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
// การเริ่มฟัง (Listen)
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});