52 lines
1.9 KiB
TypeScript
52 lines
1.9 KiB
TypeScript
import { json } from '@sveltejs/kit';
|
|
import type { RequestHandler } from './$types';
|
|
import { requireAdmin } from '$lib/server/admin/auth.js';
|
|
import * as data from '$lib/server/admin/data.js';
|
|
|
|
export const GET: RequestHandler = async (event) => {
|
|
requireAdmin((await event.locals.auth())?.user?.id);
|
|
const q = event.url.searchParams.get('q') ?? undefined;
|
|
const countryCode = event.url.searchParams.get('country_code') ?? undefined;
|
|
return json(data.listCities(q, countryCode));
|
|
};
|
|
|
|
export const POST: RequestHandler = async (event) => {
|
|
requireAdmin((await event.locals.auth())?.user?.id);
|
|
const body = await event.request.json();
|
|
const { name, country, country_code, population } = body as {
|
|
name?: string;
|
|
country?: string;
|
|
country_code?: string;
|
|
population?: number | null;
|
|
};
|
|
if (!name?.trim() || !country?.trim() || !country_code?.trim()) {
|
|
return json({ error: 'name, country and country_code required' }, { status: 400 });
|
|
}
|
|
return json(data.createCity(name, country, country_code, population ?? null));
|
|
};
|
|
|
|
export const PATCH: RequestHandler = async (event) => {
|
|
requireAdmin((await event.locals.auth())?.user?.id);
|
|
const body = await event.request.json();
|
|
const { id, name, country, country_code, population } = body as {
|
|
id?: number;
|
|
name?: string;
|
|
country?: string;
|
|
country_code?: string;
|
|
population?: number | null;
|
|
};
|
|
if (id == null || !name?.trim() || !country?.trim() || !country_code?.trim()) {
|
|
return json({ error: 'id, name, country and country_code required' }, { status: 400 });
|
|
}
|
|
data.updateCity(id, name, country, country_code, population ?? null);
|
|
return json({ ok: true });
|
|
};
|
|
|
|
export const DELETE: RequestHandler = async (event) => {
|
|
requireAdmin((await event.locals.auth())?.user?.id);
|
|
const id = parseInt(event.url.searchParams.get('id') ?? '');
|
|
if (isNaN(id)) return json({ error: 'id required' }, { status: 400 });
|
|
data.deleteCity(id);
|
|
return json({ ok: true });
|
|
};
|