Files
web2.0-frontend/src/api/eventApi.ts
T
2021-03-15 20:54:43 +02:00

92 lines
2.1 KiB
TypeScript

/* eslint-disable no-console */
import axios from "axios";
import Event from "@models/Event";
import { getAuthHeader } from "@utils/auth";
export const URL = `${process.env.NEXT_PUBLIC_API_URL}/events/`;
export interface Options {
onlyNonPast?: boolean;
limit?: number;
auth?: boolean;
}
class EventApi {
static async getEvent(id: number, auth = false): Promise<Event> {
try {
const headers = auth ? { Authorization: getAuthHeader() } : null;
const resp = await axios.get(`${URL}${id}/`, {
headers,
});
return resp.data;
} catch (err) {
console.error(err);
throw err;
}
}
static async getEvents(options: Options = {}): Promise<Event[]> {
const { onlyNonPast, limit, auth } = options;
try {
const params = {
since: onlyNonPast ? (new Date()).toISOString() : undefined,
limit,
};
const headers = auth ? { Authorization: getAuthHeader() } : null;
const resp = await axios.get(`${URL}`, {
headers,
params,
});
return resp.data.results;
} catch (err) {
console.error(err);
throw err;
}
}
static async createEvent(data: Event): Promise<Event> {
try {
const resp = await axios.post(URL, data, {
headers: {
Authorization: getAuthHeader(),
},
});
return resp.data;
} catch (err) {
console.error(err);
throw err;
}
}
static async updateEvent(data: Event): Promise<Event> {
try {
const putUrl = `${URL}${data.id}/`;
const resp = await axios.put(putUrl, data, {
headers: {
Authorization: getAuthHeader(),
},
});
return resp.data;
} catch (err) {
console.error(err);
throw err;
}
}
static async deleteEvent(id: number) {
try {
const resp = await axios.delete(`${URL}${id}`, {
headers: {
Authorization: getAuthHeader(),
},
});
return resp.data;
} catch (err) {
console.error(err);
throw err;
}
}
}
export default EventApi;