/
AppSyncApi.ts
1169 lines (1096 loc) · 29.8 KB
/
AppSyncApi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from "path";
import fs from "fs";
export async function weakImport(pkg: string) {
try {
return await import(pkg);
} catch {
return {};
}
}
const { print } = await weakImport("graphql");
const { mergeTypeDefs } = await weakImport("@graphql-tools/merge");
import { Construct } from "constructs";
import { App } from "./App.js";
import { Stack } from "./Stack.js";
import { Table } from "./Table.js";
import { RDS } from "./RDS.js";
import * as appSyncApiDomain from "./util/appSyncApiDomain.js";
import { getFunctionRef, SSTConstruct, isCDKConstruct } from "./Construct.js";
import {
Function as Fn,
FunctionProps,
FunctionInlineDefinition,
FunctionDefinition,
} from "./Function.js";
import { BindingResource, BindingProps } from "./util/binding.js";
import { Permissions } from "./util/permission.js";
import { useProject } from "../project.js";
import { Table as CDKTable } from "aws-cdk-lib/aws-dynamodb";
import { IServerlessCluster } from "aws-cdk-lib/aws-rds";
import { ISecret } from "aws-cdk-lib/aws-secretsmanager";
import {
AwsIamConfig,
BaseDataSource,
CfnDomainName,
CfnDomainNameApiAssociation,
GraphqlApi,
GraphqlApiProps,
IGraphqlApi,
MappingTemplate as CDKMappingTemplate,
Resolver,
ResolverProps,
SchemaFile,
Definition,
LambdaDataSource,
DynamoDbDataSource,
RdsDataSource,
OpenSearchDataSource,
HttpDataSource,
NoneDataSource,
} from "aws-cdk-lib/aws-appsync";
import { ICertificate } from "aws-cdk-lib/aws-certificatemanager";
import { IDomain } from "aws-cdk-lib/aws-opensearchservice";
/////////////////////
// Interfaces
/////////////////////
export interface AppSyncApiDomainProps
extends appSyncApiDomain.CustomDomainProps {}
interface AppSyncApiBaseDataSourceProps {
/**
* Name of the data source
*/
name?: string;
/**
* Description of the data source
*/
description?: string;
}
/**
* Used to define a lambda data source
*
* @example
* ```js
* new AppSyncApi(stack, "AppSync", {
* dataSources: {
* lambda: {
* type: "function",
* function: "src/function.handler"
* },
* },
* });
* ```
*
*/
export interface AppSyncApiLambdaDataSourceProps
extends AppSyncApiBaseDataSourceProps {
/**
* String literal to signify that this data source is a function
*/
type?: "function";
/**
* Function definition
*/
function: FunctionDefinition;
}
/**
* Used to define a DynamoDB data source
*
* @example
* ```js
* new AppSyncApi(stack, "AppSync", {
* dataSources: {
* table: {
* type: "table",
* table: MyTable
* },
* },
* });
* ```
*/
export interface AppSyncApiDynamoDbDataSourceProps
extends AppSyncApiBaseDataSourceProps {
/**
* String literal to signify that this data source is a dynamodb table
*/
type: "dynamodb";
/**
* Target table
*/
table?: Table;
cdk?: {
dataSource?: {
table: CDKTable;
};
};
}
/**
* Used to define a RDS data source
*
* @example
* ```js
* new AppSyncApi(stack, "AppSync", {
* dataSources: {
* rds: {
* type: "rds",
* rds: myRDSCluster
* },
* },
* });
* ```
*/
export interface AppSyncApiRdsDataSourceProps
extends AppSyncApiBaseDataSourceProps {
/**
* String literal to signify that this data source is an RDS database
*/
type: "rds";
/**
* Target RDS construct
*/
rds?: RDS;
/**
* The name of the database to connect to
*/
databaseName?: string;
cdk?: {
dataSource?: {
serverlessCluster: IServerlessCluster;
secretStore: ISecret;
databaseName?: string;
};
};
}
/**
* Used to define a OpenSearch data source
*
* @example
* ```js
* new AppSyncApi(stack, "AppSync", {
* dataSources: {
* search: {
* type: "open_search",
* cdk: {
* dataSource: {
* domain: myOpenSearchDomain,
* }
* }
* }
* }
* });
* ```
*/
export interface AppSyncApiOpenSearchDataSourceProps
extends AppSyncApiBaseDataSourceProps {
/**
* String literal to signify that this data source is an OpenSearch domain
*/
type: "open_search";
cdk: {
dataSource: {
domain: IDomain;
};
};
}
/**
* Used to define an http data source
*
* @example
* ```js
* new AppSyncApi(stack, "AppSync", {
* dataSources: {
* http: {
* type: "http",
* endpoint: "https://example.com"
* },
* },
* });
* ```
*/
export interface AppSyncApiHttpDataSourceProps
extends AppSyncApiBaseDataSourceProps {
/**
* String literal to signify that this data source is an HTTP endpoint
*/
type: "http";
/**
* URL to forward requests to
*/
endpoint: string;
cdk?: {
dataSource?: {
authorizationConfig?: AwsIamConfig;
};
};
}
/**
* Used to define a none data source
*
* @example
* ```js
* new AppSyncApi(stack, "AppSync", {
* dataSources: {
* none: {
* type: "none",
* },
* },
* });
* ```
*/
export interface AppSyncApiNoneDataSourceProps
extends AppSyncApiBaseDataSourceProps {
/**
* String literal to signify that this data source is an HTTP endpoint
*/
type: "none";
}
export interface MappingTemplateFile {
/**
* Path to the file containing the VTL mapping template
*/
file: string;
}
export interface MappingTemplateInline {
/**
* Inline definition of the VTL mapping template
*/
inline: string;
}
export type MappingTemplate = MappingTemplateFile | MappingTemplateInline;
/**
* Used to define full resolver config
*/
export interface AppSyncApiResolverProps {
/**
* The data source for this resolver. The data source must be already created.
*/
dataSource?: string;
/**
* The function definition used to create the data source for this resolver.
*/
function?: FunctionDefinition;
/**
* VTL request mapping template
*
* @example
* ```js
* requestMapping: {
* inline: '{"version" : "2017-02-28", "operation" : "Scan"}',
* },
* ```
*
* @example
* ```js
* requestMapping: {
* file: "path/to/template.vtl",
* },
* ```
*/
requestMapping?: MappingTemplate;
/**
* VTL response mapping template
*
* @example
* ```js
* responseMapping: {
* inline: "$util.toJson($ctx.result.items)",
* },
* ```
*
* @example
* ```js
* responseMapping: {
* file: "path/to/template.vtl",
* },
* ```
*/
responseMapping?: MappingTemplate;
cdk?: {
/**
* This allows you to override the default settings this construct uses internally to create the resolver.
*/
resolver: Omit<
ResolverProps,
"api" | "fieldName" | "typeName" | "dataSource"
>;
};
}
export interface AppSyncApiProps {
/**
* The GraphQL schema definition.
*
* @example
*
* ```js
* new AppSyncApi(stack, "GraphqlApi", {
* schema: "graphql/schema.graphql",
* });
* ```
*/
schema?: string | string[];
/**
* Specify a custom domain to use in addition to the automatically generated one. SST currently supports domains that are configured using [Route 53](https://aws.amazon.com/route53/)
*
* @example
* ```js
* new AppSyncApi(stack, "GraphqlApi", {
* customDomain: "api.example.com"
* })
* ```
*
* @example
* ```js
* new AppSyncApi(stack, "GraphqlApi", {
* customDomain: {
* domainName: "api.example.com",
* hostedZone: "domain.com",
* }
* })
* ```
*/
customDomain?: string | AppSyncApiDomainProps;
/**
* Define datasources. Can be a function, dynamodb table, rds cluster or http endpoint
*
* @example
* ```js
* new AppSyncApi(stack, "GraphqlApi", {
* dataSources: {
* notes: "src/notes.main",
* },
* resolvers: {
* "Query listNotes": "notes",
* },
* });
* ```
*/
dataSources?: Record<
string,
| FunctionInlineDefinition
| AppSyncApiLambdaDataSourceProps
| AppSyncApiDynamoDbDataSourceProps
| AppSyncApiRdsDataSourceProps
| AppSyncApiOpenSearchDataSourceProps
| AppSyncApiHttpDataSourceProps
| AppSyncApiNoneDataSourceProps
>;
/**
* The resolvers for this API. Takes an object, with the key being the type name and field name as a string and the value is either a string with the name of existing data source.
*
* @example
* ```js
* new AppSyncApi(stack, "GraphqlApi", {
* resolvers: {
* "Query listNotes": "src/list.main",
* "Query getNoteById": "src/get.main",
* "Mutation createNote": "src/create.main",
* "Mutation updateNote": "src/update.main",
* "Mutation deleteNote": "src/delete.main",
* },
* });
* ```
*/
resolvers?: Record<
string,
string | FunctionInlineDefinition | AppSyncApiResolverProps
>;
defaults?: {
/**
* The default function props to be applied to all the Lambda functions in the AppSyncApi. The `environment`, `permissions` and `layers` properties will be merged with per route definitions if they are defined.
*
* @example
* ```js
* new AppSync(stack, "AppSync", {
* defaults: {
* function: {
* timeout: 20,
* environment: { tableName: table.tableName },
* permissions: [table],
* }
* },
* });
* ```
*/
function?: FunctionProps;
};
cdk?: {
/**
* Allows you to override default id for this construct.
*/
id?: string;
/**
* Allows you to override default settings this construct uses internally to create the AppSync API.
*/
graphqlApi?: IGraphqlApi | AppSyncApiCdkGraphqlProps;
};
}
export interface AppSyncApiCdkGraphqlProps
extends Omit<GraphqlApiProps, "name" | "schema"> {
name?: string;
}
/////////////////////
// Construct
/////////////////////
/**
*
* The `AppSyncApi` construct is a higher level CDK construct that makes it easy to create an AppSync GraphQL API.
*
* @example
*
* ```js
* import { AppSyncApi } from "sst/constructs";
*
* new AppSyncApi(stack, "GraphqlApi", {
* schema: "graphql/schema.graphql",
* dataSources: {
* notesDS: "src/notes.main",
* },
* resolvers: {
* "Query listNotes": "notesDS",
* "Query getNoteById": "notesDS",
* "Mutation createNote": "notesDS",
* "Mutation updateNote": "notesDS",
* "Mutation deleteNote": "notesDS",
* },
* });
* ```
*/
export class AppSyncApi extends Construct implements SSTConstruct {
public readonly id: string;
public readonly cdk: {
/**
* The internally created appsync api
*/
graphqlApi: GraphqlApi;
/**
* If custom domain is enabled, this is the internally created CDK Certificate instance.
*/
certificate?: ICertificate;
};
private readonly props: AppSyncApiProps;
private _customDomainUrl?: string;
private readonly functionsByDsKey: { [key: string]: Fn } = {};
private readonly dataSourcesByDsKey: {
[key: string]: BaseDataSource;
} = {};
private readonly dsKeysByResKey: { [key: string]: string } = {};
private readonly resolversByResKey: { [key: string]: Resolver } = {};
private readonly bindingForAllFunctions: BindingResource[] = [];
private readonly permissionsAttachedForAllFunctions: Permissions[] = [];
constructor(scope: Construct, id: string, props: AppSyncApiProps) {
super(scope, props?.cdk?.id || id);
this.id = id;
this.props = props;
this.cdk = {} as any;
this.createGraphApi();
// Configure data sources
if (props?.dataSources) {
for (const key of Object.keys(props.dataSources)) {
this.addDataSource(this, key, props.dataSources[key]);
}
}
// Configure resolvers
if (props?.resolvers) {
for (const key of Object.keys(props.resolvers)) {
this.addResolver(this, key, props.resolvers[key]);
}
}
const app = this.node.root as App;
app.registerTypes(this);
}
/**
* The Id of the internally created AppSync GraphQL API.
*/
public get apiId(): string {
return this.cdk.graphqlApi.apiId;
}
/**
* The ARN of the internally created AppSync GraphQL API.
*/
public get apiArn(): string {
return this.cdk.graphqlApi.arn;
}
/**
* The name of the internally created AppSync GraphQL API.
*/
public get apiName(): string {
return this.cdk.graphqlApi.name;
}
/**
* The AWS generated URL of the Api.
*/
public get url(): string {
return this.cdk.graphqlApi.graphqlUrl;
}
/**
* If custom domain is enabled, this is the custom domain URL of the Api.
*/
public get customDomainUrl(): string | undefined {
return this._customDomainUrl;
}
/**
* Add data sources after the construct has been created
*
* @example
* ```js
* api.addDataSources(stack, {
* billingDS: "src/billing.main",
* });
* ```
*/
public addDataSources(
scope: Construct,
dataSources: {
[key: string]:
| FunctionInlineDefinition
| AppSyncApiLambdaDataSourceProps
| AppSyncApiDynamoDbDataSourceProps
| AppSyncApiRdsDataSourceProps
| AppSyncApiOpenSearchDataSourceProps
| AppSyncApiHttpDataSourceProps
| AppSyncApiNoneDataSourceProps;
}
): void {
Object.keys(dataSources).forEach((key: string) => {
this.addDataSource(scope, key, dataSources[key]);
});
}
/**
* Add resolvers the construct has been created
*
* @example
* ```js
* api.addResolvers(stack, {
* "Mutation charge": "billingDS",
* });
* ```
*/
public addResolvers(
scope: Construct,
resolvers: {
[key: string]: FunctionInlineDefinition | AppSyncApiResolverProps;
}
): void {
Object.keys(resolvers).forEach((key: string) => {
this.addResolver(scope, key, resolvers[key]);
});
}
/**
* Get the instance of the internally created Function, for a given resolver.
*
* @example
* ```js
* const func = api.getFunction("Mutation charge");
* ```
*/
public getFunction(key: string): Fn | undefined {
let fn = this.functionsByDsKey[key];
if (!fn) {
const resKey = this.normalizeResolverKey(key);
const dsKey = this.dsKeysByResKey[resKey];
fn = this.functionsByDsKey[dsKey];
}
return fn;
}
/**
* Get a datasource by name
* @example
* ```js
* api.getDataSource("billingDS");
* ```
*/
public getDataSource(key: string): BaseDataSource | undefined {
let ds = this.dataSourcesByDsKey[key];
if (!ds) {
const resKey = this.normalizeResolverKey(key);
const dsKey = this.dsKeysByResKey[resKey];
ds = this.dataSourcesByDsKey[dsKey];
}
return ds;
}
/**
* Get a resolver
*
* @example
* ```js
* api.getResolver("Mutation charge");
* ```
*/
public getResolver(key: string): Resolver | undefined {
const resKey = this.normalizeResolverKey(key);
return this.resolversByResKey[resKey];
}
/**
* Binds the given list of resources to all function data sources.
*
* @example
*
* ```js
* api.bind([STRIPE_KEY, bucket]);
* ```
*/
public bind(constructs: BindingResource[]) {
Object.values(this.functionsByDsKey).forEach((fn) => fn.bind(constructs));
this.bindingForAllFunctions.push(...constructs);
}
/**
* Binds the given list of resources to a specific function data source.
*
* @example
* ```js
* api.bindToDataSource("Mutation charge", [STRIPE_KEY, bucket]);
* ```
*
*/
public bindToDataSource(key: string, constructs: BindingResource[]): void {
const fn = this.getFunction(key);
if (!fn) {
throw new Error(
`Failed to bind resources. Function does not exist for key "${key}".`
);
}
fn.bind(constructs);
}
/**
* Attaches the given list of permissions to all function data sources
*
* @example
* ```js
* api.attachPermissions(["s3"]);
* ```
*/
public attachPermissions(permissions: Permissions): void {
Object.values(this.functionsByDsKey).forEach((fn) =>
fn.attachPermissions(permissions)
);
this.permissionsAttachedForAllFunctions.push(permissions);
}
/**
* Attaches the given list of permissions to a specific function datasource. This allows that function to access other AWS resources.
*
* @example
* ```js
* api.attachPermissionsToDataSource("Mutation charge", ["s3"]);
* ```
*/
public attachPermissionsToDataSource(
key: string,
permissions: Permissions
): void {
const fn = this.getFunction(key);
if (!fn) {
throw new Error(
`Failed to attach permissions. Function does not exist for key "${key}".`
);
}
fn.attachPermissions(permissions);
}
public getConstructMetadata() {
return {
type: "AppSync" as const,
data: {
url: this.cdk.graphqlApi.graphqlUrl,
appSyncApiId: this.cdk.graphqlApi.apiId,
appSyncApiKey: this.cdk.graphqlApi.apiKey,
customDomainUrl: this._customDomainUrl,
dataSources: Object.entries(this.dataSourcesByDsKey).map(([key]) => ({
name: key,
fn: getFunctionRef(this.functionsByDsKey[key]),
})),
},
};
}
/** @internal */
public getBindings() {
// Do not bind imported AppSync APIs b/c we don't know the API URL
if (!this.url) {
return;
}
return {
clientPackage: "api",
variables: {
url: {
type: "plain",
value: this.customDomainUrl || this.url,
},
},
permissions: {},
} as BindingProps;
}
private createGraphApi() {
const { schema, customDomain, cdk } = this.props;
const id = this.node.id;
const app = this.node.root as App;
if (isCDKConstruct(cdk?.graphqlApi)) {
if (customDomain !== undefined) {
throw new Error(
`Cannot configure the "customDomain" when "graphqlApi" is a construct`
);
}
this.cdk.graphqlApi = cdk?.graphqlApi as GraphqlApi;
} else {
const graphqlApiProps = (cdk?.graphqlApi ||
{}) as AppSyncApiCdkGraphqlProps;
// build schema
let mainSchema: SchemaFile;
if (!schema) {
throw new Error(`Missing "schema" in "${id}" AppSyncApi`);
} else if (typeof schema === "string") {
mainSchema = SchemaFile.fromAsset(schema);
} else {
if (schema.length === 0) {
throw new Error(
"Invalid schema. At least one schema file must be provided"
);
}
// merge schema files
const mergedSchema = mergeTypeDefs(
schema.map((file) => fs.readFileSync(file).toString())
);
const filePath = path.join(
useProject().paths.out,
`appsyncapi-${id}-${this.node.addr}.graphql`
);
fs.writeFileSync(filePath, print(mergedSchema));
mainSchema = SchemaFile.fromAsset(filePath);
}
// build domain
const domainData = appSyncApiDomain.buildCustomDomainData(
this,
customDomain
);
this._customDomainUrl =
domainData && `https://${domainData.domainName}/graphql`;
this.cdk.graphqlApi = new GraphqlApi(this, "Api", {
name: app.logicalPrefixedName(id),
xrayEnabled: true,
definition: Definition.fromSchema(mainSchema),
domainName: domainData && {
certificate: domainData.certificate,
domainName: domainData.domainName,
},
...graphqlApiProps,
});
this.cdk.certificate = domainData?.certificate;
if (domainData) {
appSyncApiDomain.cleanup(this, domainData);
}
}
}
private addDataSource(
scope: Construct,
dsKey: string,
dsValue:
| FunctionInlineDefinition
| AppSyncApiLambdaDataSourceProps
| AppSyncApiDynamoDbDataSourceProps
| AppSyncApiRdsDataSourceProps
| AppSyncApiOpenSearchDataSourceProps
| AppSyncApiHttpDataSourceProps
| AppSyncApiNoneDataSourceProps
) {
let dataSource;
let lambda: Fn | undefined;
// Lambda function
if (Fn.isInlineDefinition(dsValue)) {
lambda = Fn.fromDefinition(
scope,
`Lambda_${dsKey}`,
dsValue,
this.props.defaults?.function,
`Cannot define defaults.function when a Function is passed in to the "${dsKey} data source`
);
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addLambdaDataSource(dsKey, lambda)
: new LambdaDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
lambdaFunction: lambda,
});
}
// DynamoDb ds
else if (dsValue.type === "dynamodb") {
const dsTable = dsValue.table
? dsValue.table.cdk.table
: dsValue.cdk?.dataSource?.table!;
const dsOptions = {
name: dsValue.name,
description: dsValue.description,
};
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addDynamoDbDataSource(dsKey, dsTable, dsOptions)
: new DynamoDbDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
table: dsTable,
...dsOptions,
});
}
// RDS ds
else if (dsValue.type === "rds") {
const dsCluster = dsValue.rds
? dsValue.rds.cdk.cluster
: dsValue.cdk?.dataSource?.serverlessCluster!;
const dsSecret = dsValue.rds
? dsValue.rds.cdk.cluster.secret!
: dsValue.cdk?.dataSource?.secretStore!;
const dsDatabaseName = dsValue.rds
? dsValue.databaseName || dsValue.rds.defaultDatabaseName
: dsValue.cdk?.dataSource?.databaseName;
const dsOptions = {
name: dsValue.name,
description: dsValue.description,
};
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addRdsDataSource(
dsKey,
dsCluster,
dsSecret,
dsDatabaseName,
dsOptions
)
: new RdsDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
serverlessCluster: dsCluster,
secretStore: dsSecret,
databaseName: dsDatabaseName,
...dsOptions,
});
}
// OpenSearch ds
else if (dsValue.type === "open_search") {
const dsOptions = {
name: dsValue.name,
description: dsValue.description,
};
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addOpenSearchDataSource(
dsKey,
dsValue.cdk?.dataSource?.domain!,
dsOptions
)
: new OpenSearchDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
domain: dsValue.cdk?.dataSource?.domain!,
...dsOptions,
});
}
// Http ds
else if (dsValue.type === "http") {
const dsOptions = {
name: dsValue.name,
description: dsValue.description,
};
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addHttpDataSource(
dsKey,
dsValue.endpoint,
dsOptions
)
: new HttpDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
endpoint: dsValue.endpoint,
...dsOptions,
});
}
// Http ds
else if (dsValue.type === "none") {
const dsOptions = {
name: dsValue.name,
description: dsValue.description,
};
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addNoneDataSource(dsKey, dsOptions)
: new NoneDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
...dsOptions,
});
}
// Lambda ds
else {
lambda = Fn.fromDefinition(
scope,
`Lambda_${dsKey}`,
dsValue.function,
this.props.defaults?.function,
`Cannot define defaults.function when a Function is passed in to the "${dsKey} data source`
);
const dsOptions = {
name: dsValue.name,
description: dsValue.description,
};
dataSource = this.isSameStack(scope)
? this.cdk.graphqlApi.addLambdaDataSource(dsKey, lambda, dsOptions)
: new LambdaDataSource(scope, dsKey, {
api: this.cdk.graphqlApi,
lambdaFunction: lambda,
...dsOptions,
});
}
this.dataSourcesByDsKey[dsKey] = dataSource;
if (lambda) {
this.functionsByDsKey[dsKey] = lambda;
// attached existing permissions
this.permissionsAttachedForAllFunctions.forEach((permissions) =>
lambda!.attachPermissions(permissions)
);
lambda.bind(this.bindingForAllFunctions);
}
}
private addResolver(
scope: Construct,
resKey: string,
resValue: FunctionInlineDefinition | AppSyncApiResolverProps
): Fn | undefined {
// Normalize resKey