<?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 Felipe Trova de Araujo on Medium]]></title>
        <description><![CDATA[Stories by Felipe Trova de Araujo on Medium]]></description>
        <link>https://medium.com/@feh-araujo?source=rss-cc5d88617db8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*b6UwVPbH52jHyp2R2H-bRA.jpeg</url>
            <title>Stories by Felipe Trova de Araujo on Medium</title>
            <link>https://medium.com/@feh-araujo?source=rss-cc5d88617db8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:26:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@feh-araujo/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[S3 Versioning: A Simple Guide]]></title>
            <link>https://feh-araujo.medium.com/s3-versioning-a-simple-guide-8f0ad102edeb?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0ad102edeb</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 09:59:47 GMT</pubDate>
            <atom:updated>2025-01-16T09:59:47.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Amazon S3 (Simple Storage Service) is a widely used cloud storage solution, and one of its key features is <strong>Object Versioning</strong>. This feature helps in managing and protecting your data by allowing you to store multiple versions of an object in a bucket (kinda a Git for your objects).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdWBgFFNTVIg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdWBgFFNTVIg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdWBgFFNTVIg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e5fd50fa104b64458329d9fd68d91d7/href">https://medium.com/media/6e5fd50fa104b64458329d9fd68d91d7/href</a></iframe><h3>What is Object Versioning?</h3><p><strong>Object Versioning</strong> in S3 allows you to keep multiple versions of an object. This means that if you update or delete an object, the previous versions are still stored, making it possible to recover older versions if needed. Versioning adds an extra layer of protection for your data, especially when dealing with accidental deletions or updates.</p><h3>Key Points About S3 Versioning:</h3><ul><li><strong>Versioning is disabled by default</strong> on every S3 bucket.</li><li>Once you enable versioning, you cannot disable it completely. You can only <strong>suspend</strong> it.</li><li><strong>Suspending versioning</strong> stops the creation of new versions, but old versions are still stored in the bucket.</li><li>Every version of an object takes up storage space, and you are billed for all versions, not just the most recent one.</li></ul><h3>How Versioning Works</h3><p>When you upload an object to S3 with versioning <strong>disabled</strong>, the object is stored with a simple key (e.g., photo1.jpg) and a <strong>null version ID</strong>. If you overwrite the object, the original is replaced.</p><p>When versioning is <strong>enabled</strong>, each object also has a unique <strong>version ID</strong>. If you upload a new version of the same object (for example, updating photo1.jpg), S3 assigns a new version ID to the modified object. This way, you can retrieve, delete, or manage specific versions by referring to their unique version IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgYz5kHpIxVLaVsnhMkEHg.png" /></figure><h3>Deleting Versioned Objects</h3><p>In a versioned bucket, objects aren’t deleted in the traditional sense. Instead, when you “delete” an object, S3 adds a <strong>deletion marker</strong> to hide it. This marker acts as a signal that the object has been removed, but the older versions are still stored.</p><ul><li>If you delete an object <strong>without specifying a version ID</strong>, S3 adds the deletion marker, and the object seems “deleted,” but earlier versions remain.</li><li>If you delete an object <strong>with a specific version ID</strong>, that version is permanently deleted, and the previous version becomes the latest one.</li></ul><h3>MFA Delete</h3><p>For added security, S3 offers a feature called <strong>MFA Delete</strong>. When this feature is enabled, certain actions like permanently deleting object versions or changing the versioning status of a bucket require additional verification.</p><ul><li><strong>MFA Delete</strong> requires Multi-Factor Authentication (MFA), meaning that when you attempt to delete a version or change the versioning state, you must provide the serial number of an MFA device along with a code generated by the device.</li></ul><p>This ensures that only authorized users can make these critical changes, adding an extra layer of protection for your important data.</p><p><strong>In Summary:</strong></p><ul><li><strong>Versioning</strong> protects your objects by keeping previous versions when updates or deletions occur.</li><li>Once enabled, versioning can only be suspended — not disabled.</li><li>Deleting objects in versioned buckets uses <strong>deletion markers</strong>, which hides but doesn’t erase older versions.</li><li><strong>MFA Delete</strong> adds extra security to prevent unauthorized changes or deletions.</li></ul><p>S3 versioning is a powerful feature for data protection, but it requires careful management due to the storage costs of maintaining multiple object versions. By enabling versioning, you safeguard your data from accidental changes while still being able to access or restore older versions if necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zftlx95MzhK0SZsPpU2LRQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f0ad102edeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Dev Containers — Por qué y cómo transforman tu entorno de desarrollo]]></title>
            <link>https://medium.com/backend-horizon/dev-containers-por-qu%C3%A9-y-c%C3%B3mo-transforman-tu-entorno-de-desarrollo-e575a3b367ef?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e575a3b367ef</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spanish]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 06:37:16 GMT</pubDate>
            <atom:updated>2024-09-26T04:21:45.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Dev Containers — Por qué y cómo transforman tu entorno de desarrollo</h3><p>En el mundo del desarrollo de software, tener un <strong>entorno de desarrollo</strong> consistente y fiable es crucial para la productividad y la eficiencia. Los entornos de desarrollo locales tradicionales, donde se instalaba todo manualmente, a menudo enfrentan desafíos relacionados con problemas de compatibilidad, conflictos de dependencias y versiones, y la necesidad de una configuración y configuración extensiva. Aquí es donde entran en juego los <strong>Docker Dev Containers</strong> y cambian completamente tu experiencia de desarrollo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1ljnBvaCWAE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1ljnBvaCWAE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1ljnBvaCWAE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24a54661e69a7ff58f8f228118230b88/href">https://medium.com/media/24a54661e69a7ff58f8f228118230b88/href</a></iframe><p>Imagina una caja con todas las herramientas que necesitas para construir un proyecto específico, como una caja de herramientas para trabajar la madera (martillos, sierras, etc.). Los contenedores de desarrollo de Docker son como estas cajas, pero para el desarrollo de software. Contienen todo el software necesario preinstalado en un entorno virtual, listo para usar.</p><p>Los contenedores de desarrollo de Docker son entornos ligeros y aislados que utilizan la tecnología de Docker para empaquetar un entorno de desarrollo completo dentro de un contenedor (¡tu caja de herramientas!). Estos contenedores encapsulan todas las herramientas necesarias, bibliotecas y configuraciones de tiempo de ejecución requeridas para desarrollar un proyecto específico. Al ejecutar un contenedor de desarrollo, los desarrolladores obtienen un entorno consistente y predecible que replica el entorno de manera precisa. Esto asegura que los cambios de código realizados localmente se comportarán de manera idéntica cuando se desplieguen en la nube o entre varias personas que trabajen juntas.</p><h3>Entornos Consistentes y Reutilizables</h3><p><a href="https://containers.dev/">Dev containers</a> ayudan a que todos en un equipo utilicen la misma configuración para su entorno de desarrollo, sin importar qué computadora estén usando. Piénsalo así: en lugar de que cada uno hornee un pastel con hornos e ingredientes ligeramente diferentes, los dev containers aseguran que todos utilicen exactamente el mismo horno y la misma receta. Esto significa que un proyecto en el que trabaje una persona funcionará igual para otra persona, y cuando nuevos miembros se unan al equipo, pueden empezar a programar de inmediato sin tener que configurar su propio entorno desde cero.</p><blockquote>“Funciona en mi máquina”. Escrito por alguien que no usa Dev Containers</blockquote><h3>Usar la extensión Dev Containers en Visual Studio Code</h3><p>La <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers">extensión Dev Containers</a> en Visual Studio Code hace que trabajar con contenedores de desarrollo sea muy fácil. Aquí tienes un resumen rápido de cómo se usa:</p><ul><li>Puedes configurar un nuevo contenedor de desarrollo directamente en VS Code sin complicadas configuraciones. Simplemente utiliza una de las plantillas preconstruidas o define la tuya propia para empezar.</li><li>La extensión te permite cambiar sin problemas entre diferentes entornos de desarrollo. Es como tener múltiples configuraciones de computadora en una sola, sin ninguna de las complicaciones habituales que esto conlleva.</li><li>Interactuar con tu código es igual que trabajar en tu escritorio local. Puedes editar, ejecutar y depurar tus proyectos dentro de VS Code, usando la misma interfaz con la que ya estás familiarizado, aunque el código real esté ejecutándose dentro de un contenedor.</li></ul><h3>Entendiendo devcontainer.json</h3><p>El archivo <strong>devcontainer.json</strong> es esencialmente el plano para tu contenedor de desarrollo. Especifica todo lo que tu entorno de desarrollo necesita tener, como:</p><ul><li><strong>Qué imagen base utilizar</strong>: Esto es como elegir el “SO” de tu configuración de desarrollo. Podría ser un entorno de Ubuntu simple o algo más personalizado.</li><li><strong>Software requerido</strong>: Enumera todas las herramientas y programas que deben estar preinstalados en el contenedor. Esto significa que no tienes que perder tiempo configurándolos manualmente.</li><li><strong>Configuraciones y extensiones</strong>: El archivo también puede incluir configuraciones para VS Code y listar las extensiones que deben instalarse automáticamente.</li></ul><p>Este archivo de configuración asegura que cualquier persona que use el contenedor de desarrollo tendrá exactamente la misma configuración, independientemente de su computadora personal, lo que ayuda a evitar el problema de “funciona en mi máquina”.</p><p>Echemos un vistazo al devcontainer.json de mi artículo sobre <a href="https://www.backendhorizon.com/posts/aws-cdk-getting-started">CDK</a>:</p><pre>{<br>    &quot;name&quot;: &quot;aws-dev-container&quot;,<br>    &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/typescript-node:1-18-bookworm&quot;,<br>    &quot;features&quot;: {<br>        &quot;ghcr.io/devcontainers/features/aws-cli:1&quot;: {},<br>        &quot;ghcr.io/devcontainers-contrib/features/aws-cdk:2&quot;: {}<br>    },<br>    &quot;customizations&quot;: {<br>        &quot;vscode&quot;: {<br>            &quot;extensions&quot;: [<br>                &quot;dbaeumer.vscode-eslint&quot;,<br>                &quot;eamodio.gitlens&quot;,<br>                &quot;firsttris.vscode-jest-runner&quot;,<br>                &quot;ryanluker.vscode-coverage-gutters&quot;,<br>                &quot;humao.rest-client&quot;<br>            ]<br>        }<br>    },<br>    &quot;remoteUser&quot;: &quot;root&quot;<br>}</pre><ul><li><strong>name</strong>: Esta clave asigna un nombre amigable al contenedor de desarrollo, lo que te ayuda a identificarlo fácilmente entre múltiples contenedores.</li><li><strong>image</strong>: Especifica la imagen de Docker a utilizar como base para el contenedor de desarrollo. Esto determina el sistema operativo y los lenguajes o marcos preinstalados. En el ejemplo anterior, utilicé una imagen que contiene NodeJS y Typescript ya instalados.</li><li><strong>features</strong>: Esa es una de las mejores … características de los contenedores de desarrollo. “Features” son herramientas o utilidades adicionales que se instalan automáticamente en el contenedor. Estos se utilizan típicamente para extender la funcionalidad base del contenedor con capacidades específicas. En el ejemplo, añadí el AWS CLI y CDK. Puedes encontrar una lista completa de características que puedes añadir a tu contenedor <a href="https://containers.dev/features">aquí</a>.</li><li><strong>customizations</strong>: Te permite personalizar el entorno de desarrollo específicamente para VS Code.</li><li><strong>extensions</strong>: Lista las extensiones de VS Code que se instalarán automáticamente en el contenedor, mejorando tu experiencia de desarrollo sin configuración manual.</li><li><strong>remoteUser</strong>: Especifica el usuario predeterminado bajo el cual el servidor de VS Code se ejecutará dentro del contenedor. Esto afecta los permisos y el acceso a archivos y procesos dentro del contenedor. Por ejemplo, <strong>root</strong> significa que operarás como el usuario root, que generalmente tiene acceso sin restricciones para modificar cualquier cosa dentro del contenedor.</li></ul><h3>Usando Dev Containers</h3><p>Para usar dev containers, primero necesitas instalar la <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers">extensión Dev Containers</a>.</p><p>Los archivos de configuración de Dev Container (devcontainer.json) se encuentran en la carpeta .devcontainer en la raíz de tu proyecto.</p><p>Cuando abras un proyecto con esta configuración por primera vez, VS Code te sugerirá una opción.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*IN_ohLrGaUT-ozB3kGYyyw.png" /></figure><p>Sugerencia de Visual Studio Code para abrir tu proyecto en un contenedor.</p><p>VS Code detectará la configuración del contenedor y te preguntará si deseas abrir el proyecto dentro de un contenedor. Al seleccionar “<strong>Reopen in Container</strong>”, se creará una imagen y un contenedor Docker. Tu pantalla se recargará y VS Code se conectará a tu contenedor.</p><p>También es posible construir/reconstruir el contenedor vía “<strong>Command Palette</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*D-VDNPMNDdzcvddcJasLug.png" /></figure><p>Opciones de Command Palette para construir/reconstruir y abrir el proyecto en un contenedor.</p><p>Después de que tu contenedor esté construido, tendrás un entorno como se describe en la configuración devcontainer.json.</p><h3>Configuración Básica con devcontainer.json</h3><p>El archivo devcontainer.json es el núcleo de la configuración del contenedor de desarrollo. Como viste arriba, te permite especificar varias configuraciones y características directamente, facilitando la configuración de un entorno de desarrollo y haciéndolo muy personalizable con “features”.</p><h3>Configuración avanzada con Dockerfile</h3><p>Si tienes la necesidad de una configuración más personalizable y modular, puedes extender tu configuración de devcontainer.json señalando a un Dockerfile. Este enfoque permite una mayor flexibilidad y control sobre el entorno.</p><pre>{<br>    &quot;name&quot;: &quot;aws-dev-container&quot;,<br>    &quot;build&quot;: {<br>        &quot;dockerfile&quot;: &quot;Dockerfile&quot;<br>    },<br>    &quot;customizations&quot;: {<br>        &quot;vscode&quot;: {<br>            &quot;extensions&quot;: [<br>                &quot;dbaeumer.vscode-eslint&quot;,<br>                &quot;eamodio.gitlens&quot;,<br>                &quot;firsttris.vscode-jest-runner&quot;,<br>                &quot;ryanluker.vscode-coverage-gutters&quot;,<br>                &quot;humao.rest-client&quot;<br>            ]<br>        }<br>    },<br>    &quot;remoteUser&quot;: &quot;root&quot;<br>}</pre><p>Preguntas o sugerencias, por favor deja un comentario, estamos todos aquí para aprender juntos. 🤠</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHbv-goG7fAurJDAje6pqw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e575a3b367ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/dev-containers-por-qu%C3%A9-y-c%C3%B3mo-transforman-tu-entorno-de-desarrollo-e575a3b367ef">Docker Dev Containers — Por qué y cómo transforman tu entorno de desarrollo</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Dev Containers — Por Que e Como Eles Transformam Seu Ambiente de Desenvolvimento]]></title>
            <link>https://medium.com/backend-horizon/dev-containers-por-que-e-como-eles-transformam-seu-ambiente-de-desenvolvimento-de3f2586f857?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3f2586f857</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Tue, 14 May 2024 19:36:25 GMT</pubDate>
            <atom:updated>2024-09-26T04:21:09.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Dev Containers — Por Que e Como Eles Transformam Seu Ambiente de Desenvolvimento</h3><p>No mundo do desenvolvimento de software, ter um ambiente de desenvolvimento consistente e confiável é crucial para a produtividade e eficiência. Ambientes de desenvolvimento locais tradicionais, onde você instalaria tudo manualmente, frequentemente enfrentam desafios relacionados a problemas de compatibilidade, conflitos de dependência e versão, e a necessidade de configuração extensa. É aqui que os <strong>Docker Dev Containers</strong> entram e se tornam um divisor de águas para sua experiência de desenvolvimento.</p><p><a href="https://feh-araujo.medium.com/dev-containers-296b8dbd2cf9">🇺🇸 English version here!</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1ljnBvaCWAE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1ljnBvaCWAE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1ljnBvaCWAE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24a54661e69a7ff58f8f228118230b88/href">https://medium.com/media/24a54661e69a7ff58f8f228118230b88/href</a></iframe><h3>O que são Docker Dev Containers?</h3><p>Imagine uma caixa com todas as ferramentas que você precisa para construir um projeto específico, como uma caixa de ferramentas para trabalhos em madeira (martelos, serras, etc.). Os Docker Dev Containers são como essas caixas, mas para desenvolvimento de software. Eles contêm todo o software necessário pré-instalado em um ambiente virtual, pronto para uso.</p><p>Os Docker Dev Containers são ambientes leves e isolados que utilizam a tecnologia Docker para empacotar um ambiente de desenvolvimento completo dentro de um container (sua caixa de ferramentas!). Esses containers encapsulam todas as ferramentas necessárias, bibliotecas e configurações de runtime necessárias para o desenvolvimento de um projeto específico. Ao executar um Dev Container, os desenvolvedores obtêm um ambiente consistente e previsível que replica o ambiente de maneira precisa. Isso garante que as alterações de código feitas localmente se comportem de maneira idêntica quando implantadas na nuvem ou entre várias pessoas trabalhando juntas.</p><h3>Ambientes Consistentes e Reutilizáveis</h3><p>Os Dev Containers ajudam todos em uma equipe a usar a mesma configuração para seu ambiente de desenvolvimento, não importa em qual computador estejam usando. Pense nisso assim: em vez de todos assarem um bolo com fornos e ingredientes ligeiramente diferentes, os Dev Containers garantem que todos usem o mesmo forno e a mesma receita. Isso significa que um projeto trabalhado por uma pessoa funcionará exatamente da mesma forma para outra pessoa, e quando novos membros da equipe se juntam, eles podem começar a programar imediatamente sem configurar seu próprio ambiente do zero.</p><blockquote><em>“Funciona na minha máquina”. Escrito por alguém que não usa Dev Containers</em></blockquote><h3>Usando a Extensão Dev Containers no Visual Studio Code</h3><p>A extensão Dev Containers no Visual Studio Code torna super fácil trabalhar com containers de desenvolvimento. Aqui está uma rápida explicação de como ela é usada:</p><ul><li>Você pode configurar um novo Dev Container diretamente dentro do VS Code sem lidar com configurações complexas. Basta usar um dos modelos pré-construídos ou definir o seu próprio para começar.</li><li>A extensão permite que você alterne perfeitamente entre diferentes ambientes de desenvolvimento. É como ter várias configurações de computador em uma, sem nenhuma das complicações usuais que vêm com isso.</li><li>Interagir com seu código é como trabalhar em seu desktop local. Você pode editar, executar e depurar seus projetos dentro do VS Code, usando a mesma interface com a qual já está familiarizado, embora o código real esteja sendo executado dentro de um container.</li></ul><h3>Entendendo o devcontainer.json</h3><p>O arquivo <strong>devcontainer.json</strong> é essencialmente o plano para o seu Dev Container. Ele especifica tudo que seu ambiente de desenvolvimento precisa ter, como:</p><ul><li><strong>Qual imagem base usar</strong>: Isso é como escolher o “SO” do seu ambiente de desenvolvimento. Pode ser um ambiente Ubuntu simples ou algo mais personalizado.</li><li><strong>Software necessário</strong>: Ele lista todas as ferramentas e programas que precisam ser pré-instalados no container. Isso significa que você não precisa perder tempo configurando esses manualmente.</li><li><strong>Configurações e extensões</strong>: O arquivo também pode incluir configurações de configuração para o VS Code e listar quaisquer extensões que devem ser instaladas automaticamente.</li></ul><p>Esta configuração de arquivo garante que qualquer pessoa que use o Dev Container terá a mesma configuração, independentemente de seu computador pessoal, ajudando a evitar o problema “funciona na minha máquina”.</p><p>Vamos dar uma olhada no <strong>devcontainer.json</strong> do meu artigo sobre <a href="https://medium.com/p/22ffc69e6234">CDK</a>:</p><pre>{<br>    &quot;name&quot;: &quot;aws-dev-container&quot;,<br>    &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/typescript-node:1-18-bookworm&quot;,<br>    &quot;features&quot;: {<br>        &quot;ghcr.io/devcontainers/features/aws-cli:1&quot;: {},<br>        &quot;ghcr.io/devcontainers-contrib/features/aws-cdk:2&quot;: {}<br>    },<br>    &quot;customizations&quot;: {<br>        &quot;vscode&quot;: {<br>            &quot;extensions&quot;: [<br>                &quot;dbaeumer.vscode-eslint&quot;,<br>                &quot;eamodio.gitlens&quot;,<br>                &quot;firsttris.vscode-jest-runner&quot;,<br>                &quot;ryanluker.vscode-coverage-gutters&quot;,<br>                &quot;humao.rest-client&quot;<br>            ]<br>        }<br>    },<br>    &quot;remoteUser&quot;: &quot;root&quot;<br>}</pre><ul><li><strong>name</strong>: Esta chave atribui um nome amigável ao container de desenvolvimento, o que ajuda você a identificá-lo facilmente entre vários containers.</li><li><strong>image</strong>: Especifica a imagem Docker a ser usada como base para o Dev Container. Isso determina o sistema operacional e as linguagens ou frameworks pré-instalados. No exemplo acima, eu usei uma imagem que já contém NodeJS e Typescript instalados.</li><li><strong>features</strong>: Essa é uma das melhores… características dos Dev Containers. “Features” são ferramentas ou utilitários adicionais que são instalados automaticamente no container. Elas são tipicamente usadas para estender a funcionalidade básica do container com capacidades específicas. No exemplo, eu adicionei o AWS CLI e CDK. Você pode encontrar uma lista completa de features que você pode adicionar no seu container <a href="https://containers.dev/features">aqui</a>.</li><li><strong>customizations</strong>: Permite que você personalize o ambiente de desenvolvimento especificamente para o VS Code.</li><li><strong>extensions</strong>: Lista as extensões do VS Code para serem instaladas automaticamente no container, melhorando sua experiência de desenvolvimento sem configuração manual.</li><li><strong>remoteUser</strong>: Especifica o usuário padrão sob o qual o servidor do VS Code será executado dentro do container. Isso afeta as permissões e o acesso a arquivos e processos dentro do container. Por exemplo, <strong>root</strong> significa que você operará como usuário root, que geralmente tem acesso irrestrito para modificar qualquer coisa dentro do container.</li></ul><h3>Usando Dev Containers</h3><p>Para usar Dev Containers, você primeiro precisa instalar a <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers">extensão Dev Containers</a>.</p><p>Arquivos de configuração do Dev Container (<strong>devcontainer.json</strong>) estão localizados na pasta <strong>.devcontainer</strong> na raiz do seu projeto.</p><p>Quando você abrir um projeto com essa configuração pela primeira vez, o VS Code o alertará com uma sugestão.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaqNtLfUiMtNGodKFg94tQ.png" /><figcaption>Sugestão do Visual Studio Code para abrir o seu projeto em um container</figcaption></figure><p>O VS Code detectará a configuração do container e perguntará se você deseja abrir o projeto dentro de um container. Ao selecionar “<strong>Reopen in Container</strong>,” uma imagem Docker e um container serão criados. Sua tela então será recarregada, e o VS Code se conectará ao seu container.</p><p>Também é possível construir/reconstruir o container via “<strong>Command Palette</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sse96Yz075mOiv1XG7AbwQ.png" /><figcaption>Opção no Command Palette para buildar/rebuildar e abrir o projeto em um container</figcaption></figure><p>Depois que seu container for construído, você terá um ambiente conforme descrito na configuração <strong>devcontainer.json</strong>.</p><h3>Configuração Básica com devcontainer.json</h3><p>O arquivo <strong>devcontainer.json</strong> é o cerne da configuração do Dev Container. Como você viu acima, ele permite que você especifique várias configurações e features diretamente, facilitando a configuração de um ambiente de desenvolvimento e sendo muito personalizável com “features”.</p><h3>Configuração Avançada com Dockerfile</h3><p>Se você tem a necessidade de uma configuração mais personalizável e modular, você pode estender sua configuração <strong>devcontainer.json</strong> apontando para um <strong>Dockerfile</strong>. Esta abordagem permite maior flexibilidade e controle sobre o ambiente.</p><pre>{<br>    &quot;name&quot;: &quot;aws-dev-container&quot;,<br>    &quot;build&quot;: {<br>        &quot;dockerfile&quot;: &quot;Dockerfile&quot;<br>    },<br>    &quot;customizations&quot;: {<br>        &quot;vscode&quot;: {<br>            &quot;extensions&quot;: [<br>                &quot;dbaeumer.vscode-eslint&quot;,<br>                &quot;eamodio.gitlens&quot;,<br>                &quot;firsttris.vscode-jest-runner&quot;,<br>                &quot;ryanluker.vscode-coverage-gutters&quot;,<br>                &quot;humao.rest-client&quot;<br>            ]<br>        }<br>    },<br>    &quot;remoteUser&quot;: &quot;root&quot;<br>}</pre><p><strong>Perguntas ou sugestões, por favor, deixe um comentário, estamos todos aqui para aprender juntos. 🤠</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHbv-goG7fAurJDAje6pqw.jpeg" /><figcaption>Docker Dev Containers</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3f2586f857" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/dev-containers-por-que-e-como-eles-transformam-seu-ambiente-de-desenvolvimento-de3f2586f857">Docker Dev Containers — Por Que e Como Eles Transformam Seu Ambiente de Desenvolvimento</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Dev Containers — Why and How They Transform Your Development Environment]]></title>
            <link>https://medium.com/backend-horizon/dev-containers-296b8dbd2cf9?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/296b8dbd2cf9</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Tue, 14 May 2024 19:07:47 GMT</pubDate>
            <atom:updated>2024-09-26T04:18:01.932Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of software development, having a consistent and reliable <strong>development environment</strong> is crucial for productivity and efficiency. Traditional local development environments, where you would install everything manually often face challenges related to compatibility issues, dependency and version conflicts, and the need for extensive setup and configuration. This is where <strong>Docker Dev Containers</strong> step in and it’s a game changer to your development experience.</p><p><a href="https://feh-araujo.medium.com/dev-containers-por-que-e-como-eles-transformam-seu-ambiente-de-desenvolvimento-de3f2586f857">🇧🇷 Versão em português aqui!</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1ljnBvaCWAE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1ljnBvaCWAE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1ljnBvaCWAE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/24a54661e69a7ff58f8f228118230b88/href">https://medium.com/media/24a54661e69a7ff58f8f228118230b88/href</a></iframe><h3>What are Docker Dev Containers?</h3><p>Imagine a box with all the tools you need to build a specific project, like a toolbox for woodworking (hammers, saws, etc.). Docker dev containers are like these boxes, but for software development. They contain all the necessary software pre-installed in a virtual environment, ready to use.</p><p>Docker dev containers are lightweight, isolated environments that utilize Docker technology to package a complete development environment within a container (your toolbox!). These containers encapsulate all the necessary tools, libraries, and runtime configurations required for developing a specific project. By running a dev container, developers gain a consistent and predictable environment that replicates the environment precisely. This ensures that code changes made locally will behave identically when deployed to the cloud or between multiple people working together.</p><h3>Consistent and Reusable Environments</h3><p><a href="https://containers.dev/">Dev containers</a> help everyone on a team use the same setup for their development environment, no matter which computer they’re using. Think of it like this: instead of everyone baking a cake with slightly different ovens and ingredients, dev containers make sure everyone uses the exact same oven and the same recipe. This means that a project worked on by one person will work just the same for someone else, and when new team members join, they can start coding right away without setting up their own environment from scratch.</p><blockquote><em>“Works on my machine”. Wrote by someone that doesn’t use Dev Containers</em></blockquote><h3>Using the Dev Containers Extension in Visual Studio Code</h3><p>The Dev Containers extension in Visual Studio Code makes it super easy to work with development containers. Here’s a quick breakdown of how it’s used:</p><ul><li>You can set up a new dev container right within VS Code without messing with complex configurations. Just use one of the pre-built templates or define your own to get started.</li><li>The extension allows you to seamlessly switch between different development environments. It’s like having multiple computer setups in one, without any of the usual complications that come with it.</li><li>Interacting with your code is just like working on your local desktop. You can edit, run, and debug your projects within VS Code, using the same interface you’re already familiar with, even though the actual code is running inside a container.</li></ul><h3>Understanding devcontainer.json</h3><p>The <strong>devcontainer.json</strong> file is essentially the blueprint for your dev container. It specifies everything your development environment needs to have, such as:</p><ul><li><strong>Which base image to use</strong>: This is like choosing the “OS” of your development setup. It could be a simple Ubuntu environment or something more customised.</li><li><strong>Required software</strong>: It lists all the tools and programs that need to be pre-installed in the container. This means you don’t have to waste time setting these up manually.</li><li><strong>Settings and extensions</strong>: The file can also include configuration settings for VS Code and list any extensions that should be installed automatically.</li></ul><p>This configuration file ensures that anyone who uses the dev container will have the exact same setup, regardless of their personal computer, which helps in avoiding the “it works on my machine” problem.</p><p>Let’s take a look on the devcontainer.json from my article about <a href="https://medium.com/p/22ffc69e6234">CDK</a>:</p><pre>{<br>    &quot;name&quot;: &quot;aws-dev-container&quot;,<br>    &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/typescript-node:1-18-bookworm&quot;,<br>    &quot;features&quot;: {<br>        &quot;ghcr.io/devcontainers/features/aws-cli:1&quot;: {},<br>        &quot;ghcr.io/devcontainers-contrib/features/aws-cdk:2&quot;: {}<br>    },<br>    &quot;customizations&quot;: {<br>        &quot;vscode&quot;: {<br>            &quot;extensions&quot;: [<br>                &quot;dbaeumer.vscode-eslint&quot;,<br>                &quot;eamodio.gitlens&quot;,<br>                &quot;firsttris.vscode-jest-runner&quot;,<br>                &quot;ryanluker.vscode-coverage-gutters&quot;,<br>                &quot;humao.rest-client&quot;<br>            ]<br>        }<br>    },<br>    &quot;remoteUser&quot;: &quot;root&quot;<br>}</pre><ul><li><strong>name</strong>: This key assigns a friendly name to the development container, which helps you easily identify it among multiple containers.</li><li><strong>image</strong>: Specifies the Docker image to use as the base for the dev container. This determines the operating system and pre-installed languages or frameworks. In the example above, I used an image that contains NodeJS and Typescript already installed.</li><li><strong>features</strong>: That’s one of the best … features of dev containers. “Features” are additional tools or utilities that are automatically installed in the container. These are typically used to extend the base functionality of the container with specific capabilities. In the example, I added the AWS CLI and CDK. You can find a full list of features that you can add in your container <a href="https://containers.dev/features">here</a>.</li><li><strong>customizations</strong>: Allows you to customize the development environment specifically for VS Code.</li><li><strong>extensions</strong>: Lists VS Code extensions to be automatically installed in the container, enhancing your development experience without manual setup.</li><li><strong>remoteUser</strong>: Specifies the default user under which the VS Code server will run inside the container. This affects permissions and access to files and processes within the container. For example, <strong>root</strong> means that you will operate as the root user, which generally has unrestricted access to modify anything within the container.</li></ul><h3>Using Dev Containers</h3><p>To use dev containers, you first need to install the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers">Dev Containers extension</a>.</p><p>Dev Container configuration files (devcontainer.json) are located in the .devcontainer folder at the root of your project.</p><p>When you open a project with this configuration for the first time, VS Code will prompt you with a suggestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaqNtLfUiMtNGodKFg94tQ.png" /><figcaption>Visual Studio Code suggestion to open your project into a container</figcaption></figure><p>VS Code will detect the container configuration and ask if you want to open the project inside a container. By selecting “<strong>Reopen in Container</strong>,” a Docker image and container will be created. Your screen will then reload, and VS Code will connect to your container.</p><p>It’s also possible to build/rebuild the container via “<strong>Command Palettte</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sse96Yz075mOiv1XG7AbwQ.png" /><figcaption>Command Palette options to build/rebuild and open the project in a container</figcaption></figure><p>After your container is built, you will have an environment as described in the devcontainer.json configuration.</p><h3>Basic Configuration with devcontainer.json</h3><p>The devcontainer.json file is the core of the dev container configuration. As you saw above It allows you to specify various settings and features directly, making it easy to set up a development environment and very customisable with “features”.</p><h3>Advanced Configuration with Dockerfile</h3><p>If you have the necessity of a more customisable and modular setup, you can extend your devcontainer.json configuration by pointing to a Dockerfile. This approach allows for greater flexibility and control over the environment.</p><pre>{<br>    &quot;name&quot;: &quot;aws-dev-container&quot;,<br>    &quot;build&quot;: {<br>        &quot;dockerfile&quot;: &quot;Dockerfile&quot;<br>    },<br>    &quot;customizations&quot;: {<br>        &quot;vscode&quot;: {<br>            &quot;extensions&quot;: [<br>                &quot;dbaeumer.vscode-eslint&quot;,<br>                &quot;eamodio.gitlens&quot;,<br>                &quot;firsttris.vscode-jest-runner&quot;,<br>                &quot;ryanluker.vscode-coverage-gutters&quot;,<br>                &quot;humao.rest-client&quot;<br>            ]<br>        }<br>    },<br>    &quot;remoteUser&quot;: &quot;root&quot;<br>}</pre><p><strong>Questions or suggestions, please leave a comment, we’re all here to learn together. 🤠</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHbv-goG7fAurJDAje6pqw.jpeg" /><figcaption>Docker Dev Containers</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=296b8dbd2cf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/dev-containers-296b8dbd2cf9">Docker Dev Containers — Why and How They Transform Your Development Environment</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDK con Typescript — Comenzando]]></title>
            <link>https://medium.com/backend-horizon/aws-cdk-con-typescript-comenzando-2b9d3d9b61ab?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b9d3d9b61ab</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[programación]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 10:18:28 GMT</pubDate>
            <atom:updated>2024-01-24T14:14:24.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CDK con Typescript — Comenzando</h3><p>Hoy vamos a aprender sobre el AWS CDK, que es una herramienta súper útil para que crees tu infraestructura en la nube de AWS.</p><p>🇺🇸 <a href="https://medium.com/@feh-araujo/aws-cdk-with-typescript-getting-started-22ffc69e6234">English version here</a></p><p>🇧🇷 <a href="https://medium.com/@feh-araujo/aws-cdk-com-typescript-primeiros-passos-071a6e465864">Versão em português aqui</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FK7xTkaPvo7M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DK7xTkaPvo7M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FK7xTkaPvo7M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8923643673c0d7e45461f6af79c3a77/href">https://medium.com/media/e8923643673c0d7e45461f6af79c3a77/href</a></iframe><p>Con el CDK, puedes crear rápidamente infraestructura a través de código y usando lenguajes que ya utilizamos en nuestro día a día, como TypeScript, Python, Java. Así que, para reducir la complejidad de gestionar tu infraestructura y todo de manera automatizada, CDK podría ser la opción ideal para ti.</p><h3>IaC</h3><p>Antes de hablar sobre el CDK, es importante entender qué es la infraestructura como código.</p><p>La infraestructura como código (IaC, por sus siglas en inglés) es una forma de crear y gestionar recursos de infraestructura utilizando código en lugar de configurar todo a través de una página web o mediante comandos en una terminal.</p><p>Digamos que necesitas crear un servidor web en la nube. En lugar de ir a la consola de AWS y hacer clic en un montón de botones para crear manualmente tu servidor, puedes escribir código que detalle todas las configuraciones del servidor, como el tipo de instancia, tamaño del disco, cuánta memoria tendrá este servidor y la configuración de la red.</p><p>Luego puedes ejecutar este código para crear y configurar automáticamente el servidor en AWS. Esto es útil porque puedes repetir el proceso tantas veces como quieras, sin preocuparte por olvidar una configuración importante, y también puedes gestionar estos recursos como si fueran código, guardar en tu repositorio git, tener todo el historial de cambios y, por supuesto, hacer revisiones de código en tu código de infraestructura.</p><p>La infraestructura por código puede sonar complicada, pero no lo es. Hoy en día, nadie configura aplicaciones manualmente, los riesgos de hacer esto en aplicaciones reales son demasiado altos. Por eso las herramientas de infraestructura como código (como el CDK) son tan importantes. ¡Y por cierto, es mucho más divertido que hacer clic en botones, ¿verdad?!</p><h3>CDK &amp; Cloud Formation</h3><p>Hay varias herramientas de infraestructura como código en el mercado. Aquí, más en el contexto de AWS, hablemos de CDK y CloudFormation. Ambas son herramientas que ayudan a los desarrolladores a construir y gestionar recursos de infraestructura en la nube. El CDK fue creado sobre el complemento de CloudFormation, y explicaré por qué.</p><p>CloudFormation es más antiguo y utiliza archivos JSON o YAML para describir la infraestructura que deseas construir. Necesitas saber cómo escribir estos archivos con la sintaxis correcta, y a veces puede ser un poco complicado y los archivos pueden volverse bastante grandes. Con CloudFormation, describes con <strong>precisión</strong> cómo será tu infraestructura.</p><p>AWS CDK es un poco diferente ya que te permite usar lenguajes de programación como TypeScript, Python, Java para describir tu infraestructura. Puedes crear infraestructura compleja y sofisticada usando clases y objetos, lo que hace que el código de infraestructura sea más familiar para los desarrolladores.</p><p>Además, con CDK, puedes reutilizar y compartir código para ahorrar tiempo. Es posible crear componentes y compartirlos en tu empresa, creando bibliotecas, por ejemplo, que tienen configuraciones estándar que pueden ser utilizadas por varios equipos en tu empresa. Y, por supuesto, existen componentes de código abierto hechos por la comunidad.</p><p>¿Y por qué dije que el CDK es un complemento de CloudFormation? Porque cuando compilamos este código de CDK, lo que se generará es un archivo de CloudFormation, que se utilizará para crear nuestra infraestructura.</p><p>¿Entonces CDK es la mejor opción siempre? ¡NO! Una cosa que siempre debes tener en mente es que el CDK es una solución con opiniones predefinidas. ¿Qué quiero decir con eso? El CDK es una herramienta construida sobre CloudFormation, y debido a eso hay varios comportamientos por defecto en esta herramienta, lo que generalmente hace que el código de CDK sea más pequeño en comparación con CloudFormation, y eso no significa que estos comportamientos no cambien con nuevas versiones. CloudFormation puede ser muy verboso y un poco más complicado de trabajar, pero, por otro lado, con CloudFormation describes con precisión cómo debería verse tu infraestructura.</p><p>Entonces, teniendo eso en cuenta, puede ser que para algunas áreas más sensibles de tu infraestructura, CDK no sea la mejor opción. ¿OK? Espero que la diferencia esté clara.</p><h3>Application</h3><p>Antes de adentrarnos en el código, necesitas tener el CDK CLI instalado. Dejaré el enlace en la descripción, donde puedes seguir el paso a paso.</p><p>Echemos un vistazo rápido a la implementación de la aplicación y luego comencemos a construir la infraestructura juntos.</p><p>Nuestra aplicación es simple y tiene dos endpoints:</p><ol><li><strong>Un endpoint tipo POST para registrar transacciones</strong>, donde pasamos un payload con correo electrónico, valor, moneda, etc.</li><li><strong>Un endpoint tipo GET para listar todas las transacciones realizadas en el día</strong>, donde tendremos los datos que registramos, más la fecha en la que se realizó la transacción y un ID.</li></ol><p>Los dos endpoints se ejecutarán a través de lambdas junto con API Gateway y los datos se guardarán en una base de datos DynamoDB.</p><p>El enlace al código en Github también está en la descripción.</p><p>No entraré en detalles sobre la implementación de la aplicación, porque no es el foco de este artículo. Son solo 2 lambdas, una guardando datos en nuestra base de datos DynamoDB y otra recuperándolos. Si quieres saber más sobre Lambdas y DynamoDB, deja un comentario y haré otros artículos al respecto.</p><h3>Proyecto y dependencias</h3><p>Si miramos en la documentación veremos que es posible crear un proyecto usando el comando <strong>cdk init</strong>. Este proyecto fue creado usando este comando y agregué algunas otras dependencias:</p><pre>@aws-cdk/aws-lambda-nodejs<br>@types/aws-lambda<br>aws-sdk</pre><ol><li><strong>@aws-cdk/aws-lambda-nodejs</strong> y<strong>@types/aws-lambda</strong>, para configurar fácilmente nuestras lambdas con NodeJS</li><li><strong>aws-sdk</strong>, para que podamos usar DynamoDB</li></ol><h3>Stacks</h3><p>El punto de entrada para un código CDK para comenzar a construir nuestra infraestructura es la carpeta <strong>bin</strong>.</p><p>Dentro de esa carpeta, tendremos un archivo que se creará junto con el proyecto, y es este archivo el que comenzará a ensamblar nuestra infraestructura.</p><pre>#!/usr/bin/env node<br>import &#39;source-map-support/register&#39;;<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { InitWithCDKTypescriptStack } from &#39;../lib/init-with-cdk-typescript-stack&#39;;</pre><pre>const app = new cdk.App();<br>new InitWithCDKTypescriptStack(app, &#39;InitWithCdkTypescriptStack&#39;);</pre><p>Podemos ver que la primera línea es la creación de una nueva aplicación CDK y luego creamos un nuevo “stack” y le damos un id.</p><p>En CDK, un “stack” es básicamente una colección de componentes que puedes crear. Es un conjunto de componentes que puedes apilar y organizar de una manera que tenga sentido para ti. Por supuesto, puedes tener solo un stack, o puedes tener varios y organizarlos como quieras.</p><p>Por ejemplo, supongamos que quieres construir una aplicación web en AWS. Puedes crear un único stack que tendrá tu instancia EC2 para alojar la aplicación, configuraciones de seguridad, un bucket S3 para almacenar archivos, y así sucesivamente.</p><p>Otro ejemplo sería dividir por stacks que contienen servicios que almacenan datos y otros que no. Así, S3 y DynamoDB en un stack, lambdas y API Gateway en otro.</p><p>Para crear un stack, necesitamos una clase que extienda <strong>cdk.stack</strong> y dentro de esa clase podemos comenzar a listar los componentes que pertenecerán a ese stack.</p><p>Es bueno mencionar que los stacks y los componentes que vamos a crear están en la carpeta <strong>lib</strong>. La carpeta bin solo se utiliza para señalar al CDK dónde comienza la declaración de la infraestructura.</p><h3>DynamoDB Stack</h3><p>Vamos a crear primero nuestra base de datos DynamoDB. Dentro de un nuevo archivo, creemos una clase TransactionsTable y extendámosla desde Table.</p><pre>import { AttributeType, Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br>import { Construct } from &quot;constructs&quot;;</pre><pre>export class TransactionsTable extends Table {<br>  constructor(scope: Construct) {<br>    super(scope, &#39;TRANSACTIONS_TABLE&#39;, {<br>      partitionKey: { name: &#39;EMAIL&#39;, type: AttributeType.STRING },<br>      sortKey: { name: &#39;CREATEDAT&#39;, type: AttributeType.STRING },<br>    });<br>  }<br>}</pre><p>La clase tiene un constructor que recibe un parámetro llamado <strong>scope</strong>, de tipo <strong>Construct</strong>. Este parámetro representa el alcance en el que se está creando la tabla. En nuestro caso, este alcance será nuestro stack principal, InitWithCDKTypescriptStack.</p><p>Dentro del constructor de la clase <strong>Table</strong>, necesitamos insertar información importante. Primero, le damos a la tabla un nombre, que es <strong>‘TRANSACTIONS_TABLE’</strong>.</p><p><strong>Un consejo rápido sobre eso</strong>: cuando llamamos a la base de datos en nuestro código y queremos usar la tabla que estamos creando, no es posible llamar a la tabla usando solo este nombre. Los nombres de los recursos en AWS deben ser únicos, por lo que la tabla se creará con el nombre que le dimos y AWS añadirá algún identificador para hacerlo único. Para poder usar esta tabla, en el código de la aplicación podemos ver que obtenemos el nombre real de la tabla a través de una variable de entorno. Luego, simplemente usamos esta variable como TableName.</p><p>Volviendo al código de infraestructura, a continuación especificamos la partitionKey y sortKey para la tabla. La partitionKey se puede usar para identificar de manera única cada elemento en la tabla. Este no es nuestro caso, ya que nuestra clave de partición es el campo <strong>‘EMAIL’</strong> y, por supuesto, podemos tener más de una transacción con el mismo email.</p><p>Estamos usando el campo <strong>‘CREATEDAT’</strong> como clave de ordenación. La sortKey siempre es la fecha y hora en que se creó esta transacción y la utilizaremos en nuestra API GET para filtrar las transacciones solo a aquellas realizadas hoy.</p><p>El truco aquí es que la combinación de estas dos claves es lo que realmente hace única esta transacción. Esta combinación se llama <strong>Clave Compuesta</strong>.</p><h3>Lambdas</h3><p>Continuando con nuestro código de lambdas. Ahora vamos a crear nuestras 2 lambdas. Empecemos con nuestra lambda POST. Aquí de nuevo vamos a crear una clase y esta vez la vamos a extender de NodeJSFunction.</p><pre>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import { Construct } from &quot;constructs&quot;;<br>import { Runtime } from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import { Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;</pre><pre>interface PostNewTransactionLambdaParams {<br>    transactionsTable: Table<br>}<br>export class PostNewTransactionLambda extends NodejsFunction {<br>    constructor(scope: Construct, params: PostNewTransactionLambdaParams) {<br>        super(scope, &#39;NewTransactionLambda&#39;, {<br>            runtime: Runtime.NODEJS_18_X,<br>            memorySize: 256,<br>            bundling: {<br>              minify: true,<br>              sourceMap: true,<br>            },<br>            entry: &quot;application/src/lambda/newTransactionLambda.ts&quot;,<br>            handler: &quot;handler&quot;,<br>            environment: {<br>                TRANSACTIONS_TABLE: params.transactionsTable.tableName<br>            }<br>        });<br>        params.transactionsTable.grantReadWriteData(this);<br>    }<br>}</pre><p>Avanzando con nuestro código de lambdas. Ahora crearemos nuestras 2 lambdas. Empecemos con nuestra lambda POST. Como mencionamos, vamos a crear una clase y esta vez la extenderemos de NodeJSFunction.</p><p>En el constructor, volveremos a recibir el scope y un nuevo parámetro, params, que es de tipo PostNewTransactionLambdaParams. Definamos esta interfaz arriba y usemos este params para recibir una referencia a la tabla que creamos, que usaremos justo después.</p><p>Ahora, algunas configuraciones para nuestra lambda:</p><ul><li>Versión de NodeJS: en este caso, usaremos la última LTS, que es la 18.</li><li>Cantidad de memoria que esta lambda asignará: 256 MB.</li><li>Configuraciones de empaquetado para comprimir nuestro código y sacar del paquete final lo que no es necesario.</li><li>Ahora, señalemos a qué lambda pertenece esta configuración. Por lo tanto, pasamos la ruta del archivo y, en handler, el nombre de la función de entrada en ese archivo, que, en nuestro caso, también se llama handler.</li><li>¿Recuerdas que dije que, para acceder a la base de datos, necesitamos obtener el nombre de la tabla a través de una variable de entorno? Para esto, necesitamos definir qué variables de entorno tendrá esta lambda. Así que creemos nuestra variable de entorno del nombre de la tabla y usemos la referencia que tenemos a nuestra tabla para obtener el nombre real de esa tabla en AWS.</li><li>A continuación, también vamos a usar esa referencia de tabla para dar permisos de escritura y lectura a nuestra lambda.</li></ul><p>Y nuestra configuración está lista. Ahora, nuestra lambda GET es exactamente la misma, solo vamos a cambiar la ruta de la lambda y la interfaz de parámetros. Incluso en un proyecto real, podrías estar creando una clase base que tenga todas estas configuraciones predeterminadas para todas tus lambdas.</p><pre>import { Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br>import { Runtime } from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import { Construct } from &quot;constructs&quot;;</pre><pre>interface TodayTransactionsLambdaParams {<br>    transactionsTable: Table<br>}<br>export class GetTodayTransactionsLambda extends NodejsFunction {<br>    constructor(scope: Construct, params: TodayTransactionsLambdaParams) {<br>        super(scope, &#39;TodayTransactionsLambda&#39;, {<br>            runtime: Runtime.NODEJS_18_X,<br>            memorySize: 256,<br>            bundling: {<br>              minify: true,<br>              sourceMap: true,<br>            },<br>            entry: &quot;application/src/lambda/todayTransactionsLambda.ts&quot;,<br>            handler: &quot;handler&quot;,<br>            environment: {<br>                TRANSACTIONS_TABLE: params.transactionsTable.tableName<br>            }<br>        });<br>        params.transactionsTable.grantReadData(this);<br>    }<br>}</pre><h3>API Gateway</h3><p>Continuemos con la creación de nuestro componente final, el API Gateway.</p><p>En lugar de extender una clase con un componente específico, como hicimos con la tabla y las funciones lambda, aquí utilizaremos un componente más genérico, conocido como <strong>Construct</strong>. Es crucial destacar que todos los otros componentes que hemos usado también son esencialmente <strong>Constructs</strong>, detrás de escena.</p><pre>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import * as apiGateway from &quot;aws-cdk-lib/aws-apigateway&quot;;<br>import { Construct } from &quot;constructs&quot;;</pre><pre>interface TransactionsGatewayParams {<br>    postNewTransactionsLambda: NodejsFunction,<br>    getTodayTransactionsLambda: NodejsFunction,<br>}<br>export class TransactionsGateway extends Construct {<br>    constructor(scope: Construct, params: TransactionsGatewayParams) {<br>        super(scope, &#39;TransactionsGateway&#39;);<br>        const api = new apiGateway.RestApi(this, &quot;TransactionsApi&quot;, {<br>            restApiName: &quot;New Transactions API&quot;,<br>            description: &quot;Backend Horizon - New Transactions API&quot;,<br>          });<br>      <br>          api.root.addMethod(&quot;POST&quot;, new apiGateway.LambdaIntegration(params.postNewTransactionsLambda, {<br>            requestTemplates: { &quot;application/json&quot;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; },<br>          }));<br>          api.root.addMethod(&quot;GET&quot;, new apiGateway.LambdaIntegration(params.getTodayTransactionsLambda, {<br>            requestTemplates: { &quot;application/json&quot;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; },<br>          }));<br>    } <br>}</pre><p>Definiremos un constructor que tomará los parámetros <strong>scope</strong> y <strong>params</strong>, los cuales contendrán referencias a nuestras dos funciones lambda.</p><p>El siguiente paso implica crear una nueva API Rest. Esta API recién creada se configurará con varios parámetros:</p><ul><li>Pasaremos nuestra propia clase <strong>TransactionsGateway</strong> como primer parámetro.</li><li>A continuación, asignaremos un ID a esta API, al cual llamaremos <strong>TransactionsApi</strong>.</li><li>Además, estableceremos un nombre y una descripción para esta API.</li></ul><p>El siguiente paso es conectar nuestras lambdas a esta API Rest. Agregaremos un método <strong>POST</strong> en la raíz de nuestra API. La integración entre nuestra función lambda <strong>postNewTransactionsLambda</strong> y esta API se llevará a cabo a través de una <strong>LambdaIntegration</strong>. Además, especificaremos el formato de respuesta que esta API devolverá. Entre las varias opciones disponibles en la documentación, elegiremos usar el modelo <strong>application/json</strong>, junto con el código de estado (<strong>statusCode</strong>), lo cual es una práctica común.</p><p>Después de eso, repetiremos este proceso para la función lambda <strong>getTodayTransactionsLambda</strong>, pero esta vez, configurándolo como un método <strong>GET</strong>.</p><h3>Main Stack</h3><p>Ahora que todos nuestros componentes están creados, es hora de conectarlos. Será bastante sencillo.</p><pre>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import { TransactionsTable } from &#39;./dynamodb/transactions-table&#39;;<br>import { TransactionsGateway } from &#39;./gateway/transactions-gateway&#39;;<br>import { GetTodayTransactionsLambda } from &#39;./lambdas/get-today-transactions-lambda&#39;;<br>import { PostNewTransactionLambda } from &#39;./lambdas/post-new-transaction-lambda&#39;;</pre><pre>export class InitWithCDKTypescriptStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br>    const transactionsTable = new TransactionsTable(this);<br>    const postNewTransactionsLambda = new PostNewTransactionLambda(this, { transactionsTable });<br>    const getTodayTransactionsLambda = new GetTodayTransactionsLambda(this, { transactionsTable });<br>    new TransactionsGateway(this, { postNewTransactionsLambda: postNewTransactionsLambda, getTodayTransactionsLambda });<br>  }<br>}</pre><p>En primer lugar, tomamos el componente <strong>TransactionsTable</strong> que desarrollamos anteriormente. Al crear este componente, pasaremos nuestro Stack como argumento para el parámetro <strong>scope</strong>.</p><p>Luego, instanciamos e integramos nuestras dos lambdas. Ambas requerirán el Stack y la <strong>transactionsTable</strong> recién creada como parámetros.</p><p>Nuestro último paso en esta fase implica configurar nuestra Gateway. Aquí, proporcionaremos el stack actual y las lambdas que configuramos previamente como argumentos.</p><p>Con esto, concluye la construcción de nuestro Stack principal. El siguiente paso es desplegar este stack y la aplicación en AWS.</p><h3>Deploy</h3><p>Antes de desplegar nuestra aplicación, necesitamos iniciar el proceso de <strong>“bootstrapping”</strong>. <strong>Este es un paso previo necesario que se realiza una sola vez</strong>.</p><ul><li>Comienza ejecutando el comando <strong>npm run cdk bootstrap</strong>.</li><li>Una vez completado con éxito, continúa con el despliegue usando <strong>npm run cdk deploy</strong>. Se mostrará un resumen de los cambios pendientes. Por favor, confirma estos cambios.</li></ul><p>Una vez que concluya el despliegue, la terminal mostrará la URL base para tus APIs, lo que te permitirá probarlas.</p><h3>Testing</h3><p>Con nuestra aplicación ahora desplegada, es hora de probarla.</p><p>Utiliza la URL base que se muestra en tu consola para hacer una solicitud <strong>POST</strong>, usando la siguiente muestra de datos. Como respuesta, deberías recibir un mensaje que dice “Transaction created with success.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kh-cdY02Md6-JsSgs_9Icg.png" /></figure><p>A continuación, cuando ejecutes una solicitud GET con el correo electrónico como parámetro de consulta, observarás la transacción recientemente creada, ahora incrementada con un campo adicional: <strong>CREATEDAT</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ZPLhlaRsRmo51kI.png" /></figure><p>Y finalmente hemos terminado. 🎉🎉🎉</p><p>Puedes encontrar el <a href="https://github.com/feharaujo/CodingTutorials/tree/feature/002-cdk-typescript/002%20-%20CDK%20Typescript/init-with-cdk-typescript">proyecto completo en GitHub</a>.</p><p><strong>Si tienes preguntas o sugerencias, por favor deja un comentario, estamos todos aquí para aprender juntos. 🤠</strong></p><p>¡Gracias por leer!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3HwMLhb0_FDiBXp1__0IA.png" /><figcaption>Artículo original: <a href="https://www.backendhorizon.com/es/post/aws-cdk-com-typescript-primeiros-passos">https://www.backendhorizon.com/es/post/aws-cdk-com-typescript-primeiros-passos</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b9d3d9b61ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/aws-cdk-con-typescript-comenzando-2b9d3d9b61ab">AWS CDK con Typescript — Comenzando</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDK com Typescript — Primeiros Passos]]></title>
            <link>https://medium.com/backend-horizon/aws-cdk-com-typescript-primeiros-passos-071a6e465864?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/071a6e465864</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[desenvolvimento-software]]></category>
            <category><![CDATA[programação]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 10:06:31 GMT</pubDate>
            <atom:updated>2024-01-24T14:15:06.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CDK com Typescript — Primeiros Passos</h3><p>Hoje vamos aprender sobre o AWS CDK, que é uma ferramenta super útil para voce criar a sua infra na nuvem da AWS.</p><p>🇺🇸 <a href="https://medium.com/@feh-araujo/aws-cdk-with-typescript-getting-started-22ffc69e6234">English version here</a></p><p>🇪🇸 <a href="https://medium.com/@feh-araujo/aws-cdk-con-typescript-comenzando-2b9d3d9b61ab">Versión en español aquí</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FK7xTkaPvo7M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DK7xTkaPvo7M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FK7xTkaPvo7M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8923643673c0d7e45461f6af79c3a77/href">https://medium.com/media/e8923643673c0d7e45461f6af79c3a77/href</a></iframe><p>Com o CDK, você pode criar infraestrutura via código de forma rápida e utilizando linguagens que a gente ja usa no nosso dia a dia, como TypeScript, Python, Java. Então, se você quer aumentar a produtividade, reduzir a complexidade de gerenciar a sua infra e tudo de forma automatizada, CDK pode ser a opçao ideal para voce. Bora la!</p><h3>IaC</h3><p>Antes de falarmos sobre CDK é importante entendermos o que é infraestutura como código</p><p>Infraestrutura como código (IaC) é uma maneira de criar e gerenciar recursos de infra usando código em vez de configurar tudo via pagina web ou por comandos em um terminal.</p><p>Digamos que você precise criar um servidor web na nuvem. Em vez de ir ao console da AWS e clicar em vários botões para criar manualmente esse servidor, você pode escrever um código que detalhe as características desejadas do servidor, como o tipo de instância, o tamanho do disco, quanta memoria esse servidor vai ter e as configurações de rede.</p><p>Em seguida, você pode executar esse código para criar e configurar automaticamente o servidor na AWS. Isso é útil porque você pode repetir o processo quantas vezes voce quiser, sem se preocupar em esquecer uma configuração importante, e também pode gerenciar esses recursos como se fossem um código, salvar no git para ter todo o controle de versão e historico de alterações.</p><p>Infraestrutura por código pode parecer complicado, mas não é. Hoje em dia, ninguém configura aplicações manualmente, pois os riscos de fazê-lo são muito grandes. Por isso, ferramentas de infraestrutura como código são tão importantes para gerenciar recursos de forma escalável, segura e automatizada.</p><h3>CDK &amp; Cloud Formation</h3><p>Existem várias ferramentas de infraestrutura como código no mercado. Aqui, mais no contexto do AWS, vamos falar sobre o CDK e o CloudFormation. Ambas são ferramentas que ajudam os desenvolvedores a criar e gerenciar recursos de infraestrutura na nuvem. O CDK é um complemento do CloudFormation, e vou explicar por que.</p><p>O CloudFormation é mais antigo e usa arquivos JSON ou YAML para descrever a infraestrutura que você deseja criar. Você precisa saber como escrever esses arquivos na sintaxe correta, e às vezes pode ser um pouco confuso e os arquivos podem ficar grandes. Com o CloudFormation, você descreve precisamente como sua infraestrutura será.</p><p>O AWS CDK é um pouco diferente, pois permite que você use linguagens de programação como TypeScript, Python, Java para descrever sua infraestrutura. Você pode criar uma infraestrutura complexa e sofisticada usando classes e objetos, o que torna o código da infra mais familiar para os desenvolvedores.</p><p>Além disso, com o CDK, você pode reutilizar e compartilhar código para economizar tempo. É possível criar componentes e compartilhá-los na sua empresa, criando bibliotecas, por exemplo, que tenham configurações padrões que possam ser utilizadas por vários times da sua empresa. E é claro que existem componentes open source feitos pela comunidade.</p><p>E por que eu disse que o CDK é um complemento do CloudFormation? Porque, quando compilamos esse código do CDK, o que será gerado é um arquivo do CloudFormation, que será usado para criar nossa infraestrutura.</p><p>Então, o CDK é a melhor opção sempre? NÃO! Uma coisa que você precisa sempre manter em mente é que o CDK é uma solução opinada. O que eu quero dizer com isso? O CDK é uma ferramenta feita em cima do CloudFormation, e por causa disso existem vários comportamentos por padrão nessa ferramenta, o que inclusive faz geralmente o codigo do CDK ser menor comparado ao do Cloud Formation, e isso não significa que esses comportamentos não mudem com novas versões. O CloudFormation pode ser muito verboso e um pouco mais complicado de trabalhar, mas, por outro lado, você descreve de forma precisa como sua infraestrutura deve ser.</p><p>Então, com isso em mente, pode ser que, para algumas áreas mais sensíveis da sua infraestrutura, o CDK não seja a melhor opção. Blz? Espero que tenha ficado claro a diferença.</p><h3>Application</h3><p>Antes de colocarmos a mão no código, você precisa ter a CLI do CDK instalado. Vou deixar o link na descrição, onde você pode seguir o passo a passo.</p><p>Vamos dar uma olhada rápida na implementação da aplicação e, em seguida, vamos começar a construir a infra juntos.</p><p>Nossa aplicação é simples e possui dois endpoints:</p><ol><li><strong>Um endpoint do tipo POST para cadastrar transações</strong>. Onde passamos um payload payload com email, valor, moeda, etc.</li><li><strong>Um endpoint GET para listar todas as transações feitas no dia por um email. </strong>Onde terá os dados que nos cadastramos incluindo a data em que a transação foi feita</li></ol><p>Os dois endpoints serão executados via lambdas em conjunto com o API Gateway e os dados salvos em um banco de dados DynamoDB.</p><p>O link para o código no Github também está na descrição.</p><p>Não vou entrar em detalhes sobre a implementação da aplicação, porque não é o foco desse artigo. Se você quiser saber mais sobre lambdas e DynamoDB, deixe um comentário que farei outros artigo sobre isso.</p><h3>Projeto e dependências</h3><p>Se olharmos na documentação iremos ver que é possível criar um projeto usando o comando <strong>cdk init</strong>. Esse projeto foi criado usando esse comando e foi adicionado as seguintes dependências:</p><pre>@aws-cdk/aws-lambda-nodejs<br>@types/aws-lambda<br>aws-sdk</pre><ol><li><strong>@aws-cdk/aws-lambda-nodejs</strong> e<strong> @types/aws-lambda</strong>, para melhor configurar nossos lambdas com NodeJS</li><li><strong>aws-sdk</strong>, para usarmos o Dynamodb</li></ol><h3>Stacks</h3><p>O ponto de entrada para o CDK começar a construir nossa aplicação é a pasta <strong>bin</strong>.</p><p>Dentro dessa pasta, teremos um arquivo que será criado junto com o projeto, e é esse arquivo que começará a montar a nossa infraestrutura.</p><pre>#!/usr/bin/env node<br>import &#39;source-map-support/register&#39;;<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { InitWithCDKTypescriptStack } from &#39;../lib/init-with-cdk-typescript-stack&#39;;</pre><pre>const app = new cdk.App();<br>new InitWithCDKTypescriptStack(app, &#39;InitWithCdkTypescriptStack&#39;);</pre><p>Podemos ver que a primeira linha é a criação de uma nova aplicação CDK e, em seguida, criamos uma nova stack e damos um id a ela.</p><p>No CDK, uma “stack” é basicamente uma pilha de componentes que você pode criar. É um conjunto de componentes que você pode empilhar e organizar de uma forma que faça sentido para você. Obviamente, você pode ter somente uma stack ou pode ter várias e organizá-las da forma que você quiser.</p><p>Por exemplo, digamos que você queira criar uma aplicação web na AWS. Você pode criar uma única stack que terá a sua instância EC2 para hospedar a aplicação, configurações de segurança, um bucket S3 para armazenar arquivos, e assim por diante.</p><p>Ou outro exemplo seria dividir por stacks que salvam dados e stacks que não, como s3 e DynamoDB em uma stack, lambdas e API Gateway em outra.</p><p>Para criarmos uma stack, precisamos de uma classe que estenda <strong>cdk.stack</strong> e dentro dessa classe podemos começar listar os componentes que pertencerão a essa stack.</p><p>Bom mencionar que stacks e os componentes que vamos criar ficam na pasta <strong>lib</strong>. A pasta <strong>bin</strong> é usada somente para sinalizar para o CDK onde começa a declaração da infra.</p><h3>DynamoDB Stack</h3><p>Vamos primeiro criar o nosso banco de dados DynamoDB. Dentro de um novo arquivo, vamos criar uma classe TransactionsTable e estendê-la de Table.</p><pre>import { AttributeType, Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br>import { Construct } from &quot;constructs&quot;;</pre><pre>export class TransactionsTable extends Table {<br>  constructor(scope: Construct) {<br>    super(scope, &#39;TRANSACTIONS_TABLE&#39;, {<br>      partitionKey: { name: &#39;EMAIL&#39;, type: AttributeType.STRING },<br>      sortKey: { name: &#39;CREATEDAT&#39;, type: AttributeType.STRING },<br>    });<br>  }<br>}</pre><p>A classe possui um construtor que recebe um parâmetro chamado <strong>scope</strong>, do tipo <strong>Construct</strong>. Esse parâmetro representa o escopo no qual a tabela está sendo criada. No nosso caso, esse escopo vai ser a nossa stack.</p><p>Dentro do construtor da classe <strong>Table</strong>, passamos algumas informações importantes. Primeiro, damos um nome para a tabela, que é <strong>‘TRANSACTIONS_TABLE’</strong>.</p><p>Uma dica rápida: quando formos chamar o banco de dados no código e quisermos usar a tabela que estamos criando, não é possível chamar a tabela usando somente esse nome. O nome de recursos no AWS precisa ser único, então a tabela será criada com o nome que demos e o AWS vai incluir algum identificador para torná-la única. Então, para podermos usar essa tabela, no código podemos ver que pegamos o nome real da tabela via variável de ambiente. Aí é só usar essa variável como TableName.</p><p>Voltando para a infraestrutura, em seguida, especificamos a partitionKey e a sortKey para a tabela. A partitionKey pode ser usada como identificação única para cada item da tabela. Não é o nosso caso, pois a nossa partition key é o campo <strong>‘EMAIL’</strong> e claro, podemos ter mais de uma transação com o mesmo e-mail.</p><p>Estamos usando o campo <strong>‘CREATEDAT’</strong> como a chave de ordenação. A sortKey é sempre a data e hora em que essa transação foi criada e vamos usar na nossa API GET para filtrar as transações para somente as feitos no dia de hoje.</p><p>O pulo do gato aqui é que a combinação dessas duas chaves é o que realmente torna essa transação única. Essa combinação se chama <strong>Composite Key</strong>.</p><h3>Lambdas</h3><p>Agora vamos para a criação dos nossos 2 lambdas. Vamos começar pelo nosso lambda POST. Aqui, novamente, vamos criar uma classe e, dessa vez, vamos estendê-la de NodeJSFunction.</p><pre>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import { Construct } from &quot;constructs&quot;;<br>import { Runtime } from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import { Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;</pre><pre>interface PostNewTransactionLambdaParams {<br>    transactionsTable: Table<br>}<br>export class PostNewTransactionLambda extends NodejsFunction {<br>    constructor(scope: Construct, params: PostNewTransactionLambdaParams) {<br>        super(scope, &#39;NewTransactionLambda&#39;, {<br>            runtime: Runtime.NODEJS_18_X,<br>            memorySize: 256,<br>            bundling: {<br>              minify: true,<br>              sourceMap: true,<br>            },<br>            entry: &quot;application/src/lambda/newTransactionLambda.ts&quot;,<br>            handler: &quot;handler&quot;,<br>            environment: {<br>                TRANSACTIONS_TABLE: params.transactionsTable.tableName<br>            }<br>        });<br>        params.transactionsTable.grantReadWriteData(this);<br>    }<br>}</pre><p>No construtor, vamos novamente receber o scope e um novo parâmetro params, que é do tipo PostNewTransactionLambdaParams. Vamos definir essa interface acima e usar esse params para receber uma referência à tabela que criamos, onde vamos usar logo abaixo.</p><p>Agora, algumas configurações para nosso lambda:</p><ul><li>Versão do NodeJS: nesse caso, vamos usar a última LTS, que é a 18.</li><li>Quantidade de memória que esse lambda vai alocar: 256 MB.</li><li>Configurações de bundling para comprimir nosso código e tirar do pacote final o que não é necessário.</li><li>Agora, vamos apontar qual é o lambda que pertence a essa configuração. Então, passamos aí o caminho do arquivo e, em handler, o nome da função de entrada nesse arquivo, que, no nosso caso, também chama-se handler.</li><li>Lembra que eu disse que, para acessarmos o banco de dados, precisamos pegar o nome da tabela via variável de ambiente? Para isso, precisamos definir quais as variáveis de ambiente esse lambda vai ter. Então, vamos criar a variável de ambiente do nome da nossa tabela e vamos usar a referência que temos da nossa tabela para pegar o nome real dessa tabela no AWS.</li><li>Em seguida, também vamos usar essa referência da tabela para dar permissão de escrita e leitura para o nosso lambda.</li></ul><p>E nossa configuração está pronta. Agora nosso lambda GET é exatamente a mesma coisa, só vamos estar mudando o caminho do lambda e a interface dos parâmetros. Inclusive, em um projeto real, você pode estar criando uma classe base que tenha todas essas configurações padrões de todos os seus lambdas.</p><pre>import { Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br>import { Runtime } from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import { Construct } from &quot;constructs&quot;;</pre><pre>interface TodayTransactionsLambdaParams {<br>    transactionsTable: Table<br>}<br>export class GetTodayTransactionsLambda extends NodejsFunction {<br>    constructor(scope: Construct, params: TodayTransactionsLambdaParams) {<br>        super(scope, &#39;TodayTransactionsLambda&#39;, {<br>            runtime: Runtime.NODEJS_18_X,<br>            memorySize: 256,<br>            bundling: {<br>              minify: true,<br>              sourceMap: true,<br>            },<br>            entry: &quot;application/src/lambda/todayTransactionsLambda.ts&quot;,<br>            handler: &quot;handler&quot;,<br>            environment: {<br>                TRANSACTIONS_TABLE: params.transactionsTable.tableName<br>            }<br>        });<br>        params.transactionsTable.grantReadData(this);<br>    }<br>}</pre><h3>API Gateway</h3><p>Vamos prosseguir com a criação do nosso último componente, que é o API Gateway.</p><p>Ao invés de estender uma classe com um component especifico, como fizemos com a tabela e a funçōes lambdas, vamos utilizar aqui um componente mais genérico, conhecido como <strong>Construct</strong>. É importante ressaltar que todos os outros componentes que utilizamos também são essencialmente <strong>Constructs</strong>, por de baixo dos panos.</p><pre>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import * as apiGateway from &quot;aws-cdk-lib/aws-apigateway&quot;;<br>import { Construct } from &quot;constructs&quot;;</pre><pre>interface TransactionsGatewayParams {<br>    postNewTransactionsLambda: NodejsFunction,<br>    getTodayTransactionsLambda: NodejsFunction,<br>}<br>export class TransactionsGateway extends Construct {<br>    constructor(scope: Construct, params: TransactionsGatewayParams) {<br>        super(scope, &#39;TransactionsGateway&#39;);<br>        const api = new apiGateway.RestApi(this, &quot;TransactionsApi&quot;, {<br>            restApiName: &quot;New Transactions API&quot;,<br>            description: &quot;Backend Horizon - New Transactions API&quot;,<br>          });<br>      <br>          api.root.addMethod(&quot;POST&quot;, new apiGateway.LambdaIntegration(params.postNewTransactionsLambda, {<br>            requestTemplates: { &quot;application/json&quot;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; },<br>          }));<br>          api.root.addMethod(&quot;GET&quot;, new apiGateway.LambdaIntegration(params.getTodayTransactionsLambda, {<br>            requestTemplates: { &quot;application/json&quot;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; },<br>          }));<br>    } <br>}</pre><p>Definiremos um construtor que receberá os parâmetros <strong>scope</strong> e <strong>params</strong>, que conterão as referências para as nossas duas funções lambda.</p><p>O próximo passo envolve a criação de uma nova Rest API. Essa API recém-criada será configurada com alguns parametros:</p><ul><li>Passaremos como primeiro parâmetro a nossa própria classe <strong>TransactionsGateway</strong></li><li>Em seguida, vamos dar um id para esta API, que chamaremos de <strong>TransactionsApi</strong>.</li><li>Além disso, definiremos um nome e uma descrição para essa API.</li></ul><p>O proximo passo é conectar nossos lambdas com essa Rest API. Adicionaremos um método <strong>POST</strong> na raiz da nossa API. A integração entre a nossa função lambda <strong>postNewTransactionsLambda</strong> e essa API será realizada por meio de uma <strong>LambdaIntegration</strong>. Adicionalmente, especificaremos o formato da resposta que essa API retornará. Dentre as várias opções disponíveis na documentação, optaremos por utilizar o modelo <strong>application/json</strong>, junto com o código de status (<strong>statusCode</strong>), que é uma prática comum.</p><p>Em seguida, repetiremos esse processo para a função lambda <strong>getTodayTransactionsLambda</strong>, porém, desta vez, configurando-a como um método <strong>GET</strong>.</p><h3>Main Stack</h3><p>Agora que todos os nossos componentes estão criados, é hora de conectá-los. Será bem simples.</p><pre>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import { TransactionsTable } from &#39;./dynamodb/transactions-table&#39;;<br>import { TransactionsGateway } from &#39;./gateway/transactions-gateway&#39;;<br>import { GetTodayTransactionsLambda } from &#39;./lambdas/get-today-transactions-lambda&#39;;<br>import { PostNewTransactionLambda } from &#39;./lambdas/post-new-transaction-lambda&#39;;</pre><pre>export class InitWithCDKTypescriptStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br>    const transactionsTable = new TransactionsTable(this);<br>    const postNewTransactionsLambda = new PostNewTransactionLambda(this, { transactionsTable });<br>    const getTodayTransactionsLambda = new GetTodayTransactionsLambda(this, { transactionsTable });<br>    new TransactionsGateway(this, { postNewTransactionsLambda: postNewTransactionsLambda, getTodayTransactionsLambda });<br>  }<br>}</pre><p>Inicialmente, desenvolvemos o componente da tabela <strong>TransactionsTable</strong> . Vamos criar esse component e passar a nossa Stack como argumento para o parâmetro <strong>scope</strong>.</p><p>Em seguida, vamos criar e integrar os nossos dois lambdas, fornecendo tanto a nossa stack quanto a <strong>transactionsTable</strong> recém-criada como parâmetros.</p><p>Por fim, concluímos com a configuração do nosso Gateway, onde mais uma vez utilizamos a Stack como argumento, juntamente com os lambdas previamente criados.</p><p>Isso conclui a criação da nossa Stack principal. Agora vamos fazer deploy dessa stack e da aplicação no AWS.</p><h3>Deploy</h3><p>Antes de realizar “deploy” da nossa aplicação, precisamos iniciar o processo de “bootstrapping”. <strong>Este é um pré-requisito feito apenas uma vez</strong>.</p><ul><li>Comece executando o comando <strong>npm run cdk bootstrap</strong>.</li><li>Após a conclusão bem-sucedida, continue com o “deploy” usando <strong>npm run cdk deploy</strong>. Uma visão geral das alterações pendentes será exibida. Por favor, confirme essas mudanças.</li></ul><p>Uma vez que o “deploy” esteja concluído, o terminal mostrará a URL base para suas APIs, permitindo que você as teste.</p><h3>Testing</h3><p>Com nossa aplicação agora implantada, é hora de testar.</p><p>Utilize a URL base exibida em seu console para fazer uma solicitação <strong>POST</strong>, usando o payload de exemplo a seguir. Como resposta, você deve receber uma mensagem dizendo “Transaction created with success.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kh-cdY02Md6-JsSgs_9Icg.png" /></figure><p>Next, when you execute a <strong>GET</strong> request with email as query parameter, you’ll observe the recently created transaction, now incremented with an additional field: <strong>CREATEDAT</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ZPLhlaRsRmo51kI.png" /></figure><p>E finalmente concluímos. 🎉🎉🎉</p><p>Você pode encontrar o <a href="https://github.com/feharaujo/CodingTutorials/tree/feature/002-cdk-typescript/002%20-%20CDK%20Typescript/init-with-cdk-typescript"><strong>projeto completo no GitHub</strong></a>.</p><p><strong>Dúvidas ou sugestões, por favor deixe um comentário, estamos todos aqui para aprender juntos. 🤠</strong></p><p>Obrigado!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3HwMLhb0_FDiBXp1__0IA.png" /><figcaption>Artigo original: <a href="https://www.backendhorizon.com/pt/post/aws-cdk-com-typescript-primeiros-passos">https://www.backendhorizon.com/pt/post/aws-cdk-com-typescript-primeiros-passos</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=071a6e465864" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/aws-cdk-com-typescript-primeiros-passos-071a6e465864">AWS CDK com Typescript — Primeiros Passos</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDK with Typescript — Getting started]]></title>
            <link>https://medium.com/backend-horizon/aws-cdk-with-typescript-getting-started-22ffc69e6234?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ffc69e6234</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 08:11:35 GMT</pubDate>
            <atom:updated>2024-01-24T14:12:49.342Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CDK with Typescript — Getting started</h3><p>Today we are going to learn about the AWS CDK, which is a super useful tool for you to create your infrastructure in the AWS cloud.</p><p>🇪🇸 <a href="https://medium.com/@feh-araujo/aws-cdk-con-typescript-comenzando-2b9d3d9b61ab">Versión en español aquí</a></p><p>🇧🇷 <a href="https://medium.com/@feh-araujo/aws-cdk-com-typescript-primeiros-passos-071a6e465864">Versão em português aqui</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FK7xTkaPvo7M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DK7xTkaPvo7M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FK7xTkaPvo7M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8923643673c0d7e45461f6af79c3a77/href">https://medium.com/media/e8923643673c0d7e45461f6af79c3a77/href</a></iframe><p>With CDK, you can quickly create infrastructure via code and using languages that we already use in our daily lives, such as TypeScript, Python, Java. So, to reduce the complexity of managing your infrastructure and everything in an automated way, CDK may be the ideal option for you.</p><h3>IaC</h3><p>Before we talk about CDK it is important to understand what is infrastructure as code</p><p>Infrastructure as code (IaC) is a way to create and manage infrastructure resources using code instead of configuring everything via a web page or by commands in a terminal.</p><p>Let’s say you need to create a web server in the cloud. Instead of going to the AWS console and clicking a bunch of buttons to manually create your server, you can write code that details all the server configurations, such as the instance type, disk size, how much memory this server will have, and network settings.</p><p>You can then run this code to automatically create and configure the server on AWS. This is useful because you can repeat the process as many times as you want, without worrying about forgetting an important configuration, and you can also manage these resources as if they were a code, save in your git repository, have all the changes history and of course, do code reviews in your infrastructure code.</p><p>Infrastructure by code may sound complicated, but it’s not. Nowadays, nobody configures applications manually, the risks of doing this in real applications is to high. That’s why infrastructure as code tools (like CDK) are so important. And by the way, way more fun than clicking in buttons right?!</p><h3>CDK &amp; Cloud Formation</h3><p>There are several infrastructure as code tools on the market. Here, more in the context of AWS, let’s talk about CDK and CloudFormation. Both are tools that help developers build and manage infra resources in the cloud. The CDK was made on top of the CloudFormation add-on, and I’ll explain why.</p><p>CloudFormation is older and uses JSON or YAML files to describe the infrastructure you want to build. You need to know how to write these files in the correct syntax, and sometimes it can be a bit messy and the files can get quite large. With CloudFormation, you describe precisely what your infrastructure will look like.</p><p>AWS CDK is a little different as it allows you to use programming languages like TypeScript, Python, Java to describe your infrastructure. You can create complex and sophisticated infrastructure using classes and objects, which makes the infrastructure code more familiar to developers.</p><p>Also, with CDK, you can reuse and share code to save time. It is possible to create components and share them in your company, creating libraries, for example, that have standard configurations that can be used by several teams in your company. And of course there are open source components made by the community.</p><p>And why did I say CDK is a CloudFormation add-on? Because when we compile this CDK code, what will be generated is a CloudFormation file, which will be used to create our infrastructure.</p><p>So is CDK the best option every time? NO! One thing you always need to keep in mind is that the CDK is an opinionated solution. What do I mean by that? The CDK is a tool built on top of CloudFormation, and because of that there are several behaviours by default in this tool, which generally makes the CDK code smaller compared to Cloud Formation, and that does not mean that these behaviours do not change with new versions. CloudFormation can be very verbose and a bit trickier to work with, but on the other hand, with cloud formation you describe precisely what your infrastructure should look like.</p><p>So, with that in mind, it may be that for some more sensitive areas of your infrastructure, CDK is not the best option. OK? I hope the difference is clear.</p><h3>Application</h3><p>Before we get into the code, you need to have the CDK CLI installed. I’ll leave the link in the description, where you can follow the step by step.</p><p>Let’s take a quick look at the implementation of the application and then let’s start building the infrastructure together.</p><p>Our application is simple and has two endpoints:</p><ol><li><strong>A POST type endpoint to record transactions</strong>. Where we pass a payload with email, value, currency, etc.</li><li><strong>A GET endpoint to list all transactions made on the day</strong>. Where we gonna have the data that we recorded, plus the date on which the transaction was made and an ID</li></ol><p>The two endpoints will be executed via lambdas together with API Gateway and the data saved in a DynamoDB database.</p><p>The link to the code on Github is also in the description.</p><p>I won’t go into details about the implementation of the application, because it’s not the focus of this video. It’s just 2 lambdas, one saving data in our DynamoDB database and other fetching it. If you want to know more about Lambdas and DynamoDB, leave a comment and I’ll make other article about it.</p><h3>Project and dependencies</h3><p>If we look in the documentation we will see that it is possible to create a project using the <strong>cdk init</strong> command. This project was created using this command and I added a few other dependencies:</p><pre>@aws-cdk/aws-lambda-nodejs<br>@types/aws-lambda<br>aws-sdk</pre><ol><li><strong>@aws-cdk/aws-lambda-nodejs</strong> and <strong>@types/aws-lambda</strong>, to easly configure our lambdas with NodeJS.</li><li><strong>aws-sdk</strong>, for us to use DynamoDB.</li></ol><h3>Stacks</h3><p>The entry point for a CDK code to start building our infrastructure is the <strong>bin</strong> folder.</p><p>Inside that folder, we will have a file that will be created along with the project, and it is this file that will start to assemble our infrastructure.</p><pre>#!/usr/bin/env node<br>import &#39;source-map-support/register&#39;;<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { InitWithCDKTypescriptStack } from &#39;../lib/init-with-cdk-typescript-stack&#39;;<br><br>const app = new cdk.App();<br>new InitWithCDKTypescriptStack(app, &#39;InitWithCdkTypescriptStack&#39;);</pre><p>We can see that the first line is the creation of a new CDK application and then we create a new stack and give it an id.</p><p>In CDK, a “stack” is basically a collection of components that you can create. It’s a set of components that you can stack and arrange in a way that makes sense to you. Of course, you can have just one stack, or you can have several and organize them any way you like.</p><p>For example, let’s say you want to build a web application on AWS. You can create a single stack that will have your EC2 instance to host the application, security settings, an S3 bucket to store files, and so on.</p><p>Or another example would be splitting by stacks that contains services that host data and others that don’t. So, s3 and DynamoDB on one stack, lambdas and API Gateway on another.</p><p>To create a stack, we need a class that extends <strong>cdk.stack</strong> and inside that class we can start listing the components that will belong to that stack.</p><p>Good to mention that stacks and the components we are going to create are in the <strong>lib</strong> folder. The <strong>bin</strong> folder is only used to signal to the CDK where the infra declaration begins.</p><h3>DynamoDB Stack</h3><p>Let’s first create our DynamoDB database. Inside a new file, let’s create a TransactionsTable class and extend it from Table.</p><pre>import { AttributeType, Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br>import { Construct } from &quot;constructs&quot;;<br><br>export class TransactionsTable extends Table {<br>  constructor(scope: Construct) {<br>    super(scope, &#39;TRANSACTIONS_TABLE&#39;, {<br>      partitionKey: { name: &#39;EMAIL&#39;, type: AttributeType.STRING },<br>      sortKey: { name: &#39;CREATEDAT&#39;, type: AttributeType.STRING },<br>    });<br>  }<br>}</pre><p>The class has a constructor that receives a parameter called <strong>scope</strong>, of type <strong>Construct</strong>. This parameter represents the scope in which the table is being created. In our case, this scope will be our main stack, InitWithCDKTypescriptStack.</p><p>Inside the <strong>Table</strong> class constructor, we need to insert some important information. First, we give the table a name, which is <strong>‘TRANSACTIONS_TABLE’</strong>.</p><p><strong>A quick tip on that</strong>: when we call the database in our code and we want to use the table that we are creating, it is not possible to call the table using only this name. Resource names in AWS are required to be unique, so the table will be created with the name we gave and AWS will append some identifier to make it unique. In order to be able to use this table, in the application code we can see that we get the real name of the table via an environment variable. Then we just use this variable as TableName.</p><p>Returning to the infra code, we next specify the partitionKey and sortKey for the table. The partitionKey can be used to uniquely identify each item in the table. This is not our case, as our partition key is the <strong>‘EMAIL’</strong> field and, of course, we can have more than one transaction with the same email.</p><p>We are using the <strong>‘CREATEDAT’</strong> field as the sort key. The sortKey is always the date and time this transaction was created and we gonna use in our GET API to filter the transactions to only those made today.</p><p>The trick here is that the combination of these two keys is what really makes this transaction unique. This combination is called <strong>Composite Key</strong>.</p><h3>Lambdas</h3><p>Moving on to our lambdas code. Now let’s create our 2 lambdas. Let’s start with our POST lambda. Here again we are going to create a class and this time we are going to extend it from NodeJSFunction.</p><pre>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import { Construct } from &quot;constructs&quot;;<br>import { Runtime } from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import { Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br><br>interface PostNewTransactionLambdaParams {<br>    transactionsTable: Table<br>}<br>export class PostNewTransactionLambda extends NodejsFunction {<br>    constructor(scope: Construct, params: PostNewTransactionLambdaParams) {<br>        super(scope, &#39;NewTransactionLambda&#39;, {<br>            runtime: Runtime.NODEJS_18_X,<br>            memorySize: 256,<br>            bundling: {<br>              minify: true,<br>              sourceMap: true,<br>            },<br>            entry: &quot;application/src/lambda/newTransactionLambda.ts&quot;,<br>            handler: &quot;handler&quot;,<br>            environment: {<br>                TRANSACTIONS_TABLE: params.transactionsTable.tableName<br>            }<br>        });<br>        params.transactionsTable.grantReadWriteData(this);<br>    }<br>}</pre><p>In the constructor, we will again receive the scope and a new parameter, params, which is of type PostNewTransactionLambdaParams. Let’s define this interface above and use this params to receive a reference to the table we created, which we’ll use just below.</p><p>Now some settings for our lambda:</p><ul><li>NodeJS version: in this case, we will use the latest LTS, which is 18.</li><li>Amount of memory this lambda will allocate: 256 MB.</li><li>Bundling settings to compress our code and take out of the final package what is not needed.</li><li>Now, let’s point out which lambda belongs to this configuration. So, we pass the file path there and, in handler, the name of the input function in that file, which, in our case, is also called handler.</li><li>Remember I said that, to access the database, we need to get the table name via an environment variable? For this, we need to define which environment variables this lambda will have. So let’s create our table name environment variable and let’s use the reference we have to our table to get the actual name of that table in AWS.</li><li>Next, we’re also going to use that table reference to give write and read permissions to our lambda.</li></ul><p>And our setup is ready. Now our GET lambda is exactly the same, we’re just going to be changing the lambda path and parameters interface. Even in a real project, you might be creating a base class that has all these default settings for all your lambdas.</p><pre>import { Table } from &quot;aws-cdk-lib/aws-dynamodb&quot;;<br>import { Runtime } from &quot;aws-cdk-lib/aws-lambda&quot;;<br>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import { Construct } from &quot;constructs&quot;;<br><br>interface TodayTransactionsLambdaParams {<br>    transactionsTable: Table<br>}<br>export class GetTodayTransactionsLambda extends NodejsFunction {<br>    constructor(scope: Construct, params: TodayTransactionsLambdaParams) {<br>        super(scope, &#39;TodayTransactionsLambda&#39;, {<br>            runtime: Runtime.NODEJS_18_X,<br>            memorySize: 256,<br>            bundling: {<br>              minify: true,<br>              sourceMap: true,<br>            },<br>            entry: &quot;application/src/lambda/todayTransactionsLambda.ts&quot;,<br>            handler: &quot;handler&quot;,<br>            environment: {<br>                TRANSACTIONS_TABLE: params.transactionsTable.tableName<br>            }<br>        });<br>        params.transactionsTable.grantReadData(this);<br>    }<br>}</pre><h3>API Gateway</h3><p>Let’s proceed with the creation of our final component, the API Gateway.</p><p>Instead of extending a class with a specific component, as we did with the table and the lambda functions, we will use a more generic component here, known as <strong>Construct</strong>. It’s crucial to note that all the other components we’ve used are also essentially <strong>Constructs</strong>, behind the scenes.</p><pre>import { NodejsFunction } from &quot;aws-cdk-lib/aws-lambda-nodejs&quot;;<br>import * as apiGateway from &quot;aws-cdk-lib/aws-apigateway&quot;;<br>import { Construct } from &quot;constructs&quot;;<br><br>interface TransactionsGatewayParams {<br>    postNewTransactionsLambda: NodejsFunction,<br>    getTodayTransactionsLambda: NodejsFunction,<br>}<br>export class TransactionsGateway extends Construct {<br>    constructor(scope: Construct, params: TransactionsGatewayParams) {<br>        super(scope, &#39;TransactionsGateway&#39;);<br>        const api = new apiGateway.RestApi(this, &quot;TransactionsApi&quot;, {<br>            restApiName: &quot;New Transactions API&quot;,<br>            description: &quot;Backend Horizon - New Transactions API&quot;,<br>          });<br>      <br>          api.root.addMethod(&quot;POST&quot;, new apiGateway.LambdaIntegration(params.postNewTransactionsLambda, {<br>            requestTemplates: { &quot;application/json&quot;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; },<br>          }));<br>          api.root.addMethod(&quot;GET&quot;, new apiGateway.LambdaIntegration(params.getTodayTransactionsLambda, {<br>            requestTemplates: { &quot;application/json&quot;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; },<br>          }));<br>    } <br>}</pre><p>We will define a constructor that will take the parameters <strong>scope</strong> and <strong>params</strong>, which will contain references to our two lambda functions.</p><p>The next step involves creating a new Rest API. This newly created API will be configured with several parameters:</p><ul><li>We will pass our own class <strong>TransactionsGateway</strong> as the first parameter.</li><li>Next, we’ll assign an ID to this API, which we’ll call <strong>TransactionsApi</strong>.</li><li>Moreover, we’ll set a name and a description for this API.</li></ul><p>The next step is to connect our lambdas to this Rest API. We’ll add a <strong>POST</strong> method at the root of our API. The integration between our lambda function <strong>postNewTransactionsLambda</strong> and this API will be carried out through a <strong>LambdaIntegration</strong>. Additionally, specify the response format that this API will return. Among the various options available in the documentation, we’ll choose to use the <strong>application/json</strong> model, along with the status code (<strong>statusCode</strong>), which is a common practice.</p><p>Following that, we’ll repeat this process for the lambda function <strong>getTodayTransactionsLambda</strong>, but this time, setting it up as a <strong>GET</strong> method.</p><h3>Main Stack</h3><p>Now that all our components are created, it’s time to connect them. It will be quite straightforward.</p><pre>import * as cdk from &#39;aws-cdk-lib&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import { TransactionsTable } from &#39;./dynamodb/transactions-table&#39;;<br>import { TransactionsGateway } from &#39;./gateway/transactions-gateway&#39;;<br>import { GetTodayTransactionsLambda } from &#39;./lambdas/get-today-transactions-lambda&#39;;<br>import { PostNewTransactionLambda } from &#39;./lambdas/post-new-transaction-lambda&#39;;<br><br>export class InitWithCDKTypescriptStack extends cdk.Stack {<br>  constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br>    super(scope, id, props);<br>    const transactionsTable = new TransactionsTable(this);<br>    const postNewTransactionsLambda = new PostNewTransactionLambda(this, { transactionsTable });<br>    const getTodayTransactionsLambda = new GetTodayTransactionsLambda(this, { transactionsTable });<br>    new TransactionsGateway(this, { postNewTransactionsLambda: postNewTransactionsLambda, getTodayTransactionsLambda });<br>  }<br>}</pre><p>Firstly, we take the <strong>TransactionsTable</strong> component, which we previously developed. When creating this component, we’ll pass our Stack as argument for the <strong>scope</strong> parameter.</p><p>Next, we’ll instantiate and integrate our two lambdas. Both will require the Stack and the newly created <strong>transactionsTable</strong> as parameters.</p><p>Our final step in this phase involves setting up our Gateway. Here, we’ll provide the current stack and the lambdas we previously set up as arguments.</p><p>With this, our primary Stack construction wraps up. The next step is deploying this stack and the application on AWS.</p><h3>Deploy</h3><p>Before deploying our application, we need to initiate the “bootstrapping” process. <strong>This is a one-time prerequisite step</strong>.</p><ul><li>Begin by executing the command <strong>npm run cdk bootstrap</strong>.</li><li>Upon successful completion, proceed with the deployment using <strong>npm run cdk deploy</strong>. An overview of the pending changes will be displayed. Please confirm these changes.</li></ul><p>Once the deployment concludes, the terminal will display the base URL for your APIs, allowing you to test them.</p><h3>Testing</h3><p>With our application now deployed, it’s time for testing.</p><p>Utilize the base URL displayed in your console to make a <strong>POST</strong> request, using the following sample payload. In response, you should receive a message stating “Transaction created with success.”</p><p>Next, when you execute a <strong>GET</strong> request with email as query parameter, you’ll observe the recently created transaction, now incremented with an additional field: <strong>CREATEDAT</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ZPLhlaRsRmo51kI.png" /></figure><p>And we’re finally done. 🎉🎉🎉</p><p>You can find the <a href="https://github.com/feharaujo/CodingTutorials/tree/feature/002-cdk-typescript/002%20-%20CDK%20Typescript/init-with-cdk-typescript">full project on GitHub</a>.</p><p><strong>Questions or suggestions, please leave a comment, we’re all here to learn together. 🤠</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3HwMLhb0_FDiBXp1__0IA.png" /><figcaption>Original article: <a href="https://www.backendhorizon.com/post/aws-cdk-with-typescript-getting-started">https://www.backendhorizon.com/post/aws-cdk-with-typescript-getting-started</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ffc69e6234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/aws-cdk-with-typescript-getting-started-22ffc69e6234">AWS CDK with Typescript — Getting started</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot with Kotlin — Creating your First API]]></title>
            <link>https://medium.com/backend-horizon/spring-boot-with-kotlin-creating-your-first-api-44e511f96b23?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e511f96b23</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 20:34:53 GMT</pubDate>
            <atom:updated>2024-01-04T13:06:12.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot with Kotlin — Creating your First API</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmTqOYpQePoY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DmTqOYpQePoY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FmTqOYpQePoY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/714892c5729bd5fd2a0eaf51d25f49ba/href">https://medium.com/media/714892c5729bd5fd2a0eaf51d25f49ba/href</a></iframe><p><strong>Spring Framework</strong> 🍃, the most popular framework in Java for application development. Millions of developers use Spring every day to create all kinds of applications. Spring&#39;s first release in 2003 had a focus on dependency injection but the framework has grown immensely, the spring team created a set of modules that support almost everything that a developer needs to create an application. Given so much maturity, it’s no wonder that the framework is used in the top tech companies in the world. That’s the advantage of a project that has been in constant development and improvement for almost 20 years.</p><h3>What’s Kotlin</h3><p><strong>Kotlin</strong> is a language made by Jetbrains, the same company that created all the amazing IDE’s like IntelliJ Idea. JetBrains was not happy with Java and the other languages in the market and decided to create Kotlin to be an improvement over Java. And when I say improvement it’s because Kotlin was designed to be completely compatible with Java, making it possible to have a shared codebase between these two languages, allowing companies to make a gradual migration from Java.</p><p>Kotlin has been becoming super popular among developers and according to the StackOverflow 2020 Survey, Kotlin is one of the most loved languages. All this love is not from nothing. Kotlin has a lot of features that make the development easier, less verbose, and higher failure-proof. One of the best functionaries is a native null safer system, extensions classes, high order functions, and the async await version of the language, called coroutines.</p><h3>Creating project</h3><p>To start creating our project we’ll be using the <strong>Spring Initializer tool</strong>. You can find it on <a href="http://start.spring.io/">start.spring.io</a>.This is a tool created by the spring team and it’s super useful because we already can do our initial setup and include our main dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzLjKGLpZTNieDhchvRVMQ.png" /><figcaption>Spring Initializer tool</figcaption></figure><p>First, you can find the full source code <a href="https://github.com/feharaujo/TutorialProjects/tree/main/001%20-%20Bank-Project/bank">here on my Github</a>. For this project, we’ll use a setup a bit different from the other common tutorial that we can find with Spring Boot. We gonna use Gradle as our build tool but of course, as you can see Maven it’s also an option. We’ll choose the most stable version of Spring, that’s 2.6.0 (when I’m writing this article). You can change the project metadata if want or just leave the default values. I choose Java 11 because I still don’t have Java 17 installed but will make no difference for this project.</p><p>In the right column, we have the option to include our initial dependencies. For this project, we will include a few of them and later we will add other dependencies manually in our Gradle file. Let’s start including:</p><ul><li><strong>Spring Boot DevTools </strong>—<strong> </strong>There are some nice features that can help us during development like automatic reload, live to reload, and disabling caching. Very useful during development.</li><li><strong>Spring Web</strong> — We’ll need to create our API&#39;s</li><li><strong>Spring JPA</strong> and <strong>H2 Database </strong>— to save our data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9P0WGQcSLGw5HtL9WU30A.png" /><figcaption>Initial setup</figcaption></figure><p>As you can see in my metadata in gonna create an example simulating a bank and we’ll make a transfer API. 💰</p><h3>IntelliJ Idea</h3><p>Unzip the file and open it in your IDE. I’ll be using IntelliJ Idea Community Edition. You can download it for free or use another IDE. Something nice to mention is that if you have the ultimate version of the IntelliJ Idea, the Spring Initialiser Tool that we just saw is already embedded in the IDE, so you can do all the project creation directly there.</p><h3>Gradle file</h3><p>The first thing we gonna take a look at is our build.gradle.kts file. You can find it in the root of the project folder. This is the file where we can manage our dependencies and since we used Spring Initialiser for the initial setup we can see the tool created this file with our configuration and the selected dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90bdbff4631b1254b1097c44347c05ac/href">https://medium.com/media/90bdbff4631b1254b1097c44347c05ac/href</a></iframe><p>Since we choose to use Kotlin, Spring Initialiser already created this configuration file as a Kotlin one. For the people that are not familiar with Gradle, I’m pointing this because it’s also possible to write your Gradle files with Groovy. Since we’re already using Kotlin I highly recommend also to use it with Gradle since there are some advantages over Groovy, like auto-completion, for example.</p><h3>Gradle Plugins</h3><p>Let’s take a look at the plugins block. Gradle itself doesn’t do a lot by default but it provides options to us developers to extend and add new features to our builds. A great example of this is the “plugins” block where we have plugins that configure and leave our project ready to use very easily.</p><p>We can see that we have a few plugins and most of them are to do an initial setup for Spring and Kotlin. Let’s take a look at the <a href="https://plugins.gradle.org/plugin/org.springframework.boot">Spring Boot Plugin page</a>, and see how the plugin is described:</p><blockquote><em>Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that can you can “just run”. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.</em></blockquote><p>In other words, easy configuration to start working on your project immediately. All the others plugins do something similar, they prepare and help manage our project dependencies to be configured and integrated in the best way.</p><p>Below plugins, we have the metadata that we choose and the Java Version.</p><p>Maven Central is the repository from where we are downloading our dependencies and under the dependencies block, it’s listed all the libraries that we have in the project. Later we will return to this file and we gonna include some extra dependencies.</p><p>There’s another important file that is worth taking a quick look and that’s our Application file.</p><h3>Application file</h3><p>Let’s open our Application file. In the project on GitHub, you can find this file titled as BankApplication but this will change depending on what you choose in your metadata. Here we find the most famous function of all, the main function, where the application starts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a1c8aa32b822e97302b21369ef5f0ff/href">https://medium.com/media/0a1c8aa32b822e97302b21369ef5f0ff/href</a></iframe><p>We can see that in the main method we have this function runApplication indicating to run with the BankApplication class and in this class, we just have a single annotation, @SpringBootApplication. This single annotation does a lot for us.</p><p>Let’s take a quick look at how the documentation describes it:</p><blockquote>Indicates a configuration class that declares one or more @Bean methods and also <strong>triggers auto-configuration and component scanning</strong>. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.</blockquote><p>In the next chapter, we’ll create our first Controller and something that you’ll notice is that we’ll not create an instance of the controller. That’s because the @SpringBootApplication annotation is composed of 3 other annotations and one of them is the @ComponentScan.</p><p>As the name already suggests, @ComponentScan will look/scan our project for <strong>components</strong> and when it finds it, Spring will create and manage this instance for us. Something nice to mention is that for a component to be auto-detected it needs to be at the same package level or below of the application class.</p><p>Components are classes annotated with special annotations that candidates these classes to be auto-detected. There’re a few different annotations that can be used for different purposes like @Component, @Controller, @RestController, @Repository and @Service.</p><p>The @EnableAutoConfiguration will do something similar for the libraries in the project. It will look in our classpath, check the libraries that we’re using and it will load an initial configuration for us. We’ll see this with our database. Keep reading. 😉</p><h3>First API</h3><p>Let’s create our first API controller. Create a package called controller and on it, a class called TransferController. Create 2 methods, newTransfer and getAllTransfers like the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b670519455238fc370215214febf250c/href">https://medium.com/media/b670519455238fc370215214febf250c/href</a></iframe><p>Let’s understand what’s happening here. On Top of our TransferController class, we used 2 annotations, @RestControllerand RequestMapping:</p><ul><li>@RestController: Using this annotation we indicate to Spring Boot that this class is a web handler/<strong>web controller</strong>. It’ll receive requests and return responses to the callers. Since it’s a type of “<strong>controller</strong>” this <strong>component</strong> (keep in mind this term) will also be managed by Spring Boot.</li><li>@RequestMapping: This indicates what’s signature this web controller will have in the request address, after the host address. For example, our 2 methods endpoints will have the following addresses: localhost:8080<strong>/transfer</strong>/new and locahost:8080<strong>/transfer</strong>/all.</li></ul><p>Following the methods, they’re relatively simple:</p><ul><li>newTransfer logs a “Saved” message in the console and his annotation indicates that this will be a “<strong>Post</strong>” request, @<strong>Post</strong>Mapping and like the controller it indicates what’s the signature for this method, localhost:8080/payment<strong>/new</strong>.</li><li>getAllTransferreturns a “Hello” message to the caller and similar to the previous method, it indicates the type of the request, in this case, a “<strong>Get</strong>” request, @<strong>Get</strong>Mapping, followed by the signature, localhost:8080/payment<strong>/all</strong>.</li></ul><p><strong>* “Get”</strong> and “<strong>Post”</strong> are part of the <strong>REST specification</strong>, if you’re not familiar with them leave a comment and I’ll create a new article explaining them more in-depth.</p><h3>Running &amp; Testing</h3><p>Now we have everything that we need to do our first test. Go to the main function in the application file and run your application. You should start to see some logs and Tomcat our WebServer will start and host the application without any problems. Notice in the logs that Tomcat will tell you what port your application is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPy89WfbOsXrkBwikA3C-g.png" /><figcaption>Application logs</figcaption></figure><p>Now we need to test these endpoints. The best way is to use a tool made for that. I personally recommend <a href="https://www.postman.com/">Postman</a>. It has full support for REST APIs, making it possible to test all the different types of REST endpoints, setting up JSON bodies, headers, authorization tokens, etc. Postman also has GraphQL support in case you’re fancy. 😂</p><p>Open a new tab on Postman, select GET and type the getAllTransfer endpoint address, like the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18MAeHhI-2ibJcrdIgS4jQ.png" /><figcaption>Postman getAllTransfer endpoint test</figcaption></figure><p>As you can see we received a “Hello” message in return. Our API is working! Do the same for newTransfer, change the URL and the type to POST. You’ll see that the API is also working and the “Saved” message printed on the IntelliJ Idea console.</p><p>Notice that we didn’t create any instance of TransferController, just the @RestController annotation indicated to Spring that our controller needed to be created. Works like a charm, right?!</p><h3>Data Models</h3><p>Let’s start to prepare our application to receive and save data. Inside the controller package create a new one called model. Create two new classes, TransactionModel and OverviewTransactionModel.</p><p>Into the TransactionModel class we gonna create a few attributes. So let’s imagine that to make a transfer to another person we need to know what’s the <strong>account identifier</strong>, which can be a number or a string, depending on the country that you live in. We also need the <strong>value</strong> and a <strong>description</strong> that can be optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0df00dd5004fbc309c25cb85ee1e08f6/href">https://medium.com/media/0df00dd5004fbc309c25cb85ee1e08f6/href</a></iframe><p>When we fetch the list of all transactions, we’d like to see a bit more data. Besides all the previous data we’ll have two extra fields, the <strong>date</strong> of the transaction and the <strong>transaction identifier</strong>(id).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db3fa3e6d4865b39f80adf590252f8fc/href">https://medium.com/media/db3fa3e6d4865b39f80adf590252f8fc/href</a></iframe><p>Update your TransferController like the code below with the new models that we created. You can notice that in the newTransfer method we have a new annotation @RequestBody. This indicates that the TransactionModel is part of this request and will deserialize the JSON automatically into our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fafcd4ab304d55b47cdcc807894799c0/href">https://medium.com/media/fafcd4ab304d55b47cdcc807894799c0/href</a></iframe><h3>Database</h3><p>Now that we’re receiving data throw our API we need to store it in a database. We gonna use an <strong>in-memory database called H2 </strong>that we already included in our build.gradle.kts file.</p><p>Create a new package at the same level as controller called repository. Inside this package, an <strong>interface</strong> called TransferRepository. Let’s also create another modelpackage inside repository and on it a class called TransactionDBModel. In the end, you should have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*ln2mIS13DuTAjs3VSs_7HA.png" /><figcaption>Project structure</figcaption></figure><p>First, let’s work on the DB model attributes. Similar to TransactionModel we’ll have the account identifier, value, and description. In order to save into the database, we need to have a <strong>unique identifier</strong> and this identifier will be <strong>generated automatically</strong> for us. We also gonna use the current date as the transaction’s date.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04a1703c201aaed64f5207f624d63a1/href">https://medium.com/media/c04a1703c201aaed64f5207f624d63a1/href</a></iframe><p>By constructor, we gonna receive the attributes that we receive via our API and in the class body, we’ll have the extra two attributes (id and date). We could already initialize the id with a random UUIDbut we’ll let JPA do that. We make the set private so we cannot override this value, just read it. The date will always be the current date, so we just initialize with the current one.</p><p>In this class we have three new annotations:</p><ul><li>@Entity: This indicates that this class will be used by JPA(Java Persistence API) to save the data into a database.</li><li>@Id: Indicates that the field annotated will be the primary key in the database for this entity.</li><li>@GeneratedValue: the name is self-explanatory. It indicates that this primary key should auto-generate its own value.</li></ul><p>Now that we have our model, we’ll create our interface that will do CRUD operations (Create, Read, Update and Delete). The way that we gonna do this is extending our TransferRepository with CrudRepository. It’s amazing how simple this is and powerful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/971f3ab82f420f69336b550aaf251a97/href">https://medium.com/media/971f3ab82f420f69336b550aaf251a97/href</a></iframe><p>If you open the CrudRepository interface it’s easy to see what’s happening. This interface has all the generic functionalities for CRUD and all we need is to indicate what type is our model and the primary key, in our case TransactionDBModel and UUID.</p><p>Just indicating the model and primary key types, Spring will find out that we’re using this interface and will <strong>inject</strong> a <strong>default implementation</strong> for this interface (and the types that we provide). You can take a look at the default implementation, it’s a class called SimpleJpaRepository.</p><p>Of course, we’re not limited to just these functions. It’s also possible to create more complex database operations, but for this article, we’ll work only with this default implementation.</p><h3>From API to Database and vice-versa</h3><p>Now that our persistence layer is done we can save the data that we’re receiving from the API. The only thing we need to do is a small conversion between our models since the model that we receive in the endpoint is different from the one that we use in the database. Let’s create two extension functions to convert these models, convertToDBModel and convertToOverviewTransactionModel.</p><p>First at TransactionModel, convert the endpoint model into a database one, TransactionDBModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e5724263e459cad2e1db1168c42677a/href">https://medium.com/media/7e5724263e459cad2e1db1168c42677a/href</a></iframe><p>And for the overview, something similar. But this time the database model TransactionDBModelinto an endpoint one, OverviewTransactionModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71088947873be90237c0f571d60dabb6/href">https://medium.com/media/71088947873be90237c0f571d60dabb6/href</a></iframe><p>OK, now we can convert the data between our endpoints and the database. Let’s update our controller to do these calls.</p><p>Into the constructor, we’ll include our TransferRepository class. Remember, Spring is smart, when Spring sees that we have this dependency in our controller, Spring will inject the implementation created for TransactionRepository (based on SimpleJpaRepository).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/719df08c31e391c35c9641c3ca19b0ed/href">https://medium.com/media/719df08c31e391c35c9641c3ca19b0ed/href</a></iframe><p>You can see in the example above that our repository class is using the generic methods of CrudRepository to <strong>save</strong> and <strong>find all</strong> the transactions in the database. We also make use of the extension methods that we created to convert the model to the most appropriate one.</p><p>At this point, our endpoints are all done. Recompile and run the application. Let’s create a new transfer request. Remember that now we need to include all the necessary data on Postman to our endpoint to be able to work correctly. Include a JSON body like the picture below and submit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*38fSksgN_ufLFcsBwP8u0g.png" /><figcaption>Creating a new transfer request</figcaption></figure><p>After submit, everything should work fine. You should receive a status 200, meaning that the request was a success. Now if you fetch all the data again, you’ll see the submitted transfer data, including the date and generated id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*rzMLt72DRNfe2qKTOS4bsA.png" /><figcaption>Fetching all transfers</figcaption></figure><p>Our API is working 🎉 but we’re not done yet!</p><h3>Database Console</h3><p>There’s a very nice way that H2 Database offers us to check the saved data and that’s the “H2 Console”. It’s a web admin where you can check the database data and run queries.</p><p>First, to enable this console you need to add the following code in your application.properties file inside the resource folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d47b1c96c023b17146732b564b05988/href">https://medium.com/media/2d47b1c96c023b17146732b564b05988/href</a></iframe><p>After added, run your application again and enter in your browser the URL <a href="http://localhost:8080/h2-console.">http://localhost:8080/h2-console</a>. You gonna see a login window to connect to your database. The only thing you need to change is the JDBC Url . Look into your console logs and search for “H2 console available at …” like in the picture below. Copy the database URL and press connect. You should see the console. Now you can play with your database, run SQL queries and see the data being saved from your API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZweZicLHPtuBiqW7od0AAQ.png" /><figcaption>H2 URL on the console</figcaption></figure><p>Now we’re done, right? <strong>WRONG!</strong> We’re good developers and good developers write tests!</p><h3>Unit tests</h3><p>Before writing our first test let’s add a new dependency in the dependencies block inside the build.gradle.kts. With this dependency instead of Mockito, we gonna use Mockk to create mock instances.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1eea40abd304d48ccf60f8909914d89/href">https://medium.com/media/f1eea40abd304d48ccf60f8909914d89/href</a></iframe><p>This library helps us to support Mockk better in the Spring context. <a href="https://github.com/Ninja-Squad/springmockk">You can read more about it here</a>.</p><p>Create a new class called PaymentsControllerTest inside the tests folder. Take a moment to take a look at the tests below and we’ll understand what’s happening.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/513a41b6596a87a161e83faaa134dfe1/href">https://medium.com/media/513a41b6596a87a161e83faaa134dfe1/href</a></iframe><p>The general idea of what the tests are doing it’s easy to understand thanks to the Spring Testing framework, that’s very expressive. Let’s take a look at the technicalities:</p><ul><li>@WebMvcTest: This annotation indicates that these tests are testing an MVC Component, in this case, a REST controller.</li><li>MockMVC: This is the entry point that will allow us to communicate with our controller during the tests, doing requests and checking the result and statuses.</li><li>@MockkBean: We’re mocking a fake TransferRepository class to simulate different scenarios. We simulate these scenarios always before we perform an action with MockMvc, mocking the result from findAll and save methods.</li></ul><p>After we set up our mocks we perform a request to the controller using MockMvc. All tests follow a similar structure:</p><ul><li>We tell to MockMvc to perform a request and what kind it’s (post or get).</li><li>If we have a body in the request we transform the object into a JSON.</li><li>The content type of the request (APPLICATION_JSON).</li><li>We print in the console the request details and results.</li><li>And finally, we declare what we expect from this request. It can be a status code checking if the request succeeds or a JSON response (and the content).</li></ul><p>And we’re finally done. 🎉🎉🎉</p><p>You can find the full project at the following address on Github:</p><p><a href="https://github.com/feharaujo/CodingTutorials/tree/main/001%20-%20Bank-Project/bank">CodingTutorials/001 - Bank-Project/bank at main · feharaujo/CodingTutorials</a></p><p><strong>Questions or suggestions, leave a comment and don’t forget to follow for more tutorials. 🤠</strong></p><p>Thanks for reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nenf6wapkpevjJlWooUTUw.png" /><figcaption>Original article: <a href="https://www.backendhorizon.com/post/spring-boot-with-kotlin-creating-your-first-api">https://www.backendhorizon.com/post/spring-boot-with-kotlin-creating-your-first-api</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e511f96b23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/spring-boot-with-kotlin-creating-your-first-api-44e511f96b23">Spring Boot with Kotlin — Creating your First API</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My most valuable advice for who wants to study abroad]]></title>
            <link>https://feh-araujo.medium.com/my-most-valuable-advice-for-who-wants-to-study-abroad-5ccb56c5be?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ccb56c5be</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[study-abroad]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 19:33:28 GMT</pubDate>
            <atom:updated>2022-01-26T21:54:34.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>Studying abroad — How to prepare yourself</h3><h4>Just one tip before your exchange trip</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uphHDRY-whT-cME6" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=medium&amp;utm_medium=referral">Anne Nygård</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In 2018 I realized a dream, I went to Canada for 6 months on my exchange trip. It was an amazing experience, probably the most remarkable in my life. I met people from a lot of different countries and cultures. All the hard work and efforts that I invested in were undoubtedly worth it.</p><p>Even though <strong>my trip was wonderful</strong> I noticed that was <strong>not the reality for a lot of students</strong>. Demotivated students that preferred to stay sleeping than go to the classes. I had friends that even staying for short periods could not enjoy their time and were counting the seconds to go back home.</p><p>Of course, each one of them probably had different reasons, but something that I noticed is that sometimes<strong> this can be related to difficulties with the language</strong>, which can lead to<strong> isolation</strong>.</p><h3>Don’t go to study in another country if you don’t know the language</h3><p>I know that a lot of people can disagree with this (and that’s totally fine) since the main point of an exchange trip is to learn a new language and I completely get it but let me clarify my point.</p><h4>The challenges for those who don’t speak anything</h4><p>Imagine, <strong>you’re finally realizing a dream</strong>, you’re going to <strong>study in a foreign country</strong>. After all the planning and packing you arrived at your destination.</p><p>After a long trip, you think that maybe a coffee it’s a good idea, you go to the airport’s coffee shop and the “first shock” happens, you had a lot of difficulties just to order a coffee. Ok, that’s fine, it’s part of the experience, right? So now you need to go to your new home, you take a Uber since you don’t know the city, all the way not even a single word with the driver. When you arrive in our new home, maybe a homestay, you can’t communicate a lot with your host family and in school, the challenges continue …</p><p>Well, maybe you think that I’m exaggerating things a little? During my time as an exchange student, I saw this so many times that’s a bit sad. The difficulties of the day-a-day making so many people demotivated. Students stoping to go to school and staying just sleeping all day or just becoming friends and hanging out with people of the same nationality. You don’t want to waste your time and money like this, right? Of course not, for that as for everything <strong>planning is the key</strong>.</p><h3>Do your trip at the right moment</h3><p>One of the most difficult periods on the journey of learning a new language is not the beginning but between the transition of intermediate to advance. It’s a hard period, <strong>there is not a lot of visible progress anymore </strong>but we’re still not totally comfortable with the language, basic mistakes still happens often, the vocabulary needs to grow about different subjects, pronunciation needs improvements, writing needs to be more complex and not just isolated sentences. <strong>That’s the perfect moment for your exchange trip</strong>.</p><p>In the perfect scenario, you’d live and study abroad for a whole year, with the possibility of learning everything from scratch. Unfortunately, that’s not the reality for a lot of people. Studying abroad can be really expensive, especially for students from countries where their currencies are much less valuable. That’s why <strong>you should plan your trip for the right moment, the moment of most need</strong>.</p><blockquote>For the amazing experience that will be your trip, preparation and planning are the keys, especially the language</blockquote><p>Honestly, it was one of the best decisions I ever made in my life. I wanted to do an exchange trip for a long time but while I was saving money to pay for it I studied a lot, preparing myself to be able to advance and enjoy as much as possible. When I finally did my trip It felt so … <strong>right</strong>, the perfect moment for that.</p><h3>Don’t waste your money with grammar</h3><p>Learning a new language is not an easy path, it requires a lot of effort, time, and patience. However, these days <strong>learning</strong> is a much easier task than some years ago, we can learn almost everything in our homes, there is a lot of very good content out there (and free) on YouTube, blogs, apps, and courses.</p><h4>Save money and study smartly</h4><p>A lot of people <strong>spend so much money</strong> doing classes <strong>to learn content</strong> that is <strong>available for free on the internet</strong>, that is a mistake. There’re thousands of <strong>YouTube channels</strong> teaching the basics and advanced principles, and vocabulary of any language, you should really start from there.</p><p>Here is my recommendation for you <strong>if you’re starting with a new language</strong>:</p><ul><li><strong>Duolingo</strong>: You definitely should <strong>begin</strong> with this one, it’s one of the best <strong>apps</strong> to learn a new language. The best thing about Duolingo is how it <strong>slowly introduces basic grammar and vocabulary</strong> by practicing again and again. The key here is to <strong>keep practicing every day</strong>, each lesson doesn’t take a lot of time and is super fun. You can download Duolingo <a href="https://bit.ly/3ok6lH5">here</a> (<em>affiliate link</em>)</li><li><strong>Youtube:</strong> Well, no surprise on this one. YouTube has content for almost everything that you want to learn, and of course, languages are not an exception. It’s your virtual school, <strong>perfect for studying grammar</strong> and watching content in the language that you’re learning, growing your vocabulary, and practicing your listening.</li><li><strong>EngVid</strong>: If you’re learning English you <strong>must</strong> check this amazing site with video lessons about everything that you can imagine. Classes cover English grammar, vocabulary, pronunciation, IELTS, TOEFL, and more. You can access it <a href="https://www.engvid.com/">here</a>.</li></ul><p>Nevertheless, even though you can achieve a really good understanding of the language just by practicing at home with Duolingo and YouTube it’s not possible to become a fluent speaker just by doing that. Now it’s necessary the most important and difficult part, <strong>speaking</strong>.</p><h4>Speaking with the right people</h4><p>I’ve studied English for years since I was a teenager and I think I experienced almost all the possible study options. I studied in private language schools for a long time, private group sessions, individual sessions; in-person and online.</p><p>Even though I dedicated a lot of time (and money) I never felt that I was really improving at the point of becoming an advanced speaker. <strong>It’s almost as if something was missing … </strong>and really was. One day, after a miserable failure in my first international interview for a company in Australia I finally figure out what I really needed … <strong>real contact, native contact</strong>.</p><blockquote>I’ve spent so much time practicing a foreign language just with people of my own country</blockquote><p>And that was a <strong>huge</strong> mistake. I’ve been living abroad for 3 years now and I know if someone is from my country even if they’re speaking in another language, just by the accent. Something so simple, that makes a total difference. <strong>You never will become totally comfortable with the language if you don’t speak to people from that country.</strong></p><h3>Studying with native-speaker teachers</h3><p>After my <strong>epic</strong> interview failure, it was clear to me what I needed. I started to look for options that I could use for studying with native-speaker teachers. That’s when I’ve found this amazing platform called <a href="https://www.italki.com/"><strong>iTalki</strong></a>.</p><p>iTalki is a platform where you can find teachers from all over the world and schedule classes with them. There are different kinds of teachers (<strong>professionals</strong> and community tutors), <strong>native</strong> and non-native speakers, <strong>specialized ones for tests like IELTS or TOEFL, </strong>business, and much more. There is a bunch of filters that can help you find the perfect teacher (or teachers, why not?!) for you, for <strong>almost all the languages</strong> that you can imagine.</p><p>The platform is super friendly and easy to manage the class appointments and payments with your teacher. Probably there are other similar platforms but honestly, I don’t know others. I personally super recommend it, that will be a gold mine for your studies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LiYA3EWyMWXdUIOX" /><figcaption>Photo by <a href="https://unsplash.com/@visuals?utm_source=medium&amp;utm_medium=referral">visuals</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The plan</h4><p>When I used to study English I had a small plan that I liked to follow. <strong>Remember</strong>, there’s <strong>no right or wrong</strong> here, I’m sharing my <em>personal experience</em>, maybe this will work for you, maybe not, but just trying the possibilities you will find out.</p><p>Grammar is something very difficult to study for a lot of people (it was for me, super boring) so the way that I used to approach this was with different kinds of content. It’s good to have some study map to not get lost in so many different topics, I used to study following the book <strong>“English Grammar in Use” </strong>by<strong> Raymond Murphy</strong>. It’s an excellent and straightforward book for those who want to study English grammar for yourself. You can find it <a href="https://amzn.to/3n5Q07m">here</a> (affiliate link).</p><p>Usually, in my studies sessions, I used to study the book and do some exercises about the topic, <strong>not</strong> a lot, <strong>not</strong> long hours studying grammar, oh god no... On the next day, instead of already starting another topic (even though sometimes I already felt comfortable with the topic) I usually liked to watch a video about it.</p><p>Personally, I love video content, I follow dozens of English channels and used them to <strong>support</strong> my studies about some subjects. It’s very common to notice things/doubts from different explanations and content formats that you don’t even think of before and will help you memorize it easier.</p><h4>Practice time</h4><p>As you could see iTalki can be a very powerful tool (probably the most important) to boost your language studies. Following your own studying sessions now it’s time to put this into practice.</p><p>Search for a teacher that you think that you like, do a session, find out if you like him/her, and schedule more and more sessions. I completely understand that it costs a little, but you can do it once a week, I used to do it once a week, and the gains to practice everything that you’ve been studying all week is astonishing.</p><h4>BUT don’t forget, don’t waste your money with grammar</h4><p>Use your time with your teacher wisely. Do what is the most important thing: talk, talk a lot. Of course, if you have doubts ask your teacher but don’t make this class a “normal” class, your main focus should be the <strong>conversation</strong>.</p><p>In my classes, the structure that I liked to follow was free conversations with my teacher, about any subject, anything that was happening in my country, in my work, my holidays, politics, technology, <strong>anything</strong>. <strong>I asked him to take notes about my mistakes</strong>. Between our talks, he used to present my mistakes and give some explanations and suggestions, but the focus was always on keeping the conversation happening.</p><p>With your teacher&#39;s notes on hand, during the week <strong>check your mistakes and learn from them</strong>. Keep doing this every week. Did you learn something new? Try on the class, try in a real conversation and you’ll see if you really got it totally.</p><p>This is the way that I learned English and it was amazing the progress I had. <strong>Now you have all you need to prepare for your trip. Enjoy, thanks for reading,</strong> and share your experience.</p><h3>Links &amp; Affiliate Links</h3><p><strong>English Grammar in Use </strong>by<strong> Raymond Murphy</strong>: <a href="https://amzn.to/3n5Q07m">https://amzn.to/3n5Q07m</a></p><p><strong>Duolingo</strong>: <a href="https://bit.ly/3ok6lH5">https://bit.ly/3ok6lH5</a></p><p><strong>English video lessons</strong>: <a href="https://www.engvid.com/">https://www.engvid.com</a></p><p><strong>iTalki</strong>: <a href="https://www.italki.com/">https://www.italki.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ccb56c5be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading Lottie’s animation from local storage]]></title>
            <link>https://medium.com/backend-horizon/loading-lotties-animation-from-local-storage-93ff29f21296?source=rss-cc5d88617db8------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ff29f21296</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[lottie]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Felipe Trova de Araujo]]></dc:creator>
            <pubDate>Sun, 30 Jun 2019 15:59:39 GMT</pubDate>
            <atom:updated>2021-12-03T13:43:45.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>Loading Lottie’s Animation from Local Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj0HyB9sGXerEmYODsa0HQ.png" /></figure><h3><strong>The Feature</strong></h3><p>Recently, I was working on a very nice feature, a dynamic animation theme. <strong>We had a static animation</strong> in the login’s background screen, and <strong>the team decided to make it a bit more modular</strong>, creating the possibility of <strong>presenting another animation in a specific range of dates </strong>(especially holidays, like Mother’s Day or Christmas) but without the need of submitting a new version to the app stores, c̵o̵f̵f̵ ̵c̵o̵f̵f̵ ̵f̵i̵r̵e̵s̵t̵o̵r̵e̵.</p><h3>Local animation</h3><p>After finishing the download and cache implementation (to save the animation files in the device’s cache folder), I noticed that the <strong>Lottie animation view doesn’t provide a way to load the animation directly from the cache folder</strong>, providing just the local path. <strong>It’s just possible to load from the Raw and Assets folder or provide a JSON string</strong> (not a good idea, remember, String has a limited size).<br>I took a look at the site’s documentation and searched the internet, and I couldn’t find anything. Fortunately, Lottie is open source and by exploring a little bit of the source code I could find the solution to the problem. <strong>The key to solving this is something called </strong><strong>LottieComposition</strong> (and LottieCompositionFactory). According to the code’s documentation, a LottieComposition is:</p><blockquote>“After Effects/Bodymovin composition model. This is the serialized model from which the animation will be created. To create one, use LottieCompositionFactory. It can be used with a LottieAnimationView or LottieDrawable”</blockquote><p>Precisely what I needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FTnnaN-tt4AH9zng" /><figcaption>Photo by <a href="https://unsplash.com/@mr_vero?utm_source=medium&amp;utm_medium=referral">Irvan Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The code is quite simple. The <strong>first step</strong> is to create an InputStream using our file path. We need to provide the path as a String and the buffer’s size (I’m using 1MB, 1024 )</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24203dc989636ec00c5e6ad8c24952ad/href">https://medium.com/media/24203dc989636ec00c5e6ad8c24952ad/href</a></iframe><p>As the documentation recommends, <strong>we need to use the </strong><strong>LottieCompositionFactory to create an instance of </strong><strong>LottieComposition</strong>. This factory class provides an effortless way to return a LottieComposition from a Stream. We can do it in two ways.</p><p>Asynchronous:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc3ca19a971aa90d8d1073d050c652f/href">https://medium.com/media/3bc3ca19a971aa90d8d1073d050c652f/href</a></iframe><p>Alternatively, Synchronous:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4ff13b751df5ae4faebe68a13e84348/href">https://medium.com/media/a4ff13b751df5ae4faebe68a13e84348/href</a></iframe><p>To finalize set the result in Lottie’s animation view using the setComposition method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de0f943fe28a52f66199300392aea9c9/href">https://medium.com/media/de0f943fe28a52f66199300392aea9c9/href</a></iframe><p>That’s it. Easy peasy!</p><p>You can find the full project at the following address on Github:</p><p><a href="https://github.com/feharaujo/TutorialsCode/tree/lottie-local-anim">feharaujo/TutorialsCode</a></p><p><strong>Questions or suggestions, leave a comment, and don’t forget to follow for more tutorials. 🤠</strong></p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ff29f21296" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend-horizon/loading-lotties-animation-from-local-storage-93ff29f21296">Loading Lottie’s animation from local storage</a> was originally published in <a href="https://medium.com/backend-horizon">Backend Horizon</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>