<?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 Rushi Patel on Medium]]></title>
        <description><![CDATA[Stories by Rushi Patel on Medium]]></description>
        <link>https://medium.com/@whimzy_live?source=rss-d9cf8ff00846------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z4wbFZo7eO3ZZ9RRPVG99w.jpeg</url>
            <title>Stories by Rushi Patel on Medium</title>
            <link>https://medium.com/@whimzy_live?source=rss-d9cf8ff00846------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:15:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@whimzy_live/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[Supercharge ⚡️ your DynamoDB  single-table design pattern with TypeDORM]]></title>
            <link>https://medium.com/nextfaze/supercharge-%EF%B8%8F-your-dynamodb-single-table-design-pattern-with-typedorm-39168d0d2e29?source=rss-d9cf8ff00846------2</link>
            <guid isPermaLink="false">https://medium.com/p/39168d0d2e29</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[single-table-design]]></category>
            <dc:creator><![CDATA[Rushi Patel]]></dc:creator>
            <pubDate>Wed, 26 May 2021 10:02:41 GMT</pubDate>
            <atom:updated>2021-05-26T10:02:41.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supercharge ⚡️ your DynamoDB single-table design pattern with TypeDORM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOoFGZ-gVMHvVFt4yokPOA.jpeg" /></figure><p><a href="https://www.youtube.com/watch?v=KYy8X8t4MB8">Single-table design for DynamoDB</a> has gained popularity due to the increased ability to query relational data in No-SQL databases.</p><p>The <a href="https://github.com/typedorm/typedorm">TypeDORM</a> is an Object Relational Mapper library running in Node,js and written in Typescript. <a href="https://github.com/typedorm/typedorm">TypeDORM</a> is a feature-rich DynamoDB ORM to help you write high-quality, loosely coupled, scalable, and maintainable applications with highly relational data in the most productive way.</p><h4>What this article is about</h4><p>In this article, we will be looking at different challenges that may arise while developing with DynamoDB using a single-table-design pattern and how <a href="https://github.com/typedorm/typedorm">TypeDORM</a> can help us avoid them.</p><h4>What this article is NOT about</h4><p>We will not be covering why and who should use DynamoDB single-table design as <a href="https://medium.com/u/3c9962a8238">Alex DeBrie</a> has done an excellent job at explaining it <a href="https://www.alexdebrie.com/posts/dynamodb-single-table/">here</a>.</p><p>Once you understand how single-table design works with DynamoDB, you would want to try it out with a real-life example. There is already a very popular article by <a href="https://medium.com/u/b8d1e8a0e0d8">Forrest Brazeal</a> that can be found <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">here</a>, which you should first look at before continuing with this article.</p><h4>What you should know before moving on</h4><ul><li><a href="https://www.alexdebrie.com/posts/dynamodb-single-table/">What is a single-table-design pattern</a></li><li><a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">How it works with a real-life relational dataset</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRuKGrhME7zewM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRuKGrhME7zewM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRuKGrhME7zewM%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3cb345d52915c15cf89acef523df124/href">https://medium.com/media/d3cb345d52915c15cf89acef523df124/href</a></iframe><p>Once you are familiar with the single-table design pattern and have also looked at how it can be used to model highly relational data in DynamoDB, let’s talk about why it isn’t a very viable way to work with data and what can we do to make it better.</p><p>When first introduced to single-table-design, there are some common questions and concerns developers start to ponder:</p><ul><li>I can’t use a single-table design, I need operation time “types safety”.</li><li>All the attributes and their names just don’t make sense anymore, how do I reliably interact with them?</li><li>As I keep adding more indexes, how do I make sure that all the attributes created for modeling don’t end up returning to clients?</li><li>If I choose to keep the original attribute value and its index-referenced attribute separate, how do I make sure they are always in sync?</li><li>How do I keep the key schema up to date with a matching pattern for each entity that I add?</li><li>How do I confidently interact with all entities without having to remember to provide correct condition expressions for common operations (i.e for unique attributes, making sure to always include condition expressions with attribute_not_exists)?</li><li>With a single table design, I can’t use data mapper libraries.</li><li>The resulting code is hard to read as there are too many attributes/symbols representing different meanings.</li><li>My colleges may know how to work with the DynamoDB but this particular way is very unfamiliar.</li><li>I want to use the single-table design but I don’t want to manage each entity schemas in a separate spreadsheet.</li></ul><p>There might be many more questions but most of them are pointing to one concern in particular:</p><blockquote>“Do I really want to trade off development ease, developer experience, code quality over this new way of working with DynamoDB?”</blockquote><p>The answer is: you don’t have to. There is a better option.</p><p>Let me introduce you to <a href="https://github.com/typedorm/typedorm"><strong>TypeDORM</strong></a>: Strongly typed ORM for DynamoDB — Built for the single-table-design pattern. Let’s first have a quick look at what it is and how it can help us to solve all the problems stated earlier.</p><p>Later, we will also have a look at how we can leverage TypeDORM to better structure entities (continuing from the example from <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">this</a> great article).</p><h3>Introduction to <a href="https://github.com/typedorm/typedorm">TypeDORM</a></h3><p>TypeDORM is an ORM built from the ground up using TypeScript to provide an easy entry point when doing complex, highly relational data modeling in DynamoDB. Its syntax might be familiar since the decorator-based syntax is highly influenced by TypeORM — one of the very popular ORM for working with SQL databases.</p><p>Let’s take a quick look at some of the many features that TypeDORM provides:</p><ul><li>Single table design first-class support</li><li>DataMapper development pattern</li><li>Full type safety enabled using advanced typescript generics</li><li>Declarative relational schema</li><li>Multiple connections support</li><li>Operation based managers per connection, includes Entity manager, Transaction manager, Batch manager, and Scan Manager</li><li>Code follows all possible best practices and provides first-class support for some of the very popular patterns used in the single-table-design pattern</li><li>Additional higher-level features like, such as the ability to declare non-key attribute as unique, automatic retries</li><li>Auto-Generated values for attributes</li><li>Auto-update attributes and its referenced indexes on UPDATE operations</li><li>Dynamic &amp; Static default values for attributes</li><li>Complex update, key condition, and condition expression all made easy to work with</li><li>Powerful expression builder to auto-generate expressions from typesafe input</li></ul><h3>Getting Started with TypeDORM</h3><h4>Installing</h4><p>Let’s first install all the modules that we will need.</p><pre>npm install @typedorm/common @typedorm/core --save</pre><p>We will also need to install reflect-metadata shim that TypeDORM relies on and configure it so that metadata’s are correctly detected by TypeDORM</p><pre>npm install reflect-metadata --save</pre><h4>Enable emitting metadata at runtime</h4><p>If you are using TypeDORM with TypeScript, make sure you also have the below options enabled in yourtsconfig.json</p><pre>&quot;emitDecoratorMetadata&quot;: true,<br>&quot;experimentalDecorators&quot;: true,</pre><p>Once this is done we need aws-sdk which TypeDORM uses to communicate with the DynamoDB table.</p><pre>npm install aws-sdk --save</pre><p>We are all set now, next we will need to configure the connection. If you have ever worked with <a href="https://github.com/typeorm/typeorm">TypeORM</a>, this setup will look very familiar.</p><p>In the next section, we will have a look at the relational data set that we will be working with. You can always refer back to <a href="https://medium.com/u/b8d1e8a0e0d8">Forrest Brazeal</a>’s <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">article</a> any time you feel lost.</p><h3>Getting to know our data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_E9H-r1KZc3VKcenB0Keg.png" /><figcaption>credit: Forrest Brazeal</figcaption></figure><p>Here are some access patterns that Brazeal has listed:</p><ol><li>Get employee by employee ID</li><li>Get direct reports for an employee</li><li>Get discontinued products</li><li>List all orders of a given product</li><li>Get the most recent 25 orders</li><li>Get shippers by company name</li><li>Get customers by contact name</li><li>List all products included in an order</li><li>Get suppliers by country and region</li></ol><h4>Entities that we will be working with</h4><p>These are all the entities we will need to create with a given signature to fulfill our access patterns. Here is a slightly modified version of the Entity chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGk7nz4WKCb1G1ny9oxNqQ.png" /><figcaption>Entity chart</figcaption></figure><p>The process of selecting what goes under PK and SK remains the same as described <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">here</a>.</p><p>If you were following this closely, you will notice few differences between the above entity chart and one presented by Brazeal, Which are:</p><ul><li>Each attribute is only ever referenced in a single index</li><li>Each entity PK now has a prefix of STATIC entity type — this helps us better identify items where they are all put together in the same table as well as allows us to use incrementing ids</li></ul><h4>Our access patterns</h4><p>Here is the list of all access patterns and what attributes we will be querying on. In case you didn’t follow <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">this</a> article and came up with different access patterns, that’s perfectly okay too.</p><p>Hereafter building on top of Brazeal’s access patterns, this is what it looks like now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fH4-cGmu5eHjOsoBZXB0g.png" /><figcaption>Access patterns</figcaption></figure><p>You will still have to follow all the steps required in a single-table design pattern, with one slight change being that all the entities need to have a SQL-like entity structure (of course, you can still add more attributes to entities later).</p><p>Understanding how to build an entity schema would be a different article on its own — our main focus is how we can reliably work with the above entities using TypeDORM.</p><h3>Developing with <a href="https://github.com/">TypeDORM</a></h3><p>This section will focus on getting connections, entities, tables configured for TypeDORM that can effectively parse data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLr3UeH9tYu3qJtsSUg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLr3UeH9tYu3qJtsSUg%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLr3UeH9tYu3qJtsSUg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="336" frameborder="0" scrolling="no"><a href="https://medium.com/media/7283cb737636d96c18333ad23608e4c0/href">https://medium.com/media/7283cb737636d96c18333ad23608e4c0/href</a></iframe><h4>Declare a Table</h4><p>Since we are doing a single-table design we really only need a single DynamoDB table with a single Global Secondary Index (GSI). We declare that by creating a new instance of Table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac8aa60ed8fb1a3ede4ca3c6de3797c/href">https://medium.com/media/1ac8aa60ed8fb1a3ede4ca3c6de3797c/href</a></iframe><h4>Define entities</h4><p>Now it’s time to covert our entity chart into an actual TypeDORM entity, we do this by annotating our model with @Entity decorator, exported by @typedorm/common . Product and Employee entities are the only ones listed here, but you got the overall idea.</p><p><em>Note: TypeDORM exposes various decorators to be able to declaratively define an entity. For those not listed here, check out the </em><a href="https://github.com/typedorm/typedorm/blob/main/docs/api.md"><em>TypeDORM API specification</em></a><em> for more up-to-date APIs.</em></p><p><em>Product Entity</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c80521b5818b7f2f6981a397cb227a5/href">https://medium.com/media/0c80521b5818b7f2f6981a397cb227a5/href</a></iframe><p><em>Employee Entity</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e6650b3b6908c8f484bb64bcd8f488/href">https://medium.com/media/15e6650b3b6908c8f484bb64bcd8f488/href</a></iframe><p>You will need to define all entities in a similar way to the above examples.</p><h4>Establishing a connection</h4><p>Once we have all the entities in, the next thing is to initialize a DynamoDB connection. We do this by creating a connection instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c4692b9465c075d49be2780eca0496e/href">https://medium.com/media/0c4692b9465c075d49be2780eca0496e/href</a></iframe><p>If all of your entities are grouped under the same directory, you can also provide a relative path to entities option and TypeDORM will auto load all the entities from a given path.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26FPnsRww5DbqoPuM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26FPnsRww5DbqoPuM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26FPnsRww5DbqoPuM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="237" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa5dab1bf1c2a776f3bd00f1eb20ea2/href">https://medium.com/media/5fa5dab1bf1c2a776f3bd00f1eb20ea2/href</a></iframe><p>Now since we have everything in place, we are ready to work with a single-table designed DynamoDB table in a type-safe way.</p><h4>Querying records</h4><p>Once everything is set up, it’s will be super easy to perform all kinds of operations like Create, Delete, Put, Update, all in a type-safe way.</p><p>For example, let’s have a look at what our queries will look like for the first two access patterns:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2241617fd63a2648c9db8c971e4efa8/href">https://medium.com/media/e2241617fd63a2648c9db8c971e4efa8/href</a></iframe><p>P.S. You can provide additional options to filter/log queries.</p><p>For the most up-to-date list of available options and entity have a look at <a href="https://github.com/typedorm/typedorm/blob/main/docs/api.md">API Spec</a>.</p><p>Even though we have only covered querying items with TypeDORM here, there are many more use-cases where TypDORM proves its worth. Experiment with different TypeDORM APIs and tell us what you think in the comments.</p><h3>More about TypeDORM</h3><p>TypeDORM is committed to delivering new features every month until all the major document client APIs are covered, meanwhile if you want to access the feature before the release we also publish a beta version.</p><p>To find out more about what new features are on the road map, check out the <a href="https://github.com/typedorm/typedorm/projects/1">TypeDORM public roadmap</a>.</p><p>If there are any other features you would like to be included, open a new issue <a href="https://github.com/typedorm/typedorm/issues/new">here</a>.</p><p><strong>Thanks for reading! If you liked this article, hit that clap button below👏 . It means a lot to us and it helps others easily find this article. For more updates follow us on </strong><a href="https://medium.com/nextfaze"><strong>Medium</strong></a><strong> or <em>follow me on </em></strong><a href="https://github.com/whimzyLive"><strong><em>Github</em></strong></a><strong><em>.</em></strong></p><p><em>Special thanks to </em><a href="https://medium.com/u/746c9ee6236f"><em>Zak Barbuto</em></a><em> for proofreading this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39168d0d2e29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/supercharge-%EF%B8%8F-your-dynamodb-single-table-design-pattern-with-typedorm-39168d0d2e29">Supercharge ⚡️ your DynamoDB  single-table design pattern with TypeDORM</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Serverless API with Nestjs and AWS CDK]]></title>
            <link>https://medium.com/nextfaze/deploying-serverless-api-with-nestjs-and-aws-cdk-3d41063543e0?source=rss-d9cf8ff00846------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d41063543e0</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[serverless-api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Rushi Patel]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 09:33:14 GMT</pubDate>
            <atom:updated>2020-09-04T09:33:14.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLwEVxd65nyttqubxclHdg.jpeg" /></figure><h3>What this article is about</h3><p>Javascript has evolved a lot in recent years and its ecosystem is bigger today than it was ever before. We are seeing more and more frameworks coming out everyday that help us write more clean, robust and highly manageable code. In this article we will mainly be looking at technologies and tools that can help us build <strong>secure,</strong> <strong>scalable</strong>, <strong>reliable</strong>, <strong>efficient</strong>, and <strong>affordable</strong> API.</p><p>we will mainly be looking two technologies: <strong>AWS CDK </strong>and<strong> NestJS</strong>.</p><p>Let’s cover some basic ground on CDK (Cloud Development Kit) and NestJs, so everyone is on the same page.</p><p>Our goal here is to build a server-less API without losing tools that we already know and like to work with. You should have some working knowledge of building serverless applications on cloud and <a href="https://hackernoon.com/what-is-serverless-architecture-what-are-its-pros-and-cons-cc4b804022e9">why go serverless</a> as this article <strong>does not</strong> explore reasons to create serverless api.</p><h3>What is AWS CDK and why use it</h3><p>AWS CDK a.k.a Cloud Development Kit is a new addition to AWS’s I<strong>nfrastructure as code</strong> initiative, to help developers provision resources on cloud with the languages that they like. You can read more about it <a href="https://docs.aws.amazon.com/cdk/latest/guide/home.html">here</a> as we won’t be going into the details of how it works. Instead we will have look at how to get a demo application up and running. 👨‍💻</p><p><em>AWS CDK also comes with a CLI tool which makes development and deployment experience very smooth.</em></p><h3>What is NestJs</h3><blockquote>A progressive Node.js framework for building efficient, reliable and scalable server-side applications. — <a href="https://nestjs.com/">Nestjs</a></blockquote><p>NestJs is a framework that enables developers to take advantage of Angular style Dependencies Injection (DI) for building highly maintainable APIs. It is built with Typescript and combines elements of Object Oriented Programming, Functional Programming and Functional Reactive Programming.</p><p><em>NestJs has a CLI to help developers quickly get started and also takes care of inferring types for swagger template without having to manually annotate each operation.</em></p><h3>But why run NestJs on lambda?</h3><p>Now you might be wondering why you would want to run a NestJs application on a Lambda, If not, you can skip this section.😉</p><p>If you have previously done some Serverless applications than you might already know how much of a blessing a <a href="https://dashbird.io/blog/business-benefits-of-serverless/">Serverless</a> application is over traditional ones that requires a server (On premises and Cloud) constantly running even though no one is using it. This is especially true when you are a startup or have an unpredictable workload. Building Serverless API can be hard as most of the frameworks and practices that we have developed in past many years simply do not work as is, instead we have small executable functions where we write a business logic and then configure it to run on some event or an operation. This means we need to create resource for each resource, and even each operation, not to mention the various limits set by cloud providers (<a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html">AWS</a>, <a href="https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-best-practices#template-limits">Azure</a>) when we try to do this. (i.e AWS cloudformation has a max limit of 200 resources per a template).</p><p>By running NestJs application on lambda we can try to get best of both world, We get reliability, and affordability and security from AWS world and scalability and better overall better development experience from NestJs land.</p><p>I hope I have convinced most of you on why to run NestJs application on lambda. Now let’s first have a look at what we will be building today and then jump straight into coding.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5QTOKia3HPBLvg9ROL%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5QTOKia3HPBLvg9ROL%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5QTOKia3HPBLvg9ROL%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/fba090b0dd09749bc5047817339e36e0/href">https://medium.com/media/fba090b0dd09749bc5047817339e36e0/href</a></iframe><h3>What we are going to build</h3><ul><li>API with CRUD operations for <strong><em>todos</em></strong></li><li>User <strong>Authentication</strong> using Cognito</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVKu5GJJbacYByHIJ6ei9Q.png" /></figure><h3>Local Environment Prerequisites</h3><ul><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html">AWS Cli</a> installed and configured with <strong>admin</strong> permissions</li><li><a href="https://www.npmjs.com/package/@nestjs/cli">Nestjs Cli</a> installed</li></ul><h3>Getting Started With Setting up Project</h3><blockquote>Bootstrap a cdk project</blockquote><pre>npx cdk init --language typescript</pre><p>This will install all the necessary tooling required to deploy our app to the cloud, because CDK often actively gets new updates, it is possible that by the time you are reading this article AWS CDK might have a new latest version then the one bootstrapped with above command, to update all the dependencies run and follow onscreen commands.</p><pre>npx npm-check-updates -u</pre><blockquote>Next, bootstrap nestjs project with name <strong>api</strong></blockquote><pre>nest new api --skip-git</pre><p>Now we have everything that we will need to create our first serverless API</p><h3>Configuring required resources for cloud ☁️️</h3><p>Before going further make sure you are in a root directory of the project, since all the dependencies that we will install now will only be required at the deployment time.</p><h4>Adding User Authentication using AWS Cognito User Pools</h4><p>Create a new Cogito construct that extends base CDK Constrct which will contain all of our auth resources.</p><blockquote>Create Cognito Construct</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21b31dd3cbc2c1ca70788ce3e0e16927/href">https://medium.com/media/21b31dd3cbc2c1ca70788ce3e0e16927/href</a></iframe><blockquote>add user pool to store user sessions</blockquote><p>First, we will configure user pool as following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/731cf3c14ec83e48a2e2e40b505e1d79/href">https://medium.com/media/731cf3c14ec83e48a2e2e40b505e1d79/href</a></iframe><blockquote>add user pool client which will allow api users to get auth tokens on login</blockquote><p>Next, we will add user pool client for earlier user pool</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f563c12317e5b09a33037fedf814c1b6/href">https://medium.com/media/f563c12317e5b09a33037fedf814c1b6/href</a></iframe><blockquote>Configure hosted OAuth server</blockquote><p>Finally, we will add a hosted OAuth server to our Cognito construct.</p><p>Instead of using Cognito hosted UI, we can also other auth flows that AWS Cognito supports but that is out of scope for the purpose of this article. So for this demo we will just stick to using cognito hosted ui.</p><p><em>Don’t forget to change </em><em>domainPrefix to be of your choice, as there can only be one app with any given name</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37751906932b40a670f020b709a2ae73/href">https://medium.com/media/37751906932b40a670f020b709a2ae73/href</a></iframe><p>Now we are all set for user signup/login, next let’s have a look at configuring Amazon API Gateway resource and AWS Lambda.</p><h4>Adding API Gateway proxy lambda resource</h4><p>Our Authentication service is configured, now we are going to add API gateway resource with backed by lambda function.</p><blockquote>Configure Lambda function and lambda layer</blockquote><p>First, add a lambda function to handle all incoming api requests. When AWS invokes your lambda function in response to configured events, it expects all of the runtime dependencies to be available next to application code.To satisfy this requirement and to also keep out application logic from its dependencies, we will use lambda layers.</p><p>Layers allows for easy sharing of external dependencies and greatly improves development experience, as all of dependencies live in a seperate directory that which gets packed and deployed separately to actual business logic.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oEduJ323JmMXE4Yxi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oEduJ323JmMXE4Yxi%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3oEduJ323JmMXE4Yxi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b072606d99c4c85c2f15d5efdff4f20/href">https://medium.com/media/5b072606d99c4c85c2f15d5efdff4f20/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bace7f8d9f749b0a688d047f653de36b/href">https://medium.com/media/bace7f8d9f749b0a688d047f653de36b/href</a></iframe><p><em>Also make sure to exclude node_modules dir from code asset.</em></p><blockquote>Configure API Gateway resource</blockquote><p>Next, we will add an api gateway resource to respond to all incoming http connections and an api key with usage plan configured.</p><p>Usage plan and API key allow us to enable API monitoring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54ff726d928de198f3436f822ba00804/href">https://medium.com/media/54ff726d928de198f3436f822ba00804/href</a></iframe><p><em>Configuring api key and usage plan is completely optional and can be skipped, if you do not with to have api monitoring.</em></p><blockquote>Create Dynamo DB table to store our todos</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ede0139aeb4808a6e740eb6dbf166ad/href">https://medium.com/media/9ede0139aeb4808a6e740eb6dbf166ad/href</a></iframe><blockquote>Enable Cognito Authentication</blockquote><p>Finally, we will be adding cogito authorizer to authenticate incoming requests. We want to eliminate all bad traffic with no or bad tokens long before it ever gets to our lambda function.</p><p>AWS CDK is very new and continuously evolving so it might not have the all the services available as a higher level constructs but you can always use low level Cfn Constructs. At the time of writing this article, aws cdk does not have a construct to create a cognito authorizer so to work around that we will be using low level <em>CfnAuthorizer.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22388e4f94dfeced30be7e6166e04479/href">https://medium.com/media/22388e4f94dfeced30be7e6166e04479/href</a></iframe><p>This is all that we need in order to be able to deploy our awesome serverless api. In the next section, we will look into how to make Nestjs respond to different endpoints and some neat things that you can do using Nestjs.</p><p>If you made it this far, congrats! Give your self a small break and come back when you are ready for more.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fg9582DNuQppxC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fg9582DNuQppxC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fg9582DNuQppxC%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eba96b395f1e17a357fe179074ce870/href">https://medium.com/media/0eba96b395f1e17a357fe179074ce870/href</a></iframe><h3>Going wild with Nestjs</h3><h4>Adding serverless capability to our Nestjs application</h4><blockquote>Updating app listener to respond to lambda invocation</blockquote><p>In our main.ts, change the cli generated function with following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369863a920c214c5c8e70d313c56f11d/href">https://medium.com/media/369863a920c214c5c8e70d313c56f11d/href</a></iframe><p><em>Here, we are simply exporting named function ‘api’, which if you remember was set as an entry point in api handler.</em></p><h4>Add todos controller</h4><p>Controller in Nestjs are responsible for managing incoming requests and responses and it is the only piece of code that directly gets mounted onto a route.</p><p>First we will add <strong>todos controller</strong> using nest cli, to do that navigate to /api directory and execute following command.</p><blockquote>bootstrap initial controller files using cli</blockquote><pre>nest generate controller todos</pre><p>this will create a todos controller and register it in app module.</p><blockquote>Next, we will create Create, Read, Put, Delete endpoints</blockquote><p>This is the brief of what each endpoints needs to do.</p><p><strong>Create: </strong>creates a todo item with given data for user</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ffb5a146f40024b799daa15e7bf0907/href">https://medium.com/media/8ffb5a146f40024b799daa15e7bf0907/href</a></iframe><p><strong>Read: </strong>Get all todos and by id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a0de525fd7186af9f96c9c3991286c/href">https://medium.com/media/d5a0de525fd7186af9f96c9c3991286c/href</a></iframe><p><strong>Update: </strong>Update item with given id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad4e03dc1bbdbf34747cd92312b3b11a/href">https://medium.com/media/ad4e03dc1bbdbf34747cd92312b3b11a/href</a></iframe><p><strong>Delete: </strong>delete all delete an item by id and</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13730dfbbcfc0a965680960e205e376d/href">https://medium.com/media/13730dfbbcfc0a965680960e205e376d/href</a></iframe><h3>Deploying</h3><p>We will use CDK cli to deploy our application to AWS. Make sure you have AWS credential configured on your machine with required permissions.</p><p>If you have never used CDK cli to deploy application, then there will be one additional step required before actually deploying our stack, we will need to deploy <a href="https://github.com/aws/aws-cdk/blob/master/design/cdk-bootstrap.md">CDK toolkit</a> stack to deploying region, so that CDK cli can attach and find metadata that it creates.</p><blockquote>To Bootstrap CDK toolkit stack, run</blockquote><pre>npm run cdk bootstrap</pre><p>then, to deploy our awesome serverless API simply run</p><pre>npm run cdk deploy</pre><p>CDK cli will use your default aws credentials configured with aws cli. Incase you have more than one profiles set up you can choose specific one by appending profile flag .</p><pre>npm run cdk deploy -- --<em>profile &lt;profileName&gt;</em></pre><p>That is it, if there were no deploy time errors, you should have a Serverless API that is <strong>secure,</strong> <strong>scalable</strong>, <strong>reliable</strong>, <strong>efficient</strong>, and <strong>affordable, </strong>just as we talk about.</p><h3><strong>Testing</strong></h3><p>Head over to <a href="https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Fap-southeast-2.console.aws.amazon.com%2Fcognito%2Fusers%2F%3Fregion%3Dap-southeast-2%26state%3DhashArgs%2523%252Fpool%252Fap-southeast-2_inVBZaxRO%252Fapp-integration-app-settings%253F_k%253Doh52b8%26isauthcode%3Dtrue&amp;client_id=arn%3Aaws%3Aiam%3A%3A015428540659%3Auser%2Fcognito&amp;forceMobileApp=0&amp;code_challenge=YK3PS-Yac5FFcs1fVs-uBRgdueCIr8y9MAQ7tt7kwW4&amp;code_challenge_method=SHA-256">AWS console</a> and then to a <em>region</em> that our resources were created. Next navigate to AWS Cognito and look for Lauch Hosted UI under App Client settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*u7ifSsfVvZRedVhKuuv57w.png" /></figure><p>Click on the Hosted UI and login/register a user. Once logged in you will be navigated to https://www.google.com if following above example (If you remember correctly, this is what we had setup as a callback url in <strong><em>Adding User Authentication using AWS Cognito User Pools</em></strong><em> section</em>), and locate tokens(mainly <strong><em>id_token</em></strong> and <strong><em>access_token</em></strong>) in query params, note them somewhere as we will need this later for invoking the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*hBuXfFZumSpNloIsCBPC9g.png" /></figure><p>Next in a different tab, open up <strong>API Gateway </strong>page,</p><p>then under <strong><em>APIS &gt; Stages &gt; v1 </em></strong>and copy the invoke URL (yes this is our deployed api url) and API key from <strong><em>APIS &gt; API Keys &gt; key.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrkezTn3-otCkh6g5pTBuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*uau6IhndMNovAZkT0WpUHw.png" /></figure><p>That’s everything we need, now open up Postman or any REST api client and invoke our API. Don’t forget to try all GET, POST, PUT and DELETE operations!</p><blockquote>i.e With cURL it will look something like this</blockquote><pre>curl --location --request GET &#39;https://{api-id}.execute-api.{region}.amazonaws.com/v1/users/{userId}/todos&#39; \</pre><pre>--header &#39;x-api-key: &lt;Your API Key&gt;&#39; \</pre><pre>--header &#39;Authorization: Bearer &lt;Your Id Token&gt;&#39;</pre><h3>Where to next…</h3><p>Complete working example is available on <a href="https://github.com/NextFaze/awesome-serverless-api">github</a>.</p><p>In the next article we will look at using NestJs with non-http AWS services, like invoking a lambda to respond to some Cloudwatch event or an S3 upload. In addition to this, we will also have a look at adding live documentation to our Serverless API (no more need to manage documentation manually 🤓) and generating client SDK(Software Development Kit) using Swagger code gen .</p><p>Happy Serverlessing!</p><p><strong>Thanks for reading! If you liked this article, hit that clap button below👏 . It means a lot to me and it helps others more easily find this article. For more updates follow us on </strong><a href="https://medium.com/nextfaze"><strong>Medium</strong></a><strong> or <em>follow me on </em></strong><a href="https://github.com/whimzyLive"><strong><em>Github</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d41063543e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/deploying-serverless-api-with-nestjs-and-aws-cdk-3d41063543e0">Deploying Serverless API with Nestjs and AWS CDK</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>