-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
175 lines (161 loc) · 5.07 KB
/
index.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
import {
TransformerNestedStack,
TransformerPluginBase,
} from "@aws-amplify/graphql-transformer-core";
import {
TransformerContextProvider,
TransformerPluginProvider,
TransformerSchemaVisitStepContextProvider,
TransformerTransformSchemaStepContextProvider,
} from "@aws-amplify/graphql-transformer-interfaces";
import {
makeField,
makeInputValueDefinition,
makeNamedType,
toCamelCase,
toPascalCase,
} from "graphql-transformer-common";
import {
DirectiveNode,
FieldDefinitionNode,
ObjectTypeDefinitionNode,
} from "graphql";
import * as lambda from "@aws-cdk/aws-lambda";
import * as path from "path";
import * as appsync from "@aws-cdk/aws-appsync";
import * as iam from "@aws-cdk/aws-iam";
export default class CountTransformer
extends TransformerPluginBase
implements TransformerPluginProvider
{
models: ObjectTypeDefinitionNode[];
constructor() {
super("count", "directive @count on OBJECT");
this.models = [];
}
object = (
definition: ObjectTypeDefinitionNode,
directive: DirectiveNode,
ctx: TransformerSchemaVisitStepContextProvider
) => {
// Keep track of everything annotated with @count
this.models.push(definition);
};
transformSchema = (ctx: TransformerTransformSchemaStepContextProvider) => {
const fields: FieldDefinitionNode[] = [];
// For each model that has been annotated with @count
for (const model of this.models) {
if (!model.directives?.find((dir) => dir.name.value === "model")) {
throw new Error(
"Any type annotated with @count must also be annotated with @model, as it re-uses types from that directive."
);
}
// The top level field inside Query
const queryName = toCamelCase(["count", model.name.value]);
// The name of the filter argument to count()
const filterInputName = toPascalCase([
"Model",
model.name.value,
"FilterInput",
]);
// Make the actual Query field
// e.g. countHits(filter: ModelHitFilterInput): Int
fields.push(
makeField(
queryName,
[makeInputValueDefinition("filter", makeNamedType(filterInputName))],
makeNamedType("Int")
)
);
}
ctx.output.addQueryFields(fields);
};
generateResolvers = (ctx: TransformerContextProvider) => {
// Path on the local filesystem to the handler zip file
const HANDLER_LOCAL_PATH = path.join(__dirname, "handler.zip");
const stack: TransformerNestedStack = ctx.stackManager.createStack(
"countResolverStack"
) as TransformerNestedStack;
const funcId = "countResolverFunc";
const HANDLER_S3_PATH = `functions/${funcId}.zip`;
// Create the resolver function. This can be shared across all tables since it receives a different payload
// for each table
const funcRole = new iam.Role(stack, `${funcId}LambdaRole`, {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
});
const func = ctx.api.host.addLambdaFunction(
"countResolver",
HANDLER_S3_PATH,
"index.handler",
HANDLER_LOCAL_PATH,
lambda.Runtime.NODEJS_14_X,
undefined, // layers
funcRole, // execution role,
undefined, // env vars
undefined, // lambda timeout
stack
);
funcRole.addManagedPolicy(
iam.ManagedPolicy.fromAwsManagedPolicyName(
"service-role/AWSLambdaBasicExecutionRole"
)
);
// Make this lambda into a data source
const dataSource = ctx.api.host.addLambdaDataSource(
`countResolverDataSource`,
func,
{},
stack
);
for (const model of this.models) {
// Find the table we want to scan
const tableDataSource = ctx.dataSources.get(
model
) as appsync.DynamoDbDataSource;
const table = tableDataSource.ds
.dynamoDbConfig as appsync.CfnDataSource.DynamoDBConfigProperty;
// Allow the lambda to access this table
funcRole.addToPolicy(
new iam.PolicyStatement({
actions: ["dynamodb:Scan"],
effect: iam.Effect.ALLOW,
resources: [
`arn:aws:dynamodb:${table.awsRegion}:${stack.account}:table/${table.tableName}`,
],
})
);
// Connect the resolver to the API
const resolver = new appsync.CfnResolver(
stack,
`${model.name.value}CountResolver`,
{
apiId: ctx.api.apiId,
fieldName: toCamelCase(["count", model.name.value]),
typeName: "Query",
kind: "UNIT",
dataSourceName: dataSource?.ds.attrName,
requestMappingTemplate: `
$util.toJson({
"version": "2018-05-29",
"operation": "Invoke",
"payload": {
"context": $ctx,
"dynamo": $util.parseJson($util.transform.toDynamoDBFilterExpression($ctx.arguments.filter)),
"tableName": "${table.tableName}"
}
})
`,
responseMappingTemplate: `
#if( $ctx.error )
$util.error($ctx.error.message, $ctx.error.type)
#else
$util.toJson($ctx.result)
#end
`,
}
);
// resolver.overrideLogicalId(resourceId);
ctx.api.addSchemaDependency(resolver);
}
};
}