98 lines
2.5 KiB
TypeScript
98 lines
2.5 KiB
TypeScript
import { isApiError } from "@/lib/errors"
|
|
import type { PlayerService } from "@/lib/types"
|
|
|
|
import { httpJson } from "./http"
|
|
|
|
type Paginated<T> = {
|
|
items: T[] | null
|
|
meta: {
|
|
total: number
|
|
offset: number
|
|
limit: number
|
|
}
|
|
}
|
|
|
|
function itemsFrom<T>(value: Paginated<T> | T[]): T[] {
|
|
if (Array.isArray(value)) return value
|
|
return value.items ?? []
|
|
}
|
|
|
|
export type ServiceInput = {
|
|
gameId: string
|
|
title: string
|
|
description: string
|
|
price: number
|
|
unit: string
|
|
rankRange?: string
|
|
availability: string[]
|
|
}
|
|
|
|
function serviceJson(input: ServiceInput) {
|
|
return {
|
|
gameId: Number(input.gameId),
|
|
title: input.title,
|
|
description: input.description,
|
|
price: input.price,
|
|
unit: input.unit,
|
|
rankRange: input.rankRange,
|
|
availability: input.availability,
|
|
}
|
|
}
|
|
|
|
export async function listServices(): Promise<PlayerService[]> {
|
|
const res = await httpJson<unknown>("/api/v1/services", { cache: "no-store" })
|
|
if (typeof res === "object" && res !== null && "items" in res) {
|
|
return itemsFrom(res as Paginated<PlayerService>)
|
|
}
|
|
return res as PlayerService[]
|
|
}
|
|
|
|
export async function getServiceById(serviceId: string): Promise<PlayerService | undefined> {
|
|
try {
|
|
return await httpJson<PlayerService>(`/api/v1/services/${encodeURIComponent(serviceId)}`, {
|
|
cache: "no-store",
|
|
})
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message === "UNAUTHORIZED") {
|
|
throw error
|
|
}
|
|
if (isApiError(error) && error.code === 404) {
|
|
return undefined
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
|
|
export async function listServicesByPlayer(playerId: string): Promise<PlayerService[]> {
|
|
const res = await httpJson<Paginated<PlayerService> | PlayerService[]>(
|
|
`/api/v1/players/${encodeURIComponent(playerId)}/services`,
|
|
{
|
|
cache: "no-store",
|
|
},
|
|
)
|
|
if (typeof res === "object" && res !== null && "items" in res) {
|
|
return itemsFrom(res as Paginated<PlayerService>)
|
|
}
|
|
return itemsFrom(res)
|
|
}
|
|
|
|
export async function createPlayerService(input: ServiceInput): Promise<PlayerService> {
|
|
return httpJson<PlayerService>("/api/v1/services", {
|
|
method: "POST",
|
|
json: serviceJson(input),
|
|
})
|
|
}
|
|
|
|
export async function updatePlayerService(serviceId: string, input: ServiceInput): Promise<void> {
|
|
await httpJson<unknown>(`/api/v1/services/${encodeURIComponent(serviceId)}`, {
|
|
method: "PUT",
|
|
json: serviceJson(input),
|
|
})
|
|
}
|
|
|
|
export async function deletePlayerService(serviceId: string): Promise<void> {
|
|
await httpJson<unknown>(`/api/v1/services/${encodeURIComponent(serviceId)}`, {
|
|
method: "DELETE",
|
|
})
|
|
}
|