frontend: throw on non-200 status code

This commit is contained in:
0x1eef 2023-12-25 02:37:18 -03:00
parent 90febb1ba5
commit e27e317896
4 changed files with 17 additions and 5 deletions

View file

@ -1,14 +1,17 @@
import receiveResponse from "/lib/fetch/receive-response";
type Params = { type Params = {
id: number; id: number;
}; };
export function useDestroyTask() { export function useDestroyTask() {
return function ({ id }: Params) { return function ({ id }: Params) {
return new Promise((accept, reject) => { return new Promise((resolve, reject) => {
const req = { method: "DELETE" }; const req = { method: "DELETE" };
return fetch(`/servlet/tasks/${id}`, req) return fetch(`/servlet/tasks/${id}`, req)
.then(receiveResponse)
.then(res => res.json()) .then(res => res.json())
.then(accept) .then(resolve)
.catch(reject); .catch(reject);
}); });
}; };

View file

@ -1,3 +1,4 @@
import receiveResponse from "/lib/fetch/receive-response";
import { TASK_STATUS } from "/types/schema"; import { TASK_STATUS } from "/types/schema";
type Params = { type Params = {
@ -14,14 +15,15 @@ export function useUpsertTask() {
return { id, title, content, status, project_id: projectId }; return { id, title, content, status, project_id: projectId };
}; };
return function ({ input }: { input: Params }) { return function ({ input }: { input: Params }) {
return new Promise((accept, reject) => { return new Promise((resolve, reject) => {
const req = { const req = {
method: input.id ? "PUT" : "POST", method: input.id ? "PUT" : "POST",
body: JSON.stringify(normalize(input)), body: JSON.stringify(normalize(input)),
}; };
return fetch("/servlet/tasks", req) return fetch("/servlet/tasks", req)
.then(receiveResponse)
.then(res => res.json()) .then(res => res.json())
.then(accept) .then(resolve)
.catch(reject); .catch(reject);
}); });
}; };

View file

@ -0,0 +1,7 @@
export default function(res: Response) {
if (res.status === 200) {
return res;
} else {
throw Error("Bad response", {cause: res});
}
}

View file

@ -9,7 +9,7 @@
"esModuleInterop": true, "esModuleInterop": true,
"jsx": "react", "jsx": "react",
"allowJs": true, "allowJs": true,
"lib": [ "ES2020", "DOM" ], "lib": [ "ES2022", "DOM" ],
"baseUrl": "src/", "baseUrl": "src/",
"paths": { "*": ["js/*"] }, "paths": { "*": ["js/*"] },