├── .gitignore ├── .npmignore ├── LICENSE ├── README.md └── services ├── auth └── serverless.yml ├── database └── serverless.yml ├── notes ├── handler.js └── serverless.yml ├── uploads └── serverless.yml └── users ├── handler.js └── serverless.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # vim 40 | .*.sw* 41 | Session.vim 42 | 43 | # Serverless 44 | .webpack 45 | .serverless 46 | 47 | # env 48 | env.yml 49 | .env 50 | 51 | # Jetbrains IDEs 52 | .idea 53 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # package directories 2 | node_modules 3 | jspm_packages 4 | 5 | # Serverless directories 6 | .serverless -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Anomaly Innovations 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless Stack Mono-Repo Backend API 2 | 3 | [Serverless Stack](https://serverless-stack.com) is a free comprehensive guide to creating full-stack serverless applications. We create a [note taking app](https://demo2.serverless-stack.com) from scratch. 4 | 5 | This repo is a sample mono-repo multi-service Serverless application with AWS CloudFormation cross-stack references. The steps to creating this are outlined in the [Serverless architecture section](http://serverless-stack.com/#extra-sls-architecture) of the Serverless Stack guide. 6 | 7 | ### Steps 8 | 9 | In this section of the guide we look at how to: 10 | 11 | - [Link multiple Serverless services using CloudFormation cross-stack references](https://serverless-stack.com/chapters/cross-stack-references-in-serverless.html) 12 | - [Create our DynamoDB table as a Serverless service](https://serverless-stack.com/chapters/dynamodb-as-a-serverless-service.html) 13 | - [Create an S3 bucket as a Serverless service](https://serverless-stack.com/chapters/s3-as-a-serverless-service.html) 14 | - [Use the same API Gateway domain and resources across multiple Serverless services](https://serverless-stack.com/chapters/api-gateway-domains-across-services.html) 15 | - [Create a Serverless service for Cognito to authenticate and authorize our users](https://serverless-stack.com/chapters/cognito-as-a-serverless-service.html) 16 | 17 | #### Usage 18 | 19 | To use this repo locally you need to have the [Serverless framework](https://serverless.com) installed. 20 | 21 | ``` bash 22 | $ npm install serverless -g 23 | ``` 24 | 25 | Clone this repo. 26 | 27 | ``` bash 28 | $ git clone https://github.com/AnomalyInnovations/serverless-stack-demo-mono-api 29 | ``` 30 | 31 | Go to one of the services in the `services/` dir. 32 | 33 | And run this to deploy to your AWS account. 34 | 35 | ``` bash 36 | $ serverless deploy 37 | ``` 38 | 39 | The services have some dependencies and need to be deployed in the following order: 40 | 41 | 1. `database` 42 | 2. `uploads` 43 | 3. `notes` 44 | 4. `users` 45 | 5. `auth` 46 | 47 | #### Maintainers 48 | 49 | Serverless Stack is authored and maintained by Frank Wang ([@fanjiewang](https://twitter.com/fanjiewang)) & Jay V ([@jayair](https://twitter.com/jayair)). [**Subscribe to our newsletter**](https://emailoctopus.com/lists/1c11b9a8-1500-11e8-a3c9-06b79b628af2/forms/subscribe) for updates on Serverless Stack. Send us an [email][Email] if you have any questions. 50 | 51 | [Email]: mailto:contact@anoma.ly 52 | 53 | 54 | -------------------------------------------------------------------------------- /services/auth/serverless.yml: -------------------------------------------------------------------------------- 1 | service: notes-app-mono-auth 2 | 3 | custom: 4 | # Our stage is based on what is passed in when running serverless 5 | # commands. Or fallsback to what we have set in the provider section. 6 | stage: ${opt:stage, self:provider.stage} 7 | 8 | provider: 9 | name: aws 10 | runtime: nodejs8.10 11 | stage: dev 12 | region: us-east-1 13 | 14 | resources: 15 | Resources: 16 | CognitoUserPool: 17 | Type: AWS::Cognito::UserPool 18 | Properties: 19 | # Generate a name based on the stage 20 | UserPoolName: ${self:custom.stage}-mono-user-pool 21 | # Set email as an alias 22 | UsernameAttributes: 23 | - email 24 | AutoVerifiedAttributes: 25 | - email 26 | 27 | CognitoUserPoolClient: 28 | Type: AWS::Cognito::UserPoolClient 29 | Properties: 30 | # Generate an app client name based on the stage 31 | ClientName: ${self:custom.stage}-mono-user-pool-client 32 | UserPoolId: 33 | Ref: CognitoUserPool 34 | ExplicitAuthFlows: 35 | - ADMIN_NO_SRP_AUTH 36 | GenerateSecret: false 37 | 38 | # The federated identity for our user pool to auth with 39 | CognitoIdentityPool: 40 | Type: AWS::Cognito::IdentityPool 41 | Properties: 42 | # Generate a name based on the stage 43 | IdentityPoolName: ${self:custom.stage}MonoIdentityPool 44 | # Don't allow unathenticated users 45 | AllowUnauthenticatedIdentities: false 46 | # Link to our User Pool 47 | CognitoIdentityProviders: 48 | - ClientId: 49 | Ref: CognitoUserPoolClient 50 | ProviderName: 51 | Fn::GetAtt: [ "CognitoUserPool", "ProviderName" ] 52 | 53 | # IAM roles 54 | CognitoIdentityPoolRoles: 55 | Type: AWS::Cognito::IdentityPoolRoleAttachment 56 | Properties: 57 | IdentityPoolId: 58 | Ref: CognitoIdentityPool 59 | Roles: 60 | authenticated: 61 | Fn::GetAtt: [CognitoAuthRole, Arn] 62 | 63 | # IAM role used for authenticated users 64 | CognitoAuthRole: 65 | Type: AWS::IAM::Role 66 | Properties: 67 | Path: / 68 | AssumeRolePolicyDocument: 69 | Version: '2012-10-17' 70 | Statement: 71 | - Effect: 'Allow' 72 | Principal: 73 | Federated: 'cognito-identity.amazonaws.com' 74 | Action: 75 | - 'sts:AssumeRoleWithWebIdentity' 76 | Condition: 77 | StringEquals: 78 | 'cognito-identity.amazonaws.com:aud': 79 | Ref: CognitoIdentityPool 80 | 'ForAnyValue:StringLike': 81 | 'cognito-identity.amazonaws.com:amr': authenticated 82 | Policies: 83 | - PolicyName: 'CognitoAuthorizedPolicy' 84 | PolicyDocument: 85 | Version: '2012-10-17' 86 | Statement: 87 | - Effect: 'Allow' 88 | Action: 89 | - 'mobileanalytics:PutEvents' 90 | - 'cognito-sync:*' 91 | - 'cognito-identity:*' 92 | Resource: '*' 93 | 94 | # Allow users to invoke our API 95 | - Effect: 'Allow' 96 | Action: 97 | - 'execute-api:Invoke' 98 | Resource: 99 | Fn::Join: 100 | - '' 101 | - 102 | - 'arn:aws:execute-api:' 103 | - Ref: AWS::Region 104 | - ':' 105 | - Ref: AWS::AccountId 106 | - ':' 107 | - 'Fn::ImportValue': ${self:custom.stage}-ApiGatewayRestApiId 108 | - '/*' 109 | 110 | # Allow users to upload attachments to their 111 | # folder inside our S3 bucket 112 | - Effect: 'Allow' 113 | Action: 114 | - 's3:*' 115 | Resource: 116 | - Fn::Join: 117 | - '' 118 | - 119 | - 'Fn::ImportValue': ${self:custom.stage}-AttachmentsBucketArn 120 | - '/private/' 121 | - '$' 122 | - '{cognito-identity.amazonaws.com:sub}/*' 123 | 124 | # Print out the Id of the User Pool and Identity Pool that are created 125 | Outputs: 126 | UserPoolId: 127 | Value: 128 | Ref: CognitoUserPool 129 | 130 | UserPoolClientId: 131 | Value: 132 | Ref: CognitoUserPoolClient 133 | 134 | IdentityPoolId: 135 | Value: 136 | Ref: CognitoIdentityPool 137 | -------------------------------------------------------------------------------- /services/database/serverless.yml: -------------------------------------------------------------------------------- 1 | service: notes-app-mono-database 2 | 3 | custom: 4 | # Our stage is based on what is passed in when running serverless 5 | # commands. Or fallsback to what we have set in the provider section. 6 | stage: ${opt:stage, self:provider.stage} 7 | # Set the table name here so we can use it while testing locally 8 | tableName: ${self:custom.stage}-mono-notes 9 | # Set our DynamoDB throughput for prod and all other non-prod stages. 10 | tableThroughputs: 11 | prod: 5 12 | default: 1 13 | tableThroughput: ${self:custom.tableThroughputs.${self:custom.stage}, self:custom.tableThroughputs.default} 14 | 15 | provider: 16 | name: aws 17 | runtime: nodejs8.10 18 | stage: dev 19 | region: us-east-1 20 | 21 | resources: 22 | Resources: 23 | NotesTable: 24 | Type: AWS::DynamoDB::Table 25 | Properties: 26 | # Generate a name based on the stage 27 | TableName: ${self:custom.tableName} 28 | AttributeDefinitions: 29 | - AttributeName: userId 30 | AttributeType: S 31 | - AttributeName: noteId 32 | AttributeType: S 33 | KeySchema: 34 | - AttributeName: userId 35 | KeyType: HASH 36 | - AttributeName: noteId 37 | KeyType: RANGE 38 | # Set the capacity based on the stage 39 | ProvisionedThroughput: 40 | ReadCapacityUnits: ${self:custom.tableThroughput} 41 | WriteCapacityUnits: ${self:custom.tableThroughput} 42 | 43 | Outputs: 44 | NotesTableArn: 45 | Value: 46 | Fn::GetAtt: 47 | - NotesTable 48 | - Arn 49 | Export: 50 | Name: ${self:custom.stage}-NotesTableArn 51 | -------------------------------------------------------------------------------- /services/notes/handler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports.main = (event, context, callback) => { 4 | const response = { 5 | statusCode: 200, 6 | body: JSON.stringify({ 7 | message: 'Go Serverless v1.0! Your function executed successfully!', 8 | input: event, 9 | }), 10 | }; 11 | 12 | callback(null, response); 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /services/notes/serverless.yml: -------------------------------------------------------------------------------- 1 | service: notes-app-mono-notes 2 | 3 | custom: 4 | # Our stage is based on what is passed in when running serverless 5 | # commands. Or fallsback to what we have set in the provider section. 6 | stage: ${opt:stage, self:provider.stage} 7 | 8 | provider: 9 | name: aws 10 | runtime: nodejs8.10 11 | stage: dev 12 | region: us-east-1 13 | 14 | # These environment variables are made available to our functions 15 | # under process.env. 16 | environment: 17 | tableName: 18 | ${file(../database/serverless.yml):custom.tableName} 19 | 20 | iamRoleStatements: 21 | - Effect: Allow 22 | Action: 23 | - dynamodb:DescribeTable 24 | - dynamodb:Query 25 | - dynamodb:Scan 26 | - dynamodb:GetItem 27 | - dynamodb:PutItem 28 | - dynamodb:UpdateItem 29 | - dynamodb:DeleteItem 30 | # Restrict our IAM role permissions to 31 | # the specific table for the stage 32 | Resource: 33 | - 'Fn::ImportValue': ${self:custom.stage}-NotesTableArn 34 | 35 | functions: 36 | # Defines an HTTP API endpoint that calls the main function in create.js 37 | # - path: url path is /notes 38 | # - method: POST request 39 | # - cors: enabled CORS (Cross-Origin Resource Sharing) for browser cross 40 | # domain api call 41 | # - authorizer: authenticate using the AWS IAM role 42 | get: 43 | # Defines an HTTP API endpoint that calls the main function in get.js 44 | # - path: url path is /notes/{id} 45 | # - method: GET request 46 | handler: handler.main 47 | events: 48 | - http: 49 | path: notes 50 | method: get 51 | cors: true 52 | authorizer: aws_iam 53 | 54 | resources: 55 | Outputs: 56 | ApiGatewayRestApiId: 57 | Value: 58 | Ref: ApiGatewayRestApi 59 | Export: 60 | Name: ${self:custom.stage}-ApiGatewayRestApiId 61 | 62 | ApiGatewayRestApiRootResourceId: 63 | Value: 64 | Fn::GetAtt: 65 | - ApiGatewayRestApi 66 | - RootResourceId 67 | Export: 68 | Name: ${self:custom.stage}-ApiGatewayRestApiRootResourceId 69 | 70 | -------------------------------------------------------------------------------- /services/uploads/serverless.yml: -------------------------------------------------------------------------------- 1 | service: notes-app-mono-uploads 2 | 3 | custom: 4 | # Our stage is based on what is passed in when running serverless 5 | # commands. Or fallsback to what we have set in the provider section. 6 | stage: ${opt:stage, self:provider.stage} 7 | 8 | provider: 9 | name: aws 10 | runtime: nodejs8.10 11 | stage: dev 12 | region: us-east-1 13 | 14 | resources: 15 | Resources: 16 | S3Bucket: 17 | Type: AWS::S3::Bucket 18 | Properties: 19 | # Set the CORS policy 20 | CorsConfiguration: 21 | CorsRules: 22 | - 23 | AllowedOrigins: 24 | - '*' 25 | AllowedHeaders: 26 | - '*' 27 | AllowedMethods: 28 | - GET 29 | - PUT 30 | - POST 31 | - DELETE 32 | - HEAD 33 | MaxAge: 3000 34 | 35 | # Print out the name of the bucket that is created 36 | Outputs: 37 | AttachmentsBucketArn: 38 | Value: 39 | Fn::GetAtt: 40 | - S3Bucket 41 | - Arn 42 | Export: 43 | Name: ${self:custom.stage}-AttachmentsBucketArn 44 | 45 | AttachmentsBucketName: 46 | Value: 47 | Ref: S3Bucket 48 | Export: 49 | Name: ${self:custom.stage}-AttachmentsBucket 50 | 51 | -------------------------------------------------------------------------------- /services/users/handler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports.main = (event, context, callback) => { 4 | const response = { 5 | statusCode: 200, 6 | body: JSON.stringify({ 7 | message: 'Go Serverless v1.0! Your function executed successfully!', 8 | input: event, 9 | }), 10 | }; 11 | 12 | callback(null, response); 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /services/users/serverless.yml: -------------------------------------------------------------------------------- 1 | service: notes-app-mono-users 2 | 3 | custom: 4 | # Our stage is based on what is passed in when running serverless 5 | # commands. Or fallsback to what we have set in the provider section. 6 | stage: ${opt:stage, self:provider.stage} 7 | 8 | provider: 9 | name: aws 10 | runtime: nodejs8.10 11 | stage: dev 12 | region: us-east-1 13 | 14 | apiGateway: 15 | restApiId: 16 | 'Fn::ImportValue': ${self:custom.stage}-ApiGatewayRestApiId 17 | restApiRootResourceId: 18 | 'Fn::ImportValue': ${self:custom.stage}-ApiGatewayRestApiRootResourceId 19 | 20 | # These environment variables are made available to our functions 21 | # under process.env. 22 | environment: 23 | tableName: 24 | ${file(../database/serverless.yml):custom.tableName} 25 | 26 | iamRoleStatements: 27 | - Effect: Allow 28 | Action: 29 | - dynamodb:DescribeTable 30 | - dynamodb:Query 31 | - dynamodb:Scan 32 | - dynamodb:GetItem 33 | - dynamodb:PutItem 34 | - dynamodb:UpdateItem 35 | - dynamodb:DeleteItem 36 | # Restrict our IAM role permissions to 37 | # the specific table for the stage 38 | Resource: 39 | - 'Fn::ImportValue': ${self:custom.stage}-NotesTableArn 40 | 41 | functions: 42 | # Defines an HTTP API endpoint that calls the main function in create.js 43 | # - path: url path is /users 44 | # - method: POST request 45 | # - cors: enabled CORS (Cross-Origin Resource Sharing) for browser cross 46 | # domain api call 47 | # - authorizer: authenticate using the AWS IAM role 48 | get: 49 | # Defines an HTTP API endpoint that calls the main function in get.js 50 | # - path: url path is /users/{id} 51 | # - method: GET request 52 | handler: handler.main 53 | events: 54 | - http: 55 | path: users 56 | method: get 57 | cors: true 58 | authorizer: aws_iam 59 | 60 | --------------------------------------------------------------------------------