@embark-black-book/api-contract 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,259 @@
1
+ # @embark-black-book/api-contract
2
+
3
+ Generated TypeScript contract types and endpoint client methods for Embark Black Book APIs.
4
+
5
+ ## Import Types
6
+
7
+ ```ts
8
+ import type {
9
+ ApiAccordion,
10
+ ApiAccordionCategory,
11
+ ApiAccordionItem,
12
+ } from "@embark-black-book/api-contract";
13
+
14
+ function mapAccordion(accordion: ApiAccordion): string {
15
+ return accordion.AccordionItems?.[0]?.Text ?? "No items";
16
+ }
17
+ ```
18
+
19
+ ## Import Client Methods
20
+
21
+ You can use either the shared singleton client or build your own client instance.
22
+
23
+ ```ts
24
+ import {
25
+ apiClient,
26
+ apiClientGroups,
27
+ createApiClient,
28
+ createApiClientGroups,
29
+ type ApiParameters,
30
+ parseApiResponse,
31
+ requireApiResponseOk,
32
+ ApiResponseError,
33
+ type ApiClientHooks,
34
+ type GeneratedApiClient,
35
+ } from "@embark-black-book/api-contract";
36
+
37
+ const singletonClient = apiClient;
38
+ const grouped = apiClientGroups;
39
+
40
+ const client: GeneratedApiClient = createApiClient();
41
+
42
+ const localGroups = createApiClientGroups(client);
43
+
44
+ const parameters: ApiParameters = {
45
+ fields: ["Name", "Slug"],
46
+ sort: ["Name:asc"],
47
+ pagination: { page: 1, pageSize: 10, withCount: true },
48
+ };
49
+ ```
50
+
51
+ ## Grouped Endpoint Clients
52
+
53
+ For better discoverability, methods are grouped by resource.
54
+
55
+ ```ts
56
+ import { apiClientGroups } from "@embark-black-book/api-contract";
57
+
58
+ async function getCategory(baseUrl: string, id: string) {
59
+ const response =
60
+ await apiClientGroups.accordionCategory.getAccordionCategoryById({
61
+ baseUrl,
62
+ pathParams: { id },
63
+ });
64
+
65
+ return response;
66
+ }
67
+ ```
68
+
69
+ ## Lifecycle Hooks
70
+
71
+ You can attach optional request/response/error hooks when creating a client.
72
+
73
+ ```ts
74
+ import {
75
+ createApiClient,
76
+ type ApiClientHooks,
77
+ } from "@embark-black-book/api-contract";
78
+
79
+ const hooks: ApiClientHooks = {
80
+ onRequest: ({ definition, url, requestInit }) => {
81
+ console.log("[api:req]", definition.name, requestInit.method, url);
82
+ },
83
+ onResponse: ({ definition, response }) => {
84
+ console.log("[api:res]", definition.name, response.status);
85
+ },
86
+ onError: ({ definition, error }) => {
87
+ console.error("[api:err]", definition.name, error);
88
+ },
89
+ };
90
+
91
+ const clientWithHooks = createApiClient({ hooks });
92
+ ```
93
+
94
+ ## Reusable Response Helper
95
+
96
+ The package includes helper functions to parse responses and throw a typed error for non-2xx status codes.
97
+
98
+ ```ts
99
+ import {
100
+ apiClient,
101
+ parseApiResponse,
102
+ requireApiResponseOk,
103
+ ApiResponseError,
104
+ type ApiAccordionCategory,
105
+ } from "@embark-black-book/api-contract";
106
+
107
+ async function loadCategories(baseUrl: string) {
108
+ const response = await apiClient.getAccordionCategories({ baseUrl });
109
+
110
+ // Option 1: parse without throwing
111
+ const parsed = await parseApiResponse<{ data: ApiAccordionCategory[] }>(
112
+ response
113
+ );
114
+ if (!parsed.ok) {
115
+ console.warn("Non-success status", parsed.status, parsed.data);
116
+ return [];
117
+ }
118
+
119
+ return parsed.data?.data ?? [];
120
+ }
121
+
122
+ async function createCategory(baseUrl: string, token?: string) {
123
+ try {
124
+ const response = await apiClient.createAccordionCategory({
125
+ baseUrl,
126
+ token,
127
+ body: { data: { Name: "Ground Partners", Type: "ground-partners" } },
128
+ });
129
+
130
+ // Option 2: throw on non-2xx
131
+ const parsed = await requireApiResponseOk<{ data: ApiAccordionCategory }>(
132
+ response
133
+ );
134
+ return parsed.data?.data;
135
+ } catch (error) {
136
+ if (error instanceof ApiResponseError) {
137
+ console.error("API error", error.status, error.parsed.data);
138
+ }
139
+ throw error;
140
+ }
141
+ }
142
+ ```
143
+
144
+ ## Call Endpoint Without Token
145
+
146
+ ```ts
147
+ import { apiClient } from "@embark-black-book/api-contract";
148
+
149
+ async function loadAccordionCategories(baseUrl: string) {
150
+ const response = await apiClient.getAccordionCategories({
151
+ baseUrl,
152
+ query: parameters,
153
+ });
154
+
155
+ if (!response.ok) {
156
+ throw new Error(`Request failed: ${response.status}`);
157
+ }
158
+
159
+ const payload = await response.json();
160
+ const categories = payload?.data ?? [];
161
+
162
+ return categories;
163
+ }
164
+ ```
165
+
166
+ ## Call Endpoint With Token
167
+
168
+ ```ts
169
+ import { apiClient } from "@embark-black-book/api-contract";
170
+
171
+ async function createAccordionCategory(baseUrl: string, token: string) {
172
+ const response = await apiClient.createAccordionCategory({
173
+ baseUrl,
174
+ token,
175
+ body: {
176
+ data: {
177
+ Name: "Ground Partners",
178
+ Type: "ground-partners",
179
+ IsDefaultOnDestinationMinor: false,
180
+ IsDefaultOnDestinationMajor: false,
181
+ IsDefaultOnDestinationEpic: false,
182
+ },
183
+ },
184
+ });
185
+
186
+ if (response.status === 401 || response.status === 403) {
187
+ return { authorized: false as const };
188
+ }
189
+
190
+ if (!response.ok) {
191
+ const errorPayload = await response.json().catch(() => null);
192
+ throw new Error(
193
+ `Create failed (${response.status}): ${JSON.stringify(errorPayload)}`
194
+ );
195
+ }
196
+
197
+ const created = await response.json();
198
+ return { authorized: true as const, created };
199
+ }
200
+ ```
201
+
202
+ ## Update Endpoint With Path Param
203
+
204
+ ```ts
205
+ import { apiClient } from "@embark-black-book/api-contract";
206
+
207
+ async function renameAccordionCategory(
208
+ baseUrl: string,
209
+ token: string,
210
+ id: string,
211
+ newName: string
212
+ ) {
213
+ const response = await apiClient.updateAccordionCategoryById({
214
+ baseUrl,
215
+ token,
216
+ pathParams: { id },
217
+ body: {
218
+ data: {
219
+ Name: newName,
220
+ },
221
+ },
222
+ });
223
+
224
+ if (!response.ok) {
225
+ throw new Error(`Update failed: ${response.status}`);
226
+ }
227
+
228
+ const updated = await response.json();
229
+ return updated;
230
+ }
231
+ ```
232
+
233
+ ## Commands
234
+
235
+ - `npm run contract:types:generate` from the repository root to regenerate OpenAPI + types.
236
+ - `npm run contract:types:watch` from the repository root to regenerate on Strapi model changes.
237
+ - `npm run contract:types:check` from the repository root to fail if generated artifacts in `package-contract/dist` are out of sync (CI-friendly drift check).
238
+ - `npm --prefix package-contract run verify:publish` to run package-level publish checks (drift check + required files + pack dry-run).
239
+
240
+ ## Versioning Policy
241
+
242
+ - Major: breaking API type/method changes and removals.
243
+ - Minor: backward-compatible additions (new endpoints/types/fields/methods).
244
+ - Patch: bug fixes, generator fixes, and documentation updates without API contract breaks.
245
+
246
+ ## Release Checklist
247
+
248
+ - Run `npm run contract:types:generate` from repository root.
249
+ - Run `npm run contract:types:check` from repository root.
250
+ - Run `npm --prefix package-contract run verify:publish`.
251
+ - Update `package-contract/CHANGELOG.md` with release notes.
252
+ - Bump version in `package-contract/package.json`.
253
+ - Publish package (internal registry).
254
+
255
+ ## Output
256
+
257
+ - Generated entity declarations are written to `dist/generated/api-types.d.ts`.
258
+ - Generated endpoint client declarations are written to `dist/generated/api-client.d.ts`.
259
+ - Generated endpoint runtime methods are written to `dist/generated/api-client.js`.
@@ -0,0 +1,26 @@
1
+ export interface ParsedApiResponse<T = unknown> {
2
+ ok: boolean;
3
+ status: number;
4
+ statusText: string;
5
+ headers: Headers;
6
+ data: T | null;
7
+ response: Response;
8
+ }
9
+
10
+ export declare class ApiResponseError<T = unknown> extends Error {
11
+ status: number;
12
+ statusText: string;
13
+ parsed: ParsedApiResponse<T>;
14
+ response: Response;
15
+
16
+ constructor(message: string, parsed: ParsedApiResponse<T>);
17
+ }
18
+
19
+ export declare function parseApiResponse<T = unknown>(
20
+ response: Response
21
+ ): Promise<ParsedApiResponse<T>>;
22
+
23
+ export declare function requireApiResponseOk<T = unknown>(
24
+ response: Response,
25
+ message?: string
26
+ ): Promise<ParsedApiResponse<T>>;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+
3
+ class ApiResponseError extends Error {
4
+ constructor(message, parsed) {
5
+ super(message);
6
+ this.name = "ApiResponseError";
7
+ this.status = parsed.status;
8
+ this.statusText = parsed.statusText;
9
+ this.parsed = parsed;
10
+ this.response = parsed.response;
11
+ }
12
+ }
13
+
14
+ function normalizePayload(payloadText) {
15
+ if (payloadText === "") {
16
+ return null;
17
+ }
18
+
19
+ return payloadText;
20
+ }
21
+
22
+ async function readResponseData(response) {
23
+ const contentType = (
24
+ response.headers.get("content-type") || ""
25
+ ).toLowerCase();
26
+
27
+ if (contentType.includes("application/json")) {
28
+ try {
29
+ return await response.json();
30
+ } catch (_err) {
31
+ const fallbackText = await response.text().catch(() => "");
32
+ return normalizePayload(fallbackText);
33
+ }
34
+ }
35
+
36
+ const text = await response.text().catch(() => "");
37
+ return normalizePayload(text);
38
+ }
39
+
40
+ async function parseApiResponse(response) {
41
+ const data = await readResponseData(response);
42
+
43
+ return {
44
+ ok: response.ok,
45
+ status: response.status,
46
+ statusText: response.statusText,
47
+ headers: response.headers,
48
+ data,
49
+ response,
50
+ };
51
+ }
52
+
53
+ async function requireApiResponseOk(response, message) {
54
+ const parsed = await parseApiResponse(response);
55
+
56
+ if (!parsed.ok) {
57
+ const defaultMessage = `API request failed with status ${parsed.status}${
58
+ parsed.statusText ? ` ${parsed.statusText}` : ""
59
+ }`;
60
+ throw new ApiResponseError(message || defaultMessage, parsed);
61
+ }
62
+
63
+ return parsed;
64
+ }
65
+
66
+ module.exports = {
67
+ ApiResponseError,
68
+ parseApiResponse,
69
+ requireApiResponseOk,
70
+ };