MCPcopy Create free account
hub / github.com/CapSoftware/Cap / createMobileApiClient

Function createMobileApiClient

apps/mobile/src/api/mobile.ts:109–305  ·  view source on GitHub ↗
({ baseUrl, getToken }: ClientOptions)

Source from the content-addressed store, hash-verified

107};
108
109export const createMobileApiClient = ({ baseUrl, getToken }: ClientOptions) => {
110 const origin = trimBaseUrl(baseUrl);
111
112 const request = async <A, I>(
113 path: string,
114 schema: Schema.Schema<A, I, never>,
115 options: RequestOptions = {},
116 ): Promise<A> => {
117 const token = await getToken();
118 if (!token) {
119 throw new MobileApiError("Missing mobile session", 401, null);
120 }
121
122 const url = new URL(path, origin);
123 appendQuery(url, options.query);
124 const headers = new Headers({
125 Authorization: `Bearer ${token}`,
126 });
127 let body: BodyInit | undefined;
128 if (options.body !== undefined) {
129 headers.set("Content-Type", "application/json");
130 body = JSON.stringify(options.body);
131 }
132
133 const response = await fetch(url.toString(), {
134 method: options.method ?? "GET",
135 headers,
136 body,
137 });
138 const payload = await parseJson(response);
139 if (!response.ok) {
140 throw new MobileApiError(
141 `Mobile API request failed with ${response.status}`,
142 response.status,
143 payload,
144 );
145 }
146 return decode(schema, payload);
147 };
148
149 const publicRequest = async <A, I>(
150 path: string,
151 schema: Schema.Schema<A, I, never>,
152 options: Omit<RequestOptions, "query"> = {},
153 ): Promise<A> => {
154 const url = new URL(path, origin);
155 const headers = new Headers();
156 let body: BodyInit | undefined;
157 if (options.body !== undefined) {
158 headers.set("Content-Type", "application/json");
159 body = JSON.stringify(options.body);
160 }
161
162 const response = await fetch(url.toString(), {
163 method: options.method ?? "GET",
164 headers,
165 body,
166 });

Callers 2

AuthProviderFunction · 0.90
mobile.test.tsFile · 0.90

Calls 3

trimBaseUrlFunction · 0.85
publicRequestFunction · 0.85
requestFunction · 0.70

Tested by

no test coverage detected