Page updated Jan 16, 2024

Authoring a new plugin

The Amplify CLI provides the command amplify plugin init (with alias amplify plugin new) for the development of plugins. This command first collects requirements, and then creates the skeleton of the plugin package for you to start the development. The newly created plugin is added to your local Amplify CLI plugin platform, so you can conveniently test its functionalities while it is being developed. It can be easily removed from the local plugin platform with the amplify plugin remove command, and added back with the amplify plugin add command.

Step 1: Install Amplify CLI

1npm install -g @aws-amplify/cli
1curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL
1curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd

Step 2: Initialize plugin

1amplify plugin init

You will be prompted to enter the plugin name, then select the plugin type, and event subscriptions. The CLI will then create a plugin package for you and add it to the local Amplify CLI plugin platform.

Step 3: Test your plugin

The newly created plugin package is already added to the local Amplify CLI, so you can start testing it immediately. Let's say you have chosen to use the default plugin name: my-amplify-plugin

1$ amplify my-amplify-plugin help
2help command to be implemented.

You will see that the default help message is printed out. At this point, there are only two sub commands in the plugin package, help and version, with dummy implementations. If you try to execute any other command, it will trigger the Amplify CLI plugin platform to perform a fresh scan, and then after it failed to find the command, it will print out the default help message.

From here, you can start to develop the plugin package. See below for the detailed explanation of the package structure.

Step 4: Publish to NPM

After the completion of one development cycle and you are ready to release your plugin to the public, you can publish it to the NPM: https://docs.npmjs.com/getting-started/publishing-npm-packages

Step 5: Install and Use

Once your plugin is published to the NPM, other developers can install and use it

1npm install -g my-amplify-plugin
2amplify plugin add my-amplify-plugin
3amplify my-amplify-plugin help

Plugin Package Structure

Here's the plugin package directory structure

1|_my-amplify-plugin/
2 |_commands/
3 | |_ help.js
4 | |_ version.js
5 |
6 |_event-handlers
7 | |_handle-PostInit.js
8 | |_handle-PostPush.js
9 | |_handle-PreInit.js
10 | |_handle-PrePush.js
11 |
12 |_amplify-plugin.json
13 |_index.js
14 |_package.json

amplify-plugin.json

The amplify-plugin.json file is the plugin's manifest file, it specifies the plugin's name, type, commands and event handlers. The Amplify CLI uses it to verify and add the plugin package into its plugin platform.

Here's the contents of the file when it's first generated by the amplify plugin init command for a util plugin.

1{
2 "name": "my-amplify-plugin",
3 "type": "util",
4 "commands": [
5 "version",
6 "help"
7 ],
8 "eventHandlers": [
9 "PreInit",
10 "PostInit",
11 "PrePush",
12 "PostPush"
13 ]
14}

index.js

The "main" file specified in the package.json is the Amplify CLI's entry to invoke the plugin's functionalities specified in the manifest file amplify-plugin.json.

Here's the contents of the file when it's first generated by the amplify plugin init command for a util plugin.

1const path = require('path');
2
3async function executeAmplifyCommand(context) {
4 const commandsDirPath = path.normalize(path.join(__dirname, 'commands'));
5 const commandPath = path.join(commandsDirPath, context.input.command);
6 const commandModule = require(commandPath);
7 await commandModule.run(context);
8}
9
10async function handleAmplifyEvent(context, args) {
11 const eventHandlersDirPath = path.normalize(path.join(__dirname, 'event-handlers'));
12 const eventHandlerPath = path.join(eventHandlersDirPath, `handle-${args.event}`);
13 const eventHandlerModule = require(eventHandlerPath);
14 await eventHandlerModule.run(context, args);
15}
16
17module.exports = {
18 executeAmplifyCommand,
19 handleAmplifyEvent,
20};

commands

The commands folder contains files that implement the commands specified in the manifest file amplify-plugin.json.

event-handlers

The event-handlers folder contains files that implement the eventHandlers specified in the manifest file amplify-plugin.json.

Authoring custom GraphQL transformers & directives

This section outlines the process of writing custom GraphQL transformers. The @aws-amplify/graphql-transformer-core package serves as a lightweight framework that takes as input a GraphQL SDL document and a list of GraphQL Transformers and returns a set of deployment resources that fully implements the data model defined by the input schema. A GraphQL Transformer is a class that defines a directive and a set of functions that manipulate a context and are called whenever that directive is found in an input schema.

For example, the AWS Amplify CLI calls the GraphQL Transform like this:

1import { GraphQLTransform } from '@aws-amplify/graphql-transformer-core';
2import { FeatureFlagProvider, TransformerPluginProvider } from '@aws-amplify/graphql-transformer-interfaces';
3import { AuthTransformer } from '@aws-amplify/graphql-auth-transformer';
4import { BelongsToTransformer, HasManyTransformer, HasOneTransformer, ManyToManyTransformer } from '@aws-amplify/graphql-relational-transformer';
5import { DefaultValueTransformer } from '@aws-amplify/graphql-default-value-transformer';
6import { FunctionTransformer } from '@aws-amplify/graphql-function-transformer';
7import { HttpTransformer } from '@aws-amplify/graphql-http-transformer';
8import { IndexTransformer, PrimaryKeyTransformer } from '@aws-amplify/graphql-index-transformer';
9import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
10import { PredictionsTransformer } from '@aws-amplify/graphql-predictions-transformer';
11import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer';
12
13// This adapter class supports the propagation of feature flag values from the CLI to the transformers
14class TransformerFeatureFlagAdapter implements FeatureFlagProvider {
15 getBoolean(featureName: string, defaultValue?: boolean): boolean {
16 throw new Error('Method not implemented.');
17 }
18 getString(featureName: string, defaultValue?: string): string {
19 throw new Error('Method not implemented.');
20 }
21 getNumber(featureName: string, defaultValue?: number): number {
22 throw new Error('Method not implemented.');
23 }
24 getObject(featureName: string, defaultValue?: object): object {
25 throw new Error('Method not implemented.');
26 }
27}
28
29const modelTransformer = new ModelTransformer();
30const indexTransformer = new IndexTransformer();
31const hasOneTransformer = new HasOneTransformer();
32const authTransformer = new AuthTransformer({
33 authConfig: {
34 defaultAuthentication: {
35 authenticationType: 'API_KEY',
36 },
37 additionalAuthenticationProviders: [
38 {
39 authenticationType: 'AMAZON_COGNITO_USER_POOLS',
40 userPoolConfig: {
41 userPoolId: 'us-east-1_abcdefghi',
42 }
43 }
44 ]
45 },
46 addAwsIamAuthInOutputSchema: true,
47});
48
49const transformers: TransformerPluginProvider[] = [
50 modelTransformer,
51 new FunctionTransformer(),
52 new HttpTransformer(),
53 new PredictionsTransformer(),
54 new PrimaryKeyTransformer(),
55 indexTransformer,
56 new BelongsToTransformer(),
57 new HasManyTransformer(),
58 hasOneTransformer,
59 new ManyToManyTransformer(modelTransformer, indexTransformer, hasOneTransformer, authTransformer),
60 new DefaultValueTransformer(),
61 authTransformer,
62 new SearchableModelTransformer(),
63];
64
65const graphQLTransform = new GraphQLTransform ({
66 transformers,
67 featureFlags: new TransformerFeatureFlagAdapter(),
68 sandboxModeEnabled: false,
69});
70
71const schema = `
72type Post @model {
73 id: ID!
74 title: String!
75 comments: [Comment] @hasMany
76}
77type Comment @model {
78 id: ID!
79 content: String!
80 post: Post @belongsTo
81}
82`;
83
84const { rootStack, stacks, schema } = graphQLTransform.transform(schema);
85
86console.log('Schema compiled successfully.')

As shown above the GraphQLTransform class takes a list of transformers and later is able to transform GraphQL SDL documents into deployment resources, this includes the transformed GraphQL schema, CloudFormation templates, AppSync service resolvers, etc.

The Transform Lifecycle

At a high level the GraphQLTransform takes the input SDL, parses it, and validates the schema is complete and satisfies the directive definitions. It then iterates through the list of transformers passed to the transform when it was created.

In order to support inter communication/dependency between these classes of transformers, the transformation will be done in phases. The table below shows the lifecycle methods that a transformer plugin can implement to handle different phases in the execution of the transformer:

Lifecycle methodDescription
beforeinitialization of the transformer
GraphQL visitor pattern functionsobjectfor each type that has the directive defined by the transformer
interfacefor each interface that has the directive defined by the transformer
fieldfor each field that has the directive defined by the transformer
argumentfor each argument that has the directive defined by the transformer
unionfor each union that has the directive defined by the transformer
enumfor each enum that has the directive defined by the transformer
enumValuefor each enumValue that has the directive defined by the transformer
scalarfor each scalar that has the directive defined by the transformer
inputfor each input that has the directive defined by the transformer
inputValuefor each inputValue that has the directive defined by the transformer
preparetransformer register themselves in the TransformerContext (as data provider or data enhancer)
validatetransformer validates the directive arguments
transformSchematransformer updates/augments the output schema
generateResolverstransformer generates resources such as resolvers, IAM policies, Tables, etc.
aftercleanup, this lifecycle method is invoked in reverse order for the registered transformers

Here is pseudo code for how const { rootStack, stacks, schema } = graphQLTransform.transform(schema); works.

1public transform(schema: string): DeploymentResources {
2
3 // ...
4
5 for (const transformer of this.transformers) {
6 // Run the prepare function one time per transformer.
7 if (isFunction(transformer.before)) {
8 transformer.before(context);
9 }
10
11 // Transform each definition in the input document.
12 for (const def of context.inputDocument.definitions as TypeDefinitionNode[]) {
13 switch (def.kind) {
14 case 'ObjectTypeDefinition':
15 this.transformObject(transformer, def, context);
16 // Walk the fields and call field transformers.
17 break;
18 case 'InterfaceTypeDefinition':
19 this.transformInterface(transformer, def, context);
20 // Walk the fields and call field transformers.
21 break;
22 case 'ScalarTypeDefinition':
23 this.transformScalar(transformer, def, context);
24 break;
25 case 'UnionTypeDefinition':
26 this.transformUnion(transformer, def, context);
27 break;
28 case 'EnumTypeDefinition':
29 this.transformEnum(transformer, def, context);
30 break;
31 case 'InputObjectTypeDefinition':
32 this.transformInputObject(transformer, def, context);
33 break;
34 // Note: Extension and operation definition nodes are not supported.
35 default:
36 continue;
37 }
38 }
39 }
40 }
41
42 // Validate
43 for (const transformer of this.transformers) {
44 if (isFunction(transformer.validate)) {
45 transformer.validate(context);
46 }
47 }
48
49 // Prepare
50 for (const transformer of this.transformers) {
51 if (isFunction(transformer.prepare)) {
52 transformer.prepare(context);
53 }
54 }
55
56 // Transform Schema
57 for (const transformer of this.transformers) {
58 if (isFunction(transformer.transformSchema)) {
59 transformer.transformSchema(context);
60 }
61 }
62
63 // After is called in the reverse order as if they were popping off a stack.
64 let reverseThroughTransformers = this.transformers.length - 1;
65 while (reverseThroughTransformers >= 0) {
66 const transformer = this.transformers[reverseThroughTransformers];
67 if (isFunction(transformer.after)) {
68 transformer.after(context);
69 }
70
71 reverseThroughTransformers -= 1;
72 }
73
74 // ...
75
76 // Return the deployment resources.
77 // In the future there will likely be a formatter concept here.
78 return this.synthesize(context);
79}

The Transformer Context

The transformer context serves like an accumulator that is manipulated by transformers. See the code to see what methods are available to you.

For now, the transformer only support CloudFormation and uses AWS CDK to create CloudFormation resources in code.

Adding Custom GraphQL Transformers to the Project

To add a custom GraphQL transformer to the list of transformers, they need to be registered within the project. This registration can be done by adding an entry to transform.conf.json file which can be found in the amplify/backend/api/<api-name> folder. A transformer can be registered by adding a file URI to the JavaScript file that implements the transformer or by specifying the npm package name. The transformer modules will be dynamically imported during the transform process.

Example transform.conf.json file

1{
2 "transformers":[
3 "some-transformer-via-npm",
4 "file:///some/absolute/local/module"
5 ]
6}

Example

As an example let's walk through how we implemented the @model transformer. The first thing to do is to define a directive for your transformer.

Note: Some parts of the code will not be shown for brevity.

1export const directiveDefinition = /* GraphQL */ `
2 directive @model(
3 queries: ModelQueryMap
4 mutations: ModelMutationMap
5 subscriptions: ModelSubscriptionMap
6 timestamps: TimestampConfiguration
7 ) on OBJECT
8`;

Our @model directive can be applied to OBJECT type definitions and automatically adds CRUD functionality, timestamp fields to an API. For example, we might write:

1type Post @model {
2 id: ID!
3 title: String!
4}

The next step after defining the directive is to implement the transformer's business logic. The @aws-amplify/graphql-transformer-core package makes this a little easier by exporting a common class through which we may define transformers. Users extend the TransformerPluginBase class and implement the required functions.

Note: In this example @model extended from a higher level class, TransformerModelBase.

1export class ModelTransformer extends TransformerModelBase implements TransformerModelProvider {
2 // ...
3}

Since your directiveDefinition only specifies OBJECT in its on condition, we have to implement the object method and some other lifecycle methods like validate, prepare and transformSchema to have a fully functioning transformer. You may implement before and after methods which will be called once at the beginning and end respectively of the transformation process.

1/**
2 * Users extend the TransformerPluginBase class and implement the relevant functions.
3 */
4export class ModelTransformer extends TransformerModelBase implements TransformerModelProvider {
5 constructor(options: ModelTransformerOptions = {}) {
6 super('amplify-model-transformer', directiveDefinition);
7 }
8
9 // ...
10}

The following snippet shows the prepare method implementation which takes all the type from the GraphQL schema and registers the transformer as a data source provider. Data source providers are used by transformers that are creating persistent resources like DynamoDB tables in this case. prepare is the place to register data enhancers as well. Data enhancers are used by transformers that enriching existing types or operations by adding or modifying fields, arguments, etc.

1prepare = (context: TransformerPrepareStepContextProvider) => {
2 for (const modelTypeName of this.typesWithModelDirective) {
3 const type = context.output.getObject(modelTypeName);
4 context.providerRegistry.registerDataSourceProvider(type!, this);
5 }
6 };

For the full source code of the @model transformer, go here.

VS Code Extension

Add the VSCode extension to get code snippets and automatic code completion for Amplify APIs.