Add exit api

This commit is contained in:
2023-06-07 09:51:32 +08:00
parent 3960d730c0
commit 2002dd4749
4 changed files with 66 additions and 6 deletions

View File

@@ -4,18 +4,20 @@
import config from "./deno.json" assert { type: "json" };
import * as $0 from "./routes/api/config.ts";
import * as $1 from "./routes/api/export/gallery/zip/[gid].ts";
import * as $2 from "./routes/api/task.ts";
import * as $3 from "./routes/index.tsx";
import * as $1 from "./routes/api/exit.ts";
import * as $2 from "./routes/api/export/gallery/zip/[gid].ts";
import * as $3 from "./routes/api/task.ts";
import * as $4 from "./routes/index.tsx";
import * as $$0 from "./islands/Container.tsx";
import * as $$1 from "./islands/Settings.tsx";
const manifest = {
routes: {
"./routes/api/config.ts": $0,
"./routes/api/export/gallery/zip/[gid].ts": $1,
"./routes/api/task.ts": $2,
"./routes/index.tsx": $3,
"./routes/api/exit.ts": $1,
"./routes/api/export/gallery/zip/[gid].ts": $2,
"./routes/api/task.ts": $3,
"./routes/index.tsx": $4,
},
islands: {
"./islands/Container.tsx": $$0,

27
routes/api/exit.ts Normal file
View File

@@ -0,0 +1,27 @@
import { Handlers } from "$fresh/server.ts";
import { parse_bool } from "../../server/parse_form.ts";
import { get_task_manager } from "../../server.ts";
export const handler: Handlers = {
async POST(req, _ctx) {
let force = false;
try {
const form = await req.formData();
force = await parse_bool(form.get("force"), false);
} catch (_) {
null;
}
setTimeout(async () => {
const m = get_task_manager();
const aborted = m.aborted;
m.abort();
if (force) {
m.force_abort();
}
if (aborted) return;
await m.waiting_unfinished_task();
m.close();
}, 1);
return new Response("Aborted.");
},
};

14
server/parse_form.ts Normal file
View File

@@ -0,0 +1,14 @@
export async function parse_bool<T extends boolean | null>(
value: FormDataEntryValue | null,
def: T,
): Promise<boolean | T> {
if (value === null) return def;
const nv = typeof value === "string" ? value : await value.text();
const v = nv.toLowerCase();
const n = parseInt(v);
if (isNaN(n)) {
return v === "true";
} else {
return n !== 0;
}
}

17
server/parse_form_test.ts Normal file
View File

@@ -0,0 +1,17 @@
import { assertEquals } from "std/testing/asserts.ts";
import { parse_bool } from "./parse_form.ts";
Deno.test("parse_bool_test", async () => {
const f = new FormData();
f.append("a", "d");
assertEquals(await parse_bool(f.get("a"), true), false);
assertEquals(await parse_bool(f.get("b"), true), true);
assertEquals(await parse_bool(f.get("b"), null), null);
assertEquals(await parse_bool(f.get("a"), null), false);
f.append("c", "1");
f.append("d", "TRue");
assertEquals(await parse_bool(f.get("c"), null), true);
assertEquals(await parse_bool(f.get("d"), null), true);
f.append("e", "tRUE", "a.png");
assertEquals(await parse_bool(f.get("e"), null), true);
});