BaseServices Một công cụ mạnh mẽ mà các nhà phát triển có thể sử dụng để tạo và tối ưu hóa các dịch vụ web của họ. Các hướng dẫn cơ bản về cách sử dụng sẽ được trình bày trong bài viết này.
Cách tích hợp vào ứng dụng, tối ưu hóa hiệu suất và áp dụng các thực hành tốt nhất để đảm bảo rằng dịch vụ của bạn hoạt động mượt mà và hiệu quả.
class BaseServiceClient { constructor(baseURL) { this.baseURL = baseURL; } async request(endpoint, options = {}) { const response = await fetch(`${this.baseURL}${endpoint}`, options); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); } } // Sử dụng lớp const apiClient = new BaseServiceClient('https://mtips5s.com'); apiClient.request('/data') .then(data => console.log(data)) .catch(error => console.error(error));
class AuthService extends BaseServiceClient { constructor(baseURL, apiKey) { super(baseURL); this.apiKey = apiKey; } async authenticate() { return this.request('/auth', { headers: { 'Authorization': `Bearer ${this.apiKey}` } }); } } // Sử dụng lớp const authService = new AuthService('https://mtips5s.com', 'your-api-key'); authService.authenticate() .then(data => console.log('Authenticated:', data)) .catch(error => console.error('Auth error:', error));
Bạn có thể sử dụng OOP và tính chất kế thừa
class DataService extends BaseServiceClient { async postData(endpoint, data) { return this.request(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); } } // Sử dụng lớp const dataService = new DataService('https://mtips5s.com'); dataService.postData('/submit', { name: 'John', age: 30 }) .then(response => console.log('Data submitted:', response)) .catch(error => console.error('Post error:', error));
class ErrorHandlerService extends BaseServiceClient { async requestWithHandler(endpoint, options = {}) { try { return await this.request(endpoint, options); } catch (error) { console.error('API error:', error.message); // Xử lý lỗi tùy theo mã lỗi if (error.message.includes('404')) { console.error('Resource not found'); } throw error; } } } // Sử dụng lớp const errorService = new ErrorHandlerService('https://mtips5s.com'); errorService.requestWithHandler('/invalid-endpoint') .then(data => console.log(data)) .catch(error => console.error('Handled error:', error));
class BatchRequestService extends BaseServiceClient { async batchRequests(endpoints) { const promises = endpoints.map(endpoint => this.request(endpoint)); return Promise.all(promises); } } // Sử dụng lớp const batchService = new BatchRequestService('https://mtips5s.com'); batchService.batchRequests(['/data1', '/data2', '/data3']) .then(responses => console.log('Batch responses:', responses)) .catch(error => console.error('Batch error:', error));
class WebSocketService extends BaseServiceClient { constructor(baseURL, socketURL) { super(baseURL); this.socket = new WebSocket(socketURL); } onMessage(callback) { this.socket.onmessage = event => callback(JSON.parse(event.data)); } } // Sử dụng lớp const webSocketService = new WebSocketService('https://mtips5s.com', 'wss://socket.example.com'); webSocketService.onMessage(data => console.log('WebSocket message:', data));
class UserService extends BaseServiceClient { async getUser(userId) { return this.request(`/users/${userId}`); } async createUser(userData) { return this.postData('/users', userData); } } // Sử dụng lớp const userService = new UserService('https://mtips5s.com'); userService.getUser(1) .then(user => console.log('User:', user)) .catch(error => console.error('Get user error:', error)); userService.createUser({ name: 'Alice', age: 25 }) .then(newUser => console.log('New user created:', newUser)) .catch(error => console.error('Create user error:', error));
class SessionService extends BaseServiceClient { async createSession(sessionData) { return this.postData('/sessions', sessionData); } async getSession(sessionId) { return this.request(`/sessions/${sessionId}`); } async endSession(sessionId) { return this.request(`/sessions/${sessionId}`, { method: 'DELETE' }); } } // Sử dụng lớp const sessionService = new SessionService('https://mtips5s.com'); sessionService.createSession({ userId: 1, token: 'abc123' }) .then(session => console.log('Session created:', session)) .catch(error => console.error('Create session error:', error)); sessionService.getSession(1) .then(session => console.log('Session details:', session)) .catch(error => console.error('Get session error:', error)); sessionService.endSession(1) .then(() => console.log('Session ended')) .catch(error => console.error('End session error:', error));
class CrudService extends BaseServiceClient { async createItem(itemData) { return this.postData('/items', itemData); } async readItem(itemId) { return this.request(`/items/${itemId}`); } async updateItem(itemId, itemData) { return this.request(`/items/${itemId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(itemData) }); } async deleteItem(itemId) { return this.request(`/items/${itemId}`, { method: 'DELETE' }); } } // Sử dụng lớp const crudService = new CrudService('https://mtips5s.com'); crudService.createItem({ name: 'Item 1', description: 'Description 1' }) .then(item => console.log('Item created:', item)) .catch(error => console.error('Create item error:', error)); crudService.readItem(1) .then(item => console.log('Item details:', item)) .catch(error => console.error('Read item error:', error)); crudService.updateItem(1, { name: 'Updated Item 1', description: 'Updated Description 1' }) .then(item => console.log('Item updated:', item)) .catch(error => console.error('Update item error:', error)); crudService.deleteItem(1) .then(() => console.log('Item deleted')) .catch(error => console.error('Delete item error:', error));
class CacheService extends BaseServiceClient { constructor(baseURL) { super(baseURL); this.cache = new Map(); } async cachedRequest(endpoint) { if (this.cache.has(endpoint)) { return this.cache.get(endpoint); } const response = await this.request(endpoint); this.cache.set(endpoint, response); return response; } } // Sử dụng lớp const cacheService = new CacheService('https://mtips5s.com'); cacheService.cachedRequest('/data') .then(data => console.log('Cached data:', data)) .catch(error => console.error('Cached request error:', error)); cacheService.cachedRequest('/data') .then(data => console.log('Cached data from cache:', data)) .catch(error => console.error('Cached request error:', error));
Các mẫu code sau đây cho thấy cách sử dụng lập trình hướng đối tượng JavaScript để tạo ra nhiều chức năng. Mỗi mẫu code được thiết kế để hoàn thành một nhiệm vụ cụ thể, chẳng hạn như quản lý người dùng, phiên bản, xử lý lỗi, tối ưu hóa hiệu suất và quản lý cache dữ liệu.
Tìm hiểu thêm về OOP
#Mtips5s #Contact
Fanpage: https://www.facebook.com/mtipscoder
Group trao đổi, chia sẻ: https://www.facebook.com/groups/mtipscoder
Website: https://mtips5s.com
Youtube: https://mtips5s.com
Twitter(X): @takagiks99
Instagram: @khuongkara
Threads: @khuongkara
Google Maps: @khuongkara
Chúc các bạn thành công!
Leave A Comment