Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jul 11, 2024. It is now read-only.

🗄🙅‍♀️ Deploy your next serverless JavaScript function in seconds

NotificationsYou must be signed in to change notification settings

postlight/serverless-typescript-starter

Repository files navigation

logoGreenkeeper badgeCircleCI

Postlight's Modern Serverless Starter Kit adds a light layer on top of the Serverless framework, giving you the latest in modern JavaScript (ES6 via Webpack, TypeScript if you want it, testing with Jest, linting with ESLint, and formatting with Prettier), the ease and power of Serverless, and a few handy helpers (like functions for handling warm functions and response helpers).

Once installed, you can create and deploy functions with the latest ES6 features in minutes, with linting and formatting baked in.

Read more about it inthis handy introduction.

Note: Currently, this starter kit specifically targets AWS.

Install

# If you don't already have the serverless cli installed, do thatyarn global add serverless# Use the serverless cli to install this reposerverless install --url https://github.com/postlight/serverless-typescript-starter --name<your-service-name># cd into project and set it upcd<your-service-name># Install dependenciesyarn install

Development

Creating and deploying a new function takes two steps, which you can see in action with this repo's default Hello World function (if you're already familiar with Serverless, you're probably familiar with these steps).

1. Add your function toserverless.yml

In the functions section of./serverless.yml, you have to add your new function like so:

functions:hello:handler:src/hello.defaultevents:      -http:path:hellomethod:get

Ignoring the scheduling event, you can see here that we're setting up a function namedhello with a handler atsrc/hello.ts (the.default piece is just indicating that the function to run will be the default export from that file). Thehttp event says that this function will run when an http event is triggered (on AWS, this happens via API Gateway).

2. Create your function

This starter kit's Hello World function (which you will of course get rid of) can be found at./src/hello.ts. There you can see a basic function that's intended to work in conjunction with API Gateway (i.e., it is web-accessible). Like most Serverless functions, thehello function is asynchronous and accepts an event & context. (This is all basic Serverless; if you've never used it, be sure to read throughtheir docs.


You can develop and test your lambda functions locally in a few different ways.

Live-reloading functions

To run the hello function with the event data defined infixtures/event.json (with live reloading), run:

yarn watch:hello

API Gateway-like local dev server

To spin up a local dev server that will more closely match the API Gateway endpoint/experience:

yarn serve

Test your functions with Jest

Jest is installed as the testrunner. To create a test, co-locate your test with the file it's testingas<filename>.test.ts and then run/watch tests with:

yarntest

Adding new functions/files to Webpack

When you add a new function to your serverless config, you don't need to also add it as a new entryfor Webpack. Theserverless-webpack plugin allows us to follow a simple convention in ourserverless.ymlfile which is uses to automatically resolve your function handlers to the appropriate file:

functions:hello:handler:src/hello.default

As you can see, the path to the file with the function has to explicitly say where the handlerfile is. (If your function weren't the default export of that file, you'd do something like:src/hello.namedExport instead.)

Keep your lambda functions warm

Lambda functions will go "cold" if they haven't been invoked for a certain period of time (estimates vary, and AWS doesn't offer a clear answer). From theServerless blog:

Cold start happens when you execute an inactive (cold) function for the first time. It occurs while your cloud provider provisions your selected runtime container and then runs your function. This process, referred to as cold start, will increase your execution time considerably.

A frequently running function won't have this problem, but you can keep your function running hot by scheduling a regular ping to your lambda function. Here's what that looks like in yourserverless.yml:

custom:warmup:enabled:trueevents:      -schedule:rate(5 minutes)prewarm:trueconcurrency:2

The above config would keep all of your deployed lambda functions running warm. Theprewarm flag will ensure your function is warmed immediately after deploys (so you don't have to wait five minutes for the first scheduled event). And by setting theconcurrency to2, we're keeping two instances warm for each deployed function.

Undercustom.warmup, you can set project-wide warmup behaviors. On the other hand, if you want to set function-specific behaviours, you should use thewarmup key under the select functions. You can browse all the optionshere.

Your handler function can then handle this event like so:

constmyFunc=(event,context,callback)=>{// Detect the keep-alive ping from CloudWatch and exit early. This keeps our// lambda function running hot.if(event.source==='serverless-plugin-warmup'){// serverless-plugin-warmup is the source for Scheduled eventsreturncallback(null,'pinged');}// ... the rest of your function};exportdefaultmyFunc;

Copying and pasting the above can be tedious, so we've added a higher order function to wrap your run-warm functions. You still need to config the ping in yourserverless.yml file; then your function should look like this:

importrunWarmfrom'./utils';constmyFunc=(event,context,callback)=>{// Your function logic};exportdefaultrunWarm(myFunc);

Pruning old versions of deployed functions

The Serverless framework doesn't purge previous versions of functions from AWS, so the number of previous versions can grow out of hand and eventually filling up your code storage. This starter kit includesserverless-prune-plugin which automatically prunes old versions from AWS. The config for this plugin can be found inserverless.yml file. The defaults are:

custom:prune:automatic:truenumber:5# Number of versions to keep

The above config removes all but the last five stale versions automatically after each deployment.

Gohere for more on why pruning is useful.

Environment Variables

If you have environment variables stored in a.env file, you can reference them inside yourserverless.yml and inside your functions. Considering you have aNAME variable:

In a function:

process.env.NAME

Inserverless.yml:

provider:name:${env:NAME}runtime:nodejs12.x

You can check the documentationhere.

Deploy

Assuming you've already set up your default AWS credentials (or have set a different AWS profile viathe profile field):

yarn deploy

yarn deploy will deploy to "dev" environment. You can deploy tostage orproductionwith:

yarn deploy:stage# -- or --yarn deploy:production

After you've deployed, the output of the deploy script will give you the API endpointfor your deployed function(s), so you should be able to test the deployed API via that URL.


🔬 A Labs project from your friends atPostlight. Happy coding!

About

🗄🙅‍♀️ Deploy your next serverless JavaScript function in seconds

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors11


[8]ページ先頭

©2009-2025 Movatter.jp