[ New ] 1 BaseServices CURD API User Đơn Giản Hóa Của Bạn

Avatar admin | June 7, 2024

Đây là một ví dụ về cách sử dụng lập trình hướng đối tượng trong JavaScript để tạo một lớp BaseService với các chức năng CRUD (tạo, đọc, cập nhật và loại bỏ).

Với các chức năng mở rộng này, lớp BaseUser sẽ có thể đáp ứng được hầu hết các yêu cầu quản lý người dùng trong các ứng dụng phức tạp.

Base Service với chức năng CURD
Base Service với chức năng CURD

Tạo lớp BaseService CURD

class BaseService {
    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();
    }

    async create(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
    }

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

    async update(endpoint, data) {
        return this.request(endpoint, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
    }

    async delete(endpoint) {
        return this.request(endpoint, {
            method: 'DELETE'
        });
    }
}

// Sử dụng lớp BaseService
const baseService = new BaseService('https://api.example.com');

// Tạo một mục mới
baseService.create('/items', { name: 'NewItem', description: 'This is a new item.' })
    .then(response => console.log('Created:', response))
    .catch(error => console.error('Create error:', error));

// Đọc một mục
baseService.read('/items/1')
    .then(item => console.log('Read:', item))
    .catch(error => console.error('Read error:', error));

// Cập nhật một mục
baseService.update('/items/1', { name: 'UpdatedItem', description: 'This is an updated item.' })
    .then(response => console.log('Updated:', response))
    .catch(error => console.error('Update error:', error));

// Xóa một mục
baseService.delete('/items/1')
    .then(() => console.log('Deleted'))
    .catch(error => console.error('Delete error:', error));

Giải thích mã nguồn Lớp BaseService:

-Đây là lớp cơ bản cho các dịch vụ của bạn và chứa các phương thức CRUD cơ bản.
-Phương thức yêu cầu: Phương thức này xử lý các yêu cầu HTTP và phản hồi từ máy chủ. Nó sẽ gửi một lỗi HTTP nếu có.
-Phương thức tạo: Phương thức này tạo một mục mới bằng cách sử dụng HTTP POST.
-Phương thức đọc: Phương thức này đọc một mục bằng HTTP GET.
-Phương thức cập nhật: Phương thức này sử dụng HTTP PUT để cập nhật một mục.
-Phương thức xóa: Phương thức này sử dụng HTTP DELETE để xóa một mục.

Tạo lớp BaseUser kế thừa từ BaseService

class BaseUser extends BaseService {
    constructor(baseURL) {
        super(baseURL);
    }

    async createUser(userData) {
        return this.create('/users', userData);
    }

    async getUser(userId) {
        return this.read(`/users/${userId}`);
    }

    async updateUser(userId, userData) {
        return this.update(`/users/${userId}`, userData);
    }

    async deleteUser(userId) {
        return this.delete(`/users/${userId}`);
    }

    async getAllUsers() {
        return this.read('/users');
    }
}

// Sử dụng lớp BaseUser
const baseUser = new BaseUser('https://api.example.com');

// Tạo một người dùng mới
baseUser.createUser({ name: 'John Doe', email: '[email protected]' })
    .then(response => console.log('User Created:', response))
    .catch(error => console.error('Create User Error:', error));

// Đọc thông tin người dùng
baseUser.getUser(1)
    .then(user => console.log('User Details:', user))
    .catch(error => console.error('Get User Error:', error));

// Cập nhật thông tin người dùng
baseUser.updateUser(1, { name: 'John Doe Updated', email: '[email protected]' })
    .then(response => console.log('User Updated:', response))
    .catch(error => console.error('Update User Error:', error));

// Xóa người dùng
baseUser.deleteUser(1)
    .then(() => console.log('User Deleted'))
    .catch(error => console.error('Delete User Error:', error));

// Lấy danh sách tất cả người dùng
baseUser.getAllUsers()
    .then(users => console.log('All Users:', users))
    .catch(error => console.error('Get All Users Error:', error));

Tìm hiểu mã nguồn.
– Lớp BaseService cung cấp các phương thức cơ bản cho các hoạt động CRUD.
– Lớp người dùng Base, kế thừa từ BaseService, cung cấp các chiến lược quản lý người dùng cụ thể.


Để tạo người dùng mới, hãy thực hiện yêu cầu HTTP POST.
– Phương thức getUser: sử dụng yêu cầu HTTP GET để thu thập dữ liệu người dùng.
– Phương thức cập nhật người dùng: Để cập nhật thông tin người dùng, hãy sử dụng HTTP PUT.
– Phương thức xóa người dùng: Để xóa người dùng, hãy sử dụng HTTP DELETE.
– Phương thức getAllUsers: Thực hiện yêu cầu HTTP GET để thu thập danh sách tất cả người dùng.
Ví dụ này minh họa cách sử dụng lớp BaseUser để thực hiện các thao tác CRUD liên quan đến người dùng.

Lớp này có thể được mở rộng dễ dàng hoặc bạn có thể tạo ra các cách khác để đáp ứng các yêu cầu cụ thể của ứng dụng của bạn.

Một ví dụ khác

“Đây là ví dụ mẫu còn thực tế sẽ khác đi rất nhiều”

Base Service với chức năng CURD
Base Service với chức năng CURD

Xem thêm:

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

Tìm hiểu thêm:

CURD Viblo

Crockford, D. (2006). The application/json Media Type for JavaScript Object Notation (JSON). https://doi.org/10.17487/rfc4627

mtips5s -. (n.d.). mtips5s. https://mtips5s.com/

Written by admin


Comments

This post currently has no responses.

Leave a Reply