UNPKG

reqres-api

Version:

A managed API client for ReqResIn.

82 lines (81 loc) 3.17 kB
//import { GenericAppApiCore } from "@managed-api/generic-core"; /** * ReqResAPI provides a wrapper around the ReqRes API client to perform user operations. * It includes methods for fetching, creating, updating, and deleting users. */ export class ReqResAPI { /** * Creates an instance of ReqResAPI. * @param client - An instance of the ReqRes API client. */ constructor(client) { this.client = client; } /** * Handles the execution of an API request. * @param request - A function that returns a `Response` object when invoked. * @returns A promise resolving to an object containing the parsed data or an error message. */ async handleRequest(request) { try { const response = await request(); if (!response.ok) { const errorText = await response.text(); return { error: `Unexpected response code: ${response.status} - ${errorText}` }; } const data = await response.json(); return { data }; } catch (err) { return { error: `Network or parsing error: ${err.message}` }; } } /** * Fetches a paginated list of users. * @param pageNumber - The page number to fetch. * @returns A promise that resolves to an object containing user data or an error message. */ async getUsers(pageNumber) { return this.handleRequest(() => this.client.fetch(`/users?page=${pageNumber}`)); } /** * Creates a new user. * @param data - The user details including name and job title. * @returns A promise that resolves to the created user data or an error message. */ async createUser(data) { return this.handleRequest(() => this.client.fetch('/users', { method: 'POST', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data), })); } /** * Updates an existing user. * @param userId - The ID of the user to update. * @param data - The new user details including name and job title. * @param method - Define how update should happen, in fully (PUT) or partial (PATCH) * @returns A promise that resolves to the updated user data or an error message. */ async updateUser(userId, data, method) { return this.handleRequest(() => this.client.fetch(`/users/${userId}`, { method: method, headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data), })); } /** * Deletes a user by ID. * @param userId - The ID of the user to delete. * @returns A promise that resolves to `true` if the user was deleted successfully or an error message. */ async deleteUser(userId) { return this.handleRequest(async () => { const response = await this.client.fetch(`/users/${userId}`, { method: 'DELETE' }); if (response.ok) { return new Response(JSON.stringify(true)); // Simulate a JSON `true` response for consistency } return response; }); } }