Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ serverless deploy
| [AWS Nest application example (NodeJS & Typescript)](https://github.com/serverless/examples/tree/v4/aws-node-typescript-nest) <br/> 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) <br/> 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) <br/> 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) <br/> 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) <br/> 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) <br/> 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) <br/> The example shows you how to deploy simple websocket authorizers | nodeJS |
| [AWS NodeJS Example](https://github.com/serverless/examples/tree/v4/aws-node) <br/> This template demonstrates how to deploy a simple NodeJS function running on AWS Lambda using the Serverless Framework. | nodeJS |
Expand Down Expand Up @@ -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) <br/> 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) <br/> 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) <br/> 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) <br/> 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 |
<!-- AUTO-GENERATED-CONTENT:END -->

## Community Examples
Expand Down
174 changes: 174 additions & 0 deletions aws-node-appsync-dynamodb/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
<!--
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.'
layout: Doc
framework: v4
platform: AWS
language: nodeJS
authorLink: 'https://github.com/serverless'
authorName: 'Serverless, Inc.'
authorAvatar: 'https://avatars1.githubusercontent.com/u/13742415?s=200&v=4'
-->

# 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-<stage>`, 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 `<type>.<field>`. 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).
27 changes: 27 additions & 0 deletions aws-node-appsync-dynamodb/example.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
]
}
}
14 changes: 14 additions & 0 deletions aws-node-appsync-dynamodb/resolvers/createPost.js
Original file line number Diff line number Diff line change
@@ -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;
}
13 changes: 13 additions & 0 deletions aws-node-appsync-dynamodb/resolvers/getPost.js
Original file line number Diff line number Diff line change
@@ -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;
}
12 changes: 12 additions & 0 deletions aws-node-appsync-dynamodb/schema.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
type Post {
id: ID!
title: String!
}

type Query {
getPost(id: ID!): Post
}

type Mutation {
createPost(title: String!): Post
}
48 changes: 48 additions & 0 deletions aws-node-appsync-dynamodb/serverless.yml
Original file line number Diff line number Diff line change
@@ -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}
83 changes: 83 additions & 0 deletions aws-node-appsync-dynamodb/test/smoke.mjs
Original file line number Diff line number Diff line change
@@ -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);
}
Loading