/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2023 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
import type {ExtendedEvent, ShortEvent, SWEvent} from "@type/event";
import {fetchWithToken, tokenStore} from "./repo";
import {ExtendedEventSchema, ShortEventSchema, SWEventSchema} from "@type/event.js";
import {z} from "zod";
import type {Dayjs} from "dayjs";
import {derived} from "svelte/store";
export interface CreateEvent {
name: string;
start: Dayjs;
end: Dayjs;
}
export interface UpdateEvent {
name?: string | null;
start?: Dayjs | number | null;
end?: Dayjs | number | null;
deadline?: Dayjs | number | null;
maxTeamMembers?: number | null;
schemType?: string | null;
publicSchemsOnly?: boolean | null;
addReferee?: string[] | null;
removeReferee?: string[] | null;
}
export class EventRepo {
constructor(private token: string) {
}
public async listEvents(): Promise {
return await fetchWithToken(this.token, "/events")
.then(value => value.json())
.then(value => z.array(ShortEventSchema).parse(value));
}
public async getEvent(id: string): Promise {
return await fetchWithToken(this.token, `/events/${id}`)
.then(value => value.json())
.then(ExtendedEventSchema.parse);
}
public async createEvent(event: CreateEvent): Promise {
return await fetchWithToken(this.token, "/events", {
method: "POST",
body: JSON.stringify({
name: event.name,
start: +event.start,
end: +event.end,
}),
}).then(value => value.json())
.then(SWEventSchema.parse);
}
public async updateEvent(id: string, event: UpdateEvent): Promise {
return await fetchWithToken(this.token, `/events/${id}`, {
method: "PUT",
body: JSON.stringify({
name: event.name,
start: event.start?.valueOf(),
end: event.end?.valueOf(),
deadline: event.deadline?.valueOf(),
maxTeamMembers: event.maxTeamMembers,
schemType: event.schemType,
publicSchemsOnly: event.publicSchemsOnly,
addReferee: event.addReferee,
removeReferee: event.removeReferee,
}),
headers: {
"Content-Type": "application/json",
},
}).then(value => value.json())
.then(SWEventSchema.parse);
}
public async deleteEvent(id: string): Promise {
const res = await fetchWithToken(this.token, `/events/${id}`, {
method: "DELETE",
});
return res.ok;
}
}
export const eventRepo = derived(tokenStore, ($token) => new EventRepo($token));