-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
200 lines (178 loc) · 5.84 KB
/
Copy pathclient.ts
File metadata and controls
200 lines (178 loc) · 5.84 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// HTTP client for the django-admin-react JSON API.
//
// Single source of network truth. Other packages MUST NOT call
// `fetch` directly; they go through @dar/data which goes through
// here. See `CLAUDE.md` §7.
import type {
ActionRunResponse,
CreatePayload,
CreateResponse,
DetailResponse,
FieldErrorEnvelope,
ListResponse,
RegistryResponse,
UpdatePayload,
} from './contract';
export interface ApiClientConfig {
/**
* Absolute path the package is mounted at, e.g. `/admin-react/`.
* Reported by the backend in the `registry` response and reused as
* the base for all subsequent calls.
*/
mount: string;
/**
* Fetch implementation; defaults to global fetch. Overridable for
* tests.
*/
fetchImpl?: typeof fetch;
/**
* Cookie name Django uses for the CSRF token. Default: `csrftoken`.
*/
csrfCookieName?: string;
}
export class ApiError extends Error {
status: number;
envelope: FieldErrorEnvelope | null;
constructor(status: number, envelope: FieldErrorEnvelope | null, message: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.envelope = envelope;
}
}
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
export class ApiClient {
private readonly mount: string;
private readonly fetchImpl: typeof fetch;
private readonly csrfCookieName: string;
constructor(config: ApiClientConfig) {
this.mount = config.mount.endsWith('/') ? config.mount : `${config.mount}/`;
this.fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
this.csrfCookieName = config.csrfCookieName ?? 'csrftoken';
}
private url(path: string): string {
const trimmed = path.startsWith('/') ? path.slice(1) : path;
return `${this.mount}api/v1/${trimmed}`;
}
private csrfToken(): string | null {
if (typeof document === 'undefined') return null;
const prefix = `${this.csrfCookieName}=`;
for (const part of document.cookie.split(';')) {
const trimmed = part.trim();
if (trimmed.startsWith(prefix)) {
return decodeURIComponent(trimmed.slice(prefix.length));
}
}
return null;
}
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
const headers: Record<string, string> = {
Accept: 'application/json',
};
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (!SAFE_METHODS.has(method)) {
const token = this.csrfToken();
if (token) headers['X-CSRFToken'] = token;
}
const init: RequestInit = {
method,
credentials: 'include',
headers,
};
if (body !== undefined) {
init.body = JSON.stringify(body);
}
const response = await this.fetchImpl(this.url(path), init);
if (response.status === 204) {
return undefined as unknown as T;
}
const text = await response.text();
let parsed: unknown = null;
if (text) {
try {
parsed = JSON.parse(text);
} catch {
// Fall through with parsed === null.
}
}
if (!response.ok) {
const envelope = (parsed ?? null) as FieldErrorEnvelope | null;
throw new ApiError(
response.status,
envelope,
envelope?.error?.message ?? `HTTP ${response.status}`,
);
}
return parsed as T;
}
getRegistry(): Promise<RegistryResponse> {
return this.request<RegistryResponse>('GET', 'registry/');
}
list(
appLabel: string,
modelName: string,
params: {
q?: string;
page?: number;
page_size?: number;
ordering?: string;
/**
* Arbitrary `list_filter` query params keyed by the descriptor's
* `name` (e.g. `{ created_at_filter: '7_days' }`). Empty-string /
* null values are omitted so clearing a filter drops it.
*/
filters?: Record<string, string | null | undefined>;
} = {},
): Promise<ListResponse> {
const search = new URLSearchParams();
if (params.q) search.set('q', params.q);
if (params.page) search.set('page', String(params.page));
if (params.page_size) search.set('page_size', String(params.page_size));
if (params.ordering) search.set('ordering', params.ordering);
for (const [key, value] of Object.entries(params.filters ?? {})) {
if (value !== undefined && value !== null && value !== '') {
search.set(key, value);
}
}
const qs = search.toString();
const suffix = qs ? `?${qs}` : '';
return this.request<ListResponse>('GET', `${appLabel}/${modelName}/${suffix}`);
}
detail(appLabel: string, modelName: string, pk: string | number): Promise<DetailResponse> {
return this.request<DetailResponse>('GET', `${appLabel}/${modelName}/${pk}/`);
}
create(appLabel: string, modelName: string, payload: CreatePayload): Promise<CreateResponse> {
return this.request<CreateResponse>('POST', `${appLabel}/${modelName}/`, payload);
}
update(
appLabel: string,
modelName: string,
pk: string | number,
payload: UpdatePayload,
): Promise<DetailResponse> {
return this.request<DetailResponse>('PATCH', `${appLabel}/${modelName}/${pk}/`, payload);
}
delete(appLabel: string, modelName: string, pk: string | number): Promise<void> {
return this.request<void>('DELETE', `${appLabel}/${modelName}/${pk}/`);
}
/**
* Run a `ModelAdmin` action over the selected rows (contract §5.4).
* The backend re-resolves the action name through
* `get_actions(request)` — the SPA name is never trusted as a
* callable lookup — and runs it over
* `get_queryset(request).filter(pk__in=pks)`.
*/
runAction(
appLabel: string,
modelName: string,
actionName: string,
pks: Array<string | number>,
confirmed = true,
): Promise<ActionRunResponse> {
return this.request<ActionRunResponse>(
'POST',
`${appLabel}/${modelName}/actions/${actionName}/`,
{ pks, confirmed },
);
}
}