From 4b5597b3fe6e02f1655e6a731e83bdcdf1017d63 Mon Sep 17 00:00:00 2001 From: ivarlovlie Date: Mon, 14 Nov 2022 13:56:56 +0700 Subject: refactor: Api files always returns Response --- code/app/src/lib/api/_fetch.ts | 73 +++++++--------------- code/app/src/lib/api/account/index.ts | 59 ++++++++--------- .../src/lib/api/password-reset-request/index.ts | 21 +++---- code/app/src/lib/api/root.ts | 12 ---- 4 files changed, 62 insertions(+), 103 deletions(-) delete mode 100644 code/app/src/lib/api/root.ts (limited to 'code/app') diff --git a/code/app/src/lib/api/_fetch.ts b/code/app/src/lib/api/_fetch.ts index b28e398..62cdf84 100644 --- a/code/app/src/lib/api/_fetch.ts +++ b/code/app/src/lib/api/_fetch.ts @@ -1,32 +1,30 @@ -import { Temporal } from "temporal-polyfill"; -import { clear_session_data } from "$lib/session"; -import type { Result } from "rustic"; -import { Err, Ok } from "rustic"; -import { redirect } from "@sveltejs/kit"; -import { browser } from "$app/environment"; -import { goto } from "$app/navigation"; -import { SignInPageMessage, signInPageMessageQueryKey } from "$routes/(main)/(public)/sign-in"; -import { log_error } from "$lib/logger"; +import {Temporal} from "temporal-polyfill"; +import {clear_session_data} from "$lib/session"; +import {redirect} from "@sveltejs/kit"; +import {browser} from "$app/environment"; +import {goto} from "$app/navigation"; +import {SignInPageMessage, signInPageMessageQueryKey} from "$routes/(main)/(public)/sign-in"; +import {log_error} from "$lib/logger"; -export async function http_post_async(url: string, body?: object | string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise> { +export async function http_post_async(url: string, body?: object | string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise { const init = make_request_init("post", body, abort_signal); - const response = await internal_fetch_async({ url, init, timeout }); - if (!skip_401_check && await redirect_if_401_async(response)) return Err("Server returned 401"); - return make_response_async(response); + const response = await internal_fetch_async({url, init, timeout}); + if (!skip_401_check && await redirect_if_401_async(response)) throw new Error("Server returned 401"); + return response; } -export async function http_get_async(url: string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise, string>> { +export async function http_get_async(url: string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise { const init = make_request_init("get", undefined, abort_signal); - const response = await internal_fetch_async({ url, init, timeout }); - if (!skip_401_check && await redirect_if_401_async(response)) return Err("Server returned 401"); - return make_response_async(response); + const response = await internal_fetch_async({url, init, timeout}); + if (!skip_401_check && await redirect_if_401_async(response)) throw new Error("Server returned 401"); + return response; } -export async function http_delete_async(url: string, body?: object | string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise, string>> { +export async function http_delete_async(url: string, body?: object | string, timeout = -1, skip_401_check = false, abort_signal?: AbortSignal): Promise { const init = make_request_init("delete", body, abort_signal); - const response = await internal_fetch_async({ url, init, timeout }); - if (!skip_401_check && await redirect_if_401_async(response)) return Err("Server returned 401"); - return make_response_async(response); + const response = await internal_fetch_async({url, init, timeout}); + if (!skip_401_check && await redirect_if_401_async(response)) throw new Error("Server returned 401"); + return response; } async function internal_fetch_async(request: InternalFetchRequest): Promise { @@ -38,7 +36,7 @@ async function internal_fetch_async(request: InternalFetchRequest): Promise 500) { response = await Promise.race([ fetch(fetch_request), - new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), request.timeout)) + new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), request.timeout)), ]); } else { response = await fetch(fetch_request); @@ -62,7 +60,7 @@ async function redirect_if_401_async(response: Response): Promise { const redirectUrl = `/sign-in?${signInPageMessageQueryKey}=${SignInPageMessage.LOGGED_OUT}`; clear_session_data(); if (browser) { - await goto(redirectUrl) + await goto(redirectUrl); } else { throw redirect(307, redirectUrl); } @@ -70,36 +68,18 @@ async function redirect_if_401_async(response: Response): Promise { return false; } -async function make_response_async(response: Response): Promise, string>> { - const result = { - ok: response.ok, - status: response.status, - http_response: response, - } as InternalFetchResponse; - - if (response.status !== 204) { - try { - result.data = await response.json() as T; - } catch (error) { - log_error("", { error, result }) - return Err("Deserialisation threw"); - } - } - return Ok(result); -} - function make_request_init(method: string, body?: any, signal?: AbortSignal): RequestInit { const init = { method, signal, headers: { "X-TimeZone": Temporal.Now.timeZone().id, - } + }, } as RequestInit; if (body) { init.body = JSON.stringify(body); - init.headers["Content-Type"] = "application/json;charset=UTF-8" + init.headers["Content-Type"] = "application/json;charset=UTF-8"; } return init; @@ -111,11 +91,4 @@ export type InternalFetchRequest = { init: RequestInit, timeout?: number retry_count?: number, -} - -export type InternalFetchResponse = { - ok: boolean, - status: number, - data: T | undefined, - http_response: Response } \ No newline at end of file diff --git a/code/app/src/lib/api/account/index.ts b/code/app/src/lib/api/account/index.ts index 305bd9f..cfd627b 100644 --- a/code/app/src/lib/api/account/index.ts +++ b/code/app/src/lib/api/account/index.ts @@ -1,39 +1,40 @@ -import { api_base } from "$lib/configuration"; -import { http_delete_async, http_get_async, http_post_async, type InternalFetchResponse } from "../_fetch"; -import type { LoginPayload } from "$lib/api/account/models/LoginPayload"; -import type { Result } from "rustic"; -import { isOk, Ok, Err } from "rustic"; -import type { SessionData } from "$lib/models/base/SessionData"; -import type { CreateAccountPayload } from "./models/CreateAccountPayload"; -import type { UpdateProfilePayload } from "./models/UpdateProfilePayload"; -import type { ErrorResult } from "$lib/models/internal/ErrorResult"; +import {api_base} from "$lib/configuration"; +import type {SessionData} from "src/lib/models/base/SessionData"; +import {http_delete_async, http_get_async, http_post_async} from "../_fetch"; export const http_account = { - async login_async(payload: LoginPayload): Promise>> { - const response = await http_post_async>(api_base("_/account/login"), payload); - if (isOk(response)) { - return Ok(); - } - return Err(response.data); + login_async(payload: LoginPayload): Promise { + return http_post_async(api_base("_/account/login"), payload); }, - logout_async(): Promise> { - return http_get_async(api_base("_/account/logout")); + logout_async(): Promise { + return http_get_async(api_base("_/account/logout")); }, - delete_account_async(): Promise { + delete_account_async(): Promise { return http_delete_async(api_base("_/account/delete")); }, - update_profile_async(payload: UpdateProfilePayload): Promise { - if (!payload.password && !payload.username) throw new Error("Password and Username is empty"); + update_profile_async(payload: UpdateProfilePayload): Promise { return http_post_async(api_base("_/account/update"), payload); }, - create_account_async(payload: CreateAccountPayload): Promise { - if (!payload.password && !payload.username) throw new Error("Password and Username is empty"); + create_account_async(payload: CreateAccountPayload): Promise { return http_post_async(api_base("_/account/create"), payload); }, - async get_profile_async(suppress_401: boolean): Promise> { - const response = await http_get_async(api_base("_/account"), 0, true); - if (isOk(response)) { - return Ok(response.data.data); - } - } -} \ No newline at end of file + get_profile_async(suppress_401: boolean): Promise { + return http_get_async(api_base("_/account"), 0, suppress_401); + }, +}; + +export interface CreateAccountPayload { + username: string, + password: string +} + +export interface LoginPayload { + username: string, + password: string, + persist: boolean +} + +export interface UpdateProfilePayload { + username?: string, + password?: string, +} diff --git a/code/app/src/lib/api/password-reset-request/index.ts b/code/app/src/lib/api/password-reset-request/index.ts index 9d6f0dc..53cb1d2 100644 --- a/code/app/src/lib/api/password-reset-request/index.ts +++ b/code/app/src/lib/api/password-reset-request/index.ts @@ -1,17 +1,14 @@ -import { api_base } from "$lib/configuration"; -import { http_get_async, http_post_async, type InternalFetchResponse } from "../_fetch"; +import {api_base} from "$lib/configuration"; +import {http_get_async, http_post_async} from "../_fetch"; export const http_password_reset_request = { - create_forgot_password_request(username: string): Promise { - if (!username) throw new Error("Username is empty"); - return http_get_async(api_base("_/forgot-password-requests/create?username=" + username)); + create_request_async(username: string): Promise { + return http_get_async(api_base("_/password-reset-request/create?for_user=" + username)); }, - check_forgot_password_request(public_id: string): Promise { - if (!public_id) throw new Error("Id is empty"); - return http_get_async(api_base("_/forgot-password-requests/is-valid?id=" + public_id)); + check_request_async(publicId: string): Promise { + return http_get_async(api_base("_/password-reset-request/is-valid?id=" + publicId)); }, - fulfill_forgot_password_request(public_id: string, newPassword: string): Promise { - if (!public_id) throw new Error("Id is empty"); - return http_post_async(api_base("_/forgot-password-requests/fulfill"), { id: public_id, newPassword }); + fulfill_request_async(publicId: string, newPassword: string): Promise { + return http_post_async(api_base("_/password-reset-request/fulfill"), {id: publicId, newPassword}); }, -} \ No newline at end of file +}; \ No newline at end of file diff --git a/code/app/src/lib/api/root.ts b/code/app/src/lib/api/root.ts deleted file mode 100644 index 661f24b..0000000 --- a/code/app/src/lib/api/root.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { http_get_async, http_post_async } from "$lib/api/_fetch"; -import { api_base } from "$lib/configuration"; -import type { IInternalFetchResponse } from "$lib/models/internal/IInternalFetchResponse"; -import type { Result } from "rustic"; - -export function server_log(message: string): void { - http_post_async(api_base("_/api/log"), message); -} - -export function server_version(): Promise, string>> { - return http_get_async(api_base("/version.txt")); -} \ No newline at end of file -- cgit v1.3