refactor all api files

This commit is contained in:
Aarni Halinen
2021-09-04 18:52:00 +03:00
parent efd916a8a2
commit b7518d9bed
12 changed files with 133 additions and 219 deletions
+23 -41
View File
@@ -1,41 +1,37 @@
/* eslint-disable no-console */
import axios from "axios";
import Post from "@models/Feed";
import { getAuthHeader } from "@utils/auth";
import {
APIPath, deleteBackendAPI, getBackendAPI, postBackendAPI, putBackendAPI,
} from "./backend";
export const URL = `${process.env.NEXT_PUBLIC_API_URL}/feed/`;
export interface Options {
interface Options {
limit?: number;
offset?: number;
auth?: boolean;
}
class FeedApi {
static async getFeed(options: Options = {}): Promise<Post[]> {
const {
limit, offset, auth,
} = options;
const params = {
limit,
offset,
};
const headers = auth ? { Authorization: getAuthHeader() } : null;
static async getPost(id: number, auth?: boolean): Promise<Post> {
try {
const resp = await axios.get(URL, { params, headers });
return resp.data.results;
return await getBackendAPI<Post>({
path: APIPath.FEED, urlParams: { id }, authenticated: auth,
});
} catch (err) {
console.error(err);
throw err;
}
}
static async getPost(id: number, options: Options = {}): Promise<Post> {
const { auth } = options;
const headers = auth ? { Authorization: getAuthHeader() } : null;
static async getFeed({ limit, offset, auth }: Options = {}): Promise<Post[]> {
try {
const resp = await axios.get(`${URL}${id}/`, { headers });
return resp.data;
return await getBackendAPI<Post[]>({
path: APIPath.FEED,
queryParams: {
limit,
offset,
},
authenticated: auth,
});
} catch (err) {
console.error(err);
throw err;
@@ -44,12 +40,7 @@ class FeedApi {
static async createPost(data: Post): Promise<Post> {
try {
const resp = await axios.post(URL, data, {
headers: {
Authorization: getAuthHeader(),
},
});
return resp.data;
return await postBackendAPI<Post, Post>({ path: APIPath.FEED, authenticated: true }, data);
} catch (err) {
console.error(err);
throw err;
@@ -58,27 +49,18 @@ class FeedApi {
static async updatePost(data: Post): Promise<Post> {
try {
const putUrl = `${URL}${data.id}/`;
const resp = await axios.put(putUrl, data, {
headers: {
Authorization: getAuthHeader(),
},
});
return resp.data;
return await putBackendAPI<Post, Post>({
path: APIPath.FEED, urlParams: { id: data.id }, authenticated: true,
}, data);
} catch (err) {
console.error(err);
throw err;
}
}
static async deletePost(id: number) {
static async deletePost(id: number): Promise<void> {
try {
const resp = await axios.delete(`${URL}${id}`, {
headers: {
Authorization: getAuthHeader(),
},
});
return resp.data;
await deleteBackendAPI<{ message: "OK" }>({ path: APIPath.EVENTS, urlParams: { id }, authenticated: true });
} catch (err) {
console.error(err);
throw err;