From b057f88e4d4fe04acecbc22bab6b12cfbf695761 Mon Sep 17 00:00:00 2001 From: Benedikt Pauwels <33482891+bpauwels@users.noreply.github.com> Date: Mon, 27 Jun 2022 22:05:20 +0200 Subject: [PATCH] feat: add TypeScript hello world template w/ Lambda Powertools integration (#193) * feat: add TypeScript hello world template * feat: change TypeScript hello world template to reflect new build proceess * Update manifest to include new workflow * initial commit powertools template * parametrization * various fixes * updated manifest * manifest-v2.json * fix manifest-v2.json syntax error Co-authored-by: Roman Boiko Co-authored-by: Daniel Mil <84205762+mildaniel@users.noreply.github.com> Co-authored-by: EC2 Default User Co-authored-by: Benedikt Pauwels Co-authored-by: Mehmet Nuri Deveci <5735811+mndeveci@users.noreply.github.com> --- manifest-v2.json | 8 + .../.gitignore | 229 ++++++++++++++++++ .../README.md | 20 ++ .../cookiecutter.json | 10 + .../setup.cfg | 2 + .../{{cookiecutter.project_name}}/.gitignore | 207 ++++++++++++++++ .../{{cookiecutter.project_name}}/README.md | 127 ++++++++++ .../events/event.json | 62 +++++ .../hello-world/.eslintignore | 2 + .../hello-world/.eslintrc.js | 15 ++ .../hello-world/.npmignore | 1 + .../hello-world/.prettierrc.js | 7 + .../hello-world/app.ts | 111 +++++++++ .../hello-world/jest.config.ts | 15 ++ .../hello-world/package.json | 36 +++ .../tests/unit/test-handler.test.ts | 86 +++++++ .../hello-world/tsconfig.json | 15 ++ .../template.yaml | 69 ++++++ 18 files changed, 1022 insertions(+) create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/.gitignore create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/README.md create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/cookiecutter.json create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/setup.cfg create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/.gitignore create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/README.md create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/events/event.json create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintignore create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintrc.js create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.npmignore create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.prettierrc.js create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/app.ts create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/jest.config.ts create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/package.json create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tests/unit/test-handler.test.ts create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tsconfig.json create mode 100644 nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/template.yaml diff --git a/manifest-v2.json b/manifest-v2.json index 1a6fd99ca..496dea0b1 100644 --- a/manifest-v2.json +++ b/manifest-v2.json @@ -546,6 +546,14 @@ "appTemplate": "quick-start-web", "packageType": "Zip", "useCaseName": "Serverless API" + }, + { + "directory": "nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs", + "displayName": "Hello World Example TypeScript w/ Lambda Powertools", + "dependencyManager": "npm", + "appTemplate": "hello-world-powertools-typescript", + "packageType": "Zip", + "useCaseName": "Hello World Example" } ], "nodejs12.x": [ diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/.gitignore b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/.gitignore new file mode 100644 index 000000000..41bcace31 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/.gitignore @@ -0,0 +1,229 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/osx,linux,python,windows,sam +# Edit at https://www.toptal.com/developers/gitignore?templates=osx,linux,python,windows,sam + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +pytestdebug.log + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ +doc/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +#poetry.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +# .env +.env/ +.venv/ +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +pythonenv* + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# operating system-related files +# file properties cache/storage on macOS +*.DS_Store +# thumbnail cache on Windows +Thumbs.db + +# profiling data +.prof + + +### SAM ### +# Ignore build directories for the AWS Serverless Application Model (SAM) +# Info: https://aws.amazon.com/serverless/sam/ +# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html + +**/.aws-sam + +### Windows ### +# Windows thumbnail cache files +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/osx,linux,python,windows,sam diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/README.md b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/README.md new file mode 100644 index 000000000..6a472efd3 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/README.md @@ -0,0 +1,20 @@ +# Cookiecutter NodeJS TypeScript Hello-world for SAM based Serverless App + +A cookiecutter template to create a NodeJS TypeScript Hello world boilerplate using [Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model). + +## Requirements + +* [AWS SAM CLI](https://github.com/awslabs/aws-sam-cli) + +## Usage + +Generate a boilerplate template in your current project directory using the following syntax: + +* **NodeJS 14**: `sam init --runtime nodejs14.x` + +> **NOTE**: ``--name`` allows you to specify a different project folder name (`sam-app` is the default) + +# Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) + diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/cookiecutter.json b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/cookiecutter.json new file mode 100644 index 000000000..7d00f5993 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/cookiecutter.json @@ -0,0 +1,10 @@ +{ + "project_name": "Name of the project", + "runtime": "nodejs14.x", + "architectures": { + "value": [] + }, + "Powertools X-Ray Tracing": ["enabled","disabled"], + "Powertools Metrics": ["enabled","disabled"], + "Powertools Logging": ["enabled","disabled"] +} \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/setup.cfg b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/setup.cfg new file mode 100644 index 000000000..eee4ab11a --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/setup.cfg @@ -0,0 +1,2 @@ +[install] +prefix= \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/.gitignore b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/.gitignore new file mode 100644 index 000000000..5854f05ec --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/.gitignore @@ -0,0 +1,207 @@ + +# Created by https://www.toptal.com/developers/gitignore/api/osx,node,linux,windows,sam +# Edit at https://www.toptal.com/developers/gitignore?templates=osx,node,linux,windows,sam + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test +.env*.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt +dist + +# Storybook build outputs +.out +.storybook-out +storybook-static + +# rollup.js default build output +dist/ + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# Temporary folders +tmp/ +temp/ + +### OSX ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### SAM ### +# Ignore build directories for the AWS Serverless Application Model (SAM) +# Info: https://aws.amazon.com/serverless/sam/ +# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html + +**/.aws-sam + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/osx,node,linux,windows,sam diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/README.md b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/README.md new file mode 100644 index 000000000..2ecb33ede --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,127 @@ +# {{ cookiecutter.project_name }} + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- hello-world - Code for the application's Lambda function written in TypeScript. +- events - Invocation events that you can use to invoke the function. +- hello-world/tests - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. + +To use the SAM CLI, you need the following tools. + +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* Node.js - [Install Node.js 14](https://nodejs.org/en/), including the NPM package management tool. +* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +To build and deploy your application for the first time, run the following in your shell: + +```bash +sam build +sam deploy --guided +``` + +The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts: + +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **AWS Region**: The AWS region you want to deploy your app to. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +{{ cookiecutter.project_name }}$ sam build +``` + +The SAM CLI installs dependencies defined in `hello-world/package.json`, compiles TypeScript with esbuild, creates a deployment package, and saves it in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +{{ cookiecutter.project_name }}$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +{{ cookiecutter.project_name }}$ sam local start-api +{{ cookiecutter.project_name }}$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +{{ cookiecutter.project_name }}$ sam logs -n HelloWorldFunction --stack-name {{ cookiecutter.project_name }} --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `hello-world/tests` folder in this project. Use NPM to install the [Jest test framework](https://jestjs.io/) and run unit tests. + +```bash +{{ cookiecutter.project_name }}$ cd hello-world +hello-world$ npm install +hello-world$ npm run test +``` + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +aws cloudformation delete-stack --stack-name {{ cookiecutter.project_name }} +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/events/event.json b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/events/event.json new file mode 100644 index 000000000..070ad8e01 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/events/event.json @@ -0,0 +1,62 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } +} diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintignore b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintignore new file mode 100644 index 000000000..512d4cb8b --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintignore @@ -0,0 +1,2 @@ +node_modules +.aws-sam \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintrc.js b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintrc.js new file mode 100644 index 000000000..5da871fc4 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.eslintrc.js @@ -0,0 +1,15 @@ +module.exports = { + parser: "@typescript-eslint/parser", + parserOptions: { + ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features + sourceType: "module" + }, + extends: [ + "plugin:@typescript-eslint/recommended", // recommended rules from the @typescript-eslint/eslint-plugin + "plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. + ], + rules: { + // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs + // e.g. "@typescript-eslint/explicit-function-return-type": "off", + } + }; \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.npmignore b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.npmignore new file mode 100644 index 000000000..e7e1fb04f --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.npmignore @@ -0,0 +1 @@ +tests/* diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.prettierrc.js b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.prettierrc.js new file mode 100644 index 000000000..4c2c6c78b --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/.prettierrc.js @@ -0,0 +1,7 @@ +module.exports = { + semi: true, + trailingComma: "all", + singleQuote: true, + printWidth: 120, + tabWidth: 4 + }; \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/app.ts b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/app.ts new file mode 100644 index 000000000..908b5c73c --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/app.ts @@ -0,0 +1,111 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; +{%- if cookiecutter["Powertools Metrics"] == "enabled"%} +import { Metrics, MetricUnits } from '@aws-lambda-powertools/metrics'; +{%- endif %} +{%- if cookiecutter["Powertools Logging"] == "enabled"%} +import { Logger } from '@aws-lambda-powertools/logger'; +{%- endif %} +{%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} +import { Tracer } from '@aws-lambda-powertools/tracer'; +{%- endif %} + + +{%- if cookiecutter["Powertools Metrics"] == "enabled"%} +const metrics = new Metrics(); +{%- endif %} +{%- if cookiecutter["Powertools Logging"] == "enabled"%} +const logger = new Logger(); +{%- endif %} +{%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} +const tracer = new Tracer(); +{%- endif %} + +/** + * + * Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format + * @param {APIGatewayProxyEvent} event - API Gateway Lambda Proxy Input Format + * @param {Context} object - API Gateway Lambda $context variable + * + * Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html + * @returns {APIGatewayProxyResult} object - API Gateway Lambda Proxy Output Format + * + */ + +export const lambdaHandler = async (event: APIGatewayProxyEvent, context: Context): Promise => { + let response: APIGatewayProxyResult; + + {%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} + // Get facade segment created by AWS Lambda + const segment = tracer.getSegment(); + + // Create subsegment for the function & set it as active + const handlerSegment = segment.addNewSubsegment(`## ${process.env._HANDLER}`); + tracer.setSegment(handlerSegment); + + // Annotate the subsegment with the cold start & serviceName + tracer.annotateColdStart(); + tracer.addServiceNameAnnotation(); + + // Add annotation for the awsRequestId + tracer.putAnnotation('awsRequestId', context.awsRequestId); + + {%- endif %} + {%- if cookiecutter["Powertools Metrics"] == "enabled" %} + // Capture cold start metrics + metrics.captureColdStartMetric(); + + {%- endif %} + {%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} + // Create another subsegment & set it as active + const subsegment = handlerSegment.addNewSubsegment('### MySubSegment'); + tracer.setSegment(subsegment); + + {%- endif %} + try { + // hello world code + response = { + statusCode: 200, + body: JSON.stringify({ + message: 'hello world', + }), + }; + {%- if cookiecutter["Powertools Logging"] == "enabled"%} + logger.info('This is an INFO log - sending HTTP 200 - hello world response'); + {%- else %} + console.log('sending HTTP 200 - hello world response') + {%- endif %} + } catch (err) { + // Error handling + response = { + statusCode: 500, + body: JSON.stringify({ + message: 'some error happened', + }), + }; + {%- if cookiecutter["Powertools Logging"] == "enabled"%} + logger.error('This is an ERROR log - sending HTTP 500 - some error happened response'); + {%- else %} + console.log('sending HTTP 500 - some error happened response') + {%- endif %} + {%- if cookiecutter["Powertools Metrics"] == "enabled" or cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} + } finally { + {%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} + // Close subsegments (the AWS Lambda one is closed automatically) + subsegment.close(); // (### MySubSegment) + handlerSegment.close(); // (## index.handler) + + // Set the facade segment as active again (the one created by AWS Lambda) + tracer.setSegment(segment); + + {%- endif %} + {%- if cookiecutter["Powertools Metrics"] == "enabled"%} + // Publish all stored metrics + metrics.publishStoredMetrics(); + + {%- endif %} + {%- endif %} + } + + return response; + +}; \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/jest.config.ts b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/jest.config.ts new file mode 100644 index 000000000..21d6c7c00 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/jest.config.ts @@ -0,0 +1,15 @@ +/* + * For a detailed explanation regarding each configuration property and type check, visit: + * https://jestjs.io/docs/configuration + */ + +export default { + transform: { + '^.+\\.ts?$': 'esbuild-jest', + }, + clearMocks: true, + collectCoverage: true, + coverageDirectory: 'coverage', + coverageProvider: 'v8', + testMatch: ['**/tests/unit/*.test.ts'], +}; diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/package.json b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/package.json new file mode 100644 index 000000000..e5c70865d --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/package.json @@ -0,0 +1,36 @@ +{ + "name": "hello_world", + "version": "1.0.0", + "description": "hello world sample for NodeJS", + "main": "app.js", + "repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs", + "author": "SAM CLI", + "license": "MIT", + "dependencies": { + }, + "scripts": { + "unit": "jest", + "lint": "eslint '*.ts' --quiet --fix", + "compile": "tsc", + "test": "npm run compile && npm run unit" + }, + "devDependencies": { + "@aws-lambda-powertools/logger": "^0.6.0", + "@aws-lambda-powertools/metrics": "^0.6.0", + "@aws-lambda-powertools/tracer": "^0.6.0", + "@types/aws-lambda": "^8.10.92", + "@types/jest": "^27.4.0", + "@types/node": "^17.0.13", + "@typescript-eslint/eslint-plugin": "^5.10.2", + "@typescript-eslint/parser": "^5.10.2", + "esbuild": "^0.14.14", + "esbuild-jest": "^0.5.0", + "eslint": "^8.8.0", + "eslint-config-prettier": "^8.3.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^27.5.0", + "prettier": "^2.5.1", + "ts-node": "^10.4.0", + "typescript": "^4.5.5" + } +} diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tests/unit/test-handler.test.ts b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tests/unit/test-handler.test.ts new file mode 100644 index 000000000..316b15ee8 --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tests/unit/test-handler.test.ts @@ -0,0 +1,86 @@ +import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda'; +import { lambdaHandler } from '../../app'; + +describe('Unit test for app handler', function () { + it('verifies successful response', async () => { + const event: APIGatewayProxyEvent = { + httpMethod: 'get', + body: '', + headers: {}, + isBase64Encoded: false, + multiValueHeaders: {}, + multiValueQueryStringParameters: {}, + path: '/hello', + pathParameters: {}, + queryStringParameters: {}, + requestContext: { + accountId: '123456789012', + apiId: '1234', + authorizer: {}, + httpMethod: 'get', + identity: { + accessKey: '', + accountId: '', + apiKey: '', + apiKeyId: '', + caller: '', + clientCert: { + clientCertPem: '', + issuerDN: '', + serialNumber: '', + subjectDN: '', + validity: { notAfter: '', notBefore: '' }, + }, + cognitoAuthenticationProvider: '', + cognitoAuthenticationType: '', + cognitoIdentityId: '', + cognitoIdentityPoolId: '', + principalOrgId: '', + sourceIp: '', + user: '', + userAgent: '', + userArn: '', + }, + path: '/hello', + protocol: 'HTTP/1.1', + requestId: 'c6af9ac6-7b61-11e6-9a41-93e8deadbeef', + requestTimeEpoch: 1428582896000, + resourceId: '123456', + resourcePath: '/hello', + stage: 'dev', + }, + resource: '', + stageVariables: {}, + }; + const context: Context = { + callbackWaitsForEmptyEventLoop: false, + functionName: 'lambdaHandler', + functionVersion: '1.0', + invokedFunctionArn: 'arn:1234567890:lambda:lambdaHandler', + memoryLimitInMB: '128', + awsRequestId: '1234567890', + logGroupName: 'lambdaHandlerLogGroup', + logStreamName: 'c6a789dff9326bc178', + getRemainingTimeInMillis: function (): number { + throw new Error('Function not implemented.'); + }, + done: function (error?: Error, result?: any): void { + throw new Error('Function not implemented.'); + }, + fail: function (error: string | Error): void { + throw new Error('Function not implemented.'); + }, + succeed: function (messageOrObject: any): void { + throw new Error('Function not implemented.'); + } + }; + const result: APIGatewayProxyResult = await lambdaHandler(event,context); + + expect(result.statusCode).toEqual(200); + expect(result.body).toEqual( + JSON.stringify({ + message: 'hello world', + }), + ); + }); +}); diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tsconfig.json b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tsconfig.json new file mode 100644 index 000000000..ffaf193ea --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/hello-world/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "es2020", + "strict": true, + "preserveConstEnums": true, + "noEmit": true, + "sourceMap": false, + "module":"es2015", + "moduleResolution":"node", + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + }, + "exclude": ["node_modules", "**/*.test.ts"] + } \ No newline at end of file diff --git a/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/template.yaml b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 000000000..03026251b --- /dev/null +++ b/nodejs14.x/cookiecutter-aws-sam-hello-powertools-typescript-nodejs/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,69 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 3 + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: hello-world/ + Handler: app.lambdaHandler + Runtime: nodejs14.x + {%- if cookiecutter.architectures.value != []%} + Architectures: + {%- for arch in cookiecutter.architectures.value %} + - {{arch}} + {%- endfor %} + {%- endif %} + {%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled"%} + Tracing: Active + {%- endif %} + {%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled" or cookiecutter["Powertools Metrics"] == "enabled" or cookiecutter["Powertools Logging"] == "enabled" %} + Environment: + Variables: + {%- if cookiecutter["Powertools X-Ray Tracing"] == "enabled" or cookiecutter["Powertools Metrics"] == "enabled"%} + POWERTOOLS_SERVICE_NAME: helloWorld + {%- endif %} + {%- if cookiecutter["Powertools Metrics"] == "enabled"%} + POWERTOOLS_METRICS_NAMESPACE: {{ cookiecutter.project_name|lower|replace(' ', '-') }} + {%- endif %} + {%- if cookiecutter["Powertools Logging"] == "enabled"%} + LOG_LEVEL: INFO + {%- endif %} + {%- endif %} + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + Metadata: # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + Target: "es2020" + Sourcemap: true, + EntryPoints: + - app.ts + +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn