<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Junyou Lin on Medium]]></title>
        <description><![CDATA[Stories by Junyou Lin on Medium]]></description>
        <link>https://medium.com/@junyoulin?source=rss-cb5a92b81dd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ovrvAABKIC4W7wRGby_HmQ.jpeg</url>
            <title>Stories by Junyou Lin on Medium</title>
            <link>https://medium.com/@junyoulin?source=rss-cb5a92b81dd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:40:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@junyoulin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to implement DynamoDB single table designs with AWS Amplify (AppSync, Lambda)]]></title>
            <link>https://medium.com/lapis/how-to-implement-dynamodb-single-table-designs-with-aws-amplify-appsync-lambda-8838e86b2f71?source=rss-cb5a92b81dd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8838e86b2f71</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[aws-appsync]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Junyou Lin]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 04:03:16 GMT</pubDate>
            <atom:updated>2023-02-14T04:37:55.057Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore the implementation of single table designs in an AWS Amplify application using AppSync and Lambda.</p><p>You should know some concepts beforehand since this article only focuses on the implementation of single table design. For example:</p><ul><li><a href="https://aws.amazon.com/blogs/compute/creating-a-single-table-design-with-amazon-dynamodb/">how to design single table</a></li><li><a href="https://docs.amplify.aws/cli/graphql/examples-and-solutions/">multiple tables in Amplify</a></li><li><a href="https://aws.amazon.com/blogs/mobile/single-table-vs-multi-table-dynamodb-appsync/">single table vs multiple tables</a></li></ul><p>While Amplify currently only supports multiple table designs, it is still possible to implement single table designs with some modifications as below structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*ziWssYy1p43YBphmYNQslQ.png" /></figure><h3>Step 1: Define Access Patterns</h3><p>Let’s assume a use case in which customers can buy products and place orders on an e-commerce website. To structure our partition key and sort key in the early stages, we need to define our access patterns. Let’s create three simple access patterns:</p><ol><li>Retrieve customer information using the customer ID.</li><li>Retrieve product information using the product ID.</li><li>Retrieve order information, including customer and product information, using the order ID.</li></ol><h3>Step 2: Create a Table in DynamoDB</h3><p>In the AWS DynamoDB console, we’ll create a table named “ecommerce” and name the partition key as “PK” and the sort key as “SK”. Since we’re using a single table design, we won’t be able to take advantage of the @model directive in Amplify GraphQL that automatically generates tables in DynamoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYT4_U3F2q0D8r2FCMCeBQ.png" /></figure><h3>Step 3: Create graphQL API in Amplify</h3><p>If you have not initialized the amplify project yet, please run this command:</p><pre>amplify init</pre><p>Otherwise, we can start to create a new GraphQL API in our Amplify project by running the following command:</p><pre>amplify add api<br>? Select from one of the below mentioned services: GraphQL<br>? Here is the GraphQL API that we will create. Select a setting to edit or continue Continue<br>? Choose a schema template: One-to-many relationship (e.g., &quot;Blogs&quot; with &quot;Posts&quot; and &quot;Comments&quot;)</pre><p>The schema template is not important as we will override it by our e-commerce use case. Now let’s override the code in schema.graphql as below. For the sake of the query test, we also create its mutation correspondingly.</p><pre># This &quot;input&quot; configures a global authorization rule to enable public access to<br># all models in this schema. Learn more about authorization rules here: https://docs.amplify.aws/cli/graphql/authorization-rules<br>input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY!<br><br>type Query {<br>  getCustomerById(id: ID!): Customer @function(name: &quot;ecommerce-${env}&quot;)<br>  getProductById(id: ID!): Product @function(name: &quot;ecommerce-${env}&quot;)<br>  getOrderById(id: ID!): Order @function(name: &quot;ecommerce-${env}&quot;)<br>}<br>type Mutation {<br>  createCustomer(input: createCustomerInput!): Customer @function(name: &quot;ecommerce-${env}&quot;)<br>  createProduct(input: createProductInput!): Product @function(name: &quot;ecommerce-${env}&quot;)<br>  createOrder(input: createOrderInput!): Order @function(name: &quot;ecommerce-${env}&quot;)<br>}<br>type Customer {<br>  PK: ID!<br>  email: String!<br>}<br>type Product {<br>  PK: ID!<br>  qty: Int!<br>  price: Float!<br>  name: String!<br>  detail: AWSJSON!<br>}<br>type Order {<br>  PK: ID!<br>  SK: ID!<br>  type: String!<br>  amount: Float!<br>  orderItems: [OrderItem]<br>}<br>type OrderItem {<br>  PK: ID!<br>  SK: ID!<br>  price: Float!<br>  name: String!<br>  qty: Int!<br>  type: String!<br>}<br>input createCustomerInput {<br>  email: String!<br>}<br>input createProductInput {<br>  qty: Int!<br>  price: Float!<br>  name: String!<br>  detail: AWSJSON!<br>}<br>input createOrderInput {<br>  amount: Float!<br>  products: [createOrderItemInput!]!<br>  customerID: ID!<br>}<br>input createOrderItemInput {<br>  qty: Int!<br>  price: Float!<br>  name: String!<br>  productID: ID!<br>}</pre><h3>Step 4: Create Lambda function resolver</h3><p>You may notice the type of Query and Mutation above have @funciton directive which helps to resolve the request and respond between AppSync and DynamoDB. So let’s create this function in Amplify:</p><pre>amplify add function<br>? Select which capability you want to add: Lambda function (serverless function)<br>? Provide an AWS Lambda function name: ecommerce<br>? Choose the runtime that you want to use: NodeJS<br>? Choose the function template that you want to use: Hello World<br>? Do you want to configure advanced settings? No<br>? Do you want to edit the local lambda function now? No<br>Successfully added resource ecommerce locally.</pre><p>Now let’s write some code for this lambda resolve under amplify/backend/function/ecommerce/src directory:</p><h4>index.js</h4><p>The index.js file serves as the root for a Lambda function that handles API requests based on the field name and responds with the correct data structure, as defined in the schema.graphql file.</p><pre>const AWS = require(&#39;aws-sdk&#39;)<br>const {v4: uuid} = require(&#39;uuid&#39;)<br>const getCustomerById = require(&#39;./getCustomerById&#39;)<br>const getProductById = require(&#39;./getProductById&#39;)<br>const getOrderById = require(&#39;./getOrderById&#39;)<br>const createCustomer = require(&#39;./createCustomer&#39;)<br>const createProduct = require(&#39;./createProduct&#39;)<br>const createOrder = require(&#39;./createOrder&#39;)<br>const docClient = new AWS.DynamoDB.DocumentClient()<br><br>exports.handler = async (event) =&gt; {<br>  const {fieldName, arguments} = event<br>  switch (fieldName) {<br>    case &quot;getCustomerById&quot;:<br>      return await getCustomerById(arguments, docClient)<br>    case &quot;getProductById&quot;:<br>      return await getProductById(arguments, docClient)<br>    case &quot;getOrderById&quot;:<br>      return await getOrderById(arguments, docClient)<br>    case &quot;createCustomer&quot;:<br>      return await createCustomer(arguments, docClient, uuid)<br>    case &quot;createProduct&quot;:<br>      return await createProduct(arguments, docClient, uuid)<br>    case &quot;createOrder&quot;:<br>      return await createOrder(arguments, docClient, uuid)<br>    default:<br>      return null<br>  }<br>};</pre><h4>getCustomerById.js</h4><p>Retrieve customer information by its id.</p><pre>async function getCustomerById({id}, docClient) {<br>  const params = {<br>    TableName: &quot;ecommerce&quot;,<br>    Key: {PK: id, SK: id}<br>  }<br>  try {<br>    const {Item} = await docClient.get(params).promise()<br>    if (Item !== null) {<br>      return Item<br>    }<br>  } catch (err) {<br>    return err<br>  }<br>}<br>module.exports = getCustomerById</pre><h4>GetproductById.js</h4><p>Retrieve product information by its id.</p><pre>async function getProductById({id}, docClient) {<br>  const params = {<br>    TableName: &#39;ecommerce&#39;,<br>    Key: {PK: id, SK: id}<br>  }  <br>  try {<br>    const {Item} = await docClient.get(params).promise()<br>    if (Item !== null) {<br>      return Item<br>    }<br>  } catch (err) {<br>    return err<br>  }<br>}<br>module.exports = getProductById</pre><h4>getOrderById.js:</h4><p>To retrieve order information that includes products and customer information, we will use the docClient.query() method. This method will retrieve all items in the table with the same partition key. The result will be an array of items, so we have written a function called formatOrderResponseData to format the data into the order type schema defined in schema.graphql.</p><pre>async function getOrderById({id}, docClient) {<br>  const params = {<br>    TableName: &quot;ecommerce&quot;,<br>    KeyConditionExpression: `PK = :id`,<br>    ExpressionAttributeValues: {<br>      &quot;:id&quot;: id<br>    }<br>  }<br>  try {<br>    const {Items} = await docClient.query(params).promise()<br>    if (Items.length) {<br>      return formatOrderResponseData(Items)<br>    }<br>  } catch (err) {<br>    return err<br>  }<br>}<br><br>function formatOrderResponseData(orderData) {<br>  let order;<br>  orderData.forEach(({PK, SK, type, amount, price, name, qty}) =&gt; {<br>    if (type === &#39;order&#39;) {<br>      order =<br>        {<br>          PK,<br>          SK,<br>          type,<br>          amount,<br>          orderItems: []<br>        };<br>    }<br>    if (type === &#39;orderItem&#39;) {<br>      order.orderItems.push({<br>        PK,<br>        SK,<br>        price,<br>        name,<br>        qty,<br>        type<br>      });<br>    }<br>  });<br>  return order;<br>}<br><br>module.exports = getOrderById</pre><h4>createCustomer.js</h4><p>To create a customer, we need to first define its partition and sort key. The partition and sort key should start with “C#” to indicate that it’s a customer.</p><pre>async function createCustomer({input:{email}}, docClient, uuid) {<br>  const customerID = `C#${uuid()}`<br>  const params = {<br>    TableName: &quot;ecommerce&quot;,<br>    Item: {<br>      PK: customerID,<br>      SK: customerID,<br>      email,<br>      type: &#39;customer&#39;,<br>    },<br>  }<br>  const item =  await docClient.put(params).promise()<br>  if (item !== null){<br>    return params.Item;<br>  }<br>}<br><br>module.exports = createCustomer</pre><h4>createProduct.js</h4><p>To create a product, we can set its partition and sort key that start with “P#” to indicate that it’s a product.</p><pre>async function createProduct({input: {qty, price, name, detail}}, docClient, uuid) {<br>  const productID = `P#${uuid()}`;<br>  const params = {<br>    TableName : &quot;ecommerce&quot;,<br>    Item: {<br>      PK: productID,<br>      SK: productID,<br>      qty,<br>      price,<br>      name,<br>      detail,<br>      type: &#39;product&#39;,<br>    },<br>  }<br>  try {<br>    const item =  await docClient.put(params).promise()<br>    if (item !== null){<br>      return params.Item;<br>    }<br>  } catch (err) {<br>    return err<br>  }<br>}<br><br>module.exports = createProduct</pre><h4>createOrder.js</h4><p>To create an order, there are three write requests involved:</p><ol><li>creating the order</li><li>creating the order item</li><li>updating the product quantity</li></ol><p>The docClient.transactWrite function has atomicity, meaning that if any of the requests fail, all write transactions will be abandoned.</p><pre>async function createOrder({input: {amount, products, customerID}}, docClient, uuid) {<br>    const PK = `O#${uuid()}`<br>    const TableName = &#39;ecommerce&#39;<br>    const params = {<br>      TransactItems: [{<br>        Put: {<br>          TableName,<br>          Item: {<br>            PK,<br>            SK: customerID,<br>            amount,<br>            type: &#39;order&#39;<br>          }<br>        }<br>      }].concat(products.map(({productID, qty, price, name}) =&gt; [<br>        {<br>          Put: {<br>            TableName,<br>            Item: {<br>              PK,<br>              SK: productID,<br>              type: &#39;orderItem&#39;,<br>              qty,<br>              price,<br>              name<br>            }<br>          }<br>        },<br>        {<br>          Update: {<br>            TableName,<br>            Key: {<br>              PK: productID,<br>              SK: productID<br>            },<br>            UpdateExpression: &#39;SET qty = qty - :qty&#39;,<br>            ExpressionAttributeValues: {<br>              &#39;:qty&#39;: qty<br>            },<br>            ConditionExpression: &#39;qty &gt;= :qty&#39;<br>          }<br>        }<br>      ])).flat()<br>    }<br>  try {<br>    const item =  await docClient.transactWrite(params).promise()<br>    if (item !== null){<br>      return {<br>        PK,<br>        SK: customerID,<br>        amount,<br>        type: &#39;order&#39;,<br>        orderItems: products.map(({productID, qty, price, name}) =&gt; ({<br>          PK,<br>          SK: productID,<br>          price,<br>          name,<br>          qty,<br>          type: &#39;orderItem&#39;,<br>        }<br>        ))<br>      };<br>    }<br>  } catch (err) {<br>    return err<br>  }<br>  }<br><br>module.exports = createOrder</pre><h3>Step 5: Amplify push and test the API</h3><p>We’re almost done! To deploy our code, let’s run the command amplify push in the terminal. Upon successful deployment, we should see our schema in the AppSync console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiQnck0KfNO88KQq8rfWWw.png" /></figure><p>The final step in testing our API is to grant the Lambda function permission to read and write to DynamoDB. We need to locate the Lambda function name in the IAM role and add read and write policies for DynamoDB.</p><p>Now, we can test our API on the AppSync query page by first creating a customer and a product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lffh-Iiek62HC-irimFdfw.png" /></figure><p>In our DynamoDB, we should be able to find those two new items</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4y6mVgCXCUZrh4jPScSgIA.png" /></figure><p>Next, let’s test the getCustomerById and getProductById query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peflITqhZRHyEooEMcagKQ.png" /></figure><p>Next, let’s create an order using the newly created customer and product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_eVEWQqnYdZLP-QxxD4RA.png" /></figure><p>The createOrder function will create two items in the database: one for the order itself and another for the order item. Besides the two new items, the quantity in P#ca11cf9c-17ea-4845–8566-fbb9a0961da7 was updated as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3kO4QdU7WVdXqwxfd6JrQ.png" /></figure><p>Finaaly, lets run getOrderById query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg6kscVFsNNm7uDDB-UyAg.png" /></figure><h3>Conclusion</h3><p>In conclusion, the use of a single table design in DynamoDB requires careful consideration of partition and sort key assignments, as well as extra effort in writing Lambda resolver. However, it can offer outstanding query performance. Therefore, the decision to use single table design depends on whether its benefits outweigh its drawbacks.</p><p>If you have any questions, please let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8838e86b2f71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lapis/how-to-implement-dynamodb-single-table-designs-with-aws-amplify-appsync-lambda-8838e86b2f71">How to implement DynamoDB single table designs with AWS Amplify (AppSync, Lambda)</a> was originally published in <a href="https://medium.com/lapis">Code道</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>