Navigation

AWS Service

Overview

Amazon Web Services (AWS) provides an extensive collection of cloud-based services. Stitch provides a generic AWS service that enables you to connect to many of these services.

Configuration Parameters

You will need to provide values for the following parameters when you create an AWS service interface:

<Service Name>/config.json
{
  "name": "<Service Name>",
  "type": "aws",
  "config": {
    "accessKeyId": <Access Key ID>,
    "region": "us-east-1"
  }
}
/secrets.json
{
  "services": {
    "<Service Name>": {
      "secretAccessKey" <Secret Access Key>
    }
  }
}
Parameter Description

Service Name

config.name
A unique name for the service.

Access Key ID

config.accessKeyId
The ID for an AWS IAM user. The user should have appropriate permissions for all AWS services that you plan to interact with.

Secret Access Key

services.<service name>.secretAccessKey
The secret key for the IAM user whose ID is specified in Access Key ID.

Service Actions

Each AWS service has different actions that you can perform on that service. Stitch uses the action names specified in the AWS SDK for Go for each service.

Note

Stitch uses the same names (and casing) for the AWS services and actions as the AWS Go SDK.

For each supported AWS service, Stitch supports any action that:

  1. Takes a single input parameter.
  2. Returns one of two objects: an output object, or an error.

For example, the S3 service includes a PutObject action. Stitch supports this action because it takes a single input type of PutObjectInput , and returns either a PutObjectOutput or an error.

AWS Service Rules

You must specify rules to enable the AWS services and actions. Each rule applies to a single service API, plus one or all actions on that service. As with other service rules in Stitch, a rule must evaluate to true to enable the action.

For example, the following rule enables all actions on the Kinesis service:

AWS Kinesis rule.

Note

The default value of the When field contains only empty brackets, which means the rule will always evaluate to true, and therefore all calls to the action are valid.

This rule can also be expressed as the following JSON expression. Note that in the array of actions, the asterisk (*) after the service name indicates that all actions of that service are enabled:

{
   "name": "kinesis",
   "actions": [
      "kinesis:*"
   ]
}

Rule Conditions

For each service action, the rule you create may include any of the properties of the input object for that action as a condition for validating the rule. The %%args expansion provides access to these properties.

Example

The S3 service includes the PutObject Action, which takes an input object of type of PutObjectInput. The PutObjectInput object contains several properties, any of which you can put in the When clause of your rule.

Using the Bucket property of the PutObjectInput object, you can create a rule that enables the PutObject action on the S3 service, but restricts the action to a list of approved buckets. In this example, we use a user-defined constant called myS3Buckets for the list of approved bucket names:

AWS S3 rule

This can also be expressed as the following JSON:

{
   "name": "s3",
   "actions": [
      "s3:PutObject"
   ],
   "when": {
      "%%args.Bucket": {
            "%in": "%%values.myS3Buckets"
      }
   }
}

Usage

You can call an AWS service from a Stitch function and from the SDKs. The following sections show each of these processes.

Call an AWS Service from a Stitch Function

The following examples show how to call various AWS services from within a Stitch function. In each example, it is assumed the named service has already been created.

S3 Service

exports = async function() {
  const s3 = context.services.get('MyAwsService').s3("us-east-1");
  try {
    const result = await s3.PutObject({
      "Bucket": "my-bucket",
      "Key": "example",
      "Body": "hello there"
    });
    console.log(EJSON.stringify(result));
    return result;
  } catch(error) {
    console.error(EJSON.stringify(error));
  }
};

Refer to the S3 API Reference for implementation details.

Kinesis Service

exports = async function(event) {
  const kinesis = context.services.get('MyAwsService').kinesis();
  try {
    const result = await kinesis.PutRecord({
      Data: JSON.stringify(event.fullDocument),
      StreamName: "stitchStream",
      PartitionKey: "1"
    });
    console.log(EJSON.stringify(result));
    return result;
  } catch(error) {
    console.error(EJSON.stringify(error));
  }
};

Refer to the Kinesis API Reference for implementation details.

Lambda Service

exports = async function() {
  const lambda = context.services.get('MyAwsService').lambda();
  try {
    const result = await lambda.Invoke({
      FunctionName: "myLambdaTest",
      Payload: context.user.id
    });
    console.log(EJSON.stringify(result));
    return result;
  } catch(error) {
     console.error(EJSON.stringify(error));
  }
};

Refer to the Lambda API Reference for implementation details.

SES Service

exports = async function(){
  const ses = context.services.get('MyAwsService').ses();
  try {
    const result = await ses.SendEmail({
      Source: "sender@example.com",
      Destination: { ToAddresses: ["docs@mongodb.com"] },
      Message: {
        Body: {
          Html: {
            Charset: "UTF-8",
            Data: `This is a message from user ${context.user.id}`
          }
        },
        Subject: {
          Charset: "UTF-8",
          Data: "Test Email Please Ignore"
        }
      }
    });
    console.log(EJSON.stringify(result));
    return result;
  } catch(error) {
     console.error(EJSON.stringify(error));
  }
};

Refer to the SES API Reference for implementation details.

Calling an AWS Service from the SDKs

The following example shows how to configure and call an AWS service (S3 in this case) using the AwsServiceClient factory in each SDK.

// MyAwsService is the name of the aws service you created in
// the stitch UI, and it is configured with a rule
// that allows the PutObject action on the s3 API
const aws = stitchClient.getServiceClient(AwsServiceClient.factory, "MyAwsService");

// These are the arguments specifically for the s3 service PutObject function
const args = {
   ACL: "public-read",
   Bucket: "this-should-be-a-valid-s3-bucket",
   ContentType: "plain/text",
   Key: "some_key",
   Body: "This is the body of the message I am saving to S3",
   // or Body could be a BSON object
};

const request = new AwsRequest.Builder()
   .withService("s3")
   .withAction("PutObject")
   .withRegion("us-east-1") // this is optional
   .withArgs(args); // depending on the service and action, this may be optional as well

aws.execute(request.build())
   .then(result => {
      // the shape of the result will depend on the AWS function being called
   }).catch(err => {
      // handle failure
   });
// MyAwsService is the name of the aws service you created in
// the stitch UI, and it is configured with a rule
// that allows the PutObject action on the s3 API
final AwsServiceClient aws = stitchClient.getServiceClient(AwsServiceClient.factory, "MyAwsService");

// These are the arguments specifically for s3 service PutObject function
final Document args = new Document()
   .append("Bucket", "this-should-be-a-valid-s3-bucket")
   .append("Key", "some_key")
   .append("ACL", "public-read")
   .append("ContentType", "plain/text")
   .append("Body", "This is the body of the message I am saving to S3");
   //or .append("Body", new BsonBinary(myByteArray));

AwsRequest.Builder request = new AwsRequest.Builder()
   .withService("s3")
   .withAction("PutObject")
   // .withRegion("us-east-1") // this is optional
   .withArguments(args);

// depending on the service and action, this may be optional as well
aws.execute(request.build(), Document.class)
   .addOnCompleteListener(new OnCompleteListener<Document>() {
        @Override
        public void onComplete(@NonNull Task<Document> task) {
            if (task.isSuccessful()) {
                final Document result = task.getResult();
                // the shape of the result will depend on the AWS function being called
            } else {
                // handle failure
            }
        }
    });
// MyAwsService is the name of the aws service you created in
// the stitch UI, and it is configured with a rule
// that allows the PutObject action on the s3 API
let aws = client.serviceClient(fromFactory: awsServiceClientFactory, withName: "MyAwsService")

// These are the arguments specifically for s3 service PutObject function
let args: Document = [
   "Bucket": "this-should-be-a-valid-s3-bucket",
   "Key": "some_key",
   "ACL": "public-read",
   "ContentType": "plain/text",
   "Body": "This is the body of the message I am saving to S3",
   // or "Body": Binary.init(...)
]

let request = try AWSRequestBuilder()
   .with(service: "s3")
   .with(action: "PutObject")
   // .with(region: "us-east-1") // this is optional
   .with(arguments: args) // depending on the service and action, this may be optional as well

aws.execute(request.build()) { (result: StitchResult<Document>) in
   switch result {
   case .success(let awsResult):
      // the shape of the result will depend on the AWS function being called
   case .failure:
      // handle failure
   }
}

Supported AWS Services

Your Stitch app can connect to the following AWS services:

  • Athena
  • Batch
  • CloudWatch
  • EC2
  • Firehose
  • Glacier
  • IOT
  • Kinesis
  • Lambda
  • Lex Runtime Service
  • Machine Learning
  • Mobile Analytics
  • Polly
  • RDS
  • Redshift
  • Rekognition
  • S3
  • SES
  • Step Functions (SFN)
  • SNS
  • SQS