@aws-amplify/api-graphql 4.0.29-unstable.f37faeb.0 → 4.0.29

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.
Files changed (129) hide show
  1. package/dist/cjs/internals/generateClient.js +4 -14
  2. package/dist/cjs/internals/generateClient.js.map +1 -1
  3. package/dist/cjs/internals/server/generateClientWithAmplifyInstance.js +3 -8
  4. package/dist/cjs/internals/server/generateClientWithAmplifyInstance.js.map +1 -1
  5. package/dist/cjs/internals/v6.js +6 -3
  6. package/dist/cjs/internals/v6.js.map +1 -1
  7. package/dist/cjs/types/index.js +11 -1
  8. package/dist/cjs/types/index.js.map +1 -1
  9. package/dist/cjs/utils/index.js +1 -5
  10. package/dist/cjs/utils/index.js.map +1 -1
  11. package/dist/esm/GraphQLAPI.d.ts +1 -1
  12. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  13. package/dist/esm/index.mjs +1 -1
  14. package/dist/esm/internals/InternalGraphQLAPI.d.ts +1 -1
  15. package/dist/esm/internals/generateClient.mjs +5 -15
  16. package/dist/esm/internals/generateClient.mjs.map +1 -1
  17. package/dist/esm/internals/server/generateClientWithAmplifyInstance.mjs +4 -9
  18. package/dist/esm/internals/server/generateClientWithAmplifyInstance.mjs.map +1 -1
  19. package/dist/esm/internals/types.d.ts +1 -1
  20. package/dist/esm/internals/v6.d.ts +1 -1
  21. package/dist/esm/internals/v6.mjs +7 -4
  22. package/dist/esm/internals/v6.mjs.map +1 -1
  23. package/dist/esm/types/index.d.ts +10 -40
  24. package/dist/esm/types/index.mjs +10 -1
  25. package/dist/esm/types/index.mjs.map +1 -1
  26. package/dist/esm/utils/index.d.ts +0 -2
  27. package/dist/esm/utils/index.mjs +0 -2
  28. package/dist/esm/utils/index.mjs.map +1 -1
  29. package/package.json +5 -6
  30. package/src/GraphQLAPI.ts +1 -1
  31. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +4 -1
  32. package/src/internals/InternalGraphQLAPI.ts +4 -1
  33. package/src/internals/generateClient.ts +8 -36
  34. package/src/internals/server/generateClientWithAmplifyInstance.ts +6 -16
  35. package/src/internals/types.ts +1 -1
  36. package/src/internals/v6.ts +7 -7
  37. package/src/server/generateClient.ts +1 -1
  38. package/src/types/index.ts +36 -60
  39. package/src/utils/index.ts +0 -2
  40. package/dist/cjs/internals/APIClient.js +0 -733
  41. package/dist/cjs/internals/APIClient.js.map +0 -1
  42. package/dist/cjs/internals/clientUtils.js +0 -29
  43. package/dist/cjs/internals/clientUtils.js.map +0 -1
  44. package/dist/cjs/internals/generateCustomOperationsProperty.js +0 -50
  45. package/dist/cjs/internals/generateCustomOperationsProperty.js.map +0 -1
  46. package/dist/cjs/internals/operations/custom.js +0 -356
  47. package/dist/cjs/internals/operations/custom.js.map +0 -1
  48. package/dist/cjs/internals/operations/get.js +0 -62
  49. package/dist/cjs/internals/operations/get.js.map +0 -1
  50. package/dist/cjs/internals/operations/indexQuery.js +0 -75
  51. package/dist/cjs/internals/operations/indexQuery.js.map +0 -1
  52. package/dist/cjs/internals/operations/list.js +0 -74
  53. package/dist/cjs/internals/operations/list.js.map +0 -1
  54. package/dist/cjs/internals/operations/observeQuery.js +0 -121
  55. package/dist/cjs/internals/operations/observeQuery.js.map +0 -1
  56. package/dist/cjs/internals/operations/subscription.js +0 -31
  57. package/dist/cjs/internals/operations/subscription.js.map +0 -1
  58. package/dist/cjs/internals/server/generateModelsProperty.js +0 -53
  59. package/dist/cjs/internals/server/generateModelsProperty.js.map +0 -1
  60. package/dist/cjs/internals/utils/clientProperties/generateEnumsProperty.js +0 -21
  61. package/dist/cjs/internals/utils/clientProperties/generateEnumsProperty.js.map +0 -1
  62. package/dist/cjs/internals/utils/clientProperties/generateModelsProperty.js +0 -45
  63. package/dist/cjs/internals/utils/clientProperties/generateModelsProperty.js.map +0 -1
  64. package/dist/cjs/utils/findIndexByFields.js +0 -25
  65. package/dist/cjs/utils/findIndexByFields.js.map +0 -1
  66. package/dist/cjs/utils/resolveOwnerFields.js +0 -48
  67. package/dist/cjs/utils/resolveOwnerFields.js.map +0 -1
  68. package/dist/cjs/utils/resolvePKFields.js +0 -17
  69. package/dist/cjs/utils/resolvePKFields.js.map +0 -1
  70. package/dist/esm/internals/APIClient.d.ts +0 -126
  71. package/dist/esm/internals/APIClient.mjs +0 -721
  72. package/dist/esm/internals/APIClient.mjs.map +0 -1
  73. package/dist/esm/internals/clientUtils.d.ts +0 -6
  74. package/dist/esm/internals/clientUtils.mjs +0 -26
  75. package/dist/esm/internals/clientUtils.mjs.map +0 -1
  76. package/dist/esm/internals/generateCustomOperationsProperty.d.ts +0 -9
  77. package/dist/esm/internals/generateCustomOperationsProperty.mjs +0 -45
  78. package/dist/esm/internals/generateCustomOperationsProperty.mjs.map +0 -1
  79. package/dist/esm/internals/operations/custom.d.ts +0 -63
  80. package/dist/esm/internals/operations/custom.mjs +0 -354
  81. package/dist/esm/internals/operations/custom.mjs.map +0 -1
  82. package/dist/esm/internals/operations/get.d.ts +0 -5
  83. package/dist/esm/internals/operations/get.mjs +0 -60
  84. package/dist/esm/internals/operations/get.mjs.map +0 -1
  85. package/dist/esm/internals/operations/indexQuery.d.ts +0 -9
  86. package/dist/esm/internals/operations/indexQuery.mjs +0 -73
  87. package/dist/esm/internals/operations/indexQuery.mjs.map +0 -1
  88. package/dist/esm/internals/operations/list.d.ts +0 -4
  89. package/dist/esm/internals/operations/list.mjs +0 -72
  90. package/dist/esm/internals/operations/list.mjs.map +0 -1
  91. package/dist/esm/internals/operations/observeQuery.d.ts +0 -3
  92. package/dist/esm/internals/operations/observeQuery.mjs +0 -121
  93. package/dist/esm/internals/operations/observeQuery.mjs.map +0 -1
  94. package/dist/esm/internals/operations/subscription.d.ts +0 -3
  95. package/dist/esm/internals/operations/subscription.mjs +0 -29
  96. package/dist/esm/internals/operations/subscription.mjs.map +0 -1
  97. package/dist/esm/internals/server/generateModelsProperty.d.ts +0 -3
  98. package/dist/esm/internals/server/generateModelsProperty.mjs +0 -51
  99. package/dist/esm/internals/server/generateModelsProperty.mjs.map +0 -1
  100. package/dist/esm/internals/utils/clientProperties/generateEnumsProperty.d.ts +0 -3
  101. package/dist/esm/internals/utils/clientProperties/generateEnumsProperty.mjs +0 -18
  102. package/dist/esm/internals/utils/clientProperties/generateEnumsProperty.mjs.map +0 -1
  103. package/dist/esm/internals/utils/clientProperties/generateModelsProperty.d.ts +0 -4
  104. package/dist/esm/internals/utils/clientProperties/generateModelsProperty.mjs +0 -43
  105. package/dist/esm/internals/utils/clientProperties/generateModelsProperty.mjs.map +0 -1
  106. package/dist/esm/utils/findIndexByFields.d.ts +0 -9
  107. package/dist/esm/utils/findIndexByFields.mjs +0 -22
  108. package/dist/esm/utils/findIndexByFields.mjs.map +0 -1
  109. package/dist/esm/utils/resolveOwnerFields.d.ts +0 -12
  110. package/dist/esm/utils/resolveOwnerFields.mjs +0 -45
  111. package/dist/esm/utils/resolveOwnerFields.mjs.map +0 -1
  112. package/dist/esm/utils/resolvePKFields.d.ts +0 -13
  113. package/dist/esm/utils/resolvePKFields.mjs +0 -14
  114. package/dist/esm/utils/resolvePKFields.mjs.map +0 -1
  115. package/src/internals/APIClient.ts +0 -1076
  116. package/src/internals/clientUtils.ts +0 -37
  117. package/src/internals/generateCustomOperationsProperty.ts +0 -112
  118. package/src/internals/operations/custom.ts +0 -492
  119. package/src/internals/operations/get.ts +0 -140
  120. package/src/internals/operations/indexQuery.ts +0 -170
  121. package/src/internals/operations/list.ts +0 -135
  122. package/src/internals/operations/observeQuery.ts +0 -146
  123. package/src/internals/operations/subscription.ts +0 -75
  124. package/src/internals/server/generateModelsProperty.ts +0 -97
  125. package/src/internals/utils/clientProperties/generateEnumsProperty.ts +0 -34
  126. package/src/internals/utils/clientProperties/generateModelsProperty.ts +0 -81
  127. package/src/utils/findIndexByFields.ts +0 -31
  128. package/src/utils/resolveOwnerFields.ts +0 -77
  129. package/src/utils/resolvePKFields.ts +0 -23
@@ -1,37 +0,0 @@
1
- // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type {
5
- ModelAttribute,
6
- SchemaModel,
7
- SecondaryIndexAttribute,
8
- } from '@aws-amplify/core/internals/utils';
9
-
10
- const attributeIsSecondaryIndex = (
11
- attr: ModelAttribute,
12
- ): attr is SecondaryIndexAttribute => {
13
- return (
14
- attr.type === 'key' &&
15
- // presence of `name` property distinguishes GSI from primary index
16
- attr.properties?.name &&
17
- attr.properties?.queryField &&
18
- attr.properties?.fields.length > 0
19
- );
20
- };
21
-
22
- export const getSecondaryIndexesFromSchemaModel = (model: SchemaModel) => {
23
- const idxs = model.attributes
24
- ?.filter(attributeIsSecondaryIndex)
25
- .map((attr: SecondaryIndexAttribute) => {
26
- const queryField: string = attr.properties.queryField;
27
- const [pk, ...sk] = attr.properties.fields;
28
-
29
- return {
30
- queryField,
31
- pk,
32
- sk,
33
- };
34
- });
35
-
36
- return idxs || [];
37
- };
@@ -1,112 +0,0 @@
1
- // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- import {
4
- CustomMutations,
5
- CustomQueries,
6
- CustomSubscriptions,
7
- } from '@aws-amplify/data-schema-types';
8
- import {
9
- GraphQLProviderConfig,
10
- ModelIntrospectionSchema,
11
- } from '@aws-amplify/core/internals/utils';
12
-
13
- import { V6Client, __amplify } from '../types';
14
-
15
- import { customOpFactory } from './operations/custom';
16
-
17
- type OpTypes = 'queries' | 'mutations' | 'subscriptions';
18
-
19
- type CustomOpsProperty<
20
- T extends Record<any, any>,
21
- OpType extends OpTypes,
22
- > = OpType extends 'queries'
23
- ? CustomQueries<T>
24
- : OpType extends 'mutations'
25
- ? CustomMutations<T>
26
- : OpType extends 'subscriptions'
27
- ? CustomSubscriptions<T>
28
- : never;
29
-
30
- const operationTypeMap = {
31
- queries: 'query',
32
- mutations: 'mutation',
33
- subscriptions: 'subscription',
34
- } as const;
35
-
36
- export function generateCustomOperationsProperty<
37
- T extends Record<any, any>,
38
- OpType extends OpTypes,
39
- >(
40
- client: V6Client<Record<string, any>>,
41
- config: GraphQLProviderConfig['GraphQL'],
42
- operationsType: OpType,
43
- ): OpType extends 'queries' ? CustomQueries<T> : CustomMutations<T> {
44
- // some bundlers end up with `Amplify.configure` being called *after* generate client.
45
- // if that occurs, we need to *not error* while we wait. handling for late configuration
46
- // occurs in `generateClient()`. we do not need to subscribe to Hub events here.
47
- if (!config) {
48
- return {} as CustomOpsProperty<T, OpType>;
49
- }
50
-
51
- const modelIntrospection: ModelIntrospectionSchema | undefined =
52
- config.modelIntrospection;
53
-
54
- // model intro schema might be absent if there's not actually a configured GraphQL API
55
- if (!modelIntrospection) {
56
- return {} as CustomOpsProperty<T, OpType>;
57
- }
58
-
59
- // custom operations will be absent from model intro schema if no custom ops
60
- // are present on the source schema.
61
- const operations = modelIntrospection[operationsType];
62
- if (!operations) {
63
- return {} as CustomOpsProperty<T, OpType>;
64
- }
65
-
66
- const ops = {} as CustomOpsProperty<T, OpType>;
67
- const useContext = client[__amplify] === null;
68
- for (const operation of Object.values(operations)) {
69
- (ops as any)[operation.name] = customOpFactory(
70
- client,
71
- modelIntrospection,
72
- operationTypeMap[operationsType],
73
- operation,
74
- useContext,
75
- );
76
- }
77
-
78
- return ops;
79
- }
80
-
81
- export function generateCustomMutationsProperty<T extends Record<any, any>>(
82
- client: V6Client<Record<string, any>>,
83
- config: GraphQLProviderConfig['GraphQL'],
84
- ) {
85
- return generateCustomOperationsProperty<T, 'mutations'>(
86
- client,
87
- config,
88
- 'mutations',
89
- );
90
- }
91
-
92
- export function generateCustomQueriesProperty<T extends Record<any, any>>(
93
- client: V6Client<Record<string, any>>,
94
- config: GraphQLProviderConfig['GraphQL'],
95
- ) {
96
- return generateCustomOperationsProperty<T, 'queries'>(
97
- client,
98
- config,
99
- 'queries',
100
- );
101
- }
102
-
103
- export function generateCustomSubscriptionsProperty<T extends Record<any, any>>(
104
- client: V6Client<Record<string, any>>,
105
- config: GraphQLProviderConfig['GraphQL'],
106
- ) {
107
- return generateCustomOperationsProperty<T, 'subscriptions'>(
108
- client,
109
- config,
110
- 'subscriptions',
111
- );
112
- }
@@ -1,492 +0,0 @@
1
- // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core';
4
- import {
5
- CustomOperation,
6
- ModelIntrospectionSchema,
7
- } from '@aws-amplify/core/internals/utils';
8
- import { map } from 'rxjs';
9
-
10
- import {
11
- authModeParams,
12
- flattenItems,
13
- generateSelectionSet,
14
- getCustomHeaders,
15
- getDefaultSelectionSetForNonModelWithIR,
16
- initializeModel,
17
- selectionSetIRToString,
18
- } from '../APIClient';
19
- import {
20
- AuthModeParams,
21
- ClientWithModels,
22
- GraphQLResult,
23
- GraphqlSubscriptionResult,
24
- ListArgs,
25
- QueryArgs,
26
- V6Client,
27
- V6ClientSSRRequest,
28
- } from '../../types';
29
-
30
- type CustomOperationOptions = AuthModeParams & ListArgs;
31
-
32
- // these are the 4 possible sets of arguments custom operations methods can receive
33
- type OpArgs =
34
- // SSR Request Client w Args defined
35
- | [AmplifyServer.ContextSpec, QueryArgs, CustomOperationOptions]
36
- // SSR Request Client without Args defined
37
- | [AmplifyServer.ContextSpec, CustomOperationOptions]
38
- // Client or SSR Cookies Client w Args defined
39
- | [QueryArgs, CustomOperationOptions]
40
- // Client or SSR Cookies Client without Args defined
41
- | [CustomOperationOptions];
42
-
43
- /**
44
- * Type guard for checking whether a Custom Operation argument is a contextSpec object
45
- */
46
- const argIsContextSpec = (
47
- arg: OpArgs[number],
48
- ): arg is AmplifyServer.ContextSpec => {
49
- return typeof (arg as AmplifyServer.ContextSpec)?.token?.value === 'symbol';
50
- };
51
-
52
- /**
53
- * Builds an operation function, embedded with all client and context data, that
54
- * can be attached to a client as a custom query or mutation.
55
- *
56
- * If we have this source schema:
57
- *
58
- * ```typescript
59
- * a.schema({
60
- * echo: a.query()
61
- * .arguments({input: a.string().required()})
62
- * .returns(a.string())
63
- * })
64
- * ```
65
- *
66
- * Our model intro schema will contain an entry like this:
67
- *
68
- * ```ts
69
- * {
70
- * queries: {
71
- * echo: {
72
- * name: "echo",
73
- * isArray: false,
74
- * type: 'String',
75
- * isRequired: false,
76
- * arguments: {
77
- * input: {
78
- * name: 'input',
79
- * isArray: false,
80
- * type: String,
81
- * isRequired: true
82
- * }
83
- * }
84
- * }
85
- * }
86
- * }
87
- * ```
88
- *
89
- * The `echo` object is used to build the `echo' method that goes here:
90
- *
91
- * ```typescript
92
- * const client = generateClent()
93
- * const { data } = await client.queries.echo({input: 'a string'});
94
- * // ^
95
- * // |
96
- * // +-- This one right here.
97
- * //
98
- * ```
99
- *
100
- *
101
- * @param client The client to run graphql queries through.
102
- * @param modelIntrospection The model introspection schema the op comes from.
103
- * @param operationType The broad category of graphql operation.
104
- * @param operation The operation definition from the introspection schema.
105
- * @param useContext Whether the function needs to accept an SSR context.
106
- * @returns The operation function to attach to query, mutations, etc.
107
- */
108
- export function customOpFactory(
109
- client: ClientWithModels,
110
- modelIntrospection: ModelIntrospectionSchema,
111
- operationType: 'query' | 'mutation' | 'subscription',
112
- operation: CustomOperation,
113
- useContext: boolean,
114
- ) {
115
- // .arguments() are defined for the custom operation in the schema builder
116
- // and are present in the model introspection schema
117
- const argsDefined = operation.arguments !== undefined;
118
-
119
- const op = (...args: OpArgs) => {
120
- // options is always the last argument
121
- const options = args[args.length - 1] as CustomOperationOptions;
122
-
123
- let contextSpec: AmplifyServer.ContextSpec | undefined;
124
- let arg: QueryArgs | undefined;
125
-
126
- if (useContext) {
127
- if (argIsContextSpec(args[0])) {
128
- contextSpec = args[0];
129
- } else {
130
- throw new Error(
131
- `Invalid first argument passed to ${operation.name}. Expected contextSpec`,
132
- );
133
- }
134
- }
135
-
136
- if (argsDefined) {
137
- if (useContext) {
138
- arg = args[1] as QueryArgs;
139
- } else {
140
- arg = args[0] as QueryArgs;
141
- }
142
- }
143
-
144
- if (operationType === 'subscription') {
145
- return _opSubscription(
146
- // subscriptions are only enabled on the clientside
147
- client as V6Client<Record<string, any>>,
148
- modelIntrospection,
149
- operation,
150
- arg,
151
- options,
152
- );
153
- }
154
-
155
- return _op(
156
- client,
157
- modelIntrospection,
158
- operationType,
159
- operation,
160
- arg,
161
- options,
162
- contextSpec,
163
- );
164
- };
165
-
166
- return op;
167
- }
168
-
169
- /**
170
- * Runtime test and type guard to check whether `o[field]` is a `String`.
171
- *
172
- * ```typescript
173
- * if (hasStringField(o, 'prop')) {
174
- * const s = o.prop;
175
- * // ^? const s: string
176
- * }
177
- * ```
178
- *
179
- * @param o Object to inspect
180
- * @param field Field to look for
181
- * @returns Boolean: `true` if the `o[field]` is a `string`
182
- */
183
- function hasStringField<Field extends string>(
184
- o: any,
185
- field: Field,
186
- ): o is Record<Field, string> {
187
- return typeof o[field] === 'string';
188
- }
189
-
190
- /**
191
- * Generates "outer" arguments string for a custom operation. For example,
192
- * in this operation:
193
- *
194
- * ```graphql
195
- * query MyQuery(InputString: String!) {
196
- * echoString(InputString: $InputString)
197
- * }
198
- * ```
199
- *
200
- * This function returns the top/outer level arguments as a string:
201
- *
202
- * ```json
203
- * "InputString: String!"
204
- * ```
205
- *
206
- * @param operation Operation object from model introspection schema.
207
- * @returns "outer" arguments string
208
- */
209
- function outerArguments(operation: CustomOperation): string {
210
- if (operation.arguments === undefined) {
211
- return '';
212
- }
213
- const args = Object.entries(operation.arguments)
214
- .map(([k, v]) => {
215
- const baseType = v.type + (v.isRequired ? '!' : '');
216
- const finalType = v.isArray
217
- ? `[${baseType}]${v.isArrayNullable ? '' : '!'}`
218
- : baseType;
219
-
220
- return `$${k}: ${finalType}`;
221
- })
222
- .join(', ');
223
-
224
- return args.length > 0 ? `(${args})` : '';
225
- }
226
-
227
- /**
228
- * Generates "inner" arguments string for a custom operation. For example,
229
- * in this operation:
230
- *
231
- * ```graphql
232
- * query MyQuery(InputString: String!) {
233
- * echoString(InputString: $InputString)
234
- * }
235
- * ```
236
- *
237
- * This function returns the inner arguments as a string:
238
- *
239
- * ```json
240
- * "InputString: $InputString"
241
- * ```
242
- *
243
- * @param operation Operation object from model introspection schema.
244
- * @returns "outer" arguments string
245
- */
246
- function innerArguments(operation: CustomOperation): string {
247
- if (operation.arguments === undefined) {
248
- return '';
249
- }
250
- const args = Object.keys(operation.arguments)
251
- .map(k => `${k}: $${k}`)
252
- .join(', ');
253
-
254
- return args.length > 0 ? `(${args})` : '';
255
- }
256
-
257
- /**
258
- * Generates the selection set string for a custom operation. This is slightly
259
- * different than the selection set generation for models. If the custom op returns
260
- * a primitive or enum types, it doen't require a selection set at all.
261
- *
262
- * E.g., the graphql might look like this:
263
- *
264
- * ```graphql
265
- * query MyQuery {
266
- * echoString(inputString: "whatever")
267
- * }
268
- * # ^
269
- * # |
270
- * # +-- no selection set
271
- * ```
272
- *
273
- * Non-primitive return type selection set generation will be similar to other
274
- * model operations.
275
- *
276
- * @param modelIntrospection The full code-generated introspection schema.
277
- * @param operation The operation object from the schema.
278
- * @returns The selection set as a string.
279
- */
280
- function operationSelectionSet(
281
- modelIntrospection: ModelIntrospectionSchema,
282
- operation: CustomOperation,
283
- ): string {
284
- if (
285
- hasStringField(operation, 'type') ||
286
- hasStringField(operation.type, 'enum')
287
- ) {
288
- return '';
289
- } else if (hasStringField(operation.type, 'nonModel')) {
290
- const nonModel = modelIntrospection.nonModels[operation.type.nonModel];
291
-
292
- return `{${selectionSetIRToString(
293
- getDefaultSelectionSetForNonModelWithIR(nonModel, modelIntrospection),
294
- )}}`;
295
- } else if (hasStringField(operation.type, 'model')) {
296
- return `{${generateSelectionSet(modelIntrospection, operation.type.model)}}`;
297
- } else {
298
- return '';
299
- }
300
- }
301
-
302
- /**
303
- * Maps an arguments objec to graphql variables, removing superfluous args and
304
- * screaming loudly when required args are missing.
305
- *
306
- * @param operation The operation to construct graphql request variables for.
307
- * @param args The arguments to map variables from.
308
- * @returns The graphql variables object.
309
- */
310
- function operationVariables(
311
- operation: CustomOperation,
312
- args: QueryArgs = {},
313
- ): Record<string, unknown> {
314
- const variables = {} as Record<string, unknown>;
315
- if (operation.arguments === undefined) {
316
- return variables;
317
- }
318
- for (const argDef of Object.values(operation.arguments)) {
319
- if (typeof args[argDef.name] !== 'undefined') {
320
- variables[argDef.name] = args[argDef.name];
321
- } else if (argDef.isRequired) {
322
- // At this point, the variable is both required and missing: We don't need
323
- // to continue. The operation is expected to fail.
324
- throw new Error(`${operation.name} requires arguments '${argDef.name}'`);
325
- }
326
- }
327
-
328
- return variables;
329
- }
330
-
331
- /**
332
- * Executes an operation from the given model intro schema against a client, returning
333
- * a fully instantiated model when relevant.
334
- *
335
- * @param client The client to operate `graphql()` calls through.
336
- * @param modelIntrospection The model intro schema to construct requests from.
337
- * @param operationType The high level graphql operation type.
338
- * @param operation The specific operation name, args, return type details.
339
- * @param args The arguments to provide to the operation as variables.
340
- * @param options Request options like headers, etc.
341
- * @param context SSR context if relevant.
342
- * @returns Result from the graphql request, model-instantiated when relevant.
343
- */
344
- async function _op(
345
- client: ClientWithModels,
346
- modelIntrospection: ModelIntrospectionSchema,
347
- operationType: 'query' | 'mutation',
348
- operation: CustomOperation,
349
- args?: QueryArgs,
350
- options?: AuthModeParams & ListArgs,
351
- context?: AmplifyServer.ContextSpec,
352
- ) {
353
- const { name: operationName } = operation;
354
- const auth = authModeParams(client, options);
355
- const headers = getCustomHeaders(client, options?.headers);
356
- const outerArgsString = outerArguments(operation);
357
- const innerArgsString = innerArguments(operation);
358
- const selectionSet = operationSelectionSet(modelIntrospection, operation);
359
-
360
- const returnTypeModelName = hasStringField(operation.type, 'model')
361
- ? operation.type.model
362
- : undefined;
363
-
364
- const query = `
365
- ${operationType.toLocaleLowerCase()}${outerArgsString} {
366
- ${operationName}${innerArgsString} ${selectionSet}
367
- }
368
- `;
369
-
370
- const variables = operationVariables(operation, args);
371
-
372
- try {
373
- const { data, extensions } = context
374
- ? ((await (client as V6ClientSSRRequest<Record<string, any>>).graphql(
375
- context,
376
- {
377
- ...auth,
378
- query,
379
- variables,
380
- },
381
- headers,
382
- )) as GraphQLResult<any>)
383
- : ((await (client as V6Client<Record<string, any>>).graphql(
384
- {
385
- ...auth,
386
- query,
387
- variables,
388
- },
389
- headers,
390
- )) as GraphQLResult<any>);
391
-
392
- // flatten response
393
- if (data) {
394
- const [key] = Object.keys(data);
395
- const flattenedResult = flattenItems(data)[key];
396
-
397
- // TODO: custom selection set. current selection set is default selection set only
398
- // custom selection set requires data-schema-type + runtime updates above.
399
- const [initialized] = returnTypeModelName
400
- ? initializeModel(
401
- client,
402
- returnTypeModelName,
403
- [flattenedResult],
404
- modelIntrospection,
405
- auth.authMode,
406
- auth.authToken,
407
- !!context,
408
- )
409
- : [flattenedResult];
410
-
411
- return { data: initialized, extensions };
412
- } else {
413
- return { data: null, extensions };
414
- }
415
- } catch (error: any) {
416
- if (error.errors) {
417
- // graphql errors pass through
418
- return error as any;
419
- } else {
420
- // non-graphql errors re re-thrown
421
- throw error;
422
- }
423
- }
424
- }
425
-
426
- /**
427
- * Executes an operation from the given model intro schema against a client, returning
428
- * a fully instantiated model when relevant.
429
- *
430
- * @param client The client to operate `graphql()` calls through.
431
- * @param modelIntrospection The model intro schema to construct requests from.
432
- * @param operation The specific operation name, args, return type details.
433
- * @param args The arguments to provide to the operation as variables.
434
- * @param options Request options like headers, etc.
435
- * @returns Result from the graphql request, model-instantiated when relevant.
436
- */
437
- function _opSubscription(
438
- client: V6Client<Record<string, any>>,
439
- modelIntrospection: ModelIntrospectionSchema,
440
- operation: CustomOperation,
441
- args?: QueryArgs,
442
- options?: AuthModeParams & ListArgs,
443
- ) {
444
- const operationType = 'subscription';
445
- const { name: operationName } = operation;
446
- const auth = authModeParams(client, options);
447
- const headers = getCustomHeaders(client, options?.headers);
448
- const outerArgsString = outerArguments(operation);
449
- const innerArgsString = innerArguments(operation);
450
- const selectionSet = operationSelectionSet(modelIntrospection, operation);
451
-
452
- const returnTypeModelName = hasStringField(operation.type, 'model')
453
- ? operation.type.model
454
- : undefined;
455
-
456
- const query = `
457
- ${operationType.toLocaleLowerCase()}${outerArgsString} {
458
- ${operationName}${innerArgsString} ${selectionSet}
459
- }
460
- `;
461
-
462
- const variables = operationVariables(operation, args);
463
-
464
- const observable = client.graphql(
465
- {
466
- ...auth,
467
- query,
468
- variables,
469
- },
470
- headers,
471
- ) as GraphqlSubscriptionResult<object>;
472
-
473
- return observable.pipe(
474
- map(value => {
475
- const [key] = Object.keys(value.data);
476
- const data = (value.data as any)[key];
477
-
478
- const [initialized] = returnTypeModelName
479
- ? initializeModel(
480
- client as V6Client<Record<string, any>>,
481
- returnTypeModelName,
482
- [data],
483
- modelIntrospection,
484
- auth.authMode,
485
- auth.authToken,
486
- )
487
- : [data];
488
-
489
- return initialized;
490
- }),
491
- );
492
- }