forked from Shelf-nu/shelf.nu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.ts
More file actions
64 lines (57 loc) · 1.81 KB
/
http.ts
File metadata and controls
64 lines (57 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { isRouteErrorResponse } from "@remix-run/react";
import type { ZodType } from "zod";
import { VALIDATION_ERROR } from "./error";
import type { DataOrErrorResponse, ErrorResponse } from "./http.server";
export function isErrorResponse(response: unknown): response is ErrorResponse {
return (
typeof response === "object" &&
response !== null &&
"error" in response &&
response.error !== null
);
}
export function isRouteError(
response: unknown
): response is { data: ErrorResponse } {
return isRouteErrorResponse(response) && isErrorResponse(response.data);
}
export type ValidationError<Schema extends ZodType<any, any, any>> = Record<
keyof Schema["_output"],
{ message: string | undefined }
>;
function hasValidationErrors<Schema extends ZodType<any, any, any>>(
additionalData: unknown
): additionalData is {
validationErrors: Partial<ValidationError<Schema>>;
} {
return (
typeof additionalData === "object" &&
additionalData !== null &&
VALIDATION_ERROR in additionalData &&
typeof additionalData.validationErrors === "object" &&
additionalData.validationErrors !== null
);
}
/**
* Get the validation errors returned by loader/action error.
*
*/
export function getValidationErrors<Schema extends ZodType<any, any, any>>(
error: DataOrErrorResponse["error"] | null | undefined
) {
if (!error || !hasValidationErrors<Schema>(error.additionalData)) {
return undefined;
}
return error.additionalData[VALIDATION_ERROR];
}
/**
* Get a redirect url from a request persisting the URLSearchParams
*/
export function getRedirectUrlFromRequest(request: Request) {
const url = new URL(request.url);
const searchParams = url.searchParams.toString();
const redirectUrl = `${url.pathname}${
searchParams ? `?${searchParams}` : ""
}`;
return redirectUrl;
}