добавлены классы restapi
This commit is contained in:
parent
075f2e1011
commit
90c378115d
40
src/api/ApiClient.js
Normal file
40
src/api/ApiClient.js
Normal file
@ -0,0 +1,40 @@
|
||||
import axios from "axios";
|
||||
import { Toast } from "react-bootstrap";
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(message = "") {
|
||||
super(message);
|
||||
this.name = "HttpError";
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
Toast.error(message, { id: "HttpError" });
|
||||
}
|
||||
}
|
||||
|
||||
function responseHandler(response) {
|
||||
if (response.status === 200 || response.status === 201) {
|
||||
const data = response?.data;
|
||||
if (!data) {
|
||||
throw new HttpError("API Error. No data!");
|
||||
}
|
||||
return data;
|
||||
}
|
||||
throw new HttpError(`API Error! Invalid status code ${response.status}!`);
|
||||
}
|
||||
|
||||
function responseErrorHandler(error) {
|
||||
if (error === null) {
|
||||
throw new Error("Unrecoverable error!! Error is null!");
|
||||
}
|
||||
Toast.error(error.message, { id: "AxiosError" });
|
||||
return Promise.reject(error.message);
|
||||
}
|
||||
|
||||
export const ApiClient = axios.create({
|
||||
baseURL: "http://localhost:8081/",
|
||||
timeout: "3000",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
ApiClient.interceptors.response.use(responseHandler, responseErrorHandler);
|
34
src/api/ApiService.js
Normal file
34
src/api/ApiService.js
Normal file
@ -0,0 +1,34 @@
|
||||
import { ApiClient } from "./ApiClient";
|
||||
|
||||
class ApiService {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
async getAll() {
|
||||
return ApiClient.get(`${this.url}`);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-dupe-class-members
|
||||
async getAll(expand) {
|
||||
return ApiClient.get(`${this.url}${expand || ""}`);
|
||||
}
|
||||
|
||||
async get(id, expand) {
|
||||
return ApiClient.get(`${this.url}/${id}${expand || ""}`);
|
||||
}
|
||||
|
||||
async create(body) {
|
||||
return ApiClient.post(this.url, body);
|
||||
}
|
||||
|
||||
async update(id, body) {
|
||||
return ApiClient.put(`${this.url}/${id}`, body);
|
||||
}
|
||||
|
||||
async delete(id) {
|
||||
return ApiClient.delete(`${this.url}/${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
export default ApiService;
|
5
src/service/PostsApiService.js
Normal file
5
src/service/PostsApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from "../api/ApiService.js";
|
||||
|
||||
const PostsApiService = new ApiService("posts");
|
||||
|
||||
export default PostsApiService;
|
5
src/service/UsersApiService.js
Normal file
5
src/service/UsersApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from "../api/ApiService.js";
|
||||
|
||||
const UsersApiService = new ApiService("users");
|
||||
|
||||
export default UsersApiService;
|
Loading…
x
Reference in New Issue
Block a user