@aws-amplify/api 5.3.4-api-v6.2 → 5.3.4-api-v6.23

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/lib/API.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AWSAppSyncRealTimeProvider } from '@aws-amplify/pubsub';
2
2
  import { GraphQLOptions, GraphQLResult } from '@aws-amplify/api-graphql';
3
+ import { graphql as v6graphql } from '@aws-amplify/api-graphql/internals';
3
4
  import Observable from 'zen-observable-ts';
4
5
  import { GraphQLQuery, GraphQLSubscription } from './types';
5
6
  import { InternalAPIClass } from './internals/InternalAPI';
@@ -23,5 +24,48 @@ export declare class APIClass extends InternalAPIClass {
23
24
  provider: AWSAppSyncRealTimeProvider;
24
25
  value: GraphQLResult<T>;
25
26
  }> : Promise<GraphQLResult<any>> | Observable<object>;
27
+ /**
28
+ * Generates an API client that can work with models or raw GraphQL
29
+ */
30
+ generateClient<T = never>(): V6Client<T>;
26
31
  }
32
+ declare const graphQLOperationsInfo: {
33
+ CREATE: {
34
+ operationPrefix: "create";
35
+ usePlural: boolean;
36
+ };
37
+ READ: {
38
+ operationPrefix: "get";
39
+ usePlural: boolean;
40
+ };
41
+ UPDATE: {
42
+ operationPrefix: "update";
43
+ usePlural: boolean;
44
+ };
45
+ DELETE: {
46
+ operationPrefix: "delete";
47
+ usePlural: boolean;
48
+ };
49
+ LIST: {
50
+ operationPrefix: "list";
51
+ usePlural: boolean;
52
+ };
53
+ };
54
+ declare type ModelOperation = keyof typeof graphQLOperationsInfo;
55
+ declare type OperationPrefix = (typeof graphQLOperationsInfo)[ModelOperation]['operationPrefix'];
56
+ declare type FilteredKeys<T> = {
57
+ [P in keyof T]: T[P] extends never ? never : P;
58
+ }[keyof T];
59
+ declare type ExcludeNeverFields<O> = {
60
+ [K in FilteredKeys<O>]: O[K];
61
+ };
62
+ declare type V6Client<T = never> = ExcludeNeverFields<{
63
+ graphql: typeof v6graphql;
64
+ models: {
65
+ [K in keyof T]: {
66
+ [K in OperationPrefix]: (...args: any[]) => Promise<any>;
67
+ };
68
+ };
69
+ }>;
27
70
  export declare const API: APIClass;
71
+ export {};
package/lib/API.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  var tslib_1 = require("tslib");
4
+ var internals_1 = require("@aws-amplify/api-graphql/internals");
4
5
  var core_1 = require("@aws-amplify/core");
5
6
  var InternalAPI_1 = require("./internals/InternalAPI");
6
7
  var logger = new core_1.ConsoleLogger('API');
@@ -20,9 +21,160 @@ var APIClass = /** @class */ (function (_super) {
20
21
  APIClass.prototype.graphql = function (options, additionalHeaders) {
21
22
  return _super.prototype.graphql.call(this, options, additionalHeaders);
22
23
  };
24
+ /**
25
+ * Generates an API client that can work with models or raw GraphQL
26
+ */
27
+ APIClass.prototype.generateClient = function () {
28
+ var e_1, _a;
29
+ var _this = this;
30
+ var config = _super.prototype.configure.call(this, {});
31
+ var modelIntrospection = config.modelIntrospection;
32
+ var client = {
33
+ graphql: internals_1.graphql,
34
+ models: {},
35
+ };
36
+ var _loop_1 = function (model) {
37
+ var name_1 = model.name;
38
+ client.models[name_1] = {};
39
+ Object.entries(graphQLOperationsInfo).forEach(function (_a) {
40
+ var _b = tslib_1.__read(_a, 2), key = _b[0], operationPrefix = _b[1].operationPrefix;
41
+ var operation = key;
42
+ // e.g. clients.models.Todo.update
43
+ client.models[name_1][operationPrefix] = function (arg) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
44
+ var query, variables;
45
+ return tslib_1.__generator(this, function (_a) {
46
+ query = generateGraphQLDocument(model, operation);
47
+ variables = buildGraphQLVariables(model, operation, arg);
48
+ return [2 /*return*/, this.graphql({
49
+ query: query,
50
+ variables: variables,
51
+ })];
52
+ });
53
+ }); };
54
+ });
55
+ };
56
+ try {
57
+ for (var _b = tslib_1.__values(Object.values(modelIntrospection.models)), _c = _b.next(); !_c.done; _c = _b.next()) {
58
+ var model = _c.value;
59
+ _loop_1(model);
60
+ }
61
+ }
62
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
63
+ finally {
64
+ try {
65
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
66
+ }
67
+ finally { if (e_1) throw e_1.error; }
68
+ }
69
+ return client;
70
+ };
23
71
  return APIClass;
24
72
  }(InternalAPI_1.InternalAPIClass));
25
73
  exports.APIClass = APIClass;
74
+ var graphQLOperationsInfo = {
75
+ CREATE: { operationPrefix: 'create', usePlural: false },
76
+ READ: { operationPrefix: 'get', usePlural: false },
77
+ UPDATE: { operationPrefix: 'update', usePlural: false },
78
+ DELETE: { operationPrefix: 'delete', usePlural: false },
79
+ LIST: { operationPrefix: 'list', usePlural: true },
80
+ };
81
+ var graphQLDocumentsCache = new Map();
82
+ function generateGraphQLDocument(modelDefinition, modelOperation) {
83
+ var _a;
84
+ var _b, _c;
85
+ var name = modelDefinition.name, pluralName = modelDefinition.pluralName, fields = modelDefinition.fields, _d = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _d.isCustomPrimaryKey, primaryKeyFieldName = _d.primaryKeyFieldName, sortKeyFieldNames = _d.sortKeyFieldNames;
86
+ var _e = graphQLOperationsInfo[modelOperation], operationPrefix = _e.operationPrefix, usePlural = _e.usePlural;
87
+ var fromCache = (_b = graphQLDocumentsCache.get(name)) === null || _b === void 0 ? void 0 : _b.get(modelOperation);
88
+ if (fromCache !== undefined) {
89
+ return fromCache;
90
+ }
91
+ if (!graphQLDocumentsCache.has(name)) {
92
+ graphQLDocumentsCache.set(name, new Map());
93
+ }
94
+ var graphQLFieldName = "" + operationPrefix + (usePlural ? pluralName : name);
95
+ var graphQLOperationType;
96
+ var graphQLSelectionSet;
97
+ var graphQLArguments;
98
+ var selectionSetFields = Object.values(fields)
99
+ .map(function (_a) {
100
+ var type = _a.type, name = _a.name;
101
+ return typeof type === 'string' && name;
102
+ }) // Only scalars for now
103
+ .filter(Boolean)
104
+ .join(' ');
105
+ switch (modelOperation) {
106
+ case 'CREATE':
107
+ case 'UPDATE':
108
+ case 'DELETE':
109
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
110
+ input: "" + (operationPrefix.charAt(0).toLocaleUpperCase() +
111
+ operationPrefix.slice(1)) + name + "Input!",
112
+ });
113
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'mutation');
114
+ case 'READ':
115
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = isCustomPrimaryKey
116
+ ? tslib_1.__spread([primaryKeyFieldName], sortKeyFieldNames).reduce(function (acc, fieldName) {
117
+ acc[fieldName] = fields[fieldName].type;
118
+ return acc;
119
+ }, {})
120
+ : (_a = {},
121
+ _a[primaryKeyFieldName] = fields[primaryKeyFieldName].type + "!",
122
+ _a));
123
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = selectionSetFields);
124
+ case 'LIST':
125
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'query');
126
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { " + selectionSetFields + " }");
127
+ }
128
+ var graphQLDocument = "" + graphQLOperationType + (graphQLArguments
129
+ ? "(" + Object.entries(graphQLArguments).map(function (_a) {
130
+ var _b = tslib_1.__read(_a, 2), fieldName = _b[0], type = _b[1];
131
+ return "$" + fieldName + ": " + type;
132
+ }) + ")"
133
+ : '') + " { " + graphQLFieldName + (graphQLArguments
134
+ ? "(" + Object.keys(graphQLArguments).map(function (fieldName) { return fieldName + ": $" + fieldName; }) + ")"
135
+ : '') + " { " + graphQLSelectionSet + " } }";
136
+ (_c = graphQLDocumentsCache.get(name)) === null || _c === void 0 ? void 0 : _c.set(modelOperation, graphQLDocument);
137
+ return graphQLDocument;
138
+ }
139
+ function buildGraphQLVariables(modelDefinition, operation, arg) {
140
+ var _a;
141
+ var fields = modelDefinition.fields, _b = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _b.isCustomPrimaryKey, primaryKeyFieldName = _b.primaryKeyFieldName, sortKeyFieldNames = _b.sortKeyFieldNames;
142
+ var variables = {};
143
+ switch (operation) {
144
+ case 'CREATE':
145
+ variables = { input: arg };
146
+ break;
147
+ case 'UPDATE':
148
+ // readonly fields are not updated
149
+ variables = {
150
+ input: Object.fromEntries(Object.entries(arg).filter(function (_a) {
151
+ var _b = tslib_1.__read(_a, 1), fieldName = _b[0];
152
+ var isReadOnly = fields[fieldName].isReadOnly;
153
+ return !isReadOnly;
154
+ })),
155
+ };
156
+ break;
157
+ case 'READ':
158
+ case 'DELETE':
159
+ // only identifiers are sent
160
+ variables = isCustomPrimaryKey
161
+ ? tslib_1.__spread([primaryKeyFieldName], sortKeyFieldNames).reduce(function (acc, fieldName) {
162
+ acc[fieldName] = arg[fieldName];
163
+ return acc;
164
+ }, {})
165
+ : (_a = {}, _a[primaryKeyFieldName] = arg[primaryKeyFieldName], _a);
166
+ if (operation === 'DELETE') {
167
+ variables = { input: variables };
168
+ }
169
+ break;
170
+ case 'LIST':
171
+ break;
172
+ default:
173
+ var exhaustiveCheck = operation;
174
+ throw new Error("Unhandled operation case: " + exhaustiveCheck);
175
+ }
176
+ return variables;
177
+ }
26
178
  exports.API = new APIClass(null);
27
179
  core_1.Amplify.register(exports.API);
28
180
  //# sourceMappingURL=API.js.map
package/lib/API.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"API.js","sourceRoot":"","sources":["../src/API.ts"],"names":[],"mappings":";;;AAIA,0CAAqE;AAGrE,uDAA2D;AAE3D,IAAM,MAAM,GAAG,IAAI,oBAAM,CAAC,KAAK,CAAC,CAAC;AACjC;;;;GAIG;AACH;IAA8B,oCAAgB;IAA9C;;IA6BA,CAAC;IA5BO,gCAAa,GAApB;QACC,OAAO,KAAK,CAAC;IACd,CAAC;IAoBD,0BAAO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,SAAS,CAAC;YACzC,MAAM,IAAI,KAAK,CAAC,+BAA6B,eAAiB,CAAC,CAAC;KACjE;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAmBY,QAAA,GAAG,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AACtC,cAAO,CAAC,QAAQ,CAAC,WAAG,CAAC,CAAC"}
package/lib-esm/API.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AWSAppSyncRealTimeProvider } from '@aws-amplify/pubsub';
2
2
  import { GraphQLOptions, GraphQLResult } from '@aws-amplify/api-graphql';
3
+ import { graphql as v6graphql } from '@aws-amplify/api-graphql/internals';
3
4
  import Observable from 'zen-observable-ts';
4
5
  import { GraphQLQuery, GraphQLSubscription } from './types';
5
6
  import { InternalAPIClass } from './internals/InternalAPI';
@@ -23,5 +24,48 @@ export declare class APIClass extends InternalAPIClass {
23
24
  provider: AWSAppSyncRealTimeProvider;
24
25
  value: GraphQLResult<T>;
25
26
  }> : Promise<GraphQLResult<any>> | Observable<object>;
27
+ /**
28
+ * Generates an API client that can work with models or raw GraphQL
29
+ */
30
+ generateClient<T = never>(): V6Client<T>;
26
31
  }
32
+ declare const graphQLOperationsInfo: {
33
+ CREATE: {
34
+ operationPrefix: "create";
35
+ usePlural: boolean;
36
+ };
37
+ READ: {
38
+ operationPrefix: "get";
39
+ usePlural: boolean;
40
+ };
41
+ UPDATE: {
42
+ operationPrefix: "update";
43
+ usePlural: boolean;
44
+ };
45
+ DELETE: {
46
+ operationPrefix: "delete";
47
+ usePlural: boolean;
48
+ };
49
+ LIST: {
50
+ operationPrefix: "list";
51
+ usePlural: boolean;
52
+ };
53
+ };
54
+ declare type ModelOperation = keyof typeof graphQLOperationsInfo;
55
+ declare type OperationPrefix = (typeof graphQLOperationsInfo)[ModelOperation]['operationPrefix'];
56
+ declare type FilteredKeys<T> = {
57
+ [P in keyof T]: T[P] extends never ? never : P;
58
+ }[keyof T];
59
+ declare type ExcludeNeverFields<O> = {
60
+ [K in FilteredKeys<O>]: O[K];
61
+ };
62
+ declare type V6Client<T = never> = ExcludeNeverFields<{
63
+ graphql: typeof v6graphql;
64
+ models: {
65
+ [K in keyof T]: {
66
+ [K in OperationPrefix]: (...args: any[]) => Promise<any>;
67
+ };
68
+ };
69
+ }>;
27
70
  export declare const API: APIClass;
71
+ export {};
package/lib-esm/API.js CHANGED
@@ -1,4 +1,5 @@
1
- import { __extends } from "tslib";
1
+ import { __awaiter, __extends, __generator, __read, __spread, __values } from "tslib";
2
+ import { graphql as v6graphql } from '@aws-amplify/api-graphql/internals';
2
3
  import { Amplify, ConsoleLogger as Logger } from '@aws-amplify/core';
3
4
  import { InternalAPIClass } from './internals/InternalAPI';
4
5
  var logger = new Logger('API');
@@ -18,9 +19,160 @@ var APIClass = /** @class */ (function (_super) {
18
19
  APIClass.prototype.graphql = function (options, additionalHeaders) {
19
20
  return _super.prototype.graphql.call(this, options, additionalHeaders);
20
21
  };
22
+ /**
23
+ * Generates an API client that can work with models or raw GraphQL
24
+ */
25
+ APIClass.prototype.generateClient = function () {
26
+ var e_1, _a;
27
+ var _this = this;
28
+ var config = _super.prototype.configure.call(this, {});
29
+ var modelIntrospection = config.modelIntrospection;
30
+ var client = {
31
+ graphql: v6graphql,
32
+ models: {},
33
+ };
34
+ var _loop_1 = function (model) {
35
+ var name_1 = model.name;
36
+ client.models[name_1] = {};
37
+ Object.entries(graphQLOperationsInfo).forEach(function (_a) {
38
+ var _b = __read(_a, 2), key = _b[0], operationPrefix = _b[1].operationPrefix;
39
+ var operation = key;
40
+ // e.g. clients.models.Todo.update
41
+ client.models[name_1][operationPrefix] = function (arg) { return __awaiter(_this, void 0, void 0, function () {
42
+ var query, variables;
43
+ return __generator(this, function (_a) {
44
+ query = generateGraphQLDocument(model, operation);
45
+ variables = buildGraphQLVariables(model, operation, arg);
46
+ return [2 /*return*/, this.graphql({
47
+ query: query,
48
+ variables: variables,
49
+ })];
50
+ });
51
+ }); };
52
+ });
53
+ };
54
+ try {
55
+ for (var _b = __values(Object.values(modelIntrospection.models)), _c = _b.next(); !_c.done; _c = _b.next()) {
56
+ var model = _c.value;
57
+ _loop_1(model);
58
+ }
59
+ }
60
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
61
+ finally {
62
+ try {
63
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
64
+ }
65
+ finally { if (e_1) throw e_1.error; }
66
+ }
67
+ return client;
68
+ };
21
69
  return APIClass;
22
70
  }(InternalAPIClass));
23
71
  export { APIClass };
72
+ var graphQLOperationsInfo = {
73
+ CREATE: { operationPrefix: 'create', usePlural: false },
74
+ READ: { operationPrefix: 'get', usePlural: false },
75
+ UPDATE: { operationPrefix: 'update', usePlural: false },
76
+ DELETE: { operationPrefix: 'delete', usePlural: false },
77
+ LIST: { operationPrefix: 'list', usePlural: true },
78
+ };
79
+ var graphQLDocumentsCache = new Map();
80
+ function generateGraphQLDocument(modelDefinition, modelOperation) {
81
+ var _a;
82
+ var _b, _c;
83
+ var name = modelDefinition.name, pluralName = modelDefinition.pluralName, fields = modelDefinition.fields, _d = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _d.isCustomPrimaryKey, primaryKeyFieldName = _d.primaryKeyFieldName, sortKeyFieldNames = _d.sortKeyFieldNames;
84
+ var _e = graphQLOperationsInfo[modelOperation], operationPrefix = _e.operationPrefix, usePlural = _e.usePlural;
85
+ var fromCache = (_b = graphQLDocumentsCache.get(name)) === null || _b === void 0 ? void 0 : _b.get(modelOperation);
86
+ if (fromCache !== undefined) {
87
+ return fromCache;
88
+ }
89
+ if (!graphQLDocumentsCache.has(name)) {
90
+ graphQLDocumentsCache.set(name, new Map());
91
+ }
92
+ var graphQLFieldName = "" + operationPrefix + (usePlural ? pluralName : name);
93
+ var graphQLOperationType;
94
+ var graphQLSelectionSet;
95
+ var graphQLArguments;
96
+ var selectionSetFields = Object.values(fields)
97
+ .map(function (_a) {
98
+ var type = _a.type, name = _a.name;
99
+ return typeof type === 'string' && name;
100
+ }) // Only scalars for now
101
+ .filter(Boolean)
102
+ .join(' ');
103
+ switch (modelOperation) {
104
+ case 'CREATE':
105
+ case 'UPDATE':
106
+ case 'DELETE':
107
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
108
+ input: "" + (operationPrefix.charAt(0).toLocaleUpperCase() +
109
+ operationPrefix.slice(1)) + name + "Input!",
110
+ });
111
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'mutation');
112
+ case 'READ':
113
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = isCustomPrimaryKey
114
+ ? __spread([primaryKeyFieldName], sortKeyFieldNames).reduce(function (acc, fieldName) {
115
+ acc[fieldName] = fields[fieldName].type;
116
+ return acc;
117
+ }, {})
118
+ : (_a = {},
119
+ _a[primaryKeyFieldName] = fields[primaryKeyFieldName].type + "!",
120
+ _a));
121
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = selectionSetFields);
122
+ case 'LIST':
123
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'query');
124
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { " + selectionSetFields + " }");
125
+ }
126
+ var graphQLDocument = "" + graphQLOperationType + (graphQLArguments
127
+ ? "(" + Object.entries(graphQLArguments).map(function (_a) {
128
+ var _b = __read(_a, 2), fieldName = _b[0], type = _b[1];
129
+ return "$" + fieldName + ": " + type;
130
+ }) + ")"
131
+ : '') + " { " + graphQLFieldName + (graphQLArguments
132
+ ? "(" + Object.keys(graphQLArguments).map(function (fieldName) { return fieldName + ": $" + fieldName; }) + ")"
133
+ : '') + " { " + graphQLSelectionSet + " } }";
134
+ (_c = graphQLDocumentsCache.get(name)) === null || _c === void 0 ? void 0 : _c.set(modelOperation, graphQLDocument);
135
+ return graphQLDocument;
136
+ }
137
+ function buildGraphQLVariables(modelDefinition, operation, arg) {
138
+ var _a;
139
+ var fields = modelDefinition.fields, _b = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _b.isCustomPrimaryKey, primaryKeyFieldName = _b.primaryKeyFieldName, sortKeyFieldNames = _b.sortKeyFieldNames;
140
+ var variables = {};
141
+ switch (operation) {
142
+ case 'CREATE':
143
+ variables = { input: arg };
144
+ break;
145
+ case 'UPDATE':
146
+ // readonly fields are not updated
147
+ variables = {
148
+ input: Object.fromEntries(Object.entries(arg).filter(function (_a) {
149
+ var _b = __read(_a, 1), fieldName = _b[0];
150
+ var isReadOnly = fields[fieldName].isReadOnly;
151
+ return !isReadOnly;
152
+ })),
153
+ };
154
+ break;
155
+ case 'READ':
156
+ case 'DELETE':
157
+ // only identifiers are sent
158
+ variables = isCustomPrimaryKey
159
+ ? __spread([primaryKeyFieldName], sortKeyFieldNames).reduce(function (acc, fieldName) {
160
+ acc[fieldName] = arg[fieldName];
161
+ return acc;
162
+ }, {})
163
+ : (_a = {}, _a[primaryKeyFieldName] = arg[primaryKeyFieldName], _a);
164
+ if (operation === 'DELETE') {
165
+ variables = { input: variables };
166
+ }
167
+ break;
168
+ case 'LIST':
169
+ break;
170
+ default:
171
+ var exhaustiveCheck = operation;
172
+ throw new Error("Unhandled operation case: " + exhaustiveCheck);
173
+ }
174
+ return variables;
175
+ }
24
176
  export var API = new APIClass(null);
25
177
  Amplify.register(API);
26
178
  //# sourceMappingURL=API.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"API.js","sourceRoot":"","sources":["../src/API.ts"],"names":[],"mappings":";AAIA,OAAO,EAAE,OAAO,EAAE,aAAa,IAAI,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAGrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,IAAM,MAAM,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;AACjC;;;;GAIG;AACH;IAA8B,4BA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,IAAG,GAAG,CAAC,mBAAmB,CAAC,KAAE,CAAC;YAEvD,IAAI,SAAS,KAAK,QAAQ,EAAE;gBAC3B,SAAS,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;aACjC;YACD,MAAM;QACP,KAAK,MAAM;YACV,MAAM;QACP;YACC,IAAM,eAAe,GAAU,SAAS,CAAC;YACzC,MAAM,IAAI,KAAK,CAAC,+BAA6B,eAAiB,CAAC,CAAC;KACjE;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAmBD,MAAM,CAAC,IAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC;AACtC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aws-amplify/api",
3
- "version": "5.3.4-api-v6.2+366313460",
3
+ "version": "5.3.4-api-v6.23+6a0182db2",
4
4
  "description": "Api category of aws-amplify",
5
5
  "main": "./lib/index.js",
6
6
  "module": "./lib-esm/index.js",
@@ -35,7 +35,7 @@
35
35
  "clean:size": "rimraf dual-publish-tmp tmp*",
36
36
  "format": "echo \"Not implemented\"",
37
37
  "lint": "tslint 'src/**/*.ts' && npm run ts-coverage",
38
- "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 91.93"
38
+ "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 91.14"
39
39
  },
40
40
  "repository": {
41
41
  "type": "git",
@@ -58,8 +58,8 @@
58
58
  "internals"
59
59
  ],
60
60
  "dependencies": {
61
- "@aws-amplify/api-graphql": "3.4.4-api-v6.2+366313460",
62
- "@aws-amplify/api-rest": "3.3.3-api-v6.2+366313460",
61
+ "@aws-amplify/api-graphql": "3.4.4-api-v6.23+6a0182db2",
62
+ "@aws-amplify/api-rest": "3.3.3-api-v6.23+6a0182db2",
63
63
  "tslib": "^1.8.0"
64
64
  },
65
65
  "size-limit": [
@@ -67,7 +67,7 @@
67
67
  "name": "API (top-level class)",
68
68
  "path": "./lib-esm/index.js",
69
69
  "import": "{ Amplify, API }",
70
- "limit": "89 kB"
70
+ "limit": "95 kB"
71
71
  }
72
72
  ],
73
73
  "jest": {
@@ -114,5 +114,5 @@
114
114
  "lib-esm"
115
115
  ]
116
116
  },
117
- "gitHead": "36631346052721682d49a4b3311352631ee8d6ac"
117
+ "gitHead": "6a0182db2a02dd45a2fd2d0c5cf69ffeaf452cc1"
118
118
  }
package/src/API.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  import { AWSAppSyncRealTimeProvider } from '@aws-amplify/pubsub';
4
4
  import { GraphQLOptions, GraphQLResult } from '@aws-amplify/api-graphql';
5
+ import { graphql as v6graphql } from '@aws-amplify/api-graphql/internals';
5
6
  import { Amplify, ConsoleLogger as Logger } from '@aws-amplify/core';
6
7
  import Observable from 'zen-observable-ts';
7
8
  import { GraphQLQuery, GraphQLSubscription } from './types';
@@ -42,7 +43,224 @@ export class APIClass extends InternalAPIClass {
42
43
  ): Promise<GraphQLResult<any>> | Observable<object> {
43
44
  return super.graphql(options, additionalHeaders);
44
45
  }
46
+
47
+ /**
48
+ * Generates an API client that can work with models or raw GraphQL
49
+ */
50
+ generateClient<T = never>(): V6Client<T> {
51
+ const config = super.configure({});
52
+
53
+ const { modelIntrospection } = config;
54
+
55
+ const client: V6Client<any> = {
56
+ graphql: v6graphql,
57
+ models: {},
58
+ };
59
+
60
+ for (const model of Object.values(modelIntrospection.models)) {
61
+ const { name } = model as any;
62
+
63
+ client.models[name] = {} as any;
64
+
65
+ Object.entries(graphQLOperationsInfo).forEach(
66
+ ([key, { operationPrefix }]) => {
67
+ const operation = key as ModelOperation;
68
+
69
+ // e.g. clients.models.Todo.update
70
+ client.models[name][operationPrefix] = async (arg: any) => {
71
+ const query = generateGraphQLDocument(model, operation);
72
+ const variables = buildGraphQLVariables(model, operation, arg);
73
+
74
+ return this.graphql({
75
+ query,
76
+ variables,
77
+ });
78
+ };
79
+ }
80
+ );
81
+ }
82
+
83
+ return client as V6Client<T>;
84
+ }
85
+ }
86
+
87
+ const graphQLOperationsInfo = {
88
+ CREATE: { operationPrefix: 'create' as const, usePlural: false },
89
+ READ: { operationPrefix: 'get' as const, usePlural: false },
90
+ UPDATE: { operationPrefix: 'update' as const, usePlural: false },
91
+ DELETE: { operationPrefix: 'delete' as const, usePlural: false },
92
+ LIST: { operationPrefix: 'list' as const, usePlural: true },
93
+ };
94
+ type ModelOperation = keyof typeof graphQLOperationsInfo;
95
+ type OperationPrefix =
96
+ (typeof graphQLOperationsInfo)[ModelOperation]['operationPrefix'];
97
+
98
+ const graphQLDocumentsCache = new Map<string, Map<ModelOperation, string>>();
99
+
100
+ function generateGraphQLDocument(
101
+ modelDefinition: any,
102
+ modelOperation: ModelOperation
103
+ ): string {
104
+ const {
105
+ name,
106
+ pluralName,
107
+ fields,
108
+ primaryKeyInfo: {
109
+ isCustomPrimaryKey,
110
+ primaryKeyFieldName,
111
+ sortKeyFieldNames,
112
+ },
113
+ } = modelDefinition;
114
+ const { operationPrefix, usePlural } = graphQLOperationsInfo[modelOperation];
115
+
116
+ const fromCache = graphQLDocumentsCache.get(name)?.get(modelOperation);
117
+
118
+ if (fromCache !== undefined) {
119
+ return fromCache;
120
+ }
121
+
122
+ if (!graphQLDocumentsCache.has(name)) {
123
+ graphQLDocumentsCache.set(name, new Map());
124
+ }
125
+
126
+ const graphQLFieldName = `${operationPrefix}${usePlural ? pluralName : name}`;
127
+ let graphQLOperationType: 'mutation' | 'query' | undefined;
128
+ let graphQLSelectionSet: string | undefined;
129
+ let graphQLArguments: Record<string, any> | undefined;
130
+
131
+ const selectionSetFields = Object.values<any>(fields)
132
+ .map(({ type, name }) => typeof type === 'string' && name) // Only scalars for now
133
+ .filter(Boolean)
134
+ .join(' ');
135
+
136
+ switch (modelOperation) {
137
+ case 'CREATE':
138
+ case 'UPDATE':
139
+ case 'DELETE':
140
+ graphQLArguments ??
141
+ (graphQLArguments = {
142
+ input: `${
143
+ operationPrefix.charAt(0).toLocaleUpperCase() +
144
+ operationPrefix.slice(1)
145
+ }${name}Input!`,
146
+ });
147
+ graphQLOperationType ?? (graphQLOperationType = 'mutation');
148
+ case 'READ':
149
+ graphQLArguments ??
150
+ (graphQLArguments = isCustomPrimaryKey
151
+ ? [primaryKeyFieldName, ...sortKeyFieldNames].reduce(
152
+ (acc, fieldName) => {
153
+ acc[fieldName] = fields[fieldName].type;
154
+
155
+ return acc;
156
+ },
157
+ {}
158
+ )
159
+ : {
160
+ [primaryKeyFieldName]: `${fields[primaryKeyFieldName].type}!`,
161
+ });
162
+ graphQLSelectionSet ?? (graphQLSelectionSet = selectionSetFields);
163
+ case 'LIST':
164
+ graphQLOperationType ?? (graphQLOperationType = 'query');
165
+ graphQLSelectionSet ??
166
+ (graphQLSelectionSet = `items { ${selectionSetFields} }`);
167
+ }
168
+
169
+ const graphQLDocument = `${graphQLOperationType}${
170
+ graphQLArguments
171
+ ? `(${Object.entries(graphQLArguments).map(
172
+ ([fieldName, type]) => `\$${fieldName}: ${type}`
173
+ )})`
174
+ : ''
175
+ } { ${graphQLFieldName}${
176
+ graphQLArguments
177
+ ? `(${Object.keys(graphQLArguments).map(
178
+ fieldName => `${fieldName}: \$${fieldName}`
179
+ )})`
180
+ : ''
181
+ } { ${graphQLSelectionSet} } }`;
182
+
183
+ graphQLDocumentsCache.get(name)?.set(modelOperation, graphQLDocument);
184
+
185
+ return graphQLDocument;
186
+ }
187
+
188
+ function buildGraphQLVariables(
189
+ modelDefinition: any,
190
+ operation: ModelOperation,
191
+ arg: any
192
+ ): object {
193
+ const {
194
+ fields,
195
+ primaryKeyInfo: {
196
+ isCustomPrimaryKey,
197
+ primaryKeyFieldName,
198
+ sortKeyFieldNames,
199
+ },
200
+ } = modelDefinition;
201
+
202
+ let variables = {};
203
+
204
+ switch (operation) {
205
+ case 'CREATE':
206
+ variables = { input: arg };
207
+ break;
208
+ case 'UPDATE':
209
+ // readonly fields are not updated
210
+ variables = {
211
+ input: Object.fromEntries(
212
+ Object.entries(arg).filter(([fieldName]) => {
213
+ const { isReadOnly } = fields[fieldName];
214
+
215
+ return !isReadOnly;
216
+ })
217
+ ),
218
+ };
219
+ break;
220
+ case 'READ':
221
+ case 'DELETE':
222
+ // only identifiers are sent
223
+ variables = isCustomPrimaryKey
224
+ ? [primaryKeyFieldName, ...sortKeyFieldNames].reduce(
225
+ (acc, fieldName) => {
226
+ acc[fieldName] = arg[fieldName];
227
+
228
+ return acc;
229
+ },
230
+ {}
231
+ )
232
+ : { [primaryKeyFieldName]: arg[primaryKeyFieldName] };
233
+
234
+ if (operation === 'DELETE') {
235
+ variables = { input: variables };
236
+ }
237
+ break;
238
+ case 'LIST':
239
+ break;
240
+ default:
241
+ const exhaustiveCheck: never = operation;
242
+ throw new Error(`Unhandled operation case: ${exhaustiveCheck}`);
243
+ }
244
+
245
+ return variables;
45
246
  }
46
247
 
248
+ type FilteredKeys<T> = {
249
+ [P in keyof T]: T[P] extends never ? never : P;
250
+ }[keyof T];
251
+ type ExcludeNeverFields<O> = {
252
+ [K in FilteredKeys<O>]: O[K];
253
+ };
254
+
255
+ // If no T is passed, ExcludeNeverFields removes "models" from the client
256
+ type V6Client<T = never> = ExcludeNeverFields<{
257
+ graphql: typeof v6graphql;
258
+ models: {
259
+ [K in keyof T]: {
260
+ [K in OperationPrefix]: (...args: any[]) => Promise<any>;
261
+ };
262
+ };
263
+ }>;
264
+
47
265
  export const API = new APIClass(null);
48
266
  Amplify.register(API);