<?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 Mordechai Dror on Medium]]></title>
        <description><![CDATA[Stories by Mordechai Dror on Medium]]></description>
        <link>https://medium.com/@vorant94?source=rss-43cbfe87d5bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BsOh9tOnD-3uPe56PpJZ-A.png</url>
            <title>Stories by Mordechai Dror on Medium</title>
            <link>https://medium.com/@vorant94?source=rss-43cbfe87d5bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:31:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vorant94/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[Divide and conquer: right concerns to separate]]></title>
            <link>https://vorant94.medium.com/divide-and-conquer-right-concerns-to-separate-880dc5c56e0f?source=rss-43cbfe87d5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/880dc5c56e0f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[separation-of-concerns]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Mordechai Dror]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 07:22:57 GMT</pubDate>
            <atom:updated>2024-03-10T07:27:13.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eveKYKHJNwfacPp_uJzVVQ.png" /><figcaption>Julius Caesar statue</figcaption></figure><p><em>One of the core programming principles is separation of concerns. It guides programmers to separate applications into smaller units with distinct boundaries. My view on it went over a couple of iterations and I’d like to share with you what it means for me now</em></p><h3>Historical reference (in less than 30 mins)</h3><p>Historically it happened so the UI side of websites is split into 3 technologies: markup — HTML, styling — CSS and code — JS. This separation is one of the first things newcomers to web learn. I remember I was briefly introduced that it is possible to write both CSS and JS right inside HTML, but we quickly concluded it is a bad practice because of <strong>separation of concerns</strong>: markup, styling and code should be kept separate to keep stuff in order.</p><p>The first somewhat real code I wrote in the college was Ruby on Rails, which followed MVC architecture. The first job position I landed was front-end developer with Angular as a main framework, Angular follows MVVM architecture. Both MVC and MVVM can be fairly considered a classic examples of separation of concerns: models are separate from views, views are separate from controllers etc… Angular additionally keeps HTML/CSS/JS files of the same component separate by default, which aligns perfectly with what I initially learned.</p><p>At some point of time I get acquainted with Atomic Design Methodology, which also splits the components by their technical characteristic: if component is simple — it is “Atom”, then based on increasing complexity there can be “Molecules”, “Organisms”, “Templates” and “Pages”. Component with higher complexity can use components with lower complexity, but not otherwise. I concluded that it is the common way to structure modern design systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*PaTGAkNS3WD_PlPFljyaGQ.jpeg" /><figcaption>Mandalorian telling This is The Way</figcaption></figure><p>From the other side same Angular I talked earlier introduced me to “Folders-by-feature” principle in its official style-guide. Later I found that it has a little bit nicer name outside Angular ecosystem, it is called “Vertical Slice” (as opposed to “Horizontal Slice”, that is followed by MVC and MVVM). According to it project files shouldn’t be grouped by a some technical trait like “keep all components together” and “keep all services together”. But rather by its feature or domain of use — all dashboard-related stuff should be kept together disregard of whether we are talking about components, services or whatever else. I really liked this approach and didn’t notice the contradiction with what I already learned.</p><p>At some point of time I needed to dive deep into Angular Material source code and it was my first time digging into huge open source code-base. It didn’t follow the Atomic Design Methodology, but instead more or less grouped the files by their respective domain. I still didn’t pay enough attention. After all Angular Material itself doesn’t follow the official Angular style-guide, so it may also branch itself out from “industry standard” e.g. atomic methodology.</p><p>Last year I started to play around with mobile development. Since I have an iPhone and my wife has an Android, I needed to go with cross-platform solution. I chose to learn Flutter and Dart. There is no separate technology within it for markup, styling and actual code. Everything is code, everything is Flutter. It felt wrong in the beginning, but with time I got a moment when I realized, that having a type-safe markup and styling is a huge boost for both productivity and developer experience.</p><blockquote>Imagine you have LSP for the CSS shit like <a href="https://stackoverflow.com/questions/17779293/css-text-overflow-ellipsis-not-working">text-overflow: ellipsis;</a> or <a href="https://stackoverflow.com/questions/1261955/inherited-text-decoration-style">text-decoration: none;</a>, that can instruct you which exact combination of rules you need to use to get what you want. Imagine you have LSP autocomplete for only relevant CSS properties on a target HTML element without leaving your IDE. Imagine you don’t need to wait for a good <a href="https://caniuse.com/">Can I use</a> score for CSS3 variables nor go with SCSS to get reusable styling values. This is what you get when markup, styling and code are not separated.</blockquote><p>Recently I watched the <a href="https://youtu.be/8pDqJVdNa44?si=LsjVUCznknGEjI7d">documentary about React</a>. Also I heavily use <a href="https://tailwindcss.com/">Tailwind</a> for my blog. Both those technologies are accused of violating separation of concerns principle: React merges markup and code by leveraging JSX, Tailwind puts styling back into markup. But this time it didn’t feel wrong. I finally succeeded to switch my mindset and understand why it is even better separation of concerns that what I learned initially.</p><h3>“Concern” is not technical term, but a logical one</h3><p>The common way to explain OOP is using real-world analogy, in particular via biological classification of organisms:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/713718ca1c5f124a54ef071e33297972/href">https://medium.com/media/713718ca1c5f124a54ef071e33297972/href</a></iframe><p>You have a most abstract class of <em>Animal</em>, which is distinct from <em>Plant</em>. Then you have two classes of <em>Mammal</em> and <em>Ave</em>, which are distinct from each other, but both <strong>inherit</strong> from <em>Animal</em>. Then you have a <em>Dog</em> class as a most narrow example of <em>Mammal</em> and a <em>Crow </em>as a most narrow example of <em>Ave</em>. This analogy allows developers to structure the code in DRY and well-organized manner. For example a common thing between all animals is that they can move, so the abstract class <em>Animal </em>can define abstract method <em>move</em>, then <em>Mammal </em>can implement this method considering that mammals walk and <em>Ave </em>can implement this method considering that birds fly.</p><p>Everything is nice and clear until we step out from programming courses and tip our toe into real world software especially frameworks. The abstractions I see there are: models, views, controllers, directives, components, services… WTF?! My kitten Nami doesn’t consist of separate <em>CatService</em>, <em>CatController</em> and <em>CatComponent</em> abstractions spread throughout the entire apartment. At this moment I gave up on the examples from learning courses and went along with abstractions of real world software. But now I’d like to stick with it, but with an asterisks.</p><p>There is a well-known issue with inheritance in OOP: each new bottom-level candidate might introduce a change that leads to a full refactor of the whole inheritance chain. In our example with <em>Mammal </em>and <em>Ave</em> we concluded that mammals walk, aves fly. But what about bats and penguins? We didn’t think about cases where mammal can fly and bird can swim, why would we? The required bottom level classes of <em>Dog</em> and <em>Crow</em> fit well with our initial hierarchy, but apparently this hierarchy is not scalable or flexible enough to serve us in the long run.</p><p>Here comes another programming buzzword — <strong>composition</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7294f6155c39f86f88bf5e0bdf7b91a0/href">https://medium.com/media/7294f6155c39f86f88bf5e0bdf7b91a0/href</a></iframe><p>Instead of defining deep chain of different classes we define the bottom-level set of candidates that we need (<em>Dog</em>, <em>Crow</em>) and set of traits or skills that we can attach to them (<em>Flyable</em>, <em>Walkable</em>). This way each new bottom level candidate (<em>Bat</em>, <em>Penguin</em>) can take traits that it needs or introduce a new one (<em>Swimmable</em>) without forcing existing stuff to be changed.</p><p>Now back to real-world programming and my lovely kitten. This way in the program I can have <em>Cat</em> abstraction as a single directory that has some digital characteristics like <em>CatService</em>, <em>CatController </em>and <em>CatComponent</em> as files within this directory just like in the real world it has physical characteristics of <em>Walkable</em>, <em>Talkable </em>and so on.</p><p>I consider this way of structuring the code is way more intuitive and easier to understand, but it comes with a very important mental switch under the hood: the concerns we are separating are not <em>CatComponent</em> from <em>CatController</em>, but <em>CatComponent</em> from <em>DogComponent</em>. The <strong>tech categorization</strong> comes after and only after <strong>logical categorization</strong>. On a low level it means markup, styling, code are not a concern since they are technical traits, component is a concern. On a high level it means components, directives, services are not a concern because of the same reason, the dashboard, settings, news feed are a concern. You first separate with vertical split, and only after it with horizontal split.</p><h3>Benefits of vertical split mindset</h3><p>It all sounds good and everything (I hope so), but what’s the point, yeah?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*DspGOlMxyiKSM7XV8Qm9mA.jpeg" /><figcaption>Where is the money, Lebowski</figcaption></figure><h4>Less mental overhead</h4><p>Let’s say you are in a huge back-end project having 100 resources. Each of those resources is a REST endpoint, so it consists from at least 3 type of files: route API handlers, business logic services and data access layer models. If you make horizontal slice you have 3 folders with 100 files in each one of them, if you make vertical one — 100 folders with 3 files in each.</p><p>Now you have to add a new resource. While developing with horizontal split you need to constantly jump between 3 directories full of other files irrelevant for your task, but with vertical one you scoping down your work to 1 directory with only 3 files. Less white noise you have easier the work goes.</p><p>But it doesn’t end up with developing only. Now let’s say you developed resource A, that led for changes to resource B, that already existed in the project. You finished your changes and send it to your team for code review. The order of files your team sees in PR is the following:</p><ul><li>new route handler of resource A</li><li>updated route handler of resource B</li><li>new business logic service of resource A</li><li>updated business logic service of resource B</li><li>…</li></ul><p>Which makes not only you jump in between different directories during development, but also all the people who needs to review your code. There is no option to first go over all the resource A changes and then go to resource B stuff. I worked in projects with horizontal split structure. During the review of my code I personally saw team lead constantly jumping over a bunch of resource B files just to get to next resource A file. He didn’t see it as problem, but I saw it caused him to struggle to get the full picture of this PR. Wouldn’t it be way more convenient if the order of files for review would be like this?</p><ul><li>new route handler, new business logic and all of the stuff related to resource A</li><li>updated route handler, updated business logic and all of the stuff related to resource B</li></ul><h4>Scalable out-of-the-box</h4><p>When we lay down the foundation of the project we want it to scale to 1m users with ease. Usually it means the following: micro-service event-driven architecture with load balancing deployed in cloud native technologies with zero down-time available across the globe ©️. In real world you either never finish the MVP of such or you make a lot of shortcuts only to find yourself in huge tech-debt after a while.</p><p>It comes so because all those fancy words come with a price: <strong>system complexity</strong>. Huge scalable systems not only serve a lot of users, they are meant to be developed by a lot of engineers. From the other side good old monolith can rocket-boost your MVP in less than a week. But after you get your VC money and the project gets first somewhat serious traffic it’ll face its performance ceiling and it won’t be easy task to split it into smaller standalone parts. Don’t forget about talking your investors into spending half-a-year to do the refactor without increasing the margins in the meanwhile.</p><p>I do believe that vertical split allows to get the best of two worlds. You develop a monolith at first as fast as you need. But since you have 100 folders with 3 files in each and not vise-versa when the moment comes it is easier to take 50 of those folders and put them into server on its own. Furthermore since you put the logical boundaries first it is less likely for anyone to mix things up along the way. Everybody knows not to mix controllers with models, but keep project-specific logical abstractions in the right order is way harder. Vertical split forces us to not shortcut the essential architecture.</p><h4>Unit tests aren’t nightmare anymore</h4><p>During one of the job interviews I was having recently I got home assignment to build the following component. It is a tree select dropdown with option for a single and multiple selection mode and option to filter leaves. As part of the task I was asked to cover one of the component entities with unit tests. The framework is Angular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*0veSF8jNUEaOsmHKmj1GXg.png" /><figcaption>Home assignment demo</figcaption></figure><p>The final solution included 1 component, 5 directives, 1 pipe, 2 services and 2 non-standard file types. The classic unit testing means you identify a minimal standalone unit inside your program, mocks/stub all the other and test behavior of the chosen one. In my example it can be any of the mentioned above entities since each of them is technically standalone. Mocking/stubbing is always a painful part in unit testing, because you as a developer don’t develop anything, you don’t add value to the product, you just making endless preparations to code the thing that should add value.</p><p>Here I caught myself once again thinking in <strong>technical</strong> terms instead of <strong>logical</strong>. Nobody argues that private methods shouldn’t be covered with unit testing, right? It causes too strong coupling of tests with actual code. Only public part that is meant to be used should be guarded. This principle while being grounded in technical terms of “private” and “public” actually talks logically: test covers the surface of the unit without going any deeper. Components, directives, pipes and services are technical Angular terms, the surface is what user of the component uses and in this case it is 1 root component and nothing more. So the candidate for the test coverage became obvious and nothing should be mocked, since logically it is one single unit.</p><p>You might say it’s not a unit test, but rather integrational one, because it touches several entities and theoretically user can access other internal entities. But I don’t think so. Imagine language or framework provides you with the option to keep stuff “private” while simultaneously split it into several different entities. Would you cover each entity with its own set of tests or would you cover with it only the part that is meant to be public by the definition of the feature?</p><blockquote>Dart allows it with partial files by the way. So there you can keep files within reasonable size as well as keep right level of encapsulation.</blockquote><p>We shouldn’t obey technical restrictions of our tools: just like “concern” is not a technical term, “unit” also not of this kind. Understanding this reduces amount of boilerplate and allows our code and test be more meaningful.</p><h3>Outro</h3><p>While I do see this pattern in a lot of technologies today, overwhelming majority of them isn’t developed by one person with one mindset. As a result we have React unified technically different HTML and JS into JSX, but then came NextJS with all other meta-frameworks and introduced purely technical distinction between different components with file-based routing… Angular itself preaches “Folders-by-feature”, but decided to keep markup, styling and code separate, because it wanted to achieve a more vanilla-like web-experience for its users…</p><p>After all nothing is perfect and is never meant to be. “Good enough” is our industry slogan, thats for sure. But having a right mental model as well as unlearning harmful parts of college education is a way to care for yourself during the activity, that takes almost as much time as you sleep. Now I have less chance to shoot myself in the foot, wish the same for you.</p><p>If you want more content like this, you are welcome to check out my personal blog at <a href="https://www.vorant94.io/">https://vorant94.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880dc5c56e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Amplify Functions on steroids]]></title>
            <link>https://vorant94.medium.com/aws-amplify-functions-on-steroids-bffbfc09960c?source=rss-43cbfe87d5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bffbfc09960c</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mordechai Dror]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 18:32:30 GMT</pubDate>
            <atom:updated>2023-07-05T18:40:51.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dxi3CG-tDtz7rth1.png" /></figure><p><em>My journey to AWS Amplify continues and it lead me to explore possibilities of AWS Amplify Functions, a wrapper API of Amplify to easily integrate AWS Lambdas into your project. As an example project we will build a small to-do list app</em></p><h4>What we have out of the box</h4><p>When we add an API to Amplify project it out-of-the-box offers us key-value storage to store all of our data (using DynamoDB) and GraphQL-based CRUD API to access it (using AppSync) with a bunch of directives to customize the schema. The customization means we as a developers are not limited to CRUD only. For example, there are a couple of ways to implement a custom resolvers based on our business logic requirements. One of these ways is to define a Lambda function and link it in schema via <a href="http://twitter.com/function">@function</a> directive. Those lambdas can be written in different languages, but we will focus more on Node.JS since it is nice to have the same language ecosystem both on Front-End and Back-End side. In our case there will be three custom mutation resolvers: one to mark all current todos as completed, second to delete all of the completed todos and third to toggle completion of a todo (instead of setting it to either true or false manually). The UI should look something like this:</p><figure><img alt="the presentation of the UI of the project" src="https://cdn-images-1.medium.com/max/638/1*X3ns_KuEzK0VOdJDJ2Ifvg.png" /></figure><p>After we add Amplify to the project, lets define our data model and add a functions to our project (see the official documentation <a href="https://docs.amplify.aws/cli/function/">here</a> and <a href="https://docs.amplify.aws/cli/graphql/custom-business-logic/#lambda-function-resolver">here</a> for the exact steps). In the end our schema should look somewhat like this:</p><figure><img alt="the presentation of GraphQL schema of the project" src="https://cdn-images-1.medium.com/max/629/1*jVpOnHgzUKSCB7eiz7L3dA.png" /></figure><p>A couple of side bonuses:</p><p><em>First thing no note is that Amplify CLI offers to name the function with project name used as a prefix (e.g. </em><em>functionsonsteroids1fa063ec). You would like to follow this pattern (maybe use some shortened version of your project name like in my case it is </em><em>fos) since without in lambdas from different projects with the same name can cause conflicts. When it comes to different environments of the same project Amplify under-the-hood adds suffix of the environment to avoid conflicts, but for some reason it doesn’t automatically add project name as prefix, so we need to to it manually.</em></p><p><em>In case you are using WebStorm / IntelliJ in order for IDE not to scream at you about “unknown directives” and so on, you’d like to create </em><em>appsync.graphql with content from this </em><a href="https://gist.github.com/cietho/87463cfa77ffa9917d1b1425e01049bd"><em>Gist</em></a><em> and mention it as a schema alongside with your actual project schema in </em><em>graphql.config.yml at the root of the repo.</em></p><p>So as of now we have three separate JavaScript lambda functions with all the necessary logic already implemented. Here are file structure and code of one of our three lambdas just for a reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84S6WvJSlH0O0gTrUB1ixA.png" /></figure><p>Our goals are:</p><ul><li>Migrate them to TypeScript</li><li>Share common code between them</li><li>Get types for them from Amplify CLI Codegen</li><li>Have as less trade-offs as possible</li></ul><figure><img alt="“What do we want?” meme about typescript support" src="https://cdn-images-1.medium.com/max/583/1*4lRqB4Mnzz_IpveqAhuchQ.jpeg" /></figure><h4>TypeScript support</h4><p>Amplify documentation offers us a <a href="https://docs.amplify.aws/cli/function/build-options/">handy guide</a> on how to do it, which is a good starting point (don’t ask me why they hid it under the “Build options” and didn’t do a dedicated post).</p><p>Now, there are three particular points of lambda lifecycle that we are interested in. First of all it is local runtime, when we are running lambda via amplify mock or we pushing the changes with CLI via amplify push. Second is actual runtime after building the code and pushing it to the cloud. And third is CI/CD, where the cloud is watching for git repo changes and deploying our project by itself. Each of those points has its own pitfalls, that we need to play around.</p><p>First if we just leave all of the lambda dependencies in its own package.json, neither amplify build nor amplify mock will actually work. It happens so since in those cases amplify CLI uses repo’s root package.json and not lambda’s local package.json e.g. all of the actual lambda dependencies (excluding dev dependencies) that are mentioned in the local lambda package.json must be duplicated as dev dependencies (at least) inside root package.json.</p><p><em>It can work without it only when it happens so root </em><em>package.json dependencies by themself include all lambda </em><em>package.json ones (and it is the case if we used </em><em>AppSync — GraphQL API request (with IAM) template for creating the lambda), but when we try to add more types e.g. </em><em>AmplifyGraphQlResolverEvent from </em><em>aws-lambda the IDEA and build script will start to scream at us since at this point of time root </em><em>package.json is the boss.</em></p><p><em>If running </em><em>amplify mock results in Unauthorized Error despite proper permissions of lambda and despite the fact that everything works fine in runtime itself, check this </em><a href="https://docs.amplify.aws/cli/graphql/authorization-rules/#use-iam-authorization-within-the-appsync-console"><em>section in docs</em></a><em>, which explains that we need to add </em><em>custom-roles.json file in order to have permissions we need.</em></p><p>If we would want to keep dependencies clear from duplicates otherwise by removing dependencies from lambda personal package.json and leaving them only in root package.json, we also cannot do it. It will successfully pass build and push, but will fail in the actual runtime. So those duplicates are with us (hopefully just for now).</p><p>The last point of time that I mentioned earlier is Amplify CI/CD. Since as of now all we did was via Amplify CLI locally on our machine we didn’t face another small issue yet. By default Amplify CI/CD installs dependencies only during frontend step, so the build of backend will actually fail because of lack of tsc in the machine. The easiest way to deal with it is by downloading Amplify CI/CD config from AWS console, adding there preBuild phase (you can just copy it from the frontend step) in backend step and storing the updated config in the root of the repo so it will override the default one in the cloud.</p><p>After all the preparation is done, we can now re-write the actual JS code of the lambda to be TS. Additionally I added .gitignore in src of lambda, because we don’t need to store transpilation result in the source code. Let’s just manually copy-paste required AppSync types from generated UI code for now. We will make it way a lot more DRY in the next step. In the meanwhile here are updated file structure and source code of another one of our lambdas for reference (I put all the copy-pasted AppSync types into app-sync.models.ts and moved appSyncRequest function to app-sync.helpers.ts).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZ1S1_-jYJPSYpKyC1_ZLg.png" /></figure><h4>Sharing code between lambdas</h4><p>There is obvious code duplication between our lambdas. Let’s start with the appSyncRequest function that signs and sends AppSync request. As far as I looked for a solutions our options are lambda layers and dedicated npm package. Each of them has serious trade-offs. At the moment there is no support for amplify mock for those lambdas that use lambda layers from one hand, and from another — publishing a separate npm package that is only used in the scope of one and only project is too much boilerplate and simply redundant.</p><p>Both those options are about sharing JavaScript code, but since we migrated to TypeScript we now actually have a bonus third option. We can configure the TypeScript compiler so it will combine code at build time from two places: one — our lambda-specific lib folder, second — shared utility folder. Since the project is based around Angular e.g. the repo is a fully featured multi-project workspace so we can generate a new library via ng generate library lambda-shared and store shared lambda code there nice and clear. Then in order to access it from lambdas we need to replace rootDir in each of lambdas tsconfig.json with rootDirs and thats it — amplify mock is in place, no unnecessary boilerplate, everybody is happy, yeah? Almost. There are a couple of gotchas that needs to be kept in mind…</p><ul><li>Since there are two rootDirs for TS compiler, the actual structure of the resulting JS inside src is changed (see the screenshot) and AWS Lambda runner points to actual entry file no more. We can narrow down this issue to purely cosmetic one by manually editing CloudFormation templates of lambdas (and its package.json#main property as well) so it will take into account a new file structure e.g.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UemEVGChk0ioRRatEf4G1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Atfzy-xlJDdSFgSH-oQYCA.png" /></figure><ul><li>Amplify CLI cannot detect lambda changes if only a shared code is changed. It doesn’t matter for CI/CD since we are ignoring all .js files, which means it will build it each time, but locally we might need to build lambda manually from time to time so amplify push can catch the stuff up.</li><li>Since tsc is building the whole shared folder each lambda have to include all its dependencies even though it might not use the functionality that requires those dependencies. E.g. if one of lambdas need to use lodash and its code is places into shared folder the lib have to be installed into all lambdas who benefit from shared code. It may lead to exceeding the lambda max size limit, but in that case we can swap TypeScript compiler with a Webpack, so lambda become bundled and the dependencies become tree-shakable.</li><li>Shared lambda code is not telling by itself the permissions or environment variables that lambda must have in order to successfully execute it, so we need to remember to update it accordingly.</li></ul><p><em>As a bonus in order to avoid long </em><em>../../../../ imports from shared folder, you can add a couple of path aliases into </em><em>tsconfig.json. But if you do so, don’t forget to convert shortened imports back to long ones after transpilation. It can be done by adding </em><em>tsc-alias run (after </em><em>tsc run) into </em><em>amplify:… scripts, that we added as a part of Amplify “Build options” guide.</em></p><h4>Amplify CLI Codegen multi-target</h4><p>Now that we have a good support for TS it and we placed removed repetitive code, it would be nice just like in UI to benefit from auto-generated types based on our AppSync schema. According to this GitHub <a href="https://github.com/aws-amplify/amplify-codegen/issues/49">issue</a> there is no support for multiple targets in Amplify Codegen at the moment, but… Since Amplify stores Codegen config as a file in the root of our repo we can update it manually to our needs and Codegen will do what we want him to do without any problem… Just don’t tell this secret to anyone😜</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*Is0DzIy-XQSa3esC0EmEuA.png" /></figure><p><em>For some reason it only works if you agreed to generate all possible operations and types during adding or re-adding Codegen. Otherwise Codegen throws an exception that multiple projects are not supported.</em></p><p>The only problem with this approach is that the Codegen runs after the code is built and pushed to the cloud. E.g. if you change the schema you first need to do amplify push, then after you get updated types you need to make amplify push once again to re-build lambdas, that depends on those types. A possible workaround for it may be a separate push of API and lambdas (e.g. amplify push api at first and amplify push function after it). Or we can mock API (amplify mock api), which will trigger the build of API, which will trigger Codegen with latest changes, and then we can push everything together.</p><h4>Conclusion</h4><p>To sum up we achieved everything we wanted and are now ready to boost the productivity of any Amplify-based project, the trade-offs that we have as a result are:</p><ul><li>need to duplicate all of the lambdas dependencies as a dev dependencies in root package.json</li><li>need to manually run lambdas build scripts if changes are made only in shared code</li><li>need to add all the dependencies of shared code to each of lambda package.json even if a particular lambda doesn’t use all of shared functionality</li><li>need to manually document what permissions / env variables lambda must have in order to use shared code</li><li>need to push changes twice in case lambda changes are dependent on schema API changes</li></ul><p>All the code mentioned here you can find in my <a href="https://github.com/vorant94/amplify-functions-on-steroids">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bffbfc09960c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pitfalls of AWS Amplify Serverless containers]]></title>
            <link>https://vorant94.medium.com/pitfalls-with-aws-amplify-serverless-containers-ba9e2e87a6f?source=rss-43cbfe87d5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba9e2e87a6f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[guide]]></category>
            <dc:creator><![CDATA[Mordechai Dror]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 20:57:29 GMT</pubDate>
            <atom:updated>2023-09-02T08:29:53.196Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Recently I’ve got a task that led me to exploring AWS Amplify Serverless Containers and I would like to share with you the experience I had. I built a small Angular app that allows to convert Word files into PDF</em></p><h3>Starting point</h3><p>In order to get to the point of serverless containers let’s assume we have an Angular project that is configured with AWS according to <a href="https://docs.amplify.aws/start/q/integration/angular/">this guide</a>. After the project is initialized it needs also to be configured to allow advanced workflows by running `aws configure project`.</p><h3>File converter API</h3><p>The API that I chose to implement in the scope of this app is <a href="https://gotenberg.dev/">Gotenberg</a>. It is basically a wrapper on top of the LibreOffice API distributed as a nice stateless Docker container, what makes it a perfect candidate for my purpose.</p><h3>First try (or DeploymentAwaiter problem)</h3><p>I started by adding a new api with `amplify add api` and followed by`REST -&gt; API Gateway + AWS Fargate (Container-based)`. CLI gave me a couple of templates that I am supposed to select from. I chose a custom one and continued with other configuration (for testing purpose I didn’t restrict access to the API).</p><p>Gotenberg provides a simple docker compose <a href="https://gotenberg.dev/docs/get-started/docker-compose">example</a> of how to add it to your stack, so I copied it to the project and added mapping of ports (since I want the API to be exposed on port 80 and not 3000). At this point of time compose file looks like this:</p><pre>version: &quot;3&quot;<br><br>services:<br> gotenberg:<br>  image: gotenberg/gotenberg:7<br>  ports:<br>   - 80:3000</pre><p>I ran it locally to make sure everything is working as expected and after it ran `amplify push` to push changes to cloud… only to get `CREATE_FAILED` status on some inner DeploymentAwaiter resource which I’m not even aware of.</p><p>Now lets fast-forward half a day me playing “Spot 5 differences!” with out-of-the-box examples (particularly with “Docker Compose — ExpressJS + Flask template”) that are working by the way perfectly. I noticed that syntax of the given compose file doesn’t use `image` statement, but `build` instead, e.g. it goes like this:</p><pre>version: &quot;3.8&quot;<br><br>services:<br> express:<br> build:<br>  context: ./express<br>  dockerfile: Dockerfile<br> ports:<br>  - &quot;8080:8080&quot;<br> networks:<br>  - public<br>  - private<br><br>python:<br> build:<br>  context: ./python<br>  dockerfile: Dockerfile <br> networks:<br>  - public<br>  - private<br> ports:<br>  - &quot;5000:5000&quot;<br><br>networks:<br> public:<br> private:</pre><p>And ExpressJS Dockerfile, that was also generated by Amplify CLI, looks like this:</p><pre>FROM public.ecr.aws/bitnami/node:14-prod-debian-10<br><br>ENV PORT=8080<br>EXPOSE 8080<br><br>WORKDIR /usr/src/app<br><br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br><br>CMD [ &quot;node&quot;, &quot;index.js&quot; ]</pre><p>Nothing special, it is a common instructions to bundle NodeJS applications with Docker and all steps make sense. In my case I don’t need to modify publicly available image of Gotenberg. But when you are playing “Spot 5 differences!”, you need to do weird stuff from time to time, so I decided to try and add a dummy Dockerfile, that just extends Getenberg image and runs it. It goes as followed:</p><pre>FROM gotenberg/gotenberg:7<br><br>EXPOSE 3000<br><br>CMD [ &quot;gotenberg&quot; ]</pre><p>Updated compose file looks like this:</p><pre>version: &quot;3&quot;  <br><br>services:<br> gotenberg:<br>  build:<br>   context: ./gotenberg<br>   dockerfile: Dockerfile<br>  ports:<br>   - 80:3000</pre><p>I ran `amplify push`, got another DeploymentAwaiter error, removed an API to clear any potential consequences of previous `amplify push` runs, added it again, pushed and now Gotenberg is deployed!</p><h3>Second try (or Service is Unavailable problem)</h3><p>Now I was able to connect to our API with a URL that Amplify CLI printed to output, and it resulted in Service Unavailable error, so…</p><p>Fast-forward another half a day me reading the same one-page guide for serverless containers from above and playing the same “Spot 5 differences!” game with ExpressJS + Flask template. In the end I noticed that in the template ExpressJS has port 8080 and Flask — 5000 e.g. no service is exposed at 80 port… Also in the guide it says that all services of API are deployed as a single Fargate instance, so obviously there are a lot of distinctions from how services are deployed via Docker itself and via Amplify CLI.</p><p>So I decided to do a weird thing once more and despite that I want the API to be available on 80 port make port mapping like 3000:3000 (and also add both private and public networks like in template just in case) and it worked! I can now access Gotenberg and utilize all its features! Hooray!</p><p>But at what cost? (c)</p><h3>Conclusion</h3><p>After all it was a little hard experience since the guide itself references official Docker documentation, but the basic knowledge of it actually leads the user to errors with unclear error messages. Overall the feeling is that if you code exactly the way that Amplify templates say everything kinda work, but one step left or one step right and you are lost. I don’t think that I’ll use in production AWS Amplify Serverless Containers at least for now, but I’ll keep an eye on it.</p><p>All the code mentioned here you can find in my <a href="https://github.com/vorant94/amplify-serverless-containers">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba9e2e87a6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Branding an Angular app with Docker volumes and CSS3 variables]]></title>
            <link>https://vorant94.medium.com/skin-replacement-in-angular-after-image-build-bfeb7d2be3f6?source=rss-43cbfe87d5bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfeb7d2be3f6</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[Mordechai Dror]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 19:06:42 GMT</pubDate>
            <atom:updated>2023-01-31T20:59:10.869Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hi, there! My name is Mordechai and it is my first post here. I thought what to write about and came up with an idea of sharing small tips and tricks which made my life as a developer a little bit easier, so here am I.</em></p><h3>The problem</h3><p>When you develop an app that is meant to be hosted on customer environment and you have several customers each customer will probably request to have its own theme for the app, which consists of set of images and colors that fit these images. And we are not talking here about runtime theme switch by user like light/dark theme, we are talking about environment theme, about branding of the app.</p><p>The first option here can be to set up separate build script for each environment and take advantage of replacing files at build time via Angular CLI Builder just like it replaces environment.ts with environment.prod.ts by default. Something like this:</p><pre>&quot;architect&quot;: {<br>  &quot;build&quot;: {<br>    &quot;configurations&quot;: {<br>      &quot;customer-1&quot;: {<br>        &quot;fileReplacements&quot;: [<br>          {<br>            &quot;replace&quot;: &quot;path/to/file/in/development/mode&quot;,<br>            &quot;with&quot;: &quot;path/to/file/in/build/for/customer-1/mode&quot;<br>          }<br>        ]<br>        ...<br>      }<br>      ...<br>    }<br>    ...<br>  }<br>  ...<br>}</pre><p>And it is totally working as a solution, but have a couple of problems:</p><ol><li>In order to Angular CLI Builder to work you need to keep all sets of theme assets near your code, for convenience right inside app’s repository, which means that a lot of files that are not used 99% of development time for some reason are indeed stored in source code.</li><li>You need to set up separate build for each customer, as number of them grows up number of build configs grows up too. Most likely you are using some CI/CD tool like Jenkins or CircleCI, so number of jobs there is also grows up.</li><li>Also most likely you are containerising you app with Docker using for example NGINX or Apache, so the number of images on your probably private registry will also grow up (as well as it’s cost) since literally the same app but with different image sets takes up to *number of customers* images in it.</li></ol><p>So here is my proposal, which is easy not only to implement but also to scale with time: <strong>things like environment theme assets need to be replaced after build </strong>using for example Docker volumes. As already mentioned above theme can consist of images and styles, so let’s take it one by one: how to replace images and how to replace styles.</p><h3>How to replace images</h3><p>Let’s say we want to replace the following image in our app</p><pre>&lt;img src=&#39;./assets/theme/background.png&#39;&gt;</pre><p>In order to replace it we can we can use Docker volumes as I already mentioned before. And since images are only files and nothings more there is no bicycle to invent, the syntax of docker-compose.yml can be as follows. The only thing I can advise here is to create a folder to store all theme related images so there will be no need to create new volume for each new themed image</p><pre>version: &#39;3.1&#39;</pre><pre>services:<br>  ng-app:<br>    container_name: ng-app<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    ports:<br>      - &quot;4200:80&quot;<br>    volumes:<br>      - ng-app-theme:/usr/share/nginx/html/assets/theme</pre><pre>volumes:<br>  ng-app-theme</pre><p><strong>/usr/share/nginx/html </strong>— is just a path where the app lives in order to be served by NGINX</p><p><strong>/assets/theme</strong> — is a location of our theme inside of app. Remember that files in the volume must have the same name as in repo in order to replace them.</p><h3>How to replace styles</h3><p>This one is a little bit trickier but we can nail it. Many modern CSS frameworks have their own theme set-up and most likely use one of CSS preprocessors like SASS or LESS. So we may have one general file with all of SASS/LESS variables that needs to be replaced, but only in development, not after build. After the build is done there is no such file, only compiled vanilla CSS code. We could somehow parse these files in order to replace values of each variable with the new one, but it is hard to implement and it has its own downsides.</p><p>The answer here is a vanilla CSS variables. Since they have pretty much good browser support except for IE11 (who cares about IE anyway?) why not to use them? And even if you do need to support IE11 there is a <a href="https://github.com/nuxodin/ie11CustomProperties">polyfill</a> for it.</p><p>If you don’t use CSS frameworks which relies on preprocessors you are good to go to use CSS variables all over your styles, store their config in separate file and replace it as I’ll describe below. But if you do use frameworks with preprocessor, you need to provide your framework variables as well e.g. backward compatibility, so instead of using CSS variables by their own you probably should consider use them to set framework variables as follows:</p><pre>$styled-text-color: var(--styled-text-color);</pre><p>And of course you need to provide a file where you configure all default values and which can be replaced after build. You could use another theme.css file for it, but when you do so there is a chance to make some mistake which will lead to file to be merged into style.css so there will be nothing to replace after build. In order to avoid it 100% I would like to use a theme.js file here</p><pre>var root = document.documentElement;</pre><pre>root.style.setProperty(&#39;--styled-text-color&#39;, &#39;blue&#39;)</pre><p>and add it manually to index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&#39;en&#39;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&#39;utf-8&#39; /&gt;<br>  &lt;title&gt;SkinReplacementAfterBuild&lt;/title&gt;<br>  &lt;base href=&#39;/&#39; /&gt;<br>  &lt;meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1&#39; /&gt;<br>  &lt;link rel=&#39;icon&#39; type=&#39;image/x-icon&#39; href=&#39;favicon.ico&#39; /&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;app-root&gt;&lt;/app-root&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre>&lt;script src=&#39;./assets/theme/theme.js&#39;&gt;&lt;/script&gt;</pre><p>So with all this set up we have our default theme in theme.js and what we should do here is to add a modified copy of this file into our Docker volume. Since we are storing all theme files in one directory e.g. one volume there is no need to change docker-compose.yml</p><h3>Conclusion</h3><p>This solution not only allows us to get rid of dozens of files inside our repository, but we also now can have only one build and only one image in Docker registry for all of our customers. Also since Docker volumes have a lot of different drivers theme files can be stored not only locally on customer server, but on another dedicated host. And all we’ve done is just a couple of lines of code. The only thing I want to add in conclusion is a simple check list of what we’ve done to achieve desired behaviour:</p><ol><li>We’ve placed al theme related files into separate directory so there will be only one volume in docker-compose.yml</li><li>We’ve created theme.js in this separate directory, which sets up all theme related CSS vanilla variables.</li><li>In case we are using CSS framework, which relies on preprocessor, we’ve refactored its variables file to use our own CSS variables instead of simple values.</li><li>We’ve configured docker-compose.yml to mount a volume with the different set of images and different theme.js so the default styles will be overridden by it inside the container</li></ol><p>That’s all, thank you for attention and see you later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfeb7d2be3f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>