-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
38 lines (34 loc) · 1.06 KB
/
index.ts
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
import type { RemoteFailure, RemoteSuccess } from "@devexperts/remote-data-ts";
import type { Handler } from "@powrpc/server";
const success = <S>(value: S) => ({ _tag: "RemoteSuccess", value } as const);
const failure = <E>(error: E) => ({ _tag: "RemoteFailure", error } as const);
const rpc =
<
MT extends string,
M extends { method?: MT; query?: Record<string, string> },
E,
A,
ARG extends unknown[]
>(
fn: Handler<M, E, A, ARG>
) =>
(init: M): Promise<RemoteFailure<E | [number, string]> | RemoteSuccess<A>> =>
fetch(
`${fn}?${init.query ? new URLSearchParams(init.query).toString() : ""}`,
{ method: init.method }
).then((response) =>
response
.json()
.then((json) =>
response.ok
? success([response.status, json] as A)
: failure([response.status, json] as E)
)
.catch((e) =>
failure([
response.status,
e instanceof Error ? e.message : "Unexpected error parsing JSON.",
])
)
);
export default rpc;