Serverless Project Structure
New configuration format
Please notice that the default structure of the TypeScript project has slightly changed, and it now contains serverless.ts
file instead of serverless.yaml
. You can still configure the project using YAML configuration as demonstrated in the course, but now the Serverless framework provides more configuration options, such as yml
, json
, js
, and ts
as described on serverless documentation. All functionalities work as well in the other available service file formats.
Serverless Plugins
Serverless framework's functionality can be extended using dozens of plugins developed for it. During the course we will use some of the most popular plugins, and you will see when and how to use them.
- When you are looking for a plugin for your project you can use the plugins catalog on the Serverless Framework website.
- If you can't find a plugin that would fit your needs, you can always implement your own. You can start with this guide if you want to explore this option.
Serverless Framework Events
If you want to learn more, you can find a full list of events that Serverless Framework supports in the official documentation. It provides examples for every event they support and describe all parameters it supports.
CloudFormation Resources
AWS documentation provides reference for all resource types CloudFormation support: AWS Resource and Property Types Reference.
Most of AWS resources can be created with CloudFormation, but in some rare cases you may encounter an AWS resource that is not supported by CloudFormation. In this case you would have to use AWS API, AWS CLI or AWS dashboard.
INSTALL
npm install -g serverless
CREATE PROJECT
serverless create --template aws-nodejs-typescript --path folder-name
INSTALL PLUGIN
npm install plugin-name --save-dev
DEPLOY PROJECT
sls deploy -v
- Install serverless:
npm install -g serverless
- Set up a new user in IAM named "serverless" and save the access key and secret key.
- Configure serverless to use the AWS credentials you just set up:
sls config credentials --provider aws --key YOUR_ACCESS_KEY --secret YOUR_SECRET_KEY --profile IAM_USER_NAME
-
To create a serverless boilerplate project:
sls create --template aws-nodejs-typescript --path 10-udagram-app
-
Deploy the application
sls deploy -v
Build a Lambda function get data from DynamoDB:
src/lambda/http/getGroups.ts
import * as AWS from "aws-sdk"; import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult, } from "aws-lambda"; const docClient = new AWS.DynamoDB.DocumentClient(); const groupTables = process.env.GROUPS_TABLE; export const handler: APIGatewayProxyHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { const result = await docClient .scan({ TableName: groupTables, }) .promise(); const items = result.Items; return { statusCode: 200, headers: { "Access-Control-Allow-Origin": "*", }, body: JSON.stringify({ items, }), }; };
serverless.yml:
service: name: serverless-udagram-app plugins: - serverless-webpack provider: name: aws runtime: nodejs14.x stage: ${opt:stage, 'dev'} region: ${opt:region, 'us-east-1'} environment: GROUPS_TABLE: Groups-${self:provider.stage} iamRoleStatements: - Effect: Allow Action: - dynamodb:Scan Resource: arn:aws:dynamodb:${self:provider.region}:*:table/${self:provider.environment.GROUPS_TABLE} functions: GetGroups: handler: src/lambda/http/getGroups.handler events: - http: method: get path: groups cors: true resources: Resources: GroupsDynamoDBTable: Type: AWS::DynamoDB::Table Properties: AttributeDefinitions: - AttributeName: id AttributeType: S KeySchema: - AttributeName: id KeyType: HASH BillingMode: PAY_PER_REQUEST TableName: ${self:provider.environment.GROUPS_TABLE}
Validate request in ApiGateway
Refer to: https://www.cnblogs.com/Answer1215/p/14774552.html
Query in Node.js
const docClient = new AWS.DynamoDB.DocumentClient() const result = await docClient.query({ TableName: 'GameScore', KeyConditionExpression: 'GameId = :gameId', ExpressionAttributeValues: { ':gameId': '10' } }).promise() const items = result.Items
Path parameter
functions: GetOrders: handler: src/images.handler events: - http: method: get path: /groups/{groupId}/images
export.handler = async (event) => { const grouId = event.pathParameters.groupId; ... }