@uidu/client 3.7.1 → 3.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uidu/client",
3
- "version": "3.7.1",
3
+ "version": "3.10.0",
4
4
  "description": "Typed GraphQL client for the uidu platform. Server-first, framework-agnostic.",
5
5
  "license": "MIT",
6
6
  "author": "uidu",
package/src/actions.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ ExecuteActionDocument,
4
+ type ExecuteActionMutationVariables,
5
+ } from './generated';
6
+
7
+ // Authoring (Bearer / doorkeeper token). Generic dispatcher for any
8
+ // `ActionKey` flagged `of_kind_tool_key` on the backend — invokes the same
9
+ // Concept a dedicated mutation would, by key instead of a hand-written
10
+ // GraphQL field. `attributes` uses the entity's own camelCase vocabulary;
11
+ // associations must be GlobalIDs (the id a prior `list`/`get` returned) —
12
+ // there is no by-name lookup here. See uidu/app/graphql/mutations/execute_action.rb.
13
+ export async function executeAction(
14
+ client: UiduClient,
15
+ variables: ExecuteActionMutationVariables,
16
+ ) {
17
+ const result = await client.mutate(ExecuteActionDocument, variables);
18
+ return result.executeAction ?? null;
19
+ }
@@ -0,0 +1,15 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ CreateBenefitEnrollmentDocument,
4
+ type CreateBenefitEnrollmentMutationVariables,
5
+ } from './generated';
6
+
7
+ // Authoring (Bearer / doorkeeper token). Returns the payload, incl. `errors`.
8
+
9
+ export async function createBenefitEnrollment(
10
+ client: UiduClient,
11
+ variables: CreateBenefitEnrollmentMutationVariables,
12
+ ) {
13
+ const result = await client.mutate(CreateBenefitEnrollmentDocument, variables);
14
+ return result.createBenefitEnrollment ?? null;
15
+ }
@@ -0,0 +1,15 @@
1
+ import type { UiduClient } from './client';
2
+ import {
3
+ CreateBenefitDocument,
4
+ type CreateBenefitMutationVariables,
5
+ } from './generated';
6
+
7
+ // Authoring (Bearer / doorkeeper token). Returns the payload, incl. `errors`.
8
+
9
+ export async function createBenefit(
10
+ client: UiduClient,
11
+ variables: CreateBenefitMutationVariables,
12
+ ) {
13
+ const result = await client.mutate(CreateBenefitDocument, variables);
14
+ return result.createBenefit ?? null;
15
+ }
@@ -163,3 +163,59 @@ describe('UiduClient.query', () => {
163
163
  expect(sentVariables()).toBe(variables);
164
164
  });
165
165
  });
166
+
167
+ describe('UiduClient — getToken', () => {
168
+ it('asks for the token on every request and sends it as Bearer', async () => {
169
+ let n = 0;
170
+ const getToken = vi.fn(async () => `t${++n}`);
171
+ const app = createClient({
172
+ endpoint: 'https://acme.uidu.org/graphql',
173
+ getToken,
174
+ });
175
+
176
+ await app.query(GetFormDocument, { id: 'f' } as never);
177
+ await app.query(GetFormDocument, { id: 'f' } as never);
178
+
179
+ expect(getToken).toHaveBeenCalledTimes(2);
180
+ expect(request.mock.calls[0][2]).toEqual({ Authorization: 'Bearer t1' });
181
+ expect(request.mock.calls[1][2]).toEqual({ Authorization: 'Bearer t2' });
182
+ expect(app.endpoint).toBe('https://acme.uidu.org/graphql');
183
+ });
184
+
185
+ it('wraps a failing getToken in a TOKEN_ERROR without sending the request', async () => {
186
+ const cause = new Error('Not a member of this space');
187
+ const app = createClient({
188
+ endpoint: 'https://acme.uidu.org/graphql',
189
+ getToken: () => Promise.reject(cause),
190
+ });
191
+
192
+ await expect(
193
+ app.query(GetFormDocument, { id: 'f' } as never),
194
+ ).rejects.toMatchObject({
195
+ name: 'UiduError',
196
+ code: 'TOKEN_ERROR',
197
+ message: 'Not a member of this space',
198
+ cause,
199
+ });
200
+ expect(request).not.toHaveBeenCalled();
201
+ });
202
+
203
+ it('needs a workspace or an endpoint', () => {
204
+ expect(() => createClient({})).toThrow(/workspace.*endpoint/);
205
+ });
206
+
207
+ it('fromBridge maps a bridge onto endpoint + getToken', async () => {
208
+ const { fromBridge } = await import('./client');
209
+ const bridge = {
210
+ graphqlUrl: 'https://acme.uidu.org/graphql',
211
+ getToken: vi.fn(async () => 'bridged'),
212
+ };
213
+ const app = createClient(fromBridge(bridge));
214
+
215
+ await app.query(GetFormDocument, { id: 'f' } as never);
216
+ expect(app.endpoint).toBe(bridge.graphqlUrl);
217
+ expect(request.mock.calls[0][2]).toEqual({
218
+ Authorization: 'Bearer bridged',
219
+ });
220
+ });
221
+ });
package/src/client.ts CHANGED
@@ -6,10 +6,18 @@ import { normalizeMutationVariables } from './utils/fieldValues';
6
6
  export class UiduClient {
7
7
  readonly endpoint: string;
8
8
  private readonly client: GraphQLClient;
9
+ private readonly getToken?: () => Promise<string>;
9
10
 
10
11
  constructor(config: UiduClientConfig) {
12
+ if (!config.endpoint && !config.workspace) {
13
+ throw new UiduError({
14
+ code: 'CONFIG_ERROR',
15
+ message: 'createClient needs a `workspace` or an `endpoint`',
16
+ });
17
+ }
11
18
  this.endpoint =
12
19
  config.endpoint ?? `https://${config.workspace}.uidu.org/graphql`;
20
+ this.getToken = config.getToken;
13
21
 
14
22
  const headers: Record<string, string> = { ...(config.headers ?? {}) };
15
23
  if (config.publicToken) headers['X-Uidu-Public-Token'] = config.publicToken;
@@ -22,16 +30,32 @@ export class UiduClient {
22
30
  document: TypedDocumentNode<TResult, TVariables>,
23
31
  variables?: TVariables,
24
32
  ): Promise<TResult> {
33
+ const vars = (variables ?? {}) as Record<string, unknown>;
34
+ // Asked per request, so a refreshed token is picked up without rebuilding
35
+ // the client.
36
+ const headers = this.getToken
37
+ ? { Authorization: `Bearer ${await this.tokenFor()}` }
38
+ : undefined;
39
+
25
40
  try {
26
- return await this.client.request<TResult>(
27
- document,
28
- (variables ?? {}) as Record<string, unknown>,
29
- );
41
+ return await this.client.request<TResult>(document, vars, headers);
30
42
  } catch (err) {
31
43
  throw toUiduError(err);
32
44
  }
33
45
  }
34
46
 
47
+ private async tokenFor(): Promise<string> {
48
+ try {
49
+ return await this.getToken!();
50
+ } catch (err) {
51
+ throw new UiduError({
52
+ code: 'TOKEN_ERROR',
53
+ message: err instanceof Error ? err.message : 'Could not get a token',
54
+ cause: err,
55
+ });
56
+ }
57
+ }
58
+
35
59
  mutate<TResult, TVariables extends object = Record<string, never>>(
36
60
  document: TypedDocumentNode<TResult, TVariables>,
37
61
  variables?: TVariables,
@@ -47,6 +71,25 @@ export function createClient(config: UiduClientConfig): UiduClient {
47
71
  return new UiduClient(config);
48
72
  }
49
73
 
74
+ /**
75
+ * Client config for a custom app, from a connected `@uidu/app-bridge`:
76
+ *
77
+ * ```ts
78
+ * const client = createClient(fromBridge(await connect()));
79
+ * ```
80
+ *
81
+ * Typed structurally so `@uidu/client` doesn't depend on the bridge.
82
+ */
83
+ export function fromBridge(bridge: {
84
+ graphqlUrl: string;
85
+ getToken: () => Promise<string>;
86
+ }): UiduClientConfig {
87
+ return {
88
+ endpoint: bridge.graphqlUrl,
89
+ getToken: () => bridge.getToken(),
90
+ };
91
+ }
92
+
50
93
  function toUiduError(err: unknown): UiduError {
51
94
  if (err instanceof ClientError) {
52
95
  return new UiduError({