Now.js Framework Documentation

Now.js Framework Documentation

ApiService

TH 04 Sep 2026 01:40

ApiService

ภาพรวม

ApiService คือระบบจัดการ HTTP requests ใน Now.js Framework รองรับ REST API calls, caching และ error handling

ใช้เมื่อ:

  • ต้องการ make API calls
  • ต้องการ REST operations (GET, POST, PUT, DELETE)
  • ต้องการ request caching
  • ต้องการ automatic retry

ทำไมต้องใช้:

  • ✅ Simple REST API interface
  • ✅ Automatic JSON handling
  • ✅ Request/Response interceptors
  • ✅ Caching support
  • ✅ Error normalization
  • ✅ Auth token integration

การใช้งานพื้นฐาน

GET Request

const response = await ApiService.get('/api/users');
console.log(response.data);

POST Request

const user = await ApiService.post('/api/users', {
  name: 'John',
  email: 'john@example.com'
});

PUT Request

await ApiService.put('/api/users/1', {
  name: 'John Updated'
});

DELETE Request

await ApiService.delete('/api/users/1');

การตั้งค่า

ApiService.init({
  baseUrl: '/api/v1',

  timeout: 30000,  // 30 seconds

  headers: {
    'Content-Type': 'application/json'
  },

  cache: {
    enabled: true,
    ttl: 300000  // 5 minutes
  }
});

API อ้างอิง

ApiService.get(url, params?, options?)

GET request

Parameter Type Description
url string Endpoint URL
options.params object Query parameters
options.cache boolean Enable caching

Returns: Promise<Object>

const users = await ApiService.get('/users', {
  params: { page: 1, limit: 10 }
});
// GET /users?page=1&limit=10

ApiService.post(url, data, options?)

POST request

Parameter Type Description
url string Endpoint URL
data object Request body

Returns: Promise<Object>

ApiService.put(url, data, options?)

PUT request (full replace)

ApiService.delete(url, options?)

DELETE request

ApiService.clearCache()

Clear cached responses

Parameter Type Description
pattern string/RegExp URL pattern to clear
// Clear all
ApiService.clearCache();

// Clear specific
ApiService.clearCache('/users');

Request Options

ApiService.get('/api/data', {
  // Query parameters
  params: { q: 'search' },

  // Custom headers
  headers: {
    'X-Custom-Header': 'value'
  },

  // Timeout override
  timeout: 60000,

  // Cache this request
  cache: true,

  // Cache TTL override
  cacheTtl: 600000,

  // Skip interceptors
  skipInterceptors: false
});

Interceptors

// Request interceptor
ApiService.interceptors.request.use((config) => {
  // Add auth header
  config.headers['Authorization'] = `Bearer ${getToken()}`;
  return config;
});

// Response interceptor
ApiService.interceptors.response.use(
  (response) => {
    // Transform response
    return response;
  },
  (error) => {
    // Handle errors
    if (error.status === 401) {
      AuthManager.requireAuth();
    }
    throw error;
  }
);

Error Handling

try {
  const data = await ApiService.get('/api/resource');
} catch (error) {
  // error.status - HTTP status code
  // error.message - Error message
  // error.data - Response body

  if (error.status === 404) {
    console.log('No data available');
  } else if (error.status === 422) {
    console.log('Validation errors:', error.data.errors);
  } else {
    console.log('Error:', error.message);
  }
}

ข้อควรระวัง

⚠️ 1. Error Handling

// ❌ ไม่ handle errors
const data = await ApiService.get('/api/data');

// ✅ Handle errors
try {
  const data = await ApiService.get('/api/data');
} catch (error) {
  NotificationManager.error(error.message);
}

⚠️ 2. Base URL

// ❌ Hardcode full URL
ApiService.get('https://api.example.com/users');

// ✅ ใช้ relative path
ApiService.get('/users');

เอกสารที่เกี่ยวข้อง