-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.ts
More file actions
106 lines (96 loc) · 2.71 KB
/
api.ts
File metadata and controls
106 lines (96 loc) · 2.71 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { wrapThrowsAsync } from "@/lib/common/utils";
import {
type ApiResponse,
type ApiSuccessResponse,
type CreateOrUpdateUserResponse,
} from "@/types/api";
import { type TEnvironmentState } from "@/types/config";
import { type ApiErrorResponse, type Result, err, ok } from "@/types/error";
export const makeRequest = async <T>(
appUrl: string,
endpoint: string,
method: "GET" | "POST" | "PUT" | "DELETE",
data?: unknown,
isDebug = false
): Promise<Result<T, ApiErrorResponse>> => {
const url = new URL(appUrl + endpoint);
const body = data ? JSON.stringify(data) : undefined;
const res = await wrapThrowsAsync(fetch)(url.toString(), {
method,
headers: {
"Content-Type": "application/json",
...(isDebug && { "Cache-Control": "no-cache" }),
},
body,
});
if (!res.ok) {
return err({
code: "network_error",
status: 500,
message: "Something went wrong",
});
}
const response = res.data;
const json = (await response.json()) as ApiResponse;
if (!response.ok) {
const errorResponse = json as ApiErrorResponse;
return err({
code: errorResponse.code === "forbidden" ? "forbidden" : "network_error",
status: response.status,
message: errorResponse.message || "Something went wrong",
url,
...(Object.keys(errorResponse.details ?? {}).length > 0 && {
details: errorResponse.details,
}),
});
}
const successResponse = json as ApiSuccessResponse<T>;
return ok(successResponse.data);
};
// Simple API client using fetch
export class ApiClient {
private readonly appUrl: string;
private readonly environmentId: string;
private readonly isDebug: boolean;
constructor({
appUrl,
environmentId,
isDebug = false,
}: {
appUrl: string;
environmentId: string;
isDebug: boolean;
}) {
this.appUrl = appUrl;
this.environmentId = environmentId;
this.isDebug = isDebug;
}
async createOrUpdateUser(userUpdateInput: {
userId: string;
attributes?: Record<string, string | number>;
}): Promise<Result<CreateOrUpdateUserResponse, ApiErrorResponse>> {
// Pass attributes as-is to preserve number types
// The backend will use the JS type to determine the attribute data type
return makeRequest(
this.appUrl,
`/api/v2/client/${this.environmentId}/user`,
"POST",
{
userId: userUpdateInput.userId,
attributes: userUpdateInput.attributes,
},
this.isDebug
);
}
async getEnvironmentState(): Promise<
Result<TEnvironmentState, ApiErrorResponse>
> {
return makeRequest(
this.appUrl,
`/api/v1/client/${this.environmentId}/environment`,
"GET",
undefined,
this.isDebug
);
}
}