@cycleplatform/api-client-typescript 0.1.15 → 0.2.1

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/src/index.ts CHANGED
@@ -1,61 +1,30 @@
1
- import createClient from "openapi-fetch";
1
+ import createClient, { type Middleware } from "openapi-fetch";
2
2
  import type { paths } from "./generated/types";
3
3
 
4
- let authToken: string | undefined = undefined;
5
- let hubScope: string | undefined = undefined;
6
- let baseUrl = "https://api.cycle.io";
7
-
8
- export function setAuthToken(token: string | undefined) {
9
- authToken = token;
10
- }
11
-
12
- export function setHubScope(hubId: string | undefined) {
13
- hubScope = hubId;
14
- }
15
-
16
- export function setBaseUrl(url: string) {
17
- baseUrl = url;
18
- }
19
-
20
- const baseClient = createClient<paths>();
21
- export const client = new Proxy(baseClient, {
22
- get(_, key: keyof typeof baseClient) {
23
- const headers: HeadersInit = {};
24
- if (authToken) {
25
- headers["Authorization"] = `Bearer ${authToken}`;
26
- }
27
- if (hubScope) {
28
- headers["X-Hub-Id"] = hubScope;
29
- }
30
- const newClient = createClient<paths>({
31
- headers,
32
- baseUrl,
4
+ export function getClient({
5
+ apiKey,
6
+ baseUrl = "https://api.cycle.io",
7
+ hubId,
8
+ fetch: customFetch,
9
+ }: {
10
+ baseUrl?: string;
11
+ apiKey: string;
12
+ hubId: string;
13
+ fetch?: typeof fetch;
14
+ }) {
15
+ const client = createClient<paths>({
16
+ baseUrl,
17
+ fetch: customFetch || fetch,
33
18
  });
34
- return newClient[key];
35
- },
36
- });
37
-
38
- type ParamVal = string | number | Record<string, string | number> | string[];
39
- type Params<T extends string, K extends ParamVal> = Partial<Record<T, K>>;
40
-
41
- /** Converts any Cycle query parameters into a URL search string */
42
- export function querySerializer<T extends string, K extends ParamVal>(
43
- params: Params<T, K>
44
- ): string {
45
- const nv = Object.entries(params).reduce((acc, [k, v]) => {
46
- if (typeof v === "string") {
47
- acc[k] = v;
48
- return acc;
49
- }
50
-
51
- if (v && typeof v === "object") {
52
- Object.keys(v).forEach(
53
- (sk) => (acc[`${k}[${sk}]`] = (v as Record<string, string>)[sk])
54
- );
55
- }
56
19
 
57
- return acc;
58
- }, {} as Record<string, string>);
20
+ const authMiddleware: Middleware = {
21
+ async onRequest(req) {
22
+ req.headers.set("Authorization", `Bearer ${apiKey}`);
23
+ req.headers.set("X-Hub-Id", hubId);
24
+ return req;
25
+ },
26
+ };
59
27
 
60
- return new URLSearchParams(nv).toString();
28
+ client.use(authMiddleware);
29
+ return client;
61
30
  }