├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── client ├── README.md ├── babel.config.js ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ └── index.html └── src │ ├── App.vue │ ├── assets │ └── logo.png │ ├── aws-config.js │ └── main.js ├── images ├── aws-appsync-long-query-sample-client.png └── aws-appsync-long-query.png ├── result ├── event.json ├── index.js ├── package-lock.json └── package.json ├── schema.graphql └── template.yaml /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | packaged.yaml 2 | Rakefile 3 | 4 | .DS_Store 5 | node_modules 6 | /dist 7 | 8 | # local env files 9 | .env.local 10 | .env.*.local 11 | 12 | # Log files 13 | npm-debug.log* 14 | yarn-debug.log* 15 | yarn-error.log* 16 | 17 | # Editor directories and files 18 | .idea 19 | .vscode 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw* 25 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/aws-samples/aws-appsync-long-query/issues), or [recently closed](https://github.com/aws-samples/aws-appsync-long-query/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-samples/aws-appsync-long-query/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/aws-samples/aws-appsync-long-query/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## AWS Appsync Long Query 2 | 3 | > Invoke AWS services directly from AWS AppSync via extended HTTP data source support. 4 | 5 | AWS AppSync has been extended to support directly calling AWS services via HTTP data sources. AppSync will sign requests using the Signature Version 4 process to authorize requests via AWS IAM. This means you can now call a broad array of AWS services without the need to write an intermediary Lambda function. For example, you could start execution of an AWS Step Functions state machine, retrieve a secret from AWS Secrets Manager, or list available GraphQL APIs from AppSync itself directly from an AppSync resolver. 6 | 7 | In this example, we start execution of an AWS Step Function state machine directly from AppSync to demonstrate invoking a long-running query that requires more than the 30-second maximum timeout allowed by AppSync. The state machine executes a one-minute wait before returning a fake result. 8 | 9 | ![AWS AppSync Long Query Architecture](images/aws-appsync-long-query.png) 10 | 11 | More information can be found in the accompanying blog post. 12 | 13 | ## Getting Started 14 | 15 | To get started, clone this repository. The repository contains an [AWS SAM Template](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) template, sample client application, and source code to deploy and run the sample. 16 | 17 | ### Prerequisites 18 | 19 | To run the sample, you will need to: 20 | 21 | 1. Select an AWS region that offers AWS AppSync (currently N. Virginia, Ohio, Oregon, Ireland, Frankfurt, London, Singapore, Tokyo, Sydney, Seoul, and Mumbai). 22 | 2. [Install the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html). 23 | 3. If you would like to run the sample client, you will need to [install Vue.js](https://vuejs.org/v2/guide/installation.html). 24 | 25 | ## Deployment 26 | 27 | We will use AWS SAM to deploy cloud resources: 28 | 29 | ``` bash 30 | # install node modules 31 | $ cd result && npm install & cd .. 32 | 33 | # select a unique bucket name 34 | $ aws s3 mb s3:// 35 | 36 | # package for deployment 37 | $ sam package --output-template-file packaged.yaml \ 38 | --s3-bucket 39 | 40 | # deploy cloud resources 41 | $ sam deploy --template-file packaged.yaml \ 42 | --stack-name appsync-long-query \ 43 | --capabilities CAPABILITY_NAMED_IAM 44 | ``` 45 | 46 | Once deployment is finished, we can collect a few items to configure the sample client application. Open the file `client/src/aws-config.js` in your favorite text editor. Set the value of `aws_appsync_region` to the region you selected (e.g. N. Virginia = us-east-1). Set the other values by retrieving output data from the SAM stack: 47 | 48 | ``` bash 49 | # aws_appsync_graphqlEndpoint 50 | $ aws cloudformation describe-stacks --stack-name appsync-long-query \ 51 | --query 'Stacks[0].Outputs[?OutputKey==`ApiEndpoint`].OutputValue' 52 | 53 | # aws_appsync_apiKey 54 | $ aws cloudformation describe-stacks --stack-name appsync-long-query \ 55 | --query 'Stacks[0].Outputs[?OutputKey==`ApiKey`].OutputValue' 56 | ``` 57 | 58 | After saving your changes, start the sample Vue application: 59 | 60 | ``` bash 61 | $ cd client && npm install 62 | $ npm run serve 63 | ``` 64 | 65 | Open your browser and navigate to http://localhost:8080. Click the "Search" button. View the initial response from your GraphQL API, which will automatically update the final result after approximately one minute. Use your browser's developer tools to review the Console and Network requests. 66 | 67 | ![Sample Client](images/aws-appsync-long-query-sample-client.png) 68 | 69 | ## Cleaning Up 70 | 71 | Once finished, feel free to clean-up the sample code: 72 | 73 | ``` bash 74 | $ aws cloudformation delete-stack \ 75 | --stack-name appsync-long-query 76 | 77 | $ aws s3 rm s3:// 78 | ``` 79 | 80 | Thanks! 81 | 82 | ## License Summary 83 | 84 | This sample code is made available under a modified MIT license. See the LICENSE file. 85 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # client 2 | 3 | ## Project setup 4 | ``` 5 | npm install 6 | ``` 7 | 8 | ### Compiles and hot-reloads for development 9 | ``` 10 | npm run serve 11 | ``` 12 | 13 | ### Compiles and minifies for production 14 | ``` 15 | npm run build 16 | ``` 17 | 18 | ### Run your tests 19 | ``` 20 | npm run test 21 | ``` 22 | 23 | ### Lints and fixes files 24 | ``` 25 | npm run lint 26 | ``` 27 | 28 | ### Customize configuration 29 | See [Configuration Reference](https://cli.vuejs.org/config/). 30 | -------------------------------------------------------------------------------- /client/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/app' 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "aws-amplify": "^1.3.3", 12 | "aws-amplify-vue": "^0.2.17", 13 | "vue": "^2.6.11" 14 | }, 15 | "devDependencies": { 16 | "@vue/cli-plugin-babel": "^3.12.1", 17 | "@vue/cli-plugin-eslint": "^3.12.1", 18 | "@vue/cli-service": "^4.2.3", 19 | "babel-eslint": "^10.1.0", 20 | "eslint": "^5.16.0", 21 | "eslint-plugin-vue": "^5.2.3", 22 | "vue-template-compiler": "^2.6.11" 23 | }, 24 | "eslintConfig": { 25 | "root": true, 26 | "env": { 27 | "node": true 28 | }, 29 | "extends": [ 30 | "plugin:vue/essential", 31 | "eslint:recommended" 32 | ], 33 | "rules": {}, 34 | "parserOptions": { 35 | "parser": "babel-eslint" 36 | } 37 | }, 38 | "postcss": { 39 | "plugins": { 40 | "autoprefixer": {} 41 | } 42 | }, 43 | "browserslist": [ 44 | "> 1%", 45 | "last 2 versions", 46 | "not ie <= 8" 47 | ] 48 | } 49 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-archives/aws-appsync-long-query/a143cd2b5ccb7dae83abf31221f3d79537941edf/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | aws-appsync-long-query 9 | 10 | 11 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /client/src/App.vue: -------------------------------------------------------------------------------- 1 | 5 | 14 | 15 | 72 | 73 | 83 | -------------------------------------------------------------------------------- /client/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-archives/aws-appsync-long-query/a143cd2b5ccb7dae83abf31221f3d79537941edf/client/src/assets/logo.png -------------------------------------------------------------------------------- /client/src/aws-config.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | const config = { 5 | aws_appsync_graphqlEndpoint: "https://u4iapc6ylvga7oe5cqjnk7pcqe.appsync-api.us-east-1.amazonaws.com/graphql", 6 | aws_appsync_region: "us-east-1", 7 | aws_appsync_authenticationType: "API_KEY", 8 | aws_appsync_apiKey: "da2-cmufowuchbdcri7cfp6gjvldz4" 9 | }; 10 | 11 | export default config; 12 | -------------------------------------------------------------------------------- /client/src/main.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | import Vue from 'vue'; 5 | import App from './App.vue'; 6 | 7 | import Amplify, * as AmplifyModules from 'aws-amplify'; 8 | import awsmobile from './aws-config'; 9 | Amplify.configure(awsmobile); 10 | 11 | Vue.use(AmplifyModules); 12 | 13 | Vue.config.productionTip = false; 14 | 15 | new Vue({ 16 | render: h => h(App), 17 | }).$mount('#app') 18 | -------------------------------------------------------------------------------- /images/aws-appsync-long-query-sample-client.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-archives/aws-appsync-long-query/a143cd2b5ccb7dae83abf31221f3d79537941edf/images/aws-appsync-long-query-sample-client.png -------------------------------------------------------------------------------- /images/aws-appsync-long-query.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-archives/aws-appsync-long-query/a143cd2b5ccb7dae83abf31221f3d79537941edf/images/aws-appsync-long-query.png -------------------------------------------------------------------------------- /result/event.json: -------------------------------------------------------------------------------- 1 | { "name": "b9d36474-e607-4f93-bcf5-5d296141f7fe" } -------------------------------------------------------------------------------- /result/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: MIT-0 3 | 4 | //// 5 | const axios = require('axios'); 6 | 7 | //// 8 | const PublishResultMutation = `mutation PublishResult( 9 | $id: ID!, 10 | $status: ResultStatus!, 11 | $listings: [String]! 12 | ) { 13 | publishResult(result: {id: $id, status: $status, listings: $listings}) { 14 | id 15 | status 16 | listings 17 | } 18 | }`; 19 | 20 | /** 21 | * Executes mutation on AppSync API. 22 | */ 23 | const executeMutation = async(id) => { 24 | const mutation = { 25 | query: PublishResultMutation, 26 | operationName: 'PublishResult', 27 | variables: { 28 | id: id, 29 | status: 'COMPLETE', 30 | listings: [ "foo", "bar" ] 31 | }, 32 | }; 33 | 34 | try { 35 | let response = await axios({ 36 | method: 'POST', 37 | url: process.env.APPSYNC_ENDPOINT, 38 | data: JSON.stringify(mutation), 39 | headers: { 40 | 'Content-Type': 'application/json', 41 | 'x-api-key': process.env.APPSYNC_API_KEY, 42 | } 43 | }); 44 | console.log(response.data); 45 | } catch (error) { 46 | console.error(`[ERROR] ${error.response.status} - ${error.response.data}`); 47 | throw error; 48 | } 49 | }; 50 | 51 | /** 52 | * Main handler function. 53 | */ 54 | exports.handler = async(event) => { 55 | await executeMutation(event.name); 56 | return { message: `finished` }; 57 | } -------------------------------------------------------------------------------- /result/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-appsync-long-query-result", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "axios": { 8 | "version": "0.18.1", 9 | "resolved": "https://registry.npmjs.org/axios/-/axios-0.18.1.tgz", 10 | "integrity": "sha512-0BfJq4NSfQXd+SkFdrvFbG7addhYSBA2mQwISr46pD6E5iqkWg02RAs8vyTT/j0RTnoYmeXauBuSv1qKwR179g==", 11 | "requires": { 12 | "follow-redirects": "1.5.10", 13 | "is-buffer": "^2.0.2" 14 | } 15 | }, 16 | "debug": { 17 | "version": "3.1.0", 18 | "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", 19 | "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", 20 | "requires": { 21 | "ms": "2.0.0" 22 | } 23 | }, 24 | "follow-redirects": { 25 | "version": "1.5.10", 26 | "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", 27 | "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", 28 | "requires": { 29 | "debug": "=3.1.0" 30 | } 31 | }, 32 | "is-buffer": { 33 | "version": "2.0.4", 34 | "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz", 35 | "integrity": "sha512-Kq1rokWXOPXWuaMAqZiJW4XxsmD9zGx9q4aePabbn3qCRGedtH7Cm+zV8WETitMfu1wdh+Rvd6w5egwSngUX2A==" 36 | }, 37 | "ms": { 38 | "version": "2.0.0", 39 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 40 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /result/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-appsync-long-query-result", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "author": "jkahn@", 7 | "license": "Apache-2.0", 8 | "dependencies": { 9 | "axios": "^0.18.1" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /schema.graphql: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | type Result { 5 | id: ID! 6 | status: ResultStatus! 7 | listings: [String] 8 | } 9 | 10 | enum ResultStatus { 11 | PENDING 12 | COMPLETE 13 | ERROR 14 | } 15 | 16 | input ResultInput { 17 | id: ID! 18 | status: ResultStatus! 19 | listings: [String]! 20 | } 21 | 22 | type Query { 23 | # called by client to initiate long running search 24 | search(text: String!): Result 25 | } 26 | 27 | type Mutation { 28 | # called by backend when search is complete 29 | publishResult(result: ResultInput): Result 30 | } 31 | 32 | type Subscription { 33 | onSearchResult(id: ID!): [Result] 34 | @aws_subscribe(mutations: [ "publishResult" ]) 35 | } 36 | 37 | schema { 38 | query: Query 39 | mutation: Mutation 40 | subscription: Subscription 41 | } -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | 4 | --- 5 | AWSTemplateFormatVersion: '2010-09-09' 6 | 7 | Transform: 'AWS::Serverless-2016-10-31' 8 | 9 | Description: AWS AppSync Long Running Query 10 | 11 | Resources: 12 | ## AppSync ## 13 | SearchApi: 14 | Type: AWS::AppSync::GraphQLApi 15 | Properties: 16 | AuthenticationType: API_KEY 17 | Name: SearchApi 18 | 19 | SearchApiKey: 20 | Type: AWS::AppSync::ApiKey 21 | Properties: 22 | ApiId: !GetAtt SearchApi.ApiId 23 | Description: API Key for Search API 24 | 25 | MessagesSchema: 26 | Type: AWS::AppSync::GraphQLSchema 27 | Properties: 28 | ApiId: !GetAtt SearchApi.ApiId 29 | DefinitionS3Location: schema.graphql 30 | 31 | 32 | SearchQueryResolver: 33 | Type: AWS::AppSync::Resolver 34 | Properties: 35 | ApiId: !GetAtt SearchApi.ApiId 36 | TypeName: Query 37 | FieldName: search 38 | DataSourceName: !GetAtt StepFunctionsHttpDataSource.Name 39 | # Generate a unique execution id for the step function execution so 40 | # that it can be passed through to Lambda on Step Function start. 41 | # Use context stash so it is also available in response mapping. 42 | RequestMappingTemplate: !Sub | 43 | $util.qr($ctx.stash.put("executionId", $util.autoId())) 44 | 45 | { 46 | "version": "2018-05-29", 47 | "method": "POST", 48 | "resourcePath": "/", 49 | "params": { 50 | "headers": { 51 | "content-type": "application/x-amz-json-1.0", 52 | "x-amz-target":"AWSStepFunctions.StartExecution" 53 | }, 54 | "body": { 55 | "stateMachineArn": "${SearchStateMachine}", 56 | "input": "{ \"name\": \"$ctx.stash.executionId\" }" 57 | } 58 | } 59 | } 60 | # Return the execution id from Step Functions for client to subscribe. 61 | ResponseMappingTemplate: | 62 | { 63 | "id": "${ctx.stash.executionId}", 64 | "status": "PENDING" 65 | } 66 | 67 | PublishResultMutationResolver: 68 | Type: AWS::AppSync::Resolver 69 | Properties: 70 | ApiId: !GetAtt SearchApi.ApiId 71 | TypeName: Mutation 72 | FieldName: publishResult 73 | DataSourceName: !GetAtt PublishResultDataSource.Name 74 | RequestMappingTemplate: | 75 | { 76 | "version": "2017-02-28", 77 | "payload": { 78 | "id": "${ctx.arguments.result.id}", 79 | "status": "${ctx.arguments.result.status}", 80 | "listings": "${ctx.arguments.result.listings}" 81 | } 82 | } 83 | ResponseMappingTemplate: | 84 | $util.toJson($ctx.arguments.result) 85 | 86 | StepFunctionsHttpDataSource: 87 | Type: AWS::AppSync::DataSource 88 | Properties: 89 | ApiId: !GetAtt SearchApi.ApiId 90 | Name: StepFunctionsHttpDataSource 91 | Description: Step Functions HTTP 92 | Type: HTTP 93 | ServiceRoleArn: !GetAtt AppSyncServiceRole.Arn 94 | HttpConfig: 95 | Endpoint: !Sub https://states.${AWS::Region}.amazonaws.com/ 96 | AuthorizationConfig: 97 | AuthorizationType: AWS_IAM 98 | AwsIamConfig: 99 | SigningRegion: !Ref AWS::Region 100 | SigningServiceName: states 101 | 102 | PublishResultDataSource: 103 | Type: AWS::AppSync::DataSource 104 | Properties: 105 | ApiId: !GetAtt SearchApi.ApiId 106 | Name: PublishResultDataSource 107 | Description: Local data source to publish results 108 | Type: NONE 109 | 110 | SearchStateMachine: 111 | Type: AWS::StepFunctions::StateMachine 112 | Properties: 113 | StateMachineName: aws-appsync-long-query-search 114 | RoleArn: !GetAtt SearchStateMachineRole.Arn 115 | DefinitionString: !Sub | 116 | { 117 | "Comment": "Wait and return a result", 118 | "StartAt": "Wait For One Minute", 119 | "States": { 120 | "Wait For One Minute": { 121 | "Type": "Wait", 122 | "Seconds": 60, 123 | "Next": "Return Result" 124 | }, 125 | "Return Result": { 126 | "Type": "Task", 127 | "Resource": "${ReturnResultFunction.Arn}", 128 | "ResultPath": "$", 129 | "TimeoutSeconds": 10, 130 | "Catch": [{ 131 | "ErrorEquals": [ "States.ALL" ], 132 | "ResultPath": "$.error", 133 | "Next": "HandleError" 134 | }], 135 | "End": true 136 | }, 137 | "HandleError": { 138 | "Type": "Fail", 139 | "Cause": "$.error" 140 | } 141 | } 142 | } 143 | 144 | ReturnResultFunction: 145 | Type: AWS::Serverless::Function 146 | Properties: 147 | Description: Returns a result by calling AppSync mutation, triggering subscription 148 | CodeUri: result/ 149 | Runtime: nodejs10.x 150 | Handler: index.handler 151 | Timeout: 10 152 | Environment: 153 | Variables: 154 | APPSYNC_API_KEY: !GetAtt SearchApiKey.ApiKey 155 | APPSYNC_ENDPOINT: !GetAtt SearchApi.GraphQLUrl 156 | 157 | 158 | # 159 | # IAM 160 | # 161 | SearchStateMachineRole: 162 | Type: AWS::IAM::Role 163 | Properties: 164 | AssumeRolePolicyDocument: 165 | Version: "2012-10-17" 166 | Statement: 167 | - Effect: Allow 168 | Principal: 169 | Service: !Sub states.${AWS::Region}.amazonaws.com 170 | Action: sts:AssumeRole 171 | Path: /long-query/ 172 | Policies: 173 | - PolicyName: StatesExecutionPolicy 174 | PolicyDocument: 175 | Version: "2012-10-17" 176 | Statement: 177 | - Effect: Allow 178 | Action: 179 | - lambda:InvokeFunction 180 | Resource: 181 | - !GetAtt ReturnResultFunction.Arn 182 | 183 | AppSyncServiceRole: 184 | Type: AWS::IAM::Role 185 | Properties: 186 | Path: /long-query/ 187 | ManagedPolicyArns: 188 | - arn:aws:iam::aws:policy/service-role/AWSAppSyncPushToCloudWatchLogs 189 | AssumeRolePolicyDocument: 190 | Version: "2012-10-17" 191 | Statement: 192 | - Effect: Allow 193 | Action: 194 | - sts:AssumeRole 195 | Principal: 196 | Service: 197 | - appsync.amazonaws.com 198 | Policies: 199 | - PolicyName: appsync-long-query-service-policy 200 | PolicyDocument: 201 | Version: "2012-10-17" 202 | Statement: 203 | - Effect: Allow 204 | Action: 205 | - states:StartExecution 206 | Resource: 207 | - !Ref SearchStateMachine 208 | 209 | Outputs: 210 | ApiEndpoint: 211 | Description: AppSync Endpoint 212 | Value: !GetAtt SearchApi.GraphQLUrl 213 | 214 | ApiId: 215 | Description: AppSync API ID 216 | Value: !GetAtt SearchApi.ApiId 217 | 218 | ApiKey: 219 | Description: AppSync API Key 220 | Value: !GetAtt SearchApiKey.ApiKey 221 | --------------------------------------------------------------------------------