├── .gitignore ├── src ├── data_friendship.go ├── data_people.go ├── data.go ├── data_person.go └── main.go ├── playground.png ├── schema.graphql ├── Gopkg.lock ├── Gopkg.toml ├── LICENSE.md ├── Makefile ├── CODE_OF_CONDUCT.md ├── template.yml └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | vendor 3 | 4 | package.yml -------------------------------------------------------------------------------- /src/data_friendship.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type friendship map[int][]int 4 | -------------------------------------------------------------------------------- /playground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbstjn/appsync-resolvers-example/HEAD/playground.png -------------------------------------------------------------------------------- /schema.graphql: -------------------------------------------------------------------------------- 1 | type Person { 2 | id: Int! 3 | name: String! 4 | age: Int! 5 | 6 | friends: [Person!]! 7 | } 8 | 9 | type Query { 10 | people: [Person!]! 11 | person(id: Int): Person! 12 | } 13 | 14 | schema { 15 | query: Query 16 | } 17 | -------------------------------------------------------------------------------- /src/data_people.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type people []*person 6 | 7 | func (p people) byID(id int) (*person, error) { 8 | for _, person := range p { 9 | if person.ID == id { 10 | return person, nil 11 | } 12 | } 13 | 14 | return nil, fmt.Errorf("Cannot find person with ID: %d", id) 15 | } 16 | -------------------------------------------------------------------------------- /src/data.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var ( 4 | dataPeople = people{ 5 | &person{1, "Frank Ocean", 47, people{}}, 6 | &person{2, "Paul Gascoigne", 51, people{}}, 7 | &person{3, "Uwe Seeler", 81, people{}}, 8 | } 9 | 10 | dataFriendship = friendship{ 11 | 1: []int{2, 3}, 12 | 2: []int{1}, 13 | 3: []int{3, 1}, 14 | } 15 | ) 16 | -------------------------------------------------------------------------------- /src/data_person.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type person struct { 4 | ID int `json:"id"` 5 | Name string `json:"name"` 6 | Age int `json:"age"` 7 | Friends people `json:"friends"` 8 | } 9 | 10 | func (p person) getFriends() (people, error) { 11 | list := people{} 12 | 13 | if refs, found := dataFriendship[p.ID]; found { 14 | for _, friendID := range refs { 15 | friend, err := dataPeople.byID(friendID) 16 | 17 | if err != nil { 18 | return nil, err 19 | } 20 | 21 | list = append(list, friend) 22 | 23 | } 24 | } 25 | 26 | return list, nil 27 | } 28 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/aws/aws-lambda-go" 6 | packages = [ 7 | "lambda", 8 | "lambda/messages", 9 | "lambdacontext" 10 | ] 11 | revision = "4d30d0ff60440c2d0480a15747c96ee71c3c53d4" 12 | version = "v1.2.0" 13 | 14 | [[projects]] 15 | name = "github.com/sbstjn/appsync-resolvers" 16 | packages = ["."] 17 | revision = "e913d2f26c27fa61f73052e2037b064c85a2fcdb" 18 | version = "v0.3.0" 19 | 20 | [solve-meta] 21 | analyzer-name = "dep" 22 | analyzer-version = 1 23 | inputs-digest = "2a27af2a9d98e2cd3b09009f64cb682d181eaeed60a758fcc99a3be3df0742ca" 24 | solver-name = "gps-cdcl" 25 | solver-version = 1 26 | -------------------------------------------------------------------------------- /src/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/aws/aws-lambda-go/lambda" 5 | resolvers "github.com/sbstjn/appsync-resolvers" 6 | ) 7 | 8 | type personEvent struct { 9 | ID int `json:"id"` 10 | } 11 | 12 | func handlePeople() (people, error) { 13 | return dataPeople, nil 14 | } 15 | 16 | func handlePerson(p personEvent) (*person, error) { 17 | return dataPeople.byID(p.ID) 18 | } 19 | 20 | func handleFriends(p person) (people, error) { 21 | return p.getFriends() 22 | } 23 | 24 | var ( 25 | r = resolvers.New() 26 | ) 27 | 28 | func init() { 29 | r.Add("query.people", handlePeople) 30 | r.Add("query.person", handlePerson) 31 | r.Add("field.person.friends", handleFriends) 32 | } 33 | 34 | func main() { 35 | lambda.Start(r.Handle) 36 | } 37 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "github.com/aws/aws-lambda-go" 30 | version = "1.2.0" 31 | 32 | [[constraint]] 33 | name = "github.com/sbstjn/appsync-resolvers" 34 | version = "0.3.0" 35 | 36 | [prune] 37 | go-tests = true 38 | unused-packages = true 39 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2018 Sebastian Müller 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROJECT_NAME ?= appsync-resolvers-example 2 | ENV ?= stable 3 | 4 | AWS_BUCKET_NAME ?= $(PROJECT_NAME)-artifacts-$(ENV) 5 | AWS_STACK_NAME ?= $(PROJECT_NAME)-stack-$(ENV) 6 | AWS_REGION ?= eu-west-1 7 | GOOS ?= linux 8 | 9 | FILE_TEMPLATE = template.yml 10 | FILE_PACKAGE = package.yml 11 | 12 | EXPIRATION = $(shell echo $$(( $(shell date +%s) + 604800 ))) # 7 days from now (timestamp) 13 | 14 | clean: 15 | rm -rf dist 16 | 17 | install: 18 | @ dep ensure 19 | 20 | test: 21 | @ go test ./... -v 22 | 23 | build: 24 | @ GOOS=$(GOOS) go build -o dist/handler_$(GOOS) ./src 25 | 26 | build-osx: 27 | @ GOOS=darwin make build 28 | 29 | configure: 30 | @ aws s3api create-bucket \ 31 | --bucket $(AWS_BUCKET_NAME) \ 32 | --region $(AWS_REGION) \ 33 | --create-bucket-configuration LocationConstraint=$(AWS_REGION) 34 | 35 | package: 36 | @ aws cloudformation package \ 37 | --template-file $(FILE_TEMPLATE) \ 38 | --s3-bucket $(AWS_BUCKET_NAME) \ 39 | --region $(AWS_REGION) \ 40 | --output-template-file $(FILE_PACKAGE) 41 | 42 | deploy: 43 | @ aws cloudformation deploy \ 44 | --template-file $(FILE_PACKAGE) \ 45 | --region $(AWS_REGION) \ 46 | --capabilities CAPABILITY_IAM \ 47 | --stack-name $(AWS_STACK_NAME) \ 48 | --force-upload \ 49 | --parameter-overrides \ 50 | ParamProjectName=$(PROJECT_NAME) \ 51 | ParamKeyExpiration=$(EXPIRATION) \ 52 | ParamENV=$(ENV) 53 | 54 | describe: 55 | @ aws cloudformation describe-stacks \ 56 | --region $(AWS_REGION) \ 57 | --stack-name $(AWS_STACK_NAME) 58 | 59 | outputs: 60 | @ make describe \ 61 | | jq -r '.Stacks[0].Outputs' 62 | 63 | .PHONY: clean install build build-lambda configure package deploy describe output 64 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting our team at **code@sbstjn.com**. As an alternative feel free to reach out to any of us personally. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /template.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: "2010-09-09" 2 | Transform: AWS::Serverless-2016-10-31 3 | Resources: 4 | 5 | Lambda: 6 | Type: AWS::Serverless::Function 7 | Properties: 8 | Handler: dist/handler_linux 9 | Runtime: go1.x 10 | Tracing: Active 11 | 12 | Role: 13 | Type: AWS::IAM::Role 14 | Properties: 15 | AssumeRolePolicyDocument: 16 | Version: 2012-10-17 17 | Statement: 18 | - Effect: Allow 19 | Principal: 20 | Service: appsync.amazonaws.com 21 | Action: 22 | - sts:AssumeRole 23 | Policies: 24 | - PolicyName: allow-access-to-lambda-from-appsync 25 | PolicyDocument: 26 | Version: 2012-10-17 27 | Statement: 28 | - Effect: Allow 29 | Action: lambda:invokeFunction 30 | Resource: 31 | - !GetAtt [ Lambda, Arn ] 32 | - !Join [ '', [ !GetAtt [ Lambda, Arn ], ':*' ] ] 33 | 34 | AppSyncAPI: 35 | Type: AWS::AppSync::GraphQLApi 36 | Properties: 37 | Name: !Join [ -, [ !Ref ParamProjectName, !Ref ParamENV ] ] 38 | AuthenticationType: API_KEY 39 | 40 | AppSyncSchema: 41 | Type: AWS::AppSync::GraphQLSchema 42 | Properties: 43 | ApiId: !GetAtt [ AppSyncAPI, ApiId ] 44 | DefinitionS3Location: schema.graphql 45 | 46 | AppSyncDataSource: 47 | Type: AWS::AppSync::DataSource 48 | Properties: 49 | ApiId: !GetAtt [ AppSyncAPI, ApiId ] 50 | Name: handler 51 | Type: AWS_LAMBDA 52 | LambdaConfig: 53 | LambdaFunctionArn: !GetAtt [ Lambda, Arn ] 54 | ServiceRoleArn: !GetAtt [ Role, Arn ] 55 | 56 | AppSyncResolverPeople: 57 | Type: AWS::AppSync::Resolver 58 | Properties: 59 | ApiId: !GetAtt [ AppSyncAPI, ApiId ] 60 | TypeName: Query 61 | FieldName: people 62 | DataSourceName: !GetAtt [ AppSyncDataSource, Name ] 63 | RequestMappingTemplate: '{ "version" : "2017-02-28", "operation": "Invoke", "payload": { "resolve": "query.people", "context": $utils.toJson($context) } }' 64 | ResponseMappingTemplate: $util.toJson($context.result) 65 | 66 | AppSyncResolverPerson: 67 | Type: AWS::AppSync::Resolver 68 | Properties: 69 | ApiId: !GetAtt [ AppSyncAPI, ApiId ] 70 | TypeName: Query 71 | FieldName: person 72 | DataSourceName: !GetAtt [ AppSyncDataSource, Name ] 73 | RequestMappingTemplate: '{ "version" : "2017-02-28", "operation": "Invoke", "payload": { "resolve": "query.person", "context": $utils.toJson($context) } }' 74 | ResponseMappingTemplate: $util.toJson($context.result) 75 | 76 | AppSyncResolverFriends: 77 | Type: AWS::AppSync::Resolver 78 | Properties: 79 | ApiId: !GetAtt [ AppSyncAPI, ApiId ] 80 | TypeName: Person 81 | FieldName: friends 82 | DataSourceName: !GetAtt [ AppSyncDataSource, Name ] 83 | RequestMappingTemplate: '{ "version" : "2017-02-28", "operation": "Invoke", "payload": { "resolve": "field.person.friends", "context": $utils.toJson($context) } }' 84 | ResponseMappingTemplate: $util.toJson($context.result) 85 | 86 | AppSyncAPIKey: 87 | Type: AWS::AppSync::ApiKey 88 | Properties: 89 | ApiId: !GetAtt [ AppSyncAPI, ApiId ] 90 | Expires: !Ref ParamKeyExpiration 91 | 92 | Parameters: 93 | 94 | ParamProjectName: 95 | Type: String 96 | ParamENV: 97 | Type: String 98 | ParamKeyExpiration: 99 | Type: Number 100 | 101 | Outputs: 102 | 103 | APIKey: 104 | Description: API Key 105 | Value: !GetAtt [ AppSyncAPIKey, ApiKey ] 106 | 107 | GraphQL: 108 | Description: GraphQL URL 109 | Value: !GetAtt [ AppSyncAPI, GraphQLUrl ] 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS AppSync Resolvers w/ CloudFormation, Lambda & SAM 2 | 3 | [![MIT License](https://badgen.now.sh/badge/License/MIT/blue)](https://github.com/sbstjn/appsync-resolvers-example/blob/master/LICENSE.md) 4 | [![Read Tutorial](https://badgen.now.sh/badge/Read/Tutorial/orange)](https://sbstjn.com/serverless-graphql-with-appsync-and-lambda.html) 5 | [![Code Library](https://badgen.now.sh/badge/Code/Library/cyan)](https://github.com/sbstjn/appsync-resolvers) 6 | 7 | Fully working GraphQL API example project using [appsync-resolvers] for AWS AppSync and *ready to be deployed* with CloudFormation using the [Serverless Application Model]. Includes AWS Lambda functions for custom `Query` and `Field` resolvers written in Go. You only need the `aws` CLI application and no other third-party frameworks!  🎉 8 | 9 | See [Serverless GraphQL with AWS AppSync and Lambda](https://sbstjn.com/serverless-graphql-with-appsync-and-lambda.html) on [sbstjn.com](https://sbstjn.com) for a detailed guide how to set up and configure this project. Or just run `make configure build package deploy` and you are ready to go … 10 | 11 | ## Schema 12 | 13 | ```graphql 14 | type Person { 15 | id: Int! 16 | name: String! 17 | age: Int! 18 | 19 | friends: [Person!]! 20 | } 21 | 22 | type Query { 23 | people: [Person!]! 24 | person(id: Int): Person! 25 | } 26 | 27 | schema { 28 | query: Query 29 | } 30 | ``` 31 | 32 | ## Configuration 33 | 34 | The `Makefile` contains all tasks to set up the CloudFormation stack. 35 | 36 | ```bash 37 | # Install Go dependencies 38 | $ > make install 39 | 40 | # Create S3 Bucket to store deploy artifacts 41 | $ > make configure 42 | 43 | # Build go binary for AWS Lambda 44 | $ > make build 45 | 46 | # Create deployable artifact 47 | $ > make package 48 | 49 | # Deploy CloudFormation stack 50 | $ > make deploy 51 | ``` 52 | 53 | ## Usage 54 | 55 | ```bash 56 | # Show CloudFormation stack output 57 | $ > make outputs 58 | 59 | [ 60 | { 61 | "OutputKey": "APIKey", 62 | "OutputValue": "da2-jlewwo38ojcrfasc3dpaxqgxcc", 63 | "Description": "API Key" 64 | }, 65 | { 66 | "OutputKey": "GraphQL", 67 | "OutputValue": "https://3mhugdjvrzeclk5ssrc7qzjpxn.appsync-api.eu-west-1.amazonaws.com/graphql", 68 | "Description": "GraphQL URL" 69 | } 70 | ] 71 | ``` 72 | 73 | ### Send GraphQL Requests 74 | 75 | #### Request list of all people 76 | 77 | ```bash 78 | $ > curl \ 79 | -XPOST https://3mhugdjvrzeclk5ssrc7qzjpxn.appsync-api.eu-west-1.amazonaws.com/graphql \ 80 | -H "Content-Type:application/graphql" \ 81 | -H "x-api-key:da2-jlewwo38ojcrfasc3dpaxqgxcc" \ 82 | -d '{ "query": "query { people { name } }" }' | jq 83 | ``` 84 | 85 | ```json 86 | { 87 | "data": { 88 | "people": [ 89 | { 90 | "name": "Frank Ocean" 91 | }, 92 | { 93 | "name": "Paul Gascoigne" 94 | }, 95 | { 96 | "name": "Uwe Seeler" 97 | } 98 | ] 99 | } 100 | } 101 | ``` 102 | 103 | #### Request specific person 104 | 105 | ```bash 106 | $ > curl \ 107 | -XPOST https://3mhugdjvrzeclk5ssrc7qzjpxn.appsync-api.eu-west-1.amazonaws.com/graphql \ 108 | -H "Content-Type:application/graphql" \ 109 | -H "x-api-key:da2-jlewwo38ojcrfasc3dpaxqgxcc" \ 110 | -d '{ "query": "query { person(id: 2) { name friends { name } } }" }' | jq 111 | ``` 112 | 113 | ```json 114 | { 115 | "data": { 116 | "person": { 117 | "name": "Paul Gascoigne", 118 | "friends": [ 119 | { 120 | "name": "Frank Ocean" 121 | } 122 | ] 123 | } 124 | } 125 | } 126 | ``` 127 | 128 | ## License 129 | 130 | Feel free to use the code, it's released using the [MIT license](LICENSE.md). 131 | 132 | ## Contribution 133 | 134 | You are welcome to contribute to this project! 😘 135 | 136 | To make sure you have a pleasant experience, please read the [code of conduct](CODE_OF_CONDUCT.md). It outlines core values and beliefs and will make working together a happier experience. 137 | 138 | [appsync-resolvers]: https://github.com/sbstjn/appsync-resolvers 139 | [Serverless Application Model]: https://github.com/awslabs/serverless-application-model 140 | --------------------------------------------------------------------------------