From 7293ac8f8f178267ef911bf2b43e84b7ac9cd05c Mon Sep 17 00:00:00 2001 From: Tomasz Czubocha Date: Wed, 25 Nov 2026 20:28:51 +0000 Subject: [PATCH] feat: add AppSync DynamoDB example, bring S3 upload example to the standard Add aws-node-appsync-dynamodb: an AppSync GraphQL API from the built-in appSync block, with API key auth and two APPSYNC_JS resolvers (createPost, getPost) on a DynamoDB table, and a live test that creates a post and reads it back. Rework aws-node-upload-to-s3-and-postprocess: an upload under uploads/ triggers a Node.js 24 function that reads the object and writes a summary under processed/. The bucket name carries the stage and account ID, the s3 event uses a prefix rule, the function role is limited to the two prefixes, and a live test uploads a file and checks the summary. The HTML form and its signing script, which needed AWS keys in a local file, are removed. --- README.md | 3 +- aws-node-appsync-dynamodb/README.md | 174 ++++++++++++++++++ aws-node-appsync-dynamodb/example.json | 27 +++ .../resolvers/createPost.js | 14 ++ .../resolvers/getPost.js | 13 ++ aws-node-appsync-dynamodb/schema.graphql | 12 ++ aws-node-appsync-dynamodb/serverless.yml | 48 +++++ aws-node-appsync-dynamodb/test/smoke.mjs | 83 +++++++++ .../README.md | 168 ++++++++++++----- .../example.json | 29 +++ .../frontend/index.template.html | 26 --- .../generate-form.js | 67 ------- .../handler.js | 7 - .../handler.mjs | 40 ++++ .../package.json | 11 -- .../serverless.yml | 29 ++- .../test/smoke.mjs | 95 ++++++++++ examples.json | 17 +- 18 files changed, 699 insertions(+), 164 deletions(-) create mode 100644 aws-node-appsync-dynamodb/README.md create mode 100644 aws-node-appsync-dynamodb/example.json create mode 100644 aws-node-appsync-dynamodb/resolvers/createPost.js create mode 100644 aws-node-appsync-dynamodb/resolvers/getPost.js create mode 100644 aws-node-appsync-dynamodb/schema.graphql create mode 100644 aws-node-appsync-dynamodb/serverless.yml create mode 100644 aws-node-appsync-dynamodb/test/smoke.mjs create mode 100644 aws-node-upload-to-s3-and-postprocess/example.json delete mode 100644 aws-node-upload-to-s3-and-postprocess/frontend/index.template.html delete mode 100755 aws-node-upload-to-s3-and-postprocess/generate-form.js delete mode 100644 aws-node-upload-to-s3-and-postprocess/handler.js create mode 100644 aws-node-upload-to-s3-and-postprocess/handler.mjs delete mode 100644 aws-node-upload-to-s3-and-postprocess/package.json create mode 100644 aws-node-upload-to-s3-and-postprocess/test/smoke.mjs diff --git a/README.md b/README.md index 4a636a2c0..f205ee7a2 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ serverless deploy | [AWS Nest application example (NodeJS & Typescript)](https://github.com/serverless/examples/tree/v4/aws-node-typescript-nest)
This example demonstrates how to setup a simple [Nest](https://github.com/nestjs/nest) application. | nodeJS | | [TypeScript Serverless REST API with DynamoDB](https://github.com/serverless/examples/tree/v4/aws-node-typescript-rest-api-with-dynamodb)
This example shows your how to create a TypeScript powered REST API with DynamoDB. | nodeJS | | [AWS SQS Standard Example (NodeJS & Typescript)](https://github.com/serverless/examples/tree/v4/aws-node-typescript-sqs-standard)
This example demonstrates how to setup a SQS with Typescript. | nodeJS | -| [AWS Upload a file to S3 to trigger a Lambda function example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-upload-to-s3-and-postprocess)
This example shows how to upload a file to S3 using a HTML form, and have S3 trigger a lambda function. | nodeJS | +| [AWS Upload a file to S3 to trigger a Lambda function example in NodeJS](https://github.com/serverless/examples/tree/v4/aws-node-upload-to-s3-and-postprocess)
This example shows how an upload to an Amazon S3 bucket triggers a Lambda function that reads the new object and writes a result back to the bucket. | nodeJS | | [Next.js and Express web apps on one custom domain](https://github.com/serverless/examples/tree/v4/aws-node-web-app-custom-domain)
This example deploys a Next.js frontend and an Express API to AWS Lambda Web Functions with the Serverless Framework and serves both from one custom domain, routed by path. | nodeJS | | [Simple Websocket Authorizers](https://github.com/serverless/examples/tree/v4/aws-node-websockets-authorizers)
The example shows you how to deploy simple websocket authorizers | nodeJS | | [AWS NodeJS Example](https://github.com/serverless/examples/tree/v4/aws-node)
This template demonstrates how to deploy a simple NodeJS function running on AWS Lambda using the Serverless Framework. | nodeJS | @@ -200,6 +200,7 @@ serverless deploy | [Customer-managed Lambda runtime with Node.js](https://github.com/serverless/examples/tree/v4/aws-node-customer-managed-runtime)
Publish a customer-managed Lambda runtime from a container image and run a Node.js function on it through a runtime alias, with Serverless Compose. | nodeJS | | [REST API with a JWT authorizer and Amazon Cognito (NodeJS)](https://github.com/serverless/examples/tree/v4/aws-node-rest-api-jwt-authorizer)
Protect API Gateway REST API endpoints with a JWT authorizer that trusts an Amazon Cognito user pool, require an OAuth scope on one of them, and read the caller's claims in Node.js. | nodeJS | | [GPU function with PyTorch on Lambda Managed Instances](https://github.com/serverless/examples/tree/v4/aws-python-gpu-managed-instances)
This example runs a Python function with PyTorch on an NVIDIA GPU, using AWS Lambda Managed Instances and the Serverless Framework. | python | +| [AppSync GraphQL API with DynamoDB (NodeJS)](https://github.com/serverless/examples/tree/v4/aws-node-appsync-dynamodb)
An AWS AppSync GraphQL API with API key authentication and two JavaScript resolvers that write and read posts in a DynamoDB table, from the built-in appSync block of serverless.yml. | nodeJS | ## Community Examples diff --git a/aws-node-appsync-dynamodb/README.md b/aws-node-appsync-dynamodb/README.md new file mode 100644 index 000000000..387deb133 --- /dev/null +++ b/aws-node-appsync-dynamodb/README.md @@ -0,0 +1,174 @@ + + +# AppSync GraphQL API with DynamoDB + +[![Verified](https://raw.githubusercontent.com/serverless/examples/verified/badges/aws-node-appsync-dynamodb.svg)](https://github.com/serverless/examples/blob/verified/results.json) + +[AWS AppSync](https://docs.aws.amazon.com/appsync/latest/devguide/what-is-appsync.html) serves a GraphQL API and resolves each field from a data source, such as a DynamoDB table, without a Lambda function in between. The Serverless Framework deploys an AppSync API from the top-level [`appSync` block](https://www.serverless.com/framework/docs/providers/aws/guide/appsync) of `serverless.yml`, with no plugin to install. This example creates a GraphQL API with API key authentication and two JavaScript resolvers, `createPost` and `getPost`, that write and read posts in a DynamoDB table. + +## What it deploys + +- An AppSync GraphQL API, named `appsync-dynamodb-`, with the schema in [`schema.graphql`](https://github.com/serverless/examples/blob/v4/aws-node-appsync-dynamodb/schema.graphql) and an API key that expires after 30 days. +- A DynamoDB table for the posts, with on-demand capacity. +- An AppSync data source for the table, with an IAM role that lets AppSync read and write it. +- Two unit resolvers in the `APPSYNC_JS` runtime: `Mutation.createPost` and `Query.getPost`. +- Two stack outputs: `GraphQlApiUrl`, the API's endpoint, and `GraphQlApiKey`, its API key. + +## Prerequisites + +- The Serverless Framework CLI: `npm i -g serverless`, which needs [Node.js](https://nodejs.org/). See [Getting started](https://www.serverless.com/framework/docs/getting-started). +- An AWS account, with credentials configured on your machine. See [AWS credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials). +- A Serverless account, or a license key in `SERVERLESS_LICENSE_KEY`. The CLI asks you to sign in the first time you run it. +- `curl`, to call the API. The commands in Try it are written for Bash. + +## Deploy + +Deploy from this directory: + +```bash +serverless deploy +``` + +Without options, the deploy uses the stage `dev` and the Region `us-east-1`. To change them, pass `--stage` or `--region`, and pass the same options to every later command, including `serverless remove`. + +You should see output like this, with the API's endpoints and its API key: + +```text +Deploying "appsync-dynamodb" to stage "dev" (us-east-1) +✔ Service deployed to stack appsync-dynamodb-dev (51s) +appsync endpoints: + graphql: https://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql + realtime: wss://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-realtime-api.us-east-1.amazonaws.com/graphql + +appsync api keys: + da2-xxxxxxxxxxxxxxxxxxxxxxxxxx (defaultKey) +``` + +## Try it + +Copy the `graphql` endpoint and the API key from the deploy output into shell variables. `serverless info` prints them again: + +```bash +API_URL=https://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql +API_KEY=da2-xxxxxxxxxxxxxxxxxxxxxxxxxx +``` + +Create a post. GraphQL requests are a `POST` with the query in a JSON body, and the API key goes in the `x-api-key` header: + +```bash +curl -s "$API_URL" \ + -H 'content-type: application/json' \ + -H "x-api-key: $API_KEY" \ + -d '{"query":"mutation { createPost(title: \"Hello\") { id title } }"}' +``` + +The `createPost` resolver writes the post with a generated ID and returns it: + +```json +{"data":{"createPost":{"id":"1c38c0b2-f396-47dc-9409-9f7ead9d7cea","title":"Hello"}}} +``` + +Read the post back by its ID, replacing the ID with the one you got: + +```bash +curl -s "$API_URL" \ + -H 'content-type: application/json' \ + -H "x-api-key: $API_KEY" \ + -d '{"query":"query { getPost(id: \"1c38c0b2-f396-47dc-9409-9f7ead9d7cea\") { id title } }"}' +``` + +```json +{"data":{"getPost":{"id":"1c38c0b2-f396-47dc-9409-9f7ead9d7cea","title":"Hello"}}} +``` + +For an ID that has no post, `getPost` returns `null`. A request without the API key gets `401` from AppSync, which runs no resolver: + +```bash +curl -s -w '\n%{http_code}\n' "$API_URL" \ + -H 'content-type: application/json' \ + -d '{"query":"query { getPost(id: \"1c38c0b2-f396-47dc-9409-9f7ead9d7cea\") { id title } }"}' +``` + +```text +{ + "errors" : [ { + "errorType" : "UnauthorizedException", + "message" : "You are not authorized to make this call." + } ] +} +401 +``` + +## How it works + +The `appSync` block in [`serverless.yml`](https://github.com/serverless/examples/blob/v4/aws-node-appsync-dynamodb/serverless.yml) declares the API, its authentication, a data source for the table and a resolver for each field: + +```yaml +appSync: + name: ${self:service}-${sls:stage} + authentication: + type: API_KEY + apiKeys: + - name: defaultKey + expiresAfter: 30d + dataSources: + postsTable: + type: AMAZON_DYNAMODB + config: + tableName: !Ref PostsTable + resolvers: + Query.getPost: + kind: UNIT + dataSource: postsTable + code: resolvers/getPost.js + Mutation.createPost: + kind: UNIT + dataSource: postsTable + code: resolvers/createPost.js +``` + +- The Framework reads the schema from `schema.graphql` next to `serverless.yml`. It defines a `Post` type, the `getPost` query and the `createPost` mutation. +- The API's name includes the stage, so each stage gets its own API. +- For the `AMAZON_DYNAMODB` data source, the Framework creates an IAM role that AppSync assumes to call the table, allowing item reads and writes on that table and its indexes only. +- Each resolver key is `.`. A `UNIT` resolver runs one data source request. +- The table itself is a DynamoDB resource under `resources`, since the `appSync` block doesn't create tables. Its name is left to CloudFormation, and `!Ref PostsTable` passes it to the data source. + +Each resolver's `code` is a JavaScript file in the `APPSYNC_JS` runtime, with a `request` function that builds the DynamoDB request and a `response` function that shapes the result. [`resolvers/createPost.js`](https://github.com/serverless/examples/blob/v4/aws-node-appsync-dynamodb/resolvers/createPost.js) writes an item with an ID that `util.autoId()` generates: + +```javascript +export function request(ctx) { + return { + operation: 'PutItem', + key: util.dynamodb.toMapValues({ id: util.autoId() }), + attributeValues: util.dynamodb.toMapValues({ title: ctx.args.title }), + }; +} +``` + +[`resolvers/getPost.js`](https://github.com/serverless/examples/blob/v4/aws-node-appsync-dynamodb/resolvers/getPost.js) reads the item with `GetItem`. `@aws-appsync/utils` is provided by the AppSync runtime: the Framework bundles each resolver with esbuild and leaves that import out, so the example has no dependencies to install. + +The deploy prints the endpoint and the API key. The `Outputs` under `resources` also store them in the stack, through the `${appsync:url}` and `${appsync:apiKey.defaultKey}` variables, for tools that read stack outputs. An AppSync API key identifies the client, as in a web or mobile app; anyone who can read the stack's outputs can read it. + +## Cost and cleanup + +While the example is deployed, AppSync bills each query and mutation it receives, and DynamoDB bills each read and write request and the data the table stores. See [AWS AppSync pricing](https://aws.amazon.com/appsync/pricing/) and [Amazon DynamoDB pricing](https://aws.amazon.com/dynamodb/pricing/). Remove the stack, with the API, its key, the table and its posts, when you are done: + +```bash +serverless remove +``` + +## Next steps + +- Read [AppSync GraphQL APIs](https://www.serverless.com/framework/docs/providers/aws/guide/appsync) for the other `appSync` settings, and [Resolvers](https://www.serverless.com/framework/docs/providers/aws/guide/appsync/resolvers) for pipeline resolvers, TypeScript and Lambda resolvers. +- Require Amazon Cognito sign-in for the mutation and keep the query public with [additional authentication modes](https://www.serverless.com/framework/docs/providers/aws/guide/appsync/authentication). +- Build a REST API on the same kind of table with the [Express API with DynamoDB example](https://github.com/serverless/examples/tree/v4/aws-node-express-dynamodb-api). diff --git a/aws-node-appsync-dynamodb/example.json b/aws-node-appsync-dynamodb/example.json new file mode 100644 index 000000000..44fb1d1cc --- /dev/null +++ b/aws-node-appsync-dynamodb/example.json @@ -0,0 +1,27 @@ +{ + "title": "AppSync GraphQL API with DynamoDB (NodeJS)", + "description": "An AWS AppSync GraphQL API with API key authentication and two JavaScript resolvers that write and read posts in a DynamoDB table, from the built-in appSync block of serverless.yml.", + "language": "node", + "platform": "AWS", + "framework": "v4", + "author": { + "name": "Serverless, Inc.", + "link": "https://github.com/serverless", + "avatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" + }, + "services": [ + "appsync", + "dynamodb", + "iam" + ], + "test": { + "tier": "fast", + "checks": [ + { + "script": { + "path": "test/smoke.mjs" + } + } + ] + } +} diff --git a/aws-node-appsync-dynamodb/resolvers/createPost.js b/aws-node-appsync-dynamodb/resolvers/createPost.js new file mode 100644 index 000000000..3ac02b53b --- /dev/null +++ b/aws-node-appsync-dynamodb/resolvers/createPost.js @@ -0,0 +1,14 @@ +import { util } from '@aws-appsync/utils'; + +// Writes one post with a generated ID and returns it. +export function request(ctx) { + return { + operation: 'PutItem', + key: util.dynamodb.toMapValues({ id: util.autoId() }), + attributeValues: util.dynamodb.toMapValues({ title: ctx.args.title }), + }; +} + +export function response(ctx) { + return ctx.result; +} diff --git a/aws-node-appsync-dynamodb/resolvers/getPost.js b/aws-node-appsync-dynamodb/resolvers/getPost.js new file mode 100644 index 000000000..68c5ae7ec --- /dev/null +++ b/aws-node-appsync-dynamodb/resolvers/getPost.js @@ -0,0 +1,13 @@ +import { util } from '@aws-appsync/utils'; + +// Reads one post by its ID. Returns null when there is no such post. +export function request(ctx) { + return { + operation: 'GetItem', + key: util.dynamodb.toMapValues({ id: ctx.args.id }), + }; +} + +export function response(ctx) { + return ctx.result; +} diff --git a/aws-node-appsync-dynamodb/schema.graphql b/aws-node-appsync-dynamodb/schema.graphql new file mode 100644 index 000000000..a11272375 --- /dev/null +++ b/aws-node-appsync-dynamodb/schema.graphql @@ -0,0 +1,12 @@ +type Post { + id: ID! + title: String! +} + +type Query { + getPost(id: ID!): Post +} + +type Mutation { + createPost(title: String!): Post +} diff --git a/aws-node-appsync-dynamodb/serverless.yml b/aws-node-appsync-dynamodb/serverless.yml new file mode 100644 index 000000000..929f29203 --- /dev/null +++ b/aws-node-appsync-dynamodb/serverless.yml @@ -0,0 +1,48 @@ +service: appsync-dynamodb + +frameworkVersion: '4' + +provider: + name: aws + +appSync: + name: ${self:service}-${sls:stage} + authentication: + type: API_KEY + apiKeys: + - name: defaultKey + expiresAfter: 30d + dataSources: + postsTable: + type: AMAZON_DYNAMODB + config: + tableName: !Ref PostsTable + resolvers: + Query.getPost: + kind: UNIT + dataSource: postsTable + code: resolvers/getPost.js + Mutation.createPost: + kind: UNIT + dataSource: postsTable + code: resolvers/createPost.js + +resources: + Resources: + PostsTable: + Type: AWS::DynamoDB::Table + Properties: + BillingMode: PAY_PER_REQUEST + AttributeDefinitions: + - AttributeName: id + AttributeType: S + KeySchema: + - AttributeName: id + KeyType: HASH + Outputs: + GraphQlApiUrl: + Description: The GraphQL endpoint of the API + Value: ${appsync:url} + GraphQlApiKey: + Description: The API key that clients send in the x-api-key header + Value: ${appsync:apiKey.defaultKey} diff --git a/aws-node-appsync-dynamodb/test/smoke.mjs b/aws-node-appsync-dynamodb/test/smoke.mjs new file mode 100644 index 000000000..21b3bd058 --- /dev/null +++ b/aws-node-appsync-dynamodb/test/smoke.mjs @@ -0,0 +1,83 @@ +// Does what the README's Try it does: creates a post through the GraphQL API +// with the API key, reads it back by its ID, and checks that a request without +// the key is refused. +// +// Run by the example test runner, with the stack outputs in EXAMPLE_OUTPUTS. +// It calls only the API itself; the post goes with the table when the stack is +// removed. + +import { randomBytes } from 'node:crypto'; + +const RETRY_WINDOW_MS = 90_000; +const RETRY_DELAY_MS = 5_000; + +const outputs = JSON.parse(process.env.EXAMPLE_OUTPUTS ?? '{}'); +for (const key of ['GraphQlApiUrl', 'GraphQlApiKey']) { + if (!outputs[key]) fail(`stack output ${key} not found; got ${Object.keys(outputs).join(', ')}`); +} +const url = outputs.GraphQlApiUrl; +const apiKey = outputs.GraphQlApiKey; + +const title = `Hello from the smoke test ${randomBytes(4).toString('hex')}`; + +// A new API can take a moment to accept its key, so the first request retries. +const created = await until( + 'createPost', + () => graphql('mutation ($title: String!) { createPost(title: $title) { id title } }', { title }), + (r) => r.status === 200 && r.body?.data?.createPost, +); +const post = created.body.data.createPost; +if (post.title !== title || !post.id) fail(`createPost: expected a post with title "${title}" and an ID; got ${JSON.stringify(post)}`); + +const read = await graphql('query ($id: ID!) { getPost(id: $id) { id title } }', { id: post.id }); +const got = read.body?.data?.getPost; +if (read.status !== 200 || got?.id !== post.id || got?.title !== title) { + fail(`getPost(${post.id}): expected {"id":"${post.id}","title":"${title}"}; got status ${read.status}, ${read.text.slice(0, 300)}`); +} + +const missing = await graphql('query ($id: ID!) { getPost(id: $id) { id title } }', { id: 'no-such-post' }); +if (missing.status !== 200 || missing.body?.data?.getPost !== null) { + fail(`getPost(no-such-post): expected data.getPost null; got status ${missing.status}, ${missing.text.slice(0, 300)}`); +} + +const noKey = await graphql('query ($id: ID!) { getPost(id: $id) { id } }', { id: post.id }, { withKey: false }); +if (noKey.status !== 401) fail(`request without x-api-key: expected status 401; got ${noKey.status}, ${noKey.text.slice(0, 300)}`); + +console.log(`${url}: createPost returned ${post.id}; getPost read back "${title}"; unknown ID null; no API key 401`); + +async function graphql(query, variables, { withKey = true } = {}) { + const headers = { 'content-type': 'application/json' }; + if (withKey) headers['x-api-key'] = apiKey; + const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify({ query, variables }) }); + const text = await res.text(); + let body; + try { + body = JSON.parse(text); + } catch { + body = undefined; + } + return { status: res.status, text, body }; +} + +// Repeats `request` every RETRY_DELAY_MS until `done` accepts the response, for +// up to RETRY_WINDOW_MS. +async function until(what, request, done) { + const start = Date.now(); + let last; + for (;;) { + try { + const r = await request(); + if (done(r)) return r; + last = `status ${r.status}, body ${r.text.slice(0, 200)}`; + } catch (err) { + last = `request error: ${err.message}`; + } + if (Date.now() - start >= RETRY_WINDOW_MS) fail(`${what}: no expected answer within ${RETRY_WINDOW_MS / 1000} s; last: ${last}`); + await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS)); + } +} + +function fail(message) { + console.error(`smoke test failed: ${message}`); + process.exit(1); +} diff --git a/aws-node-upload-to-s3-and-postprocess/README.md b/aws-node-upload-to-s3-and-postprocess/README.md index e79c195ba..3aed4b115 100644 --- a/aws-node-upload-to-s3-and-postprocess/README.md +++ b/aws-node-upload-to-s3-and-postprocess/README.md @@ -1,89 +1,173 @@ -# Upload a file to S3 to trigger a lambda function -This example shows how to upload a file to S3 using a HTML form, and have S3 -trigger a lambda function. +# Process files uploaded to Amazon S3 -## Use-cases +[![Verified](https://raw.githubusercontent.com/serverless/examples/verified/badges/aws-node-upload-to-s3-and-postprocess.svg)](https://github.com/serverless/examples/blob/verified/results.json) -- Postprocess files uploaded to an S3 bucket. +An upload to an Amazon S3 bucket can start your code: S3 sends an event notification for each new object, and the [`s3` event](https://www.serverless.com/framework/docs/providers/aws/events/s3) of the Serverless Framework creates the bucket, the notification and the permission that lets S3 invoke your function. This example creates a bucket, invokes a Node.js function for every file uploaded under `uploads/`, and has the function read the file and write a summary of it under `processed/` in the same bucket. -## Setup +## What it deploys -- The upload bucket defaults to `upload-postprocess--`, which - is unique to your AWS account and stage. To use a different name, set the - `BUCKET` environment variable before deploying. -- Edit `generate-form.js` and fill in your `aws_access_key_id`, - `aws_secret_access_key` and `bucket_name` (matching the bucket name above). -- Run `yarn install` to install crypto-js dependency for `generate-form.js`. -- Generate the HTML form: +- An S3 bucket named `upload-postprocess--`, with an event notification for objects created under `uploads/`. +- A Lambda function, `postprocess`, with an IAM role that can read objects under `uploads/` and write objects under `processed/` in that bucket, and a CloudWatch Logs log group. +- A stack output, `UploadBucketName`, with the bucket's name. +## Prerequisites -```bash -yarn install -node generate-form.js -``` +- The Serverless Framework CLI: `npm i -g serverless`, which needs [Node.js](https://nodejs.org/). See [Getting started](https://www.serverless.com/framework/docs/getting-started). +- An AWS account, with credentials configured on your machine. See [AWS credentials](https://www.serverless.com/framework/docs/providers/aws/guide/credentials). +- A Serverless account, or a license key in `SERVERLESS_LICENSE_KEY`. The CLI asks you to sign in the first time you run it. +- The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), to upload a file and read the result. The commands in Try it are written for Bash. ## Deploy -In order to deploy the example, simply run: +Deploy from this directory: ```bash serverless deploy ``` -The output should look similar to: +Without options, the deploy uses the stage `dev` and the Region `us-east-1`. To change them, pass `--stage` or `--region`, and pass the same options to every later command, including `serverless remove`. + +You should see output like this: +```text +Deploying "s3-postprocess" to stage "dev" (us-east-1) +✔ Service deployed to stack s3-postprocess-dev (56s) +functions: + postprocess: s3-postprocess-dev-postprocess (6.6 kB) ``` -Deploying "upload-to-s3-and-postprocess" to stage "dev" (us-east-1) -✔ Service deployed to stack upload-to-s3-and-postprocess-dev (38s) +## Try it -functions: - postprocess: upload-to-s3-and-postprocess-dev-postprocess (1.1 kB) +Print the stack's outputs: + +```bash +serverless info --verbose +``` + +The line you need is this one: + +```text +Stack Outputs: + UploadBucketName: upload-postprocess-dev-123456789012 ``` -## Usage +Copy its value into a shell variable: -Open the generated `frontend/index.html` in your browser, or run: +```bash +BUCKET=upload-postprocess-dev-123456789012 +``` + +Upload a text file under `uploads/`: ```bash -xdg-open frontend/index.html +printf 'The quick brown fox\njumps over the lazy dog.\n' > notes.txt +aws s3 cp notes.txt "s3://$BUCKET/uploads/notes.txt" ``` -Select a PNG image smaller than 1Mb, and click "Upload File to S3". +S3 invokes the function a moment later. Read the summary it wrote to `processed/notes.txt.json`: -You should get an XML response similar to: +```bash +aws s3 cp "s3://$BUCKET/processed/notes.txt.json" - +``` -```xml - - https://serverless-fetch-file-and-store-in-s3.s3.amazonaws.com/uploads%2Fimage.png - serverless-fetch-file-and-store-in-s3 - uploads/image.png - "08c03c6a24e5058b9f3556981a23b1d7" - +```json +{ + "source": "uploads/notes.txt", + "bytes": 45, + "lines": 2, + "words": 9, + "sha256": "26e3df02e41ff53b6b16484bbdc2abe316d660fde0d09df8436ce4248ee27ab5", + "processedAt": "2026-11-25T20:16:19.406Z" +} ``` -After a while, the postprocess function gets triggered by an S3 event: +If the command answers `The specified key does not exist`, wait a few seconds and run it again. The function's log shows each file it processed: ```bash serverless logs --function postprocess ``` +```text +INFO Processed uploads/notes.txt (45 bytes, 9 words) into processed/notes.txt.json ``` -START RequestId: e2deccf2a0-11e6-b6e3fbcfad7d8c Version: $LATEST -2014 12:32:30.350 (+02:00) e2deccf2a0-11e6-b6e3fbcfad7d8c New .png object has been created: uploads/image.png (23975 bytes) -END RequestId: e2deccf2a0-11e6-b6e3fbcfad7d8c -REPORT RequestId: e2deccf2a0-11e6-b6e3fbcfad7d8c Duration: 2.84 ms Billed Duration: 100 msMemory Size: 1024 MB Max Memory Used: 29 MB + +## How it works + +The `s3` event in [`serverless.yml`](https://github.com/serverless/examples/blob/v4/aws-node-upload-to-s3-and-postprocess/serverless.yml) names a bucket the stack doesn't have yet, so the Framework creates it with the notification configuration, and adds the permission that lets S3 invoke the function: + +```yaml +custom: + bucket: upload-postprocess-${sls:stage}-${aws:accountId} + +functions: + postprocess: + handler: handler.postprocess + environment: + OUTPUT_PREFIX: processed/ + events: + - s3: + bucket: ${self:custom.bucket} + event: s3:ObjectCreated:* + rules: + - prefix: uploads/ ``` + +Bucket names are unique across all AWS accounts, so the name includes the stage and the account ID; two stages, or two readers of this example, get two buckets. The `prefix` rule limits the notification to keys under `uploads/`. The function writes its results under `processed/`, which the rule doesn't match, so its own writes don't invoke it again. Without the rule, every result would start another invocation. + +S3 invokes the function asynchronously, with one or more records per event. [`handler.mjs`](https://github.com/serverless/examples/blob/v4/aws-node-upload-to-s3-and-postprocess/handler.mjs) decodes each record's key, which arrives URL-encoded, reads the object with the AWS SDK for JavaScript v3 that the Node.js runtime includes, and writes the summary: + +```javascript +const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' ')); +const object = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key })); +// ... +await s3.send(new PutObjectCommand({ Bucket: bucket, Key: outputKey, Body: JSON.stringify(summary, null, 2) })); +``` + +The function's role can read only under `uploads/` and write only under `processed/`, set in `provider.iam.role.statements`: + +```yaml +provider: + iam: + role: + statements: + - Effect: Allow + Action: + - s3:GetObject + Resource: arn:aws:s3:::${self:custom.bucket}/uploads/* + - Effect: Allow + Action: + - s3:PutObject + Resource: arn:aws:s3:::${self:custom.bucket}/processed/* +``` + +The bucket's name is a stack output, declared under `resources.Outputs`, so that `serverless info --verbose` prints it. + +## Cost and cleanup + +While the example is deployed, Amazon S3 bills the objects it stores and the requests to them, Lambda bills each invocation and the function's compute time, and CloudWatch Logs bills the function's stored log data. See [Amazon S3 pricing](https://aws.amazon.com/s3/pricing/), [Lambda pricing](https://aws.amazon.com/lambda/pricing/) and [CloudWatch pricing](https://aws.amazon.com/cloudwatch/pricing/). + +CloudFormation deletes only an empty bucket, so delete the bucket's objects first, then remove the stack with the bucket, the function and its log group: + +```bash +aws s3 rm "s3://$BUCKET" --recursive +serverless remove +``` + +## Next steps + +- Read [S3 bucket events](https://www.serverless.com/framework/docs/providers/aws/events/s3) for other event types, suffix rules, several functions on one bucket and adding notifications to a bucket that already exists. +- Write results to a second bucket instead of a prefix: declare it under [`provider.s3`](https://www.serverless.com/framework/docs/providers/aws/events/s3) and grant the function `s3:PutObject` on it. +- Store each result in a table instead of the bucket, as the [Express API with DynamoDB example](https://github.com/serverless/examples/tree/v4/aws-node-express-dynamodb-api) does for API requests. diff --git a/aws-node-upload-to-s3-and-postprocess/example.json b/aws-node-upload-to-s3-and-postprocess/example.json new file mode 100644 index 000000000..cf4d75167 --- /dev/null +++ b/aws-node-upload-to-s3-and-postprocess/example.json @@ -0,0 +1,29 @@ +{ + "title": "AWS Upload a file to S3 to trigger a Lambda function example in NodeJS", + "description": "This example shows how an upload to an Amazon S3 bucket triggers a Lambda function that reads the new object and writes a result back to the bucket.", + "language": "node", + "platform": "AWS", + "framework": "v4", + "priority": 10, + "author": { + "name": "walgarch", + "link": "https://github.com/walgarch", + "avatar": "https://avatars1.githubusercontent.com/u/32451330?v=4&s=140" + }, + "services": [ + "lambda", + "s3", + "iam", + "logs" + ], + "test": { + "tier": "fast", + "checks": [ + { + "script": { + "path": "test/smoke.mjs" + } + } + ] + } +} diff --git a/aws-node-upload-to-s3-and-postprocess/frontend/index.template.html b/aws-node-upload-to-s3-and-postprocess/frontend/index.template.html deleted file mode 100644 index 91151ab22..000000000 --- a/aws-node-upload-to-s3-and-postprocess/frontend/index.template.html +++ /dev/null @@ -1,26 +0,0 @@ - - - S3 POST Form - - - - -
- - - - - - - - - - Destination filename: -
- File to upload to S3: - -
- -
- - diff --git a/aws-node-upload-to-s3-and-postprocess/generate-form.js b/aws-node-upload-to-s3-and-postprocess/generate-form.js deleted file mode 100755 index dbbac1341..000000000 --- a/aws-node-upload-to-s3-and-postprocess/generate-form.js +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env node - -import crypto from 'crypto-js'; -import Hex from 'crypto-js/enc-hex.js'; -import fs from 'fs'; - -// from: https://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-javascript -function getSignatureKey(key, dateStamp, regionName, serviceName) { - const kDate = crypto.HmacSHA256(dateStamp, `AWS4${key}`); - const kRegion = crypto.HmacSHA256(regionName, kDate); - const kService = crypto.HmacSHA256(serviceName, kRegion); - const kSigning = crypto.HmacSHA256('aws4_request', kService); - return kSigning; -} - -const awsAccessKeyId = ''; -const awsSecretAccessKey = ''; -const bucketName = ''; -const region = ''; - -const msPerDay = 24 * 60 * 60 * 1000; -const expiration = new Date(Date.now() + msPerDay).toISOString(); -const bucketUrl = `https://${bucketName}.s3.amazonaws.com`; -const date = new Date().toISOString().slice(0, 10).replace(/-/g, ''); -const credentials = `${awsAccessKeyId}/${date}/${region}/s3/aws4_request`; - -// Sample policy and form: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html -const policy = { - expiration, - conditions: [ - { bucket: bucketName }, - ['starts-with', '$key', 'uploads/'], - { acl: 'public-read' }, - ['starts-with', '$Content-Type', 'image/png'], - // ['starts-with', '$success_action_redirect', ''], - ['starts-with', '$success_action_status', ''], - - { 'x-amz-credential': credentials }, - { 'x-amz-algorithm': 'AWS4-HMAC-SHA256' }, - { 'x-amz-date': `${date}T000000Z` }, - ], -}; - -const policyB64 = Buffer.from(JSON.stringify(policy), 'utf-8').toString('base64'); - -const sigKey = getSignatureKey(awsSecretAccessKey, date, region, 's3'); - -const signature = Hex.stringify(crypto.HmacSHA256(policyB64, sigKey)); - -fs.readFile('frontend/index.template.html', 'utf8', (err, input) => { - if (err) { - console.log(err); - } - - const data = input - .replace(/%BUCKET_URL%/g, bucketUrl) - .replace(/%POLICY_BASE64%/g, policyB64) - .replace(/%CREDENTIAL%/g, credentials) - .replace(/%DATE%/g, `${date}T000000Z`) - .replace(/%SIGNATURE%/g, signature); - - fs.writeFile('frontend/index.html', data, 'utf8', (e) => { - if (e) { - console.log(e); - } - }); -}); diff --git a/aws-node-upload-to-s3-and-postprocess/handler.js b/aws-node-upload-to-s3-and-postprocess/handler.js deleted file mode 100644 index 0bbb3669c..000000000 --- a/aws-node-upload-to-s3-and-postprocess/handler.js +++ /dev/null @@ -1,7 +0,0 @@ -export const postprocess = async (event) => { - event.Records.forEach((record) => { - const filename = record.s3.object.key; - const filesize = record.s3.object.size; - console.log(`New .png object has been created: ${filename} (${filesize} bytes)`); - }); -}; diff --git a/aws-node-upload-to-s3-and-postprocess/handler.mjs b/aws-node-upload-to-s3-and-postprocess/handler.mjs new file mode 100644 index 000000000..26807b771 --- /dev/null +++ b/aws-node-upload-to-s3-and-postprocess/handler.mjs @@ -0,0 +1,40 @@ +import { createHash } from 'node:crypto'; +import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; + +const s3 = new S3Client(); +const OUTPUT_PREFIX = process.env.OUTPUT_PREFIX; + +// Runs for every object created under uploads/. Reads the object and writes a +// summary of it to processed/.json. The output prefix is outside the +// trigger's prefix, so writing it doesn't invoke this function again. +export const postprocess = async (event) => { + for (const record of event.Records) { + const bucket = record.s3.bucket.name; + // Keys arrive URL-encoded, with a space as "+". + const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' ')); + + const object = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key })); + const body = Buffer.from(await object.Body.transformToByteArray()); + const text = body.toString('utf8'); + + const summary = { + source: key, + bytes: body.length, + lines: text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0), + words: text.split(/\s+/).filter(Boolean).length, + sha256: createHash('sha256').update(body).digest('hex'), + processedAt: new Date().toISOString(), + }; + + const outputKey = `${OUTPUT_PREFIX}${key.slice(key.indexOf('/') + 1)}.json`; + await s3.send( + new PutObjectCommand({ + Bucket: bucket, + Key: outputKey, + Body: JSON.stringify(summary, null, 2), + ContentType: 'application/json', + }), + ); + console.log(`Processed ${key} (${summary.bytes} bytes, ${summary.words} words) into ${outputKey}`); + } +}; diff --git a/aws-node-upload-to-s3-and-postprocess/package.json b/aws-node-upload-to-s3-and-postprocess/package.json deleted file mode 100644 index d1be5d9ee..000000000 --- a/aws-node-upload-to-s3-and-postprocess/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "upload-to-s3-and-postprocess", - "description": "Upload a files to S3 to trigger a lambda function.", - "version": "1.0.0", - "type": "module", - "author": "Christoph Gysin ", - "license": "MIT", - "dependencies": { - "crypto-js": "^4.2.0" - } -} diff --git a/aws-node-upload-to-s3-and-postprocess/serverless.yml b/aws-node-upload-to-s3-and-postprocess/serverless.yml index c19fa4ce7..05ec0996b 100644 --- a/aws-node-upload-to-s3-and-postprocess/serverless.yml +++ b/aws-node-upload-to-s3-and-postprocess/serverless.yml @@ -1,11 +1,7 @@ -service: upload-to-s3-and-postprocess +service: s3-postprocess frameworkVersion: '4' -custom: - defaultBucket: upload-postprocess-${sls:stage}-${aws:accountId} - bucket: ${env:BUCKET, self:custom.defaultBucket} - provider: name: aws runtime: nodejs24.x @@ -13,17 +9,34 @@ provider: iam: role: statements: + # Read what arrives under uploads/ and write results under processed/. + - Effect: Allow + Action: + - s3:GetObject + Resource: arn:aws:s3:::${self:custom.bucket}/uploads/* - Effect: Allow Action: - - s3:* - Resource: "*" + - s3:PutObject + Resource: arn:aws:s3:::${self:custom.bucket}/processed/* + +custom: + # Bucket names are global: the stage and the account ID keep this one unique. + bucket: upload-postprocess-${sls:stage}-${aws:accountId} functions: postprocess: handler: handler.postprocess + environment: + OUTPUT_PREFIX: processed/ events: - s3: bucket: ${self:custom.bucket} event: s3:ObjectCreated:* rules: - - suffix: .png + - prefix: uploads/ + +resources: + Outputs: + UploadBucketName: + Description: The bucket to upload files to, under uploads/ + Value: ${self:custom.bucket} diff --git a/aws-node-upload-to-s3-and-postprocess/test/smoke.mjs b/aws-node-upload-to-s3-and-postprocess/test/smoke.mjs new file mode 100644 index 000000000..cd2bd4c94 --- /dev/null +++ b/aws-node-upload-to-s3-and-postprocess/test/smoke.mjs @@ -0,0 +1,95 @@ +// Does what the README's Try it does: uploads a text file under uploads/ in the +// example's bucket, waits for the postprocess function to write its summary +// under processed/, and checks that the summary describes that file. +// +// Run by the example test runner, with the stack outputs in EXAMPLE_OUTPUTS, +// EXAMPLE_REGION set and AWS credentials in the environment. It calls Amazon S3 +// with the aws CLI: put-object, get-object and delete-object on the objects it +// creates, which it deletes again so that the stack's bucket can be removed. + +import { execFileSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const WAIT_MS = 90_000; +const DELAY_MS = 3_000; + +const outputs = JSON.parse(process.env.EXAMPLE_OUTPUTS ?? '{}'); +const bucket = outputs.UploadBucketName; +if (!bucket) fail(`stack output UploadBucketName not found; got ${Object.keys(outputs).join(', ')}`); +const region = ['--region', process.env.EXAMPLE_REGION ?? 'us-east-1']; + +const name = `smoke-${randomBytes(4).toString('hex')}.txt`; +const content = `Hello from ${name}\nThis file was uploaded by the smoke test.\n`; +const expected = { + source: `uploads/${name}`, + bytes: Buffer.byteLength(content), + lines: 2, + words: 11, + sha256: createHash('sha256').update(content).digest('hex'), +}; +const outputKey = `processed/${name}.json`; + +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-')); +const input = path.join(tmp, name); +const result = path.join(tmp, 'result.json'); +fs.writeFileSync(input, content); + +let failure; +try { + aws(['s3api', 'put-object', ...region, '--bucket', bucket, '--key', expected.source, '--body', input]); + const summary = await waitForSummary(); + for (const [field, value] of Object.entries(expected)) { + if (summary[field] !== value) { + failure = `${outputKey}: expected ${field} ${JSON.stringify(value)}; got ${JSON.stringify(summary[field])} in ${JSON.stringify(summary)}`; + break; + } + } + if (!failure) { + console.log(`s3://${bucket}/${expected.source} -> ${outputKey}: ${summary.bytes} bytes, ${summary.lines} lines, ${summary.words} words, sha256 ${summary.sha256.slice(0, 12)}...`); + } +} catch (err) { + failure = err.message; +} finally { + // Leave the bucket empty, so that removing the stack can delete it. + for (const key of [expected.source, outputKey]) { + try { + aws(['s3api', 'delete-object', ...region, '--bucket', bucket, '--key', key]); + } catch { + // Reported by the failure above, or the object was never written. + } + } + fs.rmSync(tmp, { recursive: true, force: true }); +} +if (failure) fail(failure); + +// S3 invokes the function asynchronously, so the summary appears after a moment. +async function waitForSummary() { + const start = Date.now(); + let last; + for (;;) { + try { + aws(['s3api', 'get-object', ...region, '--bucket', bucket, '--key', outputKey, result]); + return JSON.parse(fs.readFileSync(result, 'utf8')); + } catch (err) { + last = err.message; + } + if (Date.now() - start >= WAIT_MS) throw new Error(`${outputKey}: not written within ${WAIT_MS / 1000} s; last: ${last}`); + await new Promise((resolve) => setTimeout(resolve, DELAY_MS)); + } +} + +function aws(args) { + try { + return execFileSync('aws', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (err) { + throw new Error(`aws ${args.slice(0, 2).join(' ')}: exit ${err.status}, ${String(err.stderr ?? '').trim().slice(0, 300)}`); + } +} + +function fail(message) { + console.error(`smoke test failed: ${message}`); + process.exit(1); +} diff --git a/examples.json b/examples.json index 54846582c..81996ef9d 100644 --- a/examples.json +++ b/examples.json @@ -882,14 +882,15 @@ { "title": "AWS Upload a file to S3 to trigger a Lambda function example in NodeJS", "name": "aws-node-upload-to-s3-and-postprocess", - "description": "This example shows how to upload a file to S3 using a HTML form, and have S3 trigger a lambda function.", + "description": "This example shows how an upload to an Amazon S3 bucket triggers a Lambda function that reads the new object and writes a result back to the bucket.", "githubUrl": "https://github.com/serverless/examples/tree/v4/aws-node-upload-to-s3-and-postprocess", "framework": "v4", "language": "node", "platform": "aws", "authorLink": "https://github.com/walgarch", "authorName": "walgarch", - "authorAvatar": "https://avatars1.githubusercontent.com/u/32451330?v=4&s=140" + "authorAvatar": "https://avatars1.githubusercontent.com/u/32451330?v=4&s=140", + "priority": 10 }, { "title": "Next.js and Express web apps on one custom domain", @@ -2884,5 +2885,17 @@ "authorLink": "https://github.com/serverless", "authorName": "Serverless, Inc.", "authorAvatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" + }, + { + "title": "AppSync GraphQL API with DynamoDB (NodeJS)", + "name": "aws-node-appsync-dynamodb", + "description": "An AWS AppSync GraphQL API with API key authentication and two JavaScript resolvers that write and read posts in a DynamoDB table, from the built-in appSync block of serverless.yml.", + "githubUrl": "https://github.com/serverless/examples/tree/v4/aws-node-appsync-dynamodb", + "framework": "v4", + "language": "node", + "platform": "aws", + "authorLink": "https://github.com/serverless", + "authorName": "Serverless, Inc.", + "authorAvatar": "https://avatars1.githubusercontent.com/u/13742415?s=200&v=4" } ]