[ New ] 10 Cách BaseServices API Đơn Giản Hóa Quy Trình [ Extends ]

Avatar admin | June 6, 2024

Để mở rộng khả năng của BaseServices, bạn có thể thêm một số chức năng mới như sau. Mỗi chức năng sẽ được hiển thị dưới dạng một lớp JavaScript bao gồm các phương thức.

Nếu bạn chưa xem BaseServices thì nhấn vào link bên dưới

[ New ] 10 Cách BaseServices API Đơn Giản Hóa Quy Trình Của Bạn

1. BaseServices Quản lý Token tự động làm mới mở rộng từ API BaseAuthentication

class TokenService extends BaseServiceClient {
    constructor(baseURL, apiKey) {
        super(baseURL);
        this.apiKey = apiKey;
        this.token = null;
        this.tokenExpiry = null;
    }

    async refreshToken() {
        const response = await this.request('/refresh-token', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${this.apiKey}`
            }
        });
        this.token = response.token;
        this.tokenExpiry = Date.now() + response.expires_in * 1000;
    }

    async requestWithToken(endpoint, options = {}) {
        if (!this.token || Date.now() >= this.tokenExpiry) {
            await this.refreshToken();
        }
        options.headers = {
            ...options.headers,
            'Authorization': `Bearer ${this.token}`
        };
        return this.request(endpoint, options);
    }
}

// Sử dụng lớp
const tokenService = new TokenService('https://api.example.com', 'your-api-key');
tokenService.requestWithToken('/secure-data')
    .then(data => console.log('Secure data:', data))
    .catch(error => console.error('Token error:', error));

Các đoạn này rất dễ hiểu nên không cần giải thích bạn nhìn vào là biết.

  • B1. Cho 1 khoảng thời gian vào
  • B2. Kiểm tra nếu token đến hạn thì bắt đầu refresh với requestWithToken
  • B3. Cập nhật lại token mới

Còn để xử lý chuyên sâu hơn hẹn bài sau

Đây là một mẫu code sau khi tôi áp dụng baseServices thực hiện chức năng refresh token khi hết hạn bạn có thể tham khảo

Để mở rộng khả năng của BaseServices
Để mở rộng khả năng của BaseServices

Sau khi token hết hạn ta tiến hành gọi đến lớp cha

Để mở rộng khả năng của BaseServices
Để mở rộng khả năng của BaseServices

Và tiếng hành xử lý token call đến server

Để mở rộng khả năng của BaseServices
Để mở rộng khả năng của BaseServices

2. BaseServices Tải lên tệp (File Upload)

class FileUploadService extends BaseServiceClient {
    async uploadFile(endpoint, file) {
        const formData = new FormData();
        formData.append('file', file);

        return this.request(endpoint, {
            method: 'POST',
            body: formData
        });
    }
}

// Sử dụng lớp
const fileUploadService = new FileUploadService('https://api.example.com');
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', () => {
    const file = fileInput.files[0];
    fileUploadService.uploadFile('/upload', file)
        .then(response => console.log('File uploaded:', response))
        .catch(error => console.error('Upload error:', error));
});

Với Chức năng upload services này chúng ta chỉ cần tạo form data và gửi qua BaseAPI là xong

Đây chỉ là cơ bản còn source chi tiết và bug lỗi sẽ được thêm sau

3. Lọc và phân trang dữ liệu (Data Filtering and Pagination)

class DataService extends BaseServiceClient {
    async getDataWithPagination(endpoint, page, limit) {
        return this.request(`${endpoint}?page=${page}&limit=${limit}`);
    }

    async filterData(endpoint, filters) {
        const queryString = new URLSearchParams(filters).toString();
        return this.request(`${endpoint}?${queryString}`);
    }
}

// Sử dụng lớp
const dataService = new DataService('https://api.example.com');
dataService.getDataWithPagination('/items', 1, 10)
    .then(data => console.log('Paginated data:', data))
    .catch(error => console.error('Pagination error:', error));

dataService.filterData('/items', { category: 'books', priceRange: '10-50' })
    .then(data => console.log('Filtered data:', data))
    .catch(error => console.error('Filter error:', error));

Công thức phân trang: ((page-1) * limit)

Page: 1, 2 ,3 ,4 …N

Limit: 10, 20, 30 …

Sẽ lên một bài về Pagination

4. Đăng ký và quản lý Webhook

class WebhookService extends BaseServiceClient {
    async registerWebhook(endpoint, webhookUrl) {
        return this.postData(endpoint, { url: webhookUrl });
    }

    async getWebhooks(endpoint) {
        return this.request(endpoint);
    }

    async deleteWebhook(endpoint, webhookId) {
        return this.request(`${endpoint}/${webhookId}`, { method: 'DELETE' });
    }
}

// Sử dụng lớp
const webhookService = new WebhookService('https://api.example.com');
webhookService.registerWebhook('/webhooks', 'https://yourapp.com/webhook')
    .then(response => console.log('Webhook registered:', response))
    .catch(error => console.error('Webhook registration error:', error));

webhookService.getWebhooks('/webhooks')
    .then(webhooks => console.log('Webhooks:', webhooks))
    .catch(error => console.error('Get webhooks error:', error));

webhookService.deleteWebhook('/webhooks', 'webhook-id')
    .then(() => console.log('Webhook deleted'))
    .catch(error => console.error('Delete webhook error:', error));

5. Quản lý thông báo (Notifications)

class NotificationService extends BaseServiceClient {
    async getNotifications() {
        return this.request('/notifications');
    }

    async markAsRead(notificationId) {
        return this.request(`/notifications/${notificationId}/read`, { method: 'POST' });
    }
}

// Sử dụng lớp
const notificationService = new NotificationService('https://api.example.com');
notificationService.getNotifications()
    .then(notifications => console.log('Notifications:', notifications))
    .catch(error => console.error('Get notifications error:', error));

notificationService.markAsRead('notification-id')
    .then(() => console.log('Notification marked as read'))
    .catch(error => console.error('Mark as read error:', error));

6. Quản lý lịch trình (Scheduling)

class ScheduleService extends BaseServiceClient {
    async createSchedule(scheduleData) {
        return this.postData('/schedules', scheduleData);
    }

    async getSchedules() {
        return this.request('/schedules');
    }

    async deleteSchedule(scheduleId) {
        return this.request(`/schedules/${scheduleId}`, { method: 'DELETE' });
    }
}

// Sử dụng lớp
const scheduleService = new ScheduleService('https://api.example.com');
scheduleService.createSchedule({ task: 'Backup', time: '02:00' })
    .then(schedule => console.log('Schedule created:', schedule))
    .catch(error => console.error('Create schedule error:', error));

scheduleService.getSchedules()
    .then(schedules => console.log('Schedules:', schedules))
    .catch(error => console.error('Get schedules error:', error));

scheduleService.deleteSchedule('schedule-id')
    .then(() => console.log('Schedule deleted'))
    .catch(error => console.error('Delete schedule error:', error));

7. Gửi email thông qua API

class EmailService extends BaseServiceClient {
    async sendEmail(emailData) {
        return this.postData('/send-email', emailData);
    }
}

// Sử dụng lớp
const emailService = new EmailService('https://api.example.com');
emailService.sendEmail({
    to: '[email protected]',
    subject: 'Test Email',
    body: 'This is a test email.'
})
    .then(response => console.log('Email sent:', response))
    .catch(error => console.error('Send email error:', error));

8. Quản lý người dùng nhóm (User Groups)

class UserGroupService extends BaseServiceClient {
    async createGroup(groupData) {
        return this.postData('/groups', groupData);
    }

    async getGroups() {
        return this.request('/groups');
    }

    async addUserToGroup(groupId, userId) {
        return this.request(`/groups/${groupId}/users`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ userId })
        });
    }

    async removeUserFromGroup(groupId, userId) {
        return this.request(`/groups/${groupId}/users/${userId}`, { method: 'DELETE' });
    }
}

// Sử dụng lớp
const userGroupService = new UserGroupService('https://api.example.com');
userGroupService.createGroup({ name: 'Admins' })
    .then(group => console.log('Group created:', group))
    .catch(error => console.error('Create group error:', error));

userGroupService.getGroups()
    .then(groups => console.log('Groups:', groups))
    .catch(error => console.error('Get groups error:', error));

userGroupService.addUserToGroup('group-id', 'user-id')
    .then(() => console.log('User added to group'))
    .catch(error => console.error('Add user to group error:', error));

userGroupService.removeUserFromGroup('group-id', 'user-id')
    .then(() => console.log('User removed from group'))
    .catch(error => console.error('Remove user from group error:', error));

9. Tạo báo cáo (Reporting)

class ReportingService extends BaseServiceClient {
    async generateReport(reportType, parameters) {
        return this.postData(`/reports/${reportType}`, parameters);
    }

    async getReportStatus(reportId) {
        return this.request(`/reports/status/${reportId}`);
    }
}

// Sử dụng lớp
const reportingService = new ReportingService('https://api.example.com');
reportingService.generateReport('sales', { startDate: '2023-01-01', endDate: '2023-01-31' })
    .then(report => console.log('Report generated:', report))
    .catch(error => console.error('Generate report error:', error));

reportingService.getReportStatus('report-id')
    .then(status => console.log('Report status:', status))
    .catch(error => console.error('Get report status error:', error));

10. BaseServices Quản lý thông tin địa điểm (Location Management)

class LocationService extends BaseServiceClient {
    async addLocation(locationData) {
        return this.postData('/locations', locationData);
    }

    async getLocation(locationId) {
        return this.request(`/locations/${locationId}`);
    }

    async updateLocation(locationId, locationData) {
        return this.request(`/locations/${locationId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(locationData)
        });
    }

    async deleteLocation(locationId) {
        return this.request(`/locations/${locationId}`, { method: 'DELETE' });
    }
}

// Sử dụng lớp
const locationService = new LocationService('https://api.example.com');
locationService.addLocation({ name: 'New York Office', address: '123 Main St, NY' })
    .then(location => console.log('Location added:', location))
    .catch(error => console.error('Add location error:', error));

locationService.getLocation('location-id')
    .then(location => console.log('Location details:', location))
    .catch(error => console.error('Get location error:', error));

locationService.updateLocation('location-id', { name: 'NY Office Updated' })
    .then(location => console.log('Location updated:', location))
    .catch(error => console.error('Update location error:', error));

locationService.deleteLocation('location-id')
    .then(() => console.log('Location deleted'))
    .catch(error => console.error('Delete location error:', error));

Kết luận

Các chức năng của BaseServices có thể được mở rộng bằng những mẫu code này. Các chức năng này bao gồm quản lý token, tải lên tệp, lọc dữ liệu, thông báo, lịch trình, email, nhóm người dùng, báo cáo và thông tin địa điểm. Chúng có thể được tích hợp vào dự án của bạn để tạo ra các ứng dụng mạnh mẽ hơn và linh hoạt hơn.

Tìm hiểu thêm về BaseServices

Access_token Wiki

#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

#Base Code #Souce Code

Npm: @tools.mtips5s.com

Bộ công cụ My Self: @github

Npm: @npm

Docker: @docker

Chúc các bạn thành công!


Written by admin


Comments

This post currently has no responses.

Leave a Reply