import { MobilettoOrmValidationErrors } from "mobiletto-orm"; import { SESSION_HEADER, sessionCookie } from "../auth"; import { isSecure } from "~/utils/config"; export function authHeader() { const session = sessionCookie(isSecure()); if (session) { const headers: Record = {}; headers[SESSION_HEADER] = session.value; return headers; } else { return {}; } } export function authHead(headers = null) { return authReq("HEAD", headers); } export function authGet(headers = null) { return authReq("GET", headers); } export function authDelete(headers = null) { return authReq("DELETE", headers); } export type OptionalHeaders = Record | null; export function authReq(method: string, headers: OptionalHeaders = null) { return { method, headers: headers ? Object.assign({}, headers, authHeader()) : authHeader(), }; } export function authPostJson(obj: T, headers: OptionalHeaders = null) { return authDataJson(obj, "POST", headers); } export function authPutJson(obj: T, headers: OptionalHeaders = null) { return authDataJson(obj, "PUT", headers); } export function authPatchJson(obj: T, headers: OptionalHeaders = null) { return authDataJson(obj, "PATCH", headers); } export function authDataJson(obj: T, method: string, headers: OptionalHeaders = null) { return { method, headers: headers ? Object.assign({}, headers, authHeader(), { "Content-Type": "application/json", }) : authHeader(), body: JSON.stringify(obj), }; } export function handleJsonResponse(response: Response): Promise { if (response && typeof response.text === "function") { return response.text().then((text) => { let data; try { data = typeof text === "string" ? JSON.parse(text) : null; } catch (e) { // console.log(`handleJsonResponse: error parsing: ${text}`); data = null; } if (!response.ok) { const error = data || text || response.statusText; return Promise.reject(error); } // console.log(`handleJsonResponse returning: ${JSON.stringify(data, null, 2)}`) return data; }); } else { return Promise.resolve(response as T); } } export const handleErrors = (serverErrors: Ref) => (e) => { if (!e.statusCode) throw e; if (e.statusCode === 403) { serverErrors.value.global = ["forbidden"]; } else if (e.statusCode === 404) { if (typeof e.data?.data === "string" && e.data.data.length > 0) { serverErrors.value[e.data.data] = ["notFound"]; } } else if (e.statusCode === 422) { if (typeof e.data?.data === "string" && e.data.data.length > 0) { serverErrors.value = JSON.parse(e.data.data) as MobilettoOrmValidationErrors; } } else { throw e; } };