<?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 Stefan Sarmir on Medium]]></title>
        <description><![CDATA[Stories by Stefan Sarmir on Medium]]></description>
        <link>https://medium.com/@stefansarmir?source=rss-8a4bdae084ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7KVemEDPhfhGI4aIUeNJ5w.jpeg</url>
            <title>Stories by Stefan Sarmir on Medium</title>
            <link>https://medium.com/@stefansarmir?source=rss-8a4bdae084ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:39:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stefansarmir/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[Dockerising Your Database for Local Development: Seeding Data —  MariaDb (SQL) and MongoDb (NoSQL)]]></title>
            <link>https://levelup.gitconnected.com/dockerising-your-database-for-local-development-seeding-data-mariadb-sql-and-mongodb-nosql-f18ba6d8c9ed?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18ba6d8c9ed</guid>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 03:12:51 GMT</pubDate>
            <atom:updated>2023-10-19T03:12:51.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dockerising Your Database for Local Development: Seeding Data — MariaDb (SQL) and MongoDb (NoSQL)</h3><h4>Improve your local development process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F0HUZn-E9Wk16WXi" /><figcaption>Photo by <a href="https://unsplash.com/@jlanzarini?utm_source=medium&amp;utm_medium=referral">Joshua Lanzarini</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Dockerising your database for local development is a common and valuable practice.</p><p>It offers numerous advantages, including:</p><ul><li>Facilitating the onboarding of new developers</li><li>Isolating local development from the test environment</li><li>Enabling the use of the application for individuals without access to the test database</li></ul><p>In this article, we will explore how to seed data to your Dockerized database instances, enhancing the efficiency and effectiveness of your local development workflow.</p><h3>Benefits of Dockerised Database for Local Development</h3><p>Before diving into the process of seeding data, let’s briefly recap the benefits of using Dockerizsed database images for local development:</p><h4><strong>Faster Onboarding</strong></h4><p>Dockerised databases simplify the setup process for new team members. With a predefined containerised environment, developers can quickly get started with their work without dealing with complex database installation and configuration.</p><h4><strong>Isolation</strong></h4><p>Separating your local development environment from the test database environment ensures that changes made during development do not impact the production or testing databases.</p><p>This isolation is crucial for maintaining data integrity.</p><h4>Accessibility</h4><p>Dockerised databases allow developers who do not have direct access to the test database to work on the application.</p><p>This is particularly helpful in scenarios where data access is restricted.</p><h3>Seeding Data to Your Dockerized Database —MariaDb (SQL)</h3><p>Now, let’s focus on the key topic of this article: seeding data to your Dockerized database instances.</p><p>Seeding data is essential for replicating real-world scenarios in your development environment, testing your application’s functionality, and ensuring that your code works with meaningful data.</p><p><strong>We will start with seeding an SQL Mariadb database.</strong></p><h4>Step 1: Create a Seed Data File</h4><p>Begin by crafting a file that houses the data you intend to seed into your database. In the case of an SQL database, we will utilize an SQL script for this purpose.</p><ol><li>Create a directory called <strong>sql</strong> within your project’s folder. We will later mount this folder as a volume to initialize our Docker container.</li><li>Inside the <strong>sql directory,</strong> create an SQL file named <strong>init.sql</strong>. You have the freedom to choose any name for this file, but for the sake of clarity in this article, we’ll stick with <strong>init.sql</strong>. It’s worth noting that you can include multiple SQL files within this directory, and <strong>all of them</strong> will be executed during the initialisation process.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*8PzxlfERIpGbxOdGIo-A7g.jpeg" /><figcaption>init.sql file within sql folder</figcaption></figure><h4>Step 2: Create the SQL script</h4><p>Now, let’s open the <strong>init.sql</strong> file you created earlier and populate it with the necessary SQL script.</p><p>This script can encompass tasks such as table creations, the definition of indexes, and, crucially, the <strong>INSERT statements</strong> responsible for seeding the data.</p><p><strong>To provide you with a practical example, consider the following:</strong></p><pre>-- Use the database<br>USE seedexample;<br><br>-- Create a test table<br>CREATE TABLE IF NOT EXISTS test (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    propertyType VARCHAR(255) NOT NULL,<br>    bedrooms INT,<br>    created_by int NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>);<br><br>-- INSERT statements to seed data<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;House&#39;, 3, 1);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Apartment&#39;, 2, 2);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Condo&#39;, 1, 3);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Townhouse&#39;, 4, 4);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Duplex&#39;, 2, 5);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;House&#39;, 5, 6);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Apartment&#39;, 1, 7);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Condo&#39;, 3, 8);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Townhouse&#39;, 4, 9);<br>INSERT INTO seedexample.test (propertyType, bedrooms, created_by) VALUES (&#39;Duplex&#39;, 2, 10);</pre><p>In this example, we first create a <strong>test</strong> <strong>table</strong> and then populate the table with sample data using INSERT statements.</p><p>Adapt this script to match the structure and data you require for your specific application and database.</p><h4>Step 2: Mount the Seed Data File</h4><p>To make the seed data available to your Dockerized database instance, you’ll need to mount the seed data file into the container.</p><p>You can achieve this by specifying a volume when running the database container. For example, if you are using Docker Compose, you can define a volume in your docker-compose.yml file:</p><pre>version: &#39;3.7&#39;<br>services:<br>  mariadb:<br>    image: mariadb:latest<br>    container_name: medium-mariadb<br>    restart: always<br>    environment:<br>      MYSQL_ROOT_PASSWORD: admin<br>      MYSQL_DATABASE: seedexample<br>    volumes:<br>      - ./sql:/docker-entrypoint-initdb.d  # Mount SQL files for initialization<br>    ports:<br>      - 3306:3306</pre><h4>Step 3: Docker compose and verify</h4><p>Now, let’s proceed to compose the Docker container and verify if everything has been set up correctly.</p><h4>Run the following command to compose the container:</h4><pre>docker-compose up -d</pre><p>This command initiates the containerisation process. Once it’s finished, your database container should be up and running, complete with the table and seeded data.</p><p>But hold on!</p><p>To ensure that everything is functioning as expected, let’s perform a verification process.</p><h4>Connect to the docker database by running :</h4><pre>docker exec -t medium-mariadb -u root -p</pre><p>You will be prompted to enter the password. We&#39;ve set this in out docker-compose.yaml file to <strong>admin.</strong></p><h4>After successfully connecting, execute the following command to view the list of databases:</h4><pre>show databases;</pre><p>You will see the list of databases, one of them being our test database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*JogYpec5uveFQPaOqjCFZA.jpeg" /><figcaption>List of databases</figcaption></figure><h4>To access our test database, run the following command:</h4><pre>use seedexample;</pre><h4>Once you’re inside, you can list the tables within the database using the following command:</h4><pre>show tables;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*uxftRveOM5w0WgOYxwpSOA.jpeg" /><figcaption>List of tables in our test database</figcaption></figure><h4>Finally, from within the database, you can query the seeded table with a simple SQL query:</h4><pre>SELECT * FROM test;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*AUjpKf8xnGmn1Dbnhh6Bkg.jpeg" /><figcaption>Seeded data within our test table</figcaption></figure><h3>Seeding Data to Your Dockerised Database — MongoDb (NoSQL)</h3><p>When it comes to Dockerising and seeding MongoDB for local development, the process differs slightly from traditional SQL databases.</p><p>In this scenario, rather than executing an SQL script during container initialisation, we will create a service linked to our MongoDB container.</p><p>This service will run an import bash script responsible for importing data from JSON files.</p><h4>Step 1: Create a Seed Data Folder</h4><p>To begin, set up a directory named mongo-seed. Within this directory, include two essential files:</p><ul><li><strong>data.json:</strong> This JSON file holds the data that will be imported into your MongoDB database.</li><li><strong>import.sh: </strong>The import.shscript is responsible for executing the data import process.</li></ul><p>This structure will help organise your seed data and the necessary import script, making it easier to manage and maintain your data seeding process.</p><h4>Step 2: Populate your data.json and import.sh</h4><p>Now, let’s fill in your ‘data.json’ file with the data you intend to import into MongoDB. You can use the following example format as a guide:</p><pre>[<br>  {<br>    &quot;propertyType&quot;: &quot;House&quot;,<br>    &quot;bedrooms&quot;: 3,<br>    &quot;created_by&quot;: 1<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Apartment&quot;,<br>    &quot;bedrooms&quot;: 2,<br>    &quot;created_by&quot;: 2<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Condo&quot;,<br>    &quot;bedrooms&quot;: 1,<br>    &quot;created_by&quot;: 3<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Townhouse&quot;,<br>    &quot;bedrooms&quot;: 4,<br>    &quot;created_by&quot;: 4<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Duplex&quot;,<br>    &quot;bedrooms&quot;: 2,<br>    &quot;created_by&quot;: 5<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;House&quot;,<br>    &quot;bedrooms&quot;: 5,<br>    &quot;created_by&quot;: 6<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Apartment&quot;,<br>    &quot;bedrooms&quot;: 1,<br>    &quot;created_by&quot;: 7<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Condo&quot;,<br>    &quot;bedrooms&quot;: 3,<br>    &quot;created_by&quot;: 8<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Townhouse&quot;,<br>    &quot;bedrooms&quot;: 4,<br>    &quot;created_by&quot;: 9<br>  },<br>  {<br>    &quot;propertyType&quot;: &quot;Duplex&quot;,<br>    &quot;bedrooms&quot;: 2,<br>    &quot;created_by&quot;: 10<br>  }<br>]</pre><p>Customize the JSON structure to match the data you want to seed into your MongoDB database.</p><p>The import script is a simple one liner. Paste the following line into the import.sh file:</p><pre>mongoimport --host mongodb --db testdb --collection properties --type json --file /mongo-seed/data.json --jsonArray</pre><p>This concise script will effectively import data from ‘data.json’ into the specified MongoDb database and collection as previously configured.</p><h4>Step 3: Assign executable permission to your import.sh file</h4><p>To grant executable permission to your ‘import.sh’ script so that it can be executed within the Docker container, you can use the following command:</p><pre>chmod +x ./mongo-seed/import.sh</pre><p>This command makes the ‘import.sh’ script executable, allowing it to be run as part of the container initialisation process.</p><h4>Step 4: Configure yur docker-compose file</h4><p>To set up the seed service and link it to your MongoDb container, you can include the following configuration in your docker-compose.yml file:</p><pre>version: &#39;3&#39;<br><br>services:<br>  mongodb:<br>    image: mongo:latest<br>    container_name: mongodb<br>    ports:<br>      - &quot;27017:27017&quot;<br>    environment:<br>      MONGO_INITDB_DATABASE: testdb<br>  mongo_seed:<br>    image: mongo:latest<br>    links:<br>      - mongodb<br>    volumes:<br>      - ./mongo-seed:/mongo-seed<br>    command:<br>      /mongo-seed/import.sh</pre><p>In this configuration:</p><ul><li>We define two services: mongodbfor your MongoDB container and mongo_seedfor your data seeding service.</li><li>The mongodbservice is set up as usual, specifying the MongoDb image, container name, ports, and environment variables.</li><li>The mongo_seedservice is linked to mongodbusing the links property, ensuring it can communicate with the MongoDB container.</li><li>We mount the mongo-seedvolume into the mongo_seedcontainer, allowing it to access the data.jsonand import.shfiles.</li><li>Finally, we specify the command to run the import.shscript within the mongo_seedcontainer, initiating the data import process.</li></ul><p>With this configuration, your Docker Compose setup will include both the MongoDb container and the data seeding service, ensuring that your data is correctly imported into the MongoDb database during container initialisation.</p><h4>Step 5: Docker compose and verify</h4><p>Now, let’s proceed to compose the Docker container and verify if everything has been set up correctly.</p><h4>Run the following command to compose the container:</h4><pre>docker-compose up -d</pre><p>This command initiates the containerisation process. Once it’s finished, your database container should be up and running, complete with the table and seeded data.</p><p>But hold on!</p><p>To ensure that everything is functioning as expected, let’s perform a verification process.</p><h4>Connect to the docker database using Mongo Compass , terminal or other tool</h4><p>We will be using Mongo Compass in this tutorial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F3ah7AChzeku3qEEIQZVw.jpeg" /><figcaption>Connecting to database on port 27017 using Mongo Compass</figcaption></figure><p>After connection to the MongoDb, we should see a list of databases including our testdb with the properties colleciton</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*U1Gq82woHOazOv0qw9vKYg.jpeg" /><figcaption>testdb with properties collection</figcaption></figure><h4>Verify the properties collection data</h4><p>By clicking on properties we will open the collection and should see our imported data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5I88sOIgFSMlK12OpVb2Ig.jpeg" /><figcaption>Collection with imported data</figcaption></figure><h3>Conclusion</h3><p>In this article, we’ve explored the process of seeding data in a Dockerised MariaDb (SQL) and MongoDB (NoSQL) environment for local development.</p><p>By following the steps outlined here, you can efficiently set up your Docker containers, populate them with meaningful data, and ensure that your development and testing processes are smooth and effective.</p><p>Remember, data seeding is just one aspect of optimising your development workflow with Docker.</p><p>As you continue to explore containerisation and other DevOps practices, you’ll unlock even more possibilities for efficient and scalable software development.</p><p>I hope you found this article helpful! If you did, please show your support by giving it a round of applause 👏.</p><p>Feel free to leave any questions or comments; I’d love to hear from you. If you want to stay updated with more insightful articles and tutorials, don’t forget to hit the <strong>“Follow”</strong> button.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18ba6d8c9ed" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/dockerising-your-database-for-local-development-seeding-data-mariadb-sql-and-mongodb-nosql-f18ba6d8c9ed">Dockerising Your Database for Local Development: Seeding Data —  MariaDb (SQL) and MongoDb (NoSQL)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Cognito — Part 2: SAM Template and deploy]]></title>
            <link>https://levelup.gitconnected.com/aws-cognito-part-2-sam-template-and-deploy-f7efeb22925c?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7efeb22925c</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Sun, 18 Jun 2023 22:34:04 GMT</pubDate>
            <atom:updated>2023-06-18T22:34:04.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Cognito — Part 2: SAM Template and deploy</h3><h4>Leverage the SAM</h4><p>The AWS SAM (Serverless Application Model) Template is a <strong>YAML </strong>configuration file used to define AWS Serverless applications and resources using the AWS CloudFormation format.</p><p>In the previous part of the tutorial we went through the manual user pool and application setup.</p><p>But who wants to do stuff manually in the AWS Console, right?</p><p>The problem with a manual setup is obvious — it’s harder to manage and you don’t have any kind of a configuration file. You can’t even get it through a PR process !</p><p>Overall, using the <strong>AWS SAM model</strong> streamlines the development, deployment, and management of <strong>server-less applications</strong>.</p><p>We will go through the process of creating what we previously did manually using SAM Template and explain along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*4FC6iKZ3skynIj0Tz4Oxxw.png" /></figure><h3>Prerequisites</h3><p>In order to finish the second part of this tutorial you will need:</p><ul><li>AWS Account</li><li>SAM CLI configured with AWS account credentials</li><li>Project folder</li></ul><h3>Let&#39;s cut to the chase!</h3><p>Navigate to your project folder and create a <strong>template.yaml </strong>folder at the root of the folder. We will be defining our resources using this file. Here is the final version of the configuration:</p><pre>AWSTemplateFormatVersion: 2010-09-09<br>Description: &gt;-<br>  cognito-tutorial<br><br>Transform:<br>- AWS::Serverless-2016-10-31<br><br>Resources:<br>  TutorialUserPool:<br>    Type: AWS::Cognito::UserPool<br>    Properties:<br>      UserPoolName: tutorial-user-pool<br>      AutoVerifiedAttributes:<br>        - email<br>      AccountRecoverySetting:<br>        RecoveryMechanisms:<br>          - Name: verified_email<br>            Priority: 1<br>      VerificationMessageTemplate:<br>        DefaultEmailOption: CONFIRM_WITH_CODE<br>      AdminCreateUserConfig:<br>        AllowAdminCreateUserOnly: false<br>      EmailConfiguration:<br>        EmailSendingAccount: COGNITO_DEFAULT<br>      Policies:<br>        PasswordPolicy:<br>          MinimumLength: 8<br>          RequireLowercase: true<br>          RequireNumbers: true<br>          RequireSymbols: true<br>          RequireUppercase: true<br>          TemporaryPasswordValidityDays: 7<br>      Schema:<br>        - AttributeDataType: String<br>          Name: sub<br>          DeveloperOnlyAttribute: false<br>          Mutable: false<br>          Required: true<br>          StringAttributeConstraints:<br>            MinLength: 1<br>            MaxLength: 2048<br>        - AttributeDataType: String<br>          Name: email<br>          DeveloperOnlyAttribute: false<br>          Mutable: false<br>          Required: true<br>          StringAttributeConstraints:<br>            MinLength: 0<br>            MaxLength: 2048<br>        - AttributeDataType: Boolean<br>          Name: email_verified<br>          DeveloperOnlyAttribute: false<br>          Mutable: true<br>          Required: false<br>      MfaConfiguration: &#39;OFF&#39;<br>      UsernameConfiguration:<br>        CaseSensitive: false<br>      UsernameAttributes:<br>        - email<br>  TutorialAppClient:<br>    Type: AWS::Cognito::UserPoolClient<br>    Properties:<br>      UserPoolId: !Ref TutorialUserPool<br>      ClientName: Tutorial App<br>      GenerateSecret: false<br>      ExplicitAuthFlows:<br>        - ALLOW_USER_PASSWORD_AUTH<br>        - ALLOW_ADMIN_USER_PASSWORD_AUTH<br>        - ALLOW_REFRESH_TOKEN_AUTH<br>      TokenValidityUnits:<br>        RefreshToken: days<br>        AccessToken: days<br>        IdToken: days<br>      RefreshTokenValidity: 60<br>      AccessTokenValidity: 1<br>      IdTokenValidity: 1<br>      PreventUserExistenceErrors: ENABLED</pre><h3>Let&#39;s break it down</h3><h4>Template Metadata</h4><pre>AWSTemplateFormatVersion: 2010-09-09<br>Description: &gt;-<br>  cognito-tutorial</pre><p>In the first section of the template we&#39;re defining the metadata. AWSTemplateFormatVersion specifies the AWS CloudFormation template version syntax that the SAM Template adheres to.</p><p>The latest version is 2010–09–09. It is also the only currently valid value.</p><p>Description is just a brief description of the template. Nothing fancy going on in here.</p><h4>Template Transform</h4><pre>Transform:<br>- AWS::Serverless-2016-10-31</pre><p>The Transform field specifies one or more macros used to process your template. The AWS::Serverless-2016-10-31 macro is required for AWS SAM Templates.</p><p>It allows us to use special syntax and resource definitions to define server-less resources in one line commands. We will point these out down the line.</p><h4>Resources</h4><pre>Resources:</pre><p>The Resources line simply indicates that resource definitions will follow.</p><h3>User Pool Resource</h3><pre>Resources:<br>  TutorialUserPool:<br>    Type: AWS::Cognito::UserPool</pre><p>This simply indicates the logical name of the resource and the resource type.</p><h4>User Pool Resource Properties</h4><p>The Properties section of the template defines the configurable properties of the user pool resource. Although we may not cover all of them in this article, we will discuss and explore the majority of these properties.</p><p>Let&#39;s dive in.</p><pre>UserPoolName: tutorial-user-pool</pre><p>Defines the user pool name.</p><pre>AutoVerifiedAttributes:<br>  - email</pre><p>Defines the user attributes that are automatically verified when a user signs up. In this case, “email” is listed as an auto-verified attribute. Cognito will automatically send a verification email when user signs-up.</p><pre>AccountRecoverySetting:<br>  RecoveryMechanisms:<br>    - Name: verified_email<br>      Priority: 1</pre><p>Defines the account recovery settings for the user pool. Here, a recovery mechanism named verified_email is specified with a priority of 1. This means that users can recover their account using the verified email address.</p><pre>VerificationMessageTemplate:<br>  DefaultEmailOption: CONFIRM_WITH_CODE</pre><p>Configures the message template for the verification process. The DefaultEmailOption is set to CONFIRM_WITH_CODE, which means that user will receive an email with a verification code to confirm their email address.</p><pre>AdminCreateUserConfig:<br>  AllowAdminCreateUserOnly: false</pre><p>Specifies the configuration for creating new users by administrators. The property AllowAdminCreateUserOnly is set to false, meaning that regular users can also create accounts.</p><pre>EmailConfiguration:<br>  EmailSendingAccount: COGNITO_DEFAULT</pre><p>Defines the email sending account used for sending emails from Amazon Cognito. In this case, COGNITO_DEFAULT is used, which refers to the Cognito default email sending account.</p><pre>Policies:<br>  PasswordPolicy:<br>    MinimumLength: 8<br>    RequireLowercase: true<br>    RequireNumbers: true<br>    RequireSymbols: true<br>    RequireUppercase: true<br>    TemporaryPasswordValidityDays: 7</pre><p>Policies specifies various policies related to user passwords. The PasswordPolicy section defines the requirements for user passwords, such as minimum length, requirements for lowercase letters, numbers, symbols, uppercase letters, and the validity period of temporary passwords.</p><pre>Schema:<br>  - AttributeDataType: String<br>    Name: sub<br>    DeveloperOnlyAttribute: false<br>    Mutable: false<br>    Required: true<br>    StringAttributeConstraints:<br>      MinLength: 1<br>      MaxLength: 2048<br>  - AttributeDataType: String<br>    Name: email<br>    DeveloperOnlyAttribute: false<br>    Mutable: false<br>    Required: true<br>    StringAttributeConstraints:<br>      MinLength: 0<br>      MaxLength: 2048<br>  - AttributeDataType: Boolean<br>    Name: email_verified<br>    DeveloperOnlyAttribute: false<br>    Mutable: true<br>    Required: false</pre><p>Describes the user attributes that the user pool will hold. The configuration includes following attributes:</p><ul><li>sub — unique indentifier</li><li>email — user’s email address</li><li>email_verified— a boolean indicating whether the email is verified</li></ul><pre>MfaConfiguration: &#39;OFF&#39;</pre><p>Sets the multi-factor authentication (MFA)configuration for the user pool. In this case, it is set to OFF, meaning MFA is disabled.</p><pre>UsernameConfiguration:<br>  CaseSensitive: false</pre><p>Configures the username attributes for the user pool. The property CaseSensitive is set to false, indicating that usernames are not case-sensitive.</p><pre>UsernameAttributes:<br>  - email</pre><p>Lists the attributes used as the username for user sign-in. In this case, email is specified as the username attribute, which means users can sign in using their email addresses.</p><p><strong>This sums up the user pool SAM Template definition.</strong></p><p>But hold on! We&#39;re not finished.</p><p>In order to integrate our app with the user pool, we will need something called App Client.An app client represents the client-side application that interacts with the user pool to authenticate and authorise users.</p><h3>App Client Definition</h3><pre>TutorialAppClient:<br>  Type: AWS::Cognito::UserPoolClient</pre><p>We&#39;re defining <strong>another</strong> resource, therefore we&#39;re once again starting with the logical resource name definition and the resource type.</p><pre>Properties:<br>  UserPoolId: !Ref TutorialUserPool</pre><p>Specifies the User Pool to which this client belongs to. The !Ref function is used to reference the previously defined User Pool resource with a logical name of TutorialUserPool.</p><pre>ClientName: Tutorial App</pre><p>Sets the name of the User Pool client to “Tutorial App”. This is the name by which the client will be identified.</p><pre>GenerateSecret: false</pre><p>Specifies whether a client secret should be generated for this User Pool client. In this case, it is set to false.</p><pre>ExplicitAuthFlows:<br>  - ALLOW_USER_PASSWORD_AUTH<br>  - ALLOW_ADMIN_USER_PASSWORD_AUTH<br>  - ALLOW_REFRESH_TOKEN_AUTH</pre><p>Lists the explicit authentication flows that are enabled for this User Pool client. It includes the following flows:</p><ul><li>ALLOW_USER_PASSWORD_AUTH — Enables authentication using user passwords.</li><li>ALLOW_ADMIN_USER_PASSWORD_AUTH — Enables authentication by administrators using user passwords.</li><li>ALLOW_REFRESH_TOKEN_AUTH — Enables authentication using refresh tokens.</li></ul><pre>TokenValidityUnits:<br>  RefreshToken: days<br>  AccessToken: days<br>  IdToken: days</pre><p>Defines the units of validity for different types of tokens issued by the User Pool client. In this case, the validity units are specified as days for all of the tokens.</p><pre>RefreshTokenValidity: 60<br>AccessTokenValidity: 1<br>IdTokenValidity: 1</pre><p>Sets the validity duration in days for the individual tokens.</p><pre>PreventUserExistenceErrors: ENABLED</pre><p>Specifies whether to enable or disable preventing user existence errors. When set to ENABLED, the User Pool client will throw a non-specific error if a user with the same username already exists during sign-up.</p><h3>Deployment</h3><p>With our user pool and app client defined, we are now ready to deploy them to AWS. Thankfully AWS SAM simplifies the deployment process, making it straightforward and hassle-free.</p><p>First, open a terminal instance in the folder where your template.yaml file is stored and run sam deploy --guided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ualawb1AbYO3iE4hE9aRrg.jpeg" /></figure><p>This will trigger the deployment process. Using the --guided flag will make SAM use prompts to guide you through the deployment.</p><p>Enter the name of the stack that will be created with this deployment and the region in which it should be deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHK_zkQjEADz2SOVxwGAFg.jpeg" /></figure><p>Answer y (yes) to Confirm changes before deploy and Allow SAM CLI IAM role creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tXzXIrVKlSGCr66o7GCIA.jpeg" /></figure><p>SAM creates a <strong>deployment plan,</strong> where we are able to see which resources will be <strong>created, modified or deleted.</strong></p><p>Answer y to Deploy this changeset?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7T7ySr7E0T8UbMq0iMM5g.jpeg" /></figure><p>The deployment process will start and you will be able to monitor it along the way. Once the deployment is finished, you will be notified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAqKzJcavNyur3t7DXy26Q.jpeg" /></figure><h3>Conclusion</h3><p>In this part of the tutorial we have looked into SAM Template configuration for Cognito User Pool and Application and deployment to AWS.</p><p>In the next one we will write our first <strong>Lambda function with layers</strong> and deploy it along with <strong>API Gateway</strong>.</p><p>As always I will greatly appreciate a clap, follow or a subscribe. They help my articles to reach broader audience.</p><p>Stay tuned for the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7efeb22925c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/aws-cognito-part-2-sam-template-and-deploy-f7efeb22925c">AWS Cognito — Part 2: SAM Template and deploy</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router Netlify Deployment— Page Not Found Error]]></title>
            <link>https://medium.com/@stefansarmir/react-router-netlify-deployment-page-not-found-error-d3143dea61c5?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3143dea61c5</guid>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Thu, 25 May 2023 12:36:17 GMT</pubDate>
            <atom:updated>2023-06-05T12:28:09.585Z</atom:updated>
            <content:encoded><![CDATA[<h4>Don&#39;t loose your nerves over it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viYKtXqhkxCLm7hNF4SNOg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@leekos?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kostiantyn Li</a> on <a href="https://unsplash.com/photos/Fi_nhg5itCw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>So you have finally finished the React Application you were working on and now you&#39;ve deployed it to <strong>Netlify</strong>. Everything looks great, you&#39;re experiencing the warm feeling of satisfaction from a job well-done.</p><p><strong>Until you realise..</strong></p><p>Trying<strong> </strong>to access a sub-route directly produces a <strong>404 error!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*4_YbU-rkLzgGje0lMcil-w.jpeg" /></figure><h3>But… Why?</h3><p>Well, the problem is that React Router handles routing on the client-side (in the browser) but Netlify treats your page as a static web-site by default and is not configured to handle client-side routing properly.</p><p><strong>What does it mean?</strong></p><p>React is a Single Page Application (SPA). Your project might have many components and “Pages” but in fact, all the content in an SPA lives in a single HTML file. In case of React, this is usually the <strong>index.html </strong>in your <strong>/public</strong> folder.</p><p>The routing is then handled on the client-side by your router framework. When you navigate to different routes within your <strong>Single Page Application, </strong>React dynamically renders and updates the content without reloading the whole page.</p><p><strong>Now we get to the point where the problem arises..</strong></p><p>The server does not understand this client-side routing mechanism. As we said before it actually by default treats your SPA as a static website. So if you try to enter a specific url directly and access it, the server will be looking for a corresponding static file for that route.</p><p><strong>But you guessed it, it&#39;s not there.</strong></p><p>It&#39;s not the 1990s anymore and we&#39;re using React, we&#39;re not actually serving static files.</p><p><strong>Fun fact!</strong></p><p>Nowadays, less then 2% of the websites are static websites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqCPGBDJBwinUzNLtikaAw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@annaxphiline?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anna-Philine</a> on <a href="https://unsplash.com/photos/SZcGcB4Fy1g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>How do we fix this?</h3><p>As always, the answer can be partly found in the <a href="https://docs.netlify.com/configure-builds/file-based-configuration/"><strong>Netlify documentation</strong></a><strong> </strong>but one does not always happen to find it. After all that&#39;s why we write these articles.. to share knowledge and help fellow developers in need.</p><p>Let&#39;s cut to the chase.</p><h4>Step 1:</h4><p>Create a <strong>netlify.toml</strong> at the root of your repository if you don&#39;t have one already. If you do, work within the already existing one.</p><p>It is a Netlify <strong>configuration file</strong> defining various settings for your Netlify deployment, one of which happens to be <strong>the routing.</strong></p><h4>Step2:</h4><p>Add the following script to your <strong>netlify.toml</strong> file:</p><pre>[[redirects]]<br>from = &quot;/*&quot;<br>to = &quot;/index.html&quot;<br>status = 200</pre><p>Let&#39;s break this down a bit.</p><p>The <strong>[[redirects]]</strong> on the first line indicates that we will be defining redirect rules in the following lines.</p><pre>[[redirects]]</pre><p>Followed by <strong>from = “/*” </strong>defining the route pattern to match and to be redirected.</p><pre>from = &quot;/*&quot;</pre><p>On the third line we have <strong>to = “/index.html”. </strong>It tells the server the destination of the redirect.</p><pre>to = &quot;/index.html</pre><p>Lastly we have <strong>status = 200. </strong>This line defines the HTTP status code for the redirect response.</p><pre>status = 200</pre><h3>Conclusion</h3><p>That&#39;s it folks, fairly simple fix for an unpleasant problem.</p><p>Thank you for reading all the way here! If you found this article helpful, consider leaving a comment, subscribe or a few claps (yes, you can do more).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3143dea61c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by step Authorisation and Authentication with AWS Cognito — Part 1: Introduction and manual…]]></title>
            <link>https://medium.com/@stefansarmir/step-by-step-authorisation-and-authentication-with-aws-cognito-part-1-introduction-and-manual-2d4bdbbf2660?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d4bdbbf2660</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Tue, 16 May 2023 17:37:36 GMT</pubDate>
            <atom:updated>2023-05-25T18:38:31.206Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Cognito — Part 1: Introduction and manual user pool setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkfMnHAmZtSG-bxmMrVnRA.jpeg" /></figure><p>In the world of web and mobile applications, ensuring secure user authentication and authorisation is a crucial aspect that cannot be overlooked.</p><p><strong>AWS Cognito</strong> is a user identity and access management service that makes it easier to handle <strong>user registration, sign-in, and access control</strong> in your applications.</p><p>With its comprehensive features and easy integration with other AWS services, AWS Cognito can help you easily implement a robust security model for your application.</p><p>What are we going to look at?</p><p>In this multi-part series we will leverage <strong>AWS Cognito User Pools, Lambda functions and AWS API Gateway</strong> to build an Authentication service, deploy it on AWS using <strong>SAM CLI</strong>, build a simple front end to use it and we will also take a look on <strong>Lambda Authorisation.</strong></p><h3>Prerequisites</h3><p>There is only one thing you will need for the process described in this article:</p><ul><li>AWS Account (Don&#39;t worry, everything we are going to use is included in the <strong>free tier</strong>)</li></ul><h3>How does Cognito User Pool work?</h3><p>Cognito stores your application users in <strong>User Pools. </strong>The <strong>User Pool</strong> allows you to to add <strong>sign-in and sign-up functionality</strong> to your application. We can leverage user pools to easily manage <strong>user registration, authentication and account recovery flows.</strong></p><p>Additionally, User Pools support features such as <strong>Multi-Factor Authentication (MFA) and Single Sign-On (SSO)</strong>, enabling you to enhance the <strong>security</strong> and <strong>user experience</strong> of your application.</p><p>But how can you set it up?</p><p>First, let&#39;s take a look on a <strong>manual set-up</strong> in order to get familiar with the flow and then we will set up the user pool using <strong>serverless.yaml</strong> configuration file and <strong>deploy to AWS using SAM CLI</strong>.</p><h3>The manual way</h3><ul><li>Log into your AWS Console, search for cogntio and select it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze8xfjhEe3vy1-adpbO9Jg.jpeg" /></figure><ul><li>You will be presented with a list of your already existing user pools (if you have any). Go ahead and hit the <strong>Create user pool button.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHAUsp13xYm5Y7Zo-W9-iw.jpeg" /></figure><p>Now you will have to go through a step by step flow of the user pool setup.</p><h4><strong>Step 1: The Sign In Experience</strong></h4><p>For our example let&#39;s keep everything in the default settings, only check the <strong>Email sign-in option</strong> because we want out users to use their emails on sign-in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DyalQZad1RkpEnelobuZw.jpeg" /></figure><p><strong>But hold on!</strong></p><p>When you are setting this up for use in an actual application, carefully consider because you will not be able to change this once the user pool is created.</p><h4>Step 2: Configure security requirements</h4><p>Setup your password policy. Either stick with the default Cognito policy or configure your own. We are going to stick with the default.</p><p>Password policy can be changed later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-nv7m7JAg1VDo04VrIJIQ.jpeg" /></figure><p>We are going to choose the <strong>No MFA</strong> option. It is possible to set up MFA later on, so we are going to do it later once we have our basic auth flow working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqBgqw7KaRDhV13hJykveg.jpeg" /></figure><p>Setting up the user account recovery will be easy as well as we are once again sticking with the Cognito default settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZlGb4JG_jZqBI69F2qKBw.jpeg" /></figure><h4>Step 3: The Sign Up Experience</h4><p>Choose whether new users of your app can register for an account themselves.</p><p>Enable the self-service registration. Otherwise only the administrator would be able to register new users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*wsixvEIh7fHcfBCNuW2axQ.jpeg" /></figure><p>We will allow Cognito to send verification emails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*14Var-X_2D5Ek3pNsKgytg.jpeg" /></figure><p>Attributes required on sign-up. This is the information we&#39;re askingthe user to fill up. In our case we will only need the email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*UPKj-hdVkfLd0SqvYDlRog.jpeg" /></figure><h4>Step 4: Email</h4><p>Configure the verification email delivery. Choose the <strong>Send email with Cognito</strong> option. This will allow us to send up to 50 emails per day for free which is more then enough for development purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*11L2aPyd8EpmUkJxfb88hQ.jpeg" /></figure><h4>Step 5: App Integration</h4><p>Enter the name of a user pool that will be created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*fUDWfxNT-muuM7xLR3F9gw.jpeg" /></figure><p>We are not going to use the Cognito Hosted UI. While some companies do use it and it could be a nice feature for internal tools, I would not use this in a customer facing application. The UI customisation is very limited, it&#39;s only available in English and getting redirected in order to sign-up / sign-in seems a bit off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*6uwLOG65pbuIVFLj5xX9ng.jpeg" /></figure><p>The <strong>Confidential client</strong> offers an extra layer of securit. We could potentially use it because any communication with Cognito will be handled by our proxy Authentication service. However for the purpose of our tutorial we will go with the<strong> Public client </strong>option. This way we don&#39;t have to handle storing and fetching of a Client secret which should be ideally stored in <strong>secrets vault</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*bt9XCMj2gVZwJb7RM7jg0Q.jpeg" /></figure><p>Choose the Authentication Flows and token settings. These settings can be updated later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*NpXPweCjHzPnTze7_blrCA.jpeg" /></figure><h4>Step 5: Review and create</h4><p>We&#39;re all set!</p><p>Review your settings and hit create. You&#39;re user pool will be created and you&#39;ll be redirected to the list of your user pools.</p><h3>Summary</h3><p>Phew, this article got a bit longer then I expected!</p><p>We went through the manual process of the user pool setup and in order to deliver the articles for this series in a bite size pieces, we&#39;re going to cut it here.</p><p>If you&#39;re interested in this topic leave a clap, comment or follow and stay tuned for the next part.</p><p>It&#39;s coming soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4bdbbf2660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to go broke developing on AWS: The S3 — Lambda death spiral loop]]></title>
            <link>https://levelup.gitconnected.com/how-to-go-broke-developing-on-aws-the-s3-lambda-death-spiral-loop-fab763363499?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab763363499</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 20:48:27 GMT</pubDate>
            <atom:updated>2023-05-30T12:02:51.383Z</atom:updated>
            <content:encoded><![CDATA[<h3>Avoid this costly mistake on AWS: The S3 — Lambda death spiral loop</h3><p>Wether you are looking for a quick way on how to<strong> loose money</strong>, want to <strong>avoid</strong> <strong>this situation altogether </strong>or you just want to know how to <strong>resolve this in case it happens to you</strong>, you&#39;re in the right place.</p><p>What am I talking about?</p><p>The infamous Lambda — S3 infinite loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IhjmxW_czGCJGkYc" /><figcaption>Photo by <a href="https://unsplash.com/@alexandermils?utm_source=medium&amp;utm_medium=referral">Alexander Mils</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is it?</strong></h3><p>Let&#39;s break it down.</p><p>Amazon S3 allows you to configure <strong>S3 Event notifications</strong> for the following events:</p><ul><li>New object created events</li><li>Object removal events</li><li>Restore object events</li><li>Reduced Redundancy Storage (RRS) object lost events</li><li>Replication events</li><li>S3 Lifecycle expiration events</li><li>S3 Lifecycle transition events</li><li>S3 Intelligent-Tiering automatic archival events</li><li>Object tagging events</li><li>Object ACL PUT events</li></ul><p>This means that once the configured event is processed by S3 an event notification will be forwarded to your <strong>configured destination</strong>. Following destinations are available:</p><ul><li>Amazon Simple Notification Service (Amazon SNS) topics</li><li>Amazon Simple Queue Service (Amazon SQS) queues</li><li>AWS Lambda function</li></ul><p>A loop between <strong>S3 and Lambda</strong> can occur if you have set up a <strong>New object created event notification</strong>, which triggers an AWS Lambda function. If this Lambda function then creates a <strong>new object</strong> and stores it in the <strong>same S3 bucket</strong>, the process may repeat and cause a loop.</p><h3>Why would this happen?</h3><p>You could be developing an application where for example audio or image files are stored inside an S3 bucket in a specific folder.</p><p>The triggered lambda is then supposed to download given files, process them ( resize, convert… ) and store them to another S3 bucket or another subfolder, which are not triggering these events.</p><p>But we&#39;re only humans, right?</p><p>So a mistake can be made and you might code your lambda in a way it stores your processed file back in<strong> the same</strong> <strong>S3 bucket or subfolder</strong> that triggers the function again.</p><p><strong>Oops, your lambda is in a loop.</strong></p><p>If you don&#39;t notice this and let it run, you might be in for an unpleasant surprise once you realise your <strong>AWS bill is stacking up at alarming rates.</strong></p><p>This has happened to many people before in one way or another. There are multiple ways you can get your lambda function in an infinite loop, so be careful when developing a lambda triggered by events.</p><h3>How to stop this?</h3><p>Fortunately, AWS has added a convenient way to prevent your Lambda function from further invocations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JekZ8S7qiMfXMVeRjq3OYQ.jpeg" /></figure><p>Hitting the the throttle button will bring up a warning window explaining that the <strong>reserved concurrency </strong>of your lambda function will be set to <strong>zero</strong>. It also states you should only use this in <strong>case of emergencies</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*kr5gPHKBCyVNRVCMxYv6Og.jpeg" /></figure><p>This seems like an emergency to me, so go ahead and hit the <strong>Confirm</strong> button.</p><h3>I&#39;ve fixed it, but the Lambda won&#39;t run now</h3><p>Well, it&#39;s simply because it&#39;s still throttled, so we have to change the <strong>reserved concurrency</strong> of the Lambda function.</p><p>Go to the <strong>Configurations / Concurrency</strong> section of your Lambda function settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBehcazCD5IpPeuRGDJTpA.jpeg" /></figure><p>As you can see, the Reserved concurrency is set to zero. Click the <strong>Edit</strong> <strong>button</strong>. The following screen will show up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*KTFFe0KG5Q6eQjp697h3Kw.jpeg" /></figure><p>Set the Reserve concurrency to a desired value or check the <strong>Use unreserved account concurrency</strong> radio button.</p><p>Hit the <strong>Save </strong>button and you should be able to use your lambda function again.</p><h3>Summary</h3><p>As you can see, there are things that can go horribly wrong when developing on AWS. Has this or something similar happen to you?</p><p>Let me know in the comments.</p><p>As always I will strongly appreciate a few claps, subscribe or a feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab763363499" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-go-broke-developing-on-aws-the-s3-lambda-death-spiral-loop-fab763363499">How to go broke developing on AWS: The S3 — Lambda death spiral loop</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for AWS Lambda Function Logging]]></title>
            <link>https://levelup.gitconnected.com/best-practices-for-aws-lambda-function-logging-4012fcddee86?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4012fcddee86</guid>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 20:31:38 GMT</pubDate>
            <atom:updated>2023-05-30T12:03:29.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance Visibility and Debugging with Effective Logging</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdPRr_pGjBb73RyJUuuWCA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/de/@tcdinger?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Timo C. Dinger</a> on <a href="https://unsplash.com/photos/Oo3L5fL1lBU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Logging in AWS Lambda functions seems fairly simple and straightforward. All you have to do is print a message and AWS will transfer it to CloudWatch for you, right?</p><p>Well, not exactly.</p><p>While it might seem like the case, considering that you are taking logs from multiple different functions and sending them to a single centralised system, server-less logging can be tough.</p><p>Therefore there are some important considerations to keep in mind to ensure your logging is effective and efficient. In this article, we’ll be covering the best practices for AWS Lambda logging.</p><h3><strong>Enforce logging standards</strong></h3><p>This probably doesn’t require a deep explanation. Using a standardised log format across your lambda functions can save you a lot of time and headaches when debugging your application or aggregating logs with 3rd party tools and platforms.</p><p>This topic presents a choice between <strong>plain text </strong>logging and <strong>JSON</strong>. Although JSON logging is generally recommended over plain text, depending on your specific use case, plain text logging may be sufficient.</p><p>However, to harness the full potential of CloudWatch or any another log aggregation platform, it is advisable to use JSON. More bout this in the <strong>JSON</strong> section of this article.</p><h3>To log or not to log</h3><p>Depending on your AWS region the price for <strong>CloudWatch</strong> log ingression ranges between <strong>0.50$ to 0.80$ per Gb</strong>.</p><p>While this not might seem like much if you&#39;re working with an application that does not face high loads, it definitely stacks up when you&#39;re dealing with millions of invocations and logs.</p><p>Apart from your own log, lambda also generates <strong>START</strong>, <strong>END</strong> and <strong>REPORT </strong>messages on every execution. These combined together are around <strong>300 Bytes</strong> of extra data ingested for each function invocation.</p><p>Example:</p><pre>START RequestId: a61709e4-820c-4cab-b2fb-643344b64799 Version: $LATEST<br>END RequestId: a61709e4-820c-4cab-b2fb-643344b64799<br>REPORT RequestId: a61709e4-820c-4cab-b2fb-643344b64799 Duration: 7.21 ms Billed Duration: 8 ms Memory Size: 128 MB Max Memory Used: 67 MB Init Duration: 207.81 ms</pre><p>Having to be aware of your log sizes is especially true when logging complete events like API Gateway proxy event or EventBridge events that depending on your data can get quite large.</p><p>Let&#39;s take an example of the following API Gateway proxy event:</p><pre>{<br>    &quot;version&quot;: &quot;2.0&quot;,<br>    &quot;routeKey&quot;: &quot;ANY /nodejs-apig-function-1G3XMPLZXVXYI&quot;,<br>    &quot;rawPath&quot;: &quot;/default/nodejs-apig-function-1G3XMPLZXVXYI&quot;,<br>    &quot;rawQueryString&quot;: &quot;&quot;,<br>    &quot;cookies&quot;: [<br>        &quot;s_fid=7AABXMPL1AFD9BBF-0643XMPL09956DE2&quot;,<br>        &quot;regStatus=pre-register&quot;<br>    ],<br>    &quot;headers&quot;: {<br>        &quot;accept&quot;: &quot;text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9&quot;,<br>        &quot;accept-encoding&quot;: &quot;gzip, deflate, br&quot;<br>    },<br>    &quot;requestContext&quot;: {<br>        &quot;accountId&quot;: &quot;123456789012&quot;,<br>        &quot;apiId&quot;: &quot;r3pmxmplak&quot;,<br>        &quot;domainName&quot;: &quot;r3pmxmplak.execute-api.us-east-2.amazonaws.com&quot;,<br>        &quot;domainPrefix&quot;: &quot;r3pmxmplak&quot;,<br>        &quot;http&quot;: {<br>            &quot;method&quot;: &quot;GET&quot;,<br>            &quot;path&quot;: &quot;/default/nodejs-apig-function-1G3XMPLZXVXYI&quot;,<br>            &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>            &quot;sourceIp&quot;: &quot;205.255.255.176&quot;,<br>            &quot;userAgent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36&quot;<br>        },<br>        &quot;requestId&quot;: &quot;JKJaXmPLvHcESHA=&quot;,<br>        &quot;routeKey&quot;: &quot;ANY /nodejs-apig-function-1G3XMPLZXVXYI&quot;,<br>        &quot;stage&quot;: &quot;default&quot;,<br>        &quot;time&quot;: &quot;10/Mar/2020:05:16:23 +0000&quot;,<br>        &quot;timeEpoch&quot;: 1583817383220<br>    },<br>    &quot;isBase64Encoded&quot;: true<br>}</pre><p>Pasting this to <a href="https://www.debugbear.com/json-size-analyzer">https://www.debugbear.com/json-size-analyzer</a> gives us a JSON size of <strong>972B. </strong>Combine this with the <strong>300B </strong>that lambda generates for each function invocation and we will reach <strong>1270B </strong>of ingested data for a single log in an invocation.</p><p>Now depending on what kind of application you are dealing with, the load on a single Lambda function can be in a range of <strong>hundreds to</strong> <strong>thousands</strong> of requests per minute.</p><p>Having 10 functions like this in production then could potentially generate multiple Gb of data daily and could add hundreds of dollars to your AWS Bill.</p><p>But hold on!</p><p><strong>Money is not the only concern</strong>. I strongly advise you against logging the full lambda event in production environment.</p><p>Depending on what kind of data is your lambda function dealing with, you might be logging <strong>sensitive information</strong> like users <strong>ID Number, phone number, etc</strong>. This could be a direct violation of <strong>GPDR</strong> regulations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcFE6CFS7qViVt7jObnsqA.jpeg" /></figure><h3>Logging levels</h3><p>With all of the above being said, there may be times when you need to log additional information, even if it’s not strictly necessary for production use.</p><p>This is especially true when debugging an application. For this, you can use log levels to filter out unnecessary information only keep the information that’s most relevant for the given environment.</p><p>Some of the common log levels include <strong>DEBUG</strong>, <strong>INFO</strong>, <strong>WARN,</strong> and <strong>ERROR.</strong></p><p>There are dozens of out of the box solutions like the widely used logger <strong>Winston, </strong>so you can either use one of the existing logging libraries or write your own custom logger.</p><p>You can use Lambda environment variables to control the log level of your lambda function. Define a <strong>LOG_LEVEL </strong>environment variable based on the environment your Lambda function runs in, for example <strong>INFO</strong> for production and <strong>DEBUG</strong> for development. Use it in your logger configuration to set the log level of your logger.</p><p>This way you control the amount of detail you get in specific environments. For example you can get all of the logs in your development environment and only the essential ones in production.</p><p>Having the <strong>LOG_LEVEL</strong> defined in the Lambda functions environment variables also allows you to easily change the <strong>LOG_LEVEL</strong> value and get instant access to full logs even in production, if you ever need them.</p><p>But be carefull!</p><p>As I stated before be careful <strong>not to log any sensitive user information.</strong></p><h3>Log retention</h3><p>If you don&#39;t create and configure a <strong>Log Group </strong>for your Lambda function manually, it might do it for you automatically. However, by default the log retention will be set to <strong>forever.</strong></p><p>Again, depending on the region you are using the log storage prices may vary between <strong>0.030$ — 0.045$ per Gb. </strong>This looks really cheap but again, it can add up over the years and also why would you pay for something that you don&#39;t actually need.</p><p>So think about how long you need to keep your logs for and don&#39;t forget to set your retention rate accordingly.</p><h3>Does the JSON structure really matter?</h3><p>Yes, it does. CloudWatch or any other log aggregation platform like <strong>Datadog </strong>index your logs in order to be able to search them.</p><p>Using a JSON format allows you to use this feature to it&#39;s full potential and therefore make the debugging experience much better and more efficient. This not only saves you time when looking for what went wrong, but also makes it more enjoyable for you.</p><p>By using JSON you keep your data organised and structured. This is important because it makes your data readable, but more importantly it allows you to filter and search by it&#39;s inner hierarchy items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*s6v05xZPpq-K7u0ldXXfmA.png" /></figure><h3>Summary</h3><p>As we can see even seemingly simple topic as logging has it&#39;s intricacies.</p><p>If you found this article useful, I&#39;d appreciate a few claps, comment or a subscribe.</p><p>Also, If you feel like I&#39;ve missed something, feel free to let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4012fcddee86" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/best-practices-for-aws-lambda-function-logging-4012fcddee86">Best Practices for AWS Lambda Function Logging</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Development with AWS Lambda, Layers, TypeScript, and Docker]]></title>
            <link>https://medium.com/@stefansarmir/streamlining-development-with-aws-lambda-layers-typescript-and-docker-8de00f6407ae?source=rss-8a4bdae084ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8de00f6407ae</guid>
            <category><![CDATA[aws-sam]]></category>
            <category><![CDATA[aws-lambda-layer]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws-local-development]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Stefan Sarmir]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 21:23:54 GMT</pubDate>
            <atom:updated>2023-03-22T17:08:51.530Z</atom:updated>
            <content:encoded><![CDATA[<p>AWS Lambda is a serverless computing service that allows developers to run their code without having to manage the underlying infrastructure.</p><p>This makes it an attractive option for building and deploying applications, especially when combined with TypeScript, a popular programming language that builds on top of JavaScript.</p><p>In this article we will go through a step by step process on how to set up your local development environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*LN9xN2qE4kDVwf-2Hdmx_w.png" /></figure><h3><strong>Prerequisites</strong></h3><p>Before diving into the setup process, it is important to make sure you have the necessary prerequisites installed on your development machine. You will need:</p><ul><li>Docker</li><li>AWS SAM CLI</li><li>NPM / Yarn</li></ul><h3><strong>Docker Setup</strong></h3><p>Setting up Docker for this project is simple and straightforward. We will only need to use one command to create a Docker network, under which our containers will run.</p><p>This network will allow our SAM API to make requests to other containers in case we need that in the future.</p><p>To create a Docker network, run the following command in your :</p><pre>docker network create local-api-network</pre><h3><strong>Project Setup</strong></h3><ol><li><strong>First, create a folder where you want to host your Lambda functions. Then, you can either run </strong><strong>npm init from within the folder or manually create a </strong><strong>package.json file.</strong></li><li><strong>Create two new folders:</strong></li></ol><ul><li><strong>lambdas</strong>- This folder will host our lambda functions</li><li><strong>layers</strong>- This folder will host our function layers</li></ul><p><strong>3. Install packages. We will need a few of them:</strong></p><pre>npm i @types/aws-lambda ts-node @types/node typescript --save-dev </pre><pre>npm i node-fetch@2.6.1</pre><p>We are installing the node-fetch package in this example using the specific version for a reason. Node fetch v3&gt; uses ESM only and SAM doesn&#39;t play well with ESM when importing dependencies from a layer.</p><p>There are workarounds for that, for this example I have decided to use an older version of the package.</p><p><strong>4. Create tsconfig.json file. Copy and paste the following configuration:</strong></p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;ES2019&quot;,<br>    &quot;module&quot;: &quot;commonjs&quot;,<br>    &quot;lib&quot;: [<br>      &quot;es2019&quot;<br>    ],<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;declaration&quot;: false,<br>    &quot;removeComments&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;noImplicitAny&quot;: true,<br>    &quot;strictNullChecks&quot;: true,<br>    &quot;noImplicitThis&quot;: true,<br>    &quot;alwaysStrict&quot;: true,<br>    &quot;noUnusedLocals&quot;: false,<br>    &quot;noUnusedParameters&quot;: false,<br>    &quot;noImplicitReturns&quot;: true,<br>    &quot;noFallthroughCasesInSwitch&quot;: false,<br>    &quot;inlineSourceMap&quot;: false,<br>    &quot;inlineSources&quot;: false,<br>    &quot;outDir&quot;: &quot;build&quot;,<br>    &quot;pretty&quot;: false,<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;strictPropertyInitialization&quot;: false,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;baseUrl&quot;: &quot;.&quot;,<br>    &quot;paths&quot;: {<br>      &quot;/opt/lambdas_example_npm_packages/nodejs/node_modules/*&quot;: [<br>        &quot;node_modules/*&quot;<br>      ],<br>      &quot;/opt/*&quot;: [<br>        &quot;layers/*&quot;<br>      ]<br>    }<br>  },<br>  &quot;include&quot;: [<br>    &quot;lambdas/**/*.ts&quot;,<br>    &quot;layers/**/*.ts&quot;<br>  ]<br>}</pre><p>You can choose to use a stricter or more relaxed TypeScript configuration, depending on your needs. However, please ensure that you include the “paths” section in your configuration.</p><p>This is because we will be using node_modules as a layer, which allows us to reuse a single node_modules folder across multiple Lambda functions. By configuring the <strong>“/opt/*”</strong> path, TypeScript will be directed towards our layers folder.</p><p>It’s worth noting that in AWS Lambda, the <strong>“/opt/”</strong> directory is a designated path within a function’s execution environment where additional libraries, dependencies, and resources can be added using layers. By using layers, we can manage our function code separately from its dependencies, making it easier to deploy and maintain our code across multiple functions.</p><p><strong>5. We need to configure module aliases in package.json as well. Open package.json file and add the following configuration:</strong></p><pre>&quot;_moduleAliases&quot;: {<br>  &quot;baseUrl&quot;: &quot;.&quot;,<br>  &quot;/opt/lambdas_example_npm_packages/nodejs/node_modules&quot;: &quot;node_modules&quot;,<br>  &quot;/opt&quot;: &quot;layers&quot;<br>},</pre><h3><strong>Create your layer</strong></h3><p>In order to promote modularity, we will divide our layers into additional subfolders. To create a new layer file that exports a function to be used in our Lambda functions, first create a new folder named “general_layers”.</p><p>Then, create a file named <strong>“helperFunctions.ts”</strong> inside that folder. This will allow us to organize our layers more effectively and make them easier to manage.</p><p>We will use these two simple functions for this example. Copy and paste them into your <strong>helperFunctions.ts</strong> file:</p><pre>const fetch = require(&#39;/opt/lambdas_example_npm_packages/nodejs/node_modules/node-fetch&#39;);<br><br>export const capitalize = (str: string): string =&gt; {<br>    return str.toUpperCase();<br>}<br><br>export const fetchPokemon = async () =&gt; {<br>    const result = await fetch(&#39;https://pokeapi.co/api/v2/pokemon/ditto&#39;);<br>    return await result.json();<br>}</pre><p>Did you notice?</p><p><strong>We are importing node-fetch from our node_modules dependencies stored in the layer.</strong></p><p>Why are we dividing the layers folder to subsequent subfolders?</p><p>For example , in addition to creating the “general_layers” folder for our helper function layer, we could later create other folders as needed to organise our layers.</p><p>If we would have multiple functions related to image processing, we could create a new folder named <strong>“image_layers”</strong> to store our image processing layers. By organising our layers into separate folders, we can keep our codebase modular and easy to maintain.</p><h3><strong>Create your lambda functions</strong></h3><p>To keep our Lambda functions organised and easy to manage, we will host each function in its own individual subfolder.</p><p>Let’s create two subfolders named <strong>“lambda_fetch_pokemon_get”</strong> and <strong>“lambda_capitalize_post”</strong>. Within each subfolder, create a file named <strong>“app.ts”</strong>. These files will contain the function code for each of our Lambda functions, and organising them into separate subfolders will make it easier to locate and modify the code for each function.</p><p>Paste following code to <strong>“/lambda_fetch_pokemon_get/app.ts”</strong>:</p><pre>import { APIGatewayEvent, Handler } from &#39;aws-lambda&#39;;<br>import { fetchPokemon } from &#39;/opt/general_layer/helperFunctions&#39;;<br><br>export const lambdaHandler: Handler = async (<br>  event: APIGatewayEvent,<br>): Promise&lt;{<br>    statusCode: number; <br>    headers?: {<br>        &#39;Content-Type&#39;: string;<br>    };<br>    isBase64Encoded?: boolean;<br>    body: string;<br>}&gt; =&gt; {<br>    try {<br>        const pokemon = await fetchPokemon();<br><br>        if (!pokemon) {<br>            throw new Error(&#39;Failed to fetch pokemon!&#39;);<br>        }<br><br>        return {<br>            statusCode: 200,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            },<br>            isBase64Encoded: false,<br>            body: JSON.stringify({<br>                message: &#39;Pokemon fetched.&#39;,<br>                data: pokemon<br>            })<br>        }<br>    } catch (err) {<br>        return { statusCode: 500, body: JSON.stringify(err) };<br>    }<br>}  </pre><p>Paste following code to “/lambda_capitalize_post/app.ts”:</p><pre>import { APIGatewayEvent, Handler } from &#39;aws-lambda&#39;;<br>import { capitalize } from &#39;/opt/general_layer/helperFunctions&#39;;<br><br>export const lambdaHandler: Handler = async (<br>  event: APIGatewayEvent,<br>): Promise&lt;{<br>    statusCode: number; <br>    headers?: {<br>        &#39;Content-Type&#39;: string;<br>    };<br>    isBase64Encoded?: boolean;<br>    body: string;<br>}&gt; =&gt; {<br>    try {<br>        if (!event.body) {<br>            throw new Error(&#39;Invalid event body!&#39;);<br>        }<br>        const body = JSON.parse(event.body);<br>        const toCapitalize = body.word;<br><br>        if (!toCapitalize) {<br>            throw new Error(&#39;Invalid request!&#39;);<br>        }<br><br>        return {<br>            statusCode: 200,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            },<br>            isBase64Encoded: false,<br>            body: JSON.stringify({<br>                message: &#39;Success.&#39;,<br>                number: capitalize(toCapitalize)<br>            })<br>        }<br>    } catch (err) {<br>        return { statusCode: 500, body: JSON.stringify(err) };<br>    }<br>}  </pre><h3><strong>AWS SAM template</strong></h3><p>To enable local run of AWS Lambda functions, it’s necessary to configure the AWS SAM (Serverless Application Model) Template file.</p><p>This file, which can be in either YAML or JSON format, defines the necessary resources for deploying a serverless application, including <strong>AWS Lambda functions, Amazon API Gateway APIs, Amazon S3 buckets, Amazon DynamoDB tables, and more.</strong></p><p>The template contains the configuration details for these resources, such as their properties, permissions, and relationships to one another.</p><p>Create <strong>“template.yaml”</strong> file in the root of your project. Copy and paste the following script into it:</p><pre><br>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: &gt;<br>  offline-development-api<br>  <br>Globals:<br>  Function:<br>    Timeout: 60<br><br>Resources:<br>  NodeModulesLayer:<br>    Type: AWS::Serverless::LayerVersion<br>    Properties:<br>      LayerName: lambdas_example_npm_packages<br>      Description: Node modules layer<br>      ContentUri: build/layers/lambdas_example_npm_packages/nodejs<br>      CompatibleRuntimes:<br>        - nodejs18.x<br>      LicenseInfo: &#39;MIT&#39;<br>      RetentionPolicy: Retain<br>  GeneralLayer:<br>    Type: AWS::Serverless::LayerVersion<br>    Properties:<br>      LayerName: general_layer<br>      Description: General functions<br>      ContentUri: build/layers<br>      CompatibleRuntimes:<br>        - nodejs18.x<br>      LicenseInfo: &#39;MIT&#39;<br>      RetentionPolicy: Retain<br>  TestApi:<br>    Type: AWS::Serverless::Api<br>    Properties:<br>      StageName: dev<br>      Cors:<br>        AllowMethods: &quot;&#39;OPTIONS,GET,POST,PUT,PATCH,DELETE&#39;&quot;<br>        AllowHeaders: &quot;&#39;Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token&#39;&quot;<br>        AllowOrigin: &quot;&#39;*&#39;&quot;<br>  FetchPokemonFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      CodeUri: build/lambdas/lambda_fetch_pokemon_get<br>      Handler: app.lambdaHandler<br>      Runtime: nodejs18.x<br>      Events:<br>        SaveInvoice:<br>          Type: Api<br>          Properties:<br>            Path: /pokemon<br>            Method: get<br>            RestApiId: !Ref TestApi<br>      Layers:<br>        - !Ref NodeModulesLayer<br>        - !Ref GeneralLayer<br>  CapitalizeFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      CodeUri: build/lambdas/lambda_capitalize_post<br>      Handler: app.lambdaHandler<br>      Runtime: nodejs18.x<br>      Events:<br>        SaveInvoice:<br>          Type: Api<br>          Properties:<br>            Path: /capitalize<br>            Method: post<br>            RestApiId: !Ref TestApi<br>      Layers:<br>        - !Ref NodeModulesLayer<br>        - !Ref GeneralLayer</pre><p>Let’s take a closer look at the steps involved in configuring the <strong>AWS SAM Template file.</strong></p><p>Firstly, we define the <strong>“NodeModulesLayer” </strong>and <strong>“GeneralLayer”</strong> under <strong>“Resources”</strong>. The <strong>“ContentUri”</strong> section specifies the location of the compiled code.</p><p>Next, we define our API, which we’ve called <strong>“TestApi”</strong>. This API will be used to invoke our Lambda functions.</p><p>Moving on, we define the <strong>“RollDiceFunction”</strong>. This includes specifying the Lambda handler, code URI, runtime, and events that will be used to invoke this function. Under <strong>“Events”</strong>, we specify the event type as API, the endpoint path, method, and reference the previously configured API.</p><p>Similarly, we define the <strong>“CapitalizeFunction”</strong> function in the same manner, except that it has a POST method and a different endpoint path. Both function configurations also reference our previously configured layers.</p><h3><strong>Build it!</strong></h3><p>To compile our code, we will need a build script. Fortunately, I’ve got you covered with this one as well. Start by creating a <strong>“scripts”</strong> folder in the root directory of your project. Then, create a <strong>“build.js”</strong> file inside the <strong>“scripts”</strong> folder and copy and paste the following script into it:</p><pre>&#39;use strict&#39;;<br><br>const fs            = require(&#39;fs&#39;);<br>const path          = require(&#39;path&#39;);<br>const { promisify } = require(&#39;util&#39;);<br>const { exec }      = require(&#39;child_process&#39;);<br><br>const execAsync = promisify(exec);<br><br>// Paths<br>const rootFolder   = process.cwd();<br><br>// Initialize Project Dir paths<br>const tsConfigFile = path.join(rootFolder, &#39;tsconfig.json&#39;);<br>const lambdasDir   = path.join(rootFolder, &#39;layers&#39;);<br>const layersDir    = path.join(rootFolder, &#39;layers&#39;);<br><br>// Initialize Build Dir paths<br>const buildDirRoot    = path.join(rootFolder, &#39;build&#39;);<br>const npmDepsLayer    = path.join(buildDirRoot, &#39;layers&#39;, &#39;lambdas_example_npm_packages&#39;, &#39;nodejs&#39;, &#39;node_modules&#39;);<br><br>// Validate path<br>if (!fs.existsSync(lambdasDir) || !fs.existsSync(layersDir)) {<br>  throw new Error(<br>    `Cannot find directory.`<br>  );<br>}<br><br>// Remove build directory if already exists<br>if (fs.existsSync(buildDirRoot)) {<br>  fs.rmdirSync(buildDirRoot, { recursive: true, force: true });<br>}<br><br>// Build app commands<br>const commands = {<br>  installProdDeps:   `npx yarn install --production --modules-folder ${npmDepsLayer}`,<br>  compileTypescript: `npx tsc --project ${tsConfigFile}`,<br>};<br><br>const build = async(cmds) =&gt; {<br>  try {<br>    const installResult = await execAsync(cmds.installProdDeps);<br>    console.log(installResult.stdout);<br>    const compileResult = await execAsync(cmds.compileTypescript);<br>    console.log(compileResult.stdout);<br>  } catch (e) {<br>    console.error(e);<br>  }<br>}<br><br>build(commands);</pre><p>Next, navigate to the <strong>“package.json”</strong> file and add the following configuration:</p><pre>&quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;node ./scripts/build.js&quot;<br> },</pre><p>You’re now ready to run the build process. Open your terminal and run the following command from the root directory of your project:</p><pre>npm run build</pre><p>The execution of the build command should create a <strong>“build”</strong> folder in the root directory of your project. This folder should contain both <strong>“lambdas”</strong> and <strong>“layers”</strong> folders, which respectively contain the transpiled JavaScript code for the Lambdas and Layers.</p><h3><strong>Running and testing the API</strong></h3><p>After completing the setup process, starting your API is as simple as running a one-line command.</p><p>To start your API, make sure your docker is started, open your terminal, navigate to the root directory of your project, and execute the following command:</p><pre>sam local start-api --docker-network local-api-network</pre><p>Once the API is running, you should see a message indicating the port on which the API has been started.</p><p>Copy and paste the port number and use it to invoke your endpoints using Postman or another technology of your choice.</p><p>Invoking GET <a href="http://127.0.0.1:3000/capitalize">http://127.0.0.1:3000/</a>pokemon using Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*3rAADwS3nTGETeXHPt8Wdw.jpeg" /></figure><p>Invoking POST <a href="http://127.0.0.1:3000/capitalize">http://127.0.0.1:3000/</a>capitalize using Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*af6qcX3TzRZKqHZt5XCNLQ.jpeg" /></figure><h3>Summary</h3><p>I hope you found this article useful. Lastly, here is a link to the GitHub repository where you can find the example code:</p><p><a href="https://github.com/stevo95/lambdas-local">https://github.com/stevo95/lambdas-local</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8de00f6407ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>