<?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 Willie Streeter on Medium]]></title>
        <description><![CDATA[Stories by Willie Streeter on Medium]]></description>
        <link>https://medium.com/@will.streeter?source=rss-ce37b550d506------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uDQwfylymOiT48TKUKsqDA.png</url>
            <title>Stories by Willie Streeter on Medium</title>
            <link>https://medium.com/@will.streeter?source=rss-ce37b550d506------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:08:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@will.streeter/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[I Let AI Write 50 Stories and Build a Full App. Here’s What I Got Wrong.]]></title>
            <link>https://medium.com/willsonic/i-let-ai-write-50-stories-and-build-a-full-app-heres-what-i-got-wrong-ab793a0214b0?source=rss-ce37b550d506------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab793a0214b0</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Willie Streeter]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 17:30:08 GMT</pubDate>
            <atom:updated>2026-06-17T17:33:11.281Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a serial: <a href="https://medium.com/@will.streeter/twenty-years-building-products-then-i-realized-i-was-the-product-49cf479ca499">to catch up , read part 1<em>:</em><strong><em>Twenty Years Building Products. Then I Realized I Was the Product</em></strong><em>.</em></a></p><p><em>An honest account of my first experiment with autonomous AI development. What worked, what didn’t, and the lesson that changed how I think about building software.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt5e_OcCizSntigGTTM-9g.jpeg" /></figure><p>The studio I’m building runs on a hypothesis: that one person, with the right systems thinking and the right tooling, can produce software at a scale that used to require a full team. The model I have in mind is not a fully dark factory where machines run without oversight. Call it a <em>Dim Factory</em>, where a human provides direction, taste, and structural guardrails while an autonomous pipeline handles implementation. The aspiration is to keep learning how close to truly autonomous that loop can get.</p><p>There is a growing segment of the AI development world working on exactly this problem: how do you organize work for autonomous agents in a way that is structured and repeatable? How do you give a machine enough context to build a real system without holding its hand through every decision? Methodologies are emerging, and I had been exploring one I believed had potential. This build was the first time I put it to a serious test.</p><p>The portal is the operational backbone of the studio. It is where client work lives: onboarding, project management, concept delivery, feedback, and sign-off, all inside a single interface built around a structured delivery loop. What makes it complex is not the feature count but what those features need to do together: a commenting engine for threaded feedback on specific work, artifact uploads, multiple rings of access control separating what an admin sees from what a client sees from what a guest reviewer sees, and a visual lifecycle for moving a project from brief to delivered concept, with version history and audit trail behind it. This is the system the studio needs to operate at a real client scale, and it is being built from the start with room to grow.</p><h3>BMAD vs BAD: The Distinction That Matters</h3><p><a href="https://docs.bmad-method.org/">BMAD</a> is the methodology I had been working with. The approach is straightforward: break the project into epics and user stories, assign them to an AI agent, and execute one story at a time with me in the loop at every handoff. I was still making the calls, still reviewing before anything moved forward. That is assisted development, not autonomous development.</p><p><a href="https://github.com/stephenleo/bmad-autonomous-development">BAD</a> changes the dynamic entirely. Background Agentic Dispatch introduces a coordinator layer: instead of a single agent executing stories while I watch, the coordinator spins up worker agents, manages parallelism, handles sequencing, and passes context between tasks without returning to me for approval. I give it an epic and step back. The pipeline takes it from there.</p><p>This was my first real BAD run. Whether I could genuinely step back and trust the pipeline to carry it was the experiment.</p><h3>What the Build Actually Felt Like</h3><p>The first day I sat watching, second-guessing permissions, waiting for something to break. Then the agent started explaining its own reasoning and I started to let it go. There was a rough patch with the git workflow that took a few correction cycles to stabilize, and I had to buy more inference mid-run when the token burn hit. At some point I set up a remote connection on my phone and went for a walk. Not because I had to, but because I could. The agent was running, epics were getting completed, and pull requests were being drafted, reviewed, and merged without me sitting at a keyboard. By the end it wasn’t pausing for me. It was just running.</p><h3>The Moment of Truth</h3><p>When all 50 stories were complete, I opened the app.</p><p>The sidebar links returned 404 errors. Routes either threw 500 errors or did nothing at all. When I clicked through to the projects page, there was no real interface waiting for me. Sometimes a page title. Sometimes a blank screen. Sometimes a 500 error where a navigation step should have been. There was no logical thread connecting one part of the app to the next, no visual or cognitive path that told you where you were or where you were supposed to go. Each system the agent had built existed somewhere in the codebase, but none of it surfaced in a way a human could actually move through. I couldn’t log in as a client at all because Clerk wasn’t configured correctly. The admin dashboard I had described in the spec didn’t exist. There was a route and a sidebar link pointing to something that was never built.</p><p>My first thought was: what the hell is this?</p><p>I had talked to Claude for hours about what I was building. How did it build all of this and not know what it was?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvAPl5DawtnX_PU-CINzug.jpeg" /></figure><h3>What Actually Worked</h3><p>Here’s the thing: the backend was correct.</p><p>Once I started poking at it, tracing errors, migrating tables, checking routes, I found real, working code underneath. The data model was right. The three-layer architecture I had specified, Data, Business, and View, had been respected throughout. Business logic was correct. API contracts were correct. The test suite came back with 2,067 passing tests, lint clean, and CI green throughout the entire run.</p><p>For anyone skeptical that autonomous execution produces real code, the test file is the answer. Open it and run it. What came back was not a prototype. It was a real, tested, production-quality system. That part worked completely.</p><h3>What Failed. And Why.</h3><p>What I found underneath the broken surface was a system that had been built correctly but had never been told what it was for.</p><p>None of that was the agent’s fault. The agent built exactly what the stories said, and the stories described systems. The spec told it to build the auth system, the project management system, the concept delivery system. It did all of that. What the spec never said was: when an admin logs in for the first time, what do they see? When a client clicks on a project, what happens? What does success look like after a form submits?</p><p>The agent put all the structure in place but had no instruction for what that structure was supposed to mean to a human being moving through it. I had run a previous build where I felt I had over-invested in UX detail and it slowed things down, so this time I backed off deliberately. I thought Shadcn and Tailwind would give the agent enough to improvise the interface.</p><p>Anyone who has spent time as a developer on a team knows what it feels like to get a ticket with nothing in it but a title. No description of what is broken, no explanation of where in the application the problem lives, no definition of what the correct behavior is supposed to be. I have been in those rooms, asking the project manager to tell me what this ticket actually means, what I am supposed to be fixing and why.</p><h3>The Lesson</h3><p>What I came away with is a distinction that seems obvious in retrospect but took a broken app to actually understand. A system is something a machine can build from a precise enough description of its parts. A product is something a human has to be able to move through, understand, and use to accomplish something real. Those are not the same brief, and they do not produce the same output.</p><p>BAD built the system correctly. What it could not do was invent the product that the system was supposed to become, because nobody had written that down. The fix was not a better pipeline. It was a better spec, one that described the human experience of the thing, not just the technical structure underneath it.</p><h3>What We’re Trying Next</h3><p>Phase 2 looked different from the start. Before a single story was dispatched, I built a route map: every page in the application, its purpose, and who was supposed to see it, admin views, client views, and guest views, each ring of access accounted for before any implementation began. From that map came a light spec for each route, not exhaustive UX documentation but enough experience intent that the agent knew what a human was supposed to encounter when they landed there. Each screen went out as a dispatch, came back, and got reviewed in the browser before the next one went out. This was not an autonomous pipeline. It was a <em>Dim Factory</em>, me and the agent working through it together, with me providing the direction and judgment at every stage.</p><h3>Where This Goes</h3><p>The portal backend is solid. Smoke testing is complete and Phase 2 is running now with the new approach. What I have learned through both phases is that the <em>Dim Factory</em> model is more within reach than it is out of reach, but it requires more from the person running it than I initially understood. The spec is not just a planning document. It is the brief that determines whether the agent builds a system or a product, and getting that brief right turns out to be the hardest part of the process.</p><p>Like most things in this space, the reality is more complicated than the promise. But complicated does not mean impossible. I am forging ahead, and the next article will tell us whether Phase 2 delivered what Phase 1 could not.</p><p><em>Will Streeter is the founder of Tasty Maker Studio, a product studio focused on building the interaction that proves the idea works. This is the second in a series documenting what happens when you try to run a one-person Dim Factory.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab793a0214b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/willsonic/i-let-ai-write-50-stories-and-build-a-full-app-heres-what-i-got-wrong-ab793a0214b0">I Let AI Write 50 Stories and Build a Full App. Here’s What I Got Wrong.</a> was originally published in <a href="https://medium.com/willsonic">will.streeter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twenty Years Building Products. Then I Realized I Was the Product.]]></title>
            <link>https://medium.com/willsonic/twenty-years-building-products-then-i-realized-i-was-the-product-49cf479ca499?source=rss-ce37b550d506------2</link>
            <guid isPermaLink="false">https://medium.com/p/49cf479ca499</guid>
            <category><![CDATA[ux-design]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Willie Streeter]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 22:58:31 GMT</pubDate>
            <atom:updated>2026-06-17T17:33:26.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnKSI6-q0qunEV5MAPDk0Q.jpeg" /></figure><p>I started as a literature major.</p><p>That surprises people when I tell them now. But reading was never just pleasure. It was pleasure and construction at the same time, learning how an author organized a set of ideas so they would mean something to another person, not just communicate to them but actually land. That instinct, figuring out how to put things together so they make meaning for someone else, is what eventually pulled me toward software. I just didn’t understand that yet.</p><p>After I graduated, I went into teaching, working as an AmeriCorps teacher in a communication arts program in the inner city of San Francisco. That’s where Noc Sonic came from. The students I worked with were rappers and vocalists, people who needed a platform to record over beats, and I thought I could build it. I didn’t have the technical skills yet, so I went back to school and earned a degree in software engineering.</p><p>The plan was to develop the craft at a 9–5 and tinker on Noc Sonic in the spare time, learning by doing and building the skill through real employment while keeping the project alive.</p><p>My first job was at a user-generated video startup, one of the first platforms letting people upload and share content publicly. I was building video playback applications and working with something new at the time, single-page applications with JavaScript. I was tasked with evaluating frameworks, choosing one, implementing it. That was my first real experience making architecture decisions.</p><p>When that chapter ended, I took some time off and built a working prototype of NocSonic. The development part I had. The distribution part, the networking, selling an idea to the right people, I couldn’t crack it. I walked away.</p><p>Then I moved into a large healthcare organization. I was charged with defining how Angular 2 would be adopted across both the local team and the offshore team, not just implementing the framework but scaffolding the organizational approach for how an entire engineering operation would take it on. That’s where the layered architecture thinking crystallized. A pattern using observables to separate the view layer from the business logic from the data layer. Clean separation meant teams could develop independently, build new views without rebuilding the whole stack, and hand a new developer a codebase they could find their way around.</p><p>I applied the same principle at a product optimization company. Different codebase, different team, same result. Separation is what enables coordination.</p><p>Then came the one that tested everything. A massive international software suite, used by properties across the globe, maintained by developers spread across multiple countries, built ad hoc over more than a decade with no clean architecture and years of decisions stacked on top of each other. My job was to bring React into that system without stopping operations. The answer was WebPack Federated Modules, consuming the legacy code inside the new React application and converting section by section. Rebuilding the airplane while it’s flying. It worked. I was proud of that.</p><p>The pattern is obvious in hindsight. Every role, I was solving the coordination problem: how do multiple people build something together without chaos, how do you migrate a system without breaking it, how do you scale a codebase across teams that don’t communicate? I was always good at those problems. But I was always one layer removed from the product itself, from the decision about what to build and why.</p><p>I was building inside someone else’s vision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31IFg9Wh-J44nePLK6nvtA.jpeg" /></figure><h3><strong>What Changed</strong></h3><p>At some point I stopped thinking about what I could build and started thinking about what I was.</p><p>I had spent twenty years helping product owners and creators architect their ideas into scalable code. I had always worked closely with designers and UX professionals, translating their concepts into scaffolding that could actually support them. That was a specific set of skills, developed and refined across two decades of real systems work. Why not offer it as a service? Why not move further up the stack?</p><p>Around that same time, I enrolled at DesignLab’s UX Academy. Not to become a designer, but to develop the judgment: when is something right, what’s missing, what does a UX problem look like before it becomes a code problem? That judgment had always been adjacent to my work. I was ready to own it directly.</p><p>And I was watching AI coding agents change in real time. They had moved from junior developer level to senior developer level in the span of a couple of years, not in hype but in actual capability, in the quality of what they were producing. When that shift clicked, something else clicked with it.</p><p>The silos that had defined my entire career, front-end, back-end, product thinking, design, QA, were collapsing. One person, with the right systems thinking and AI as the multiplier, could hold all of it. I had spent my career solving the coordination problem across those silos from inside one of them. What if I could stand above all of them?</p><p>That’s what Product Inception Specialist means. Not a hybrid title. A recognition that the walls between those disciplines are coming down, and someone with judgment on both sides can own the entire inception of a product.</p><h3><strong>The Bet</strong></h3><p>There’s an African proverb: if you want to go fast, go alone, and if you want to go far, go together. I understand what going together means inside a corporation. I’ve done it for two decades. But in a corporation, together comes with costs that go beyond coordination. You lose control of the direction. The purpose gets divided among too many competing priorities. What you’re actually building stops being the point.</p><p>I’m betting on a third path. A small, autonomous operation with enough throughput to go far and enough focus to stay fast, where the purpose stays intact because you never hand it over.</p><p>I’ve been right before about where architecture was going. This is me testing whether those same instincts carry into the AI era. It’s not just a business bet. It’s an architectural thesis.</p><p>I walked away from corporate stability because I saw a window, and I don’t know how long it stays open.</p><h3><strong>The Studio</strong></h3><p>Taste is the thing AI will never have, the empathy to understand what someone is trying to make, what it should feel like, what’s missing. That’s the human layer, the judgment that sits at the center of every product decision. The studio is where that judgment meets AI production capacity.</p><p>The vision is a machine shop, tooled up and running efficiently, producing real things for real customers at lower cost and in less time than the alternative, but with real craft and real skill behind every decision. One operator, AI agents running the stations, enough throughput to do serious work without a large team.</p><p>The work starts simple: branding sites, interactive prototypes, the kind of working code a stakeholder can actually feel rather than just see. Then it moves toward MVPs, real products built for real people. The first things I’m building to prove this model works are the sites that represent the studio itself.</p><h3><strong>Why the Portal Comes First</strong></h3><p>Before I could build for clients, I started building a product of my own, something voice-based and AI-powered, built for a UX community I’ve been getting to know from the inside. I’ll say more about it in a later article. For now, just know it exists and that it’s the end goal.</p><p>But before I could get far with that product, I hit a systems wall. I realized I didn’t have a clear platform for working with clients, a communication layer, a place where work could be delivered and managed at the level I was describing. I needed that foundation first.</p><p>So the first real test of this model is a client portal, a delivery system for client work, built using autonomous AI execution: I write the specs, an AI pipeline handles the implementation, I review the output. I am a week and a half into that process right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-gc6Ae-73yrLqOAm6L6sA.jpeg" /></figure><h3><strong>Why I’m Writing This Publicly</strong></h3><p>This is not a retrospective. I am not writing this after it worked. I’m writing it while it’s happening, because that’s what makes it worth reading.</p><p>I want to show how the sausage gets made, the real version, the one where I don’t know yet how it comes out. The stakes are real. I walked away from corporate stability because I saw a window and because I believe I have the right combination of skills to walk through it. That makes this worth documenting.</p><p>So this is the first entry: who I am, what I’m betting on, and why I’m writing it down as I go.</p><p>The portal build is next. Follow along.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49cf479ca499" width="1" height="1" alt=""><hr><p><a href="https://medium.com/willsonic/twenty-years-building-products-then-i-realized-i-was-the-product-49cf479ca499">Twenty Years Building Products. Then I Realized I Was the Product.</a> was originally published in <a href="https://medium.com/willsonic">will.streeter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Web Development and Architecture]]></title>
            <link>https://medium.com/willsonic/practical-web-development-and-architecture-26a37d04c10f?source=rss-ce37b550d506------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a37d04c10f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Willie Streeter]]></dc:creator>
            <pubDate>Mon, 12 Jun 2017 01:10:25 GMT</pubDate>
            <atom:updated>2017-06-13T21:40:48.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqLD1YSw1aMKVsyeYp83aQ.jpeg" /><figcaption>My Machine is better than yours!</figcaption></figure><p>The basic purpose of any web site, like all software products, is to facilitate the processing and presentation of data. As the volume and intricacy of data grows, the challenge becomes how to best present the data in a meaningful and engaging manner. Quality software architecture is often perceived by the resulting scalability and how adaptable the system is to an expansion of capabilities without the need for constant refactoring. The efficiency with which developers of varying skill levels can meet these challenges is dependent on how quickly and precisely they can intuit optimal places within the code to implement various types of logic on sets of data.</p><p>In my experiences, adhering to a few basic concepts has served me well in my development endeavors both as individual and as a leader of a team:</p><ul><li><strong>Advocate a code structure emphasizing a separation of concerns between a view-layer, service-layer, business-layer and data-layer</strong></li><li><strong>As much as possible keep business logic away from the UI</strong></li><li><strong>Store and maintain data, especially global State data, in the data-layer no matter where it originates.</strong></li><li><strong>Prevent direct references from the view-layer to the data-layer</strong></li></ul><h3><strong>Good fences make good neighbors</strong></h3><p>Robert Frost’s poem, “<a href="https://www.poetryfoundation.org/poems-and-poets/poems/detail/44266">Mending Wall</a>”, can be interpreted as a contemplation between two neighbors on the rationale for maintaining a fence between their properties. Applying this adage ‘<strong>Good fences make good neighbors</strong>’, as a metaphor for software development is quite appropriate. Like any successful building effort, the first step begins with creating a strong foundation. In my professional experiences as software developer, building a infrastructure for optimal growth always begins by organizing the initial division of the code into a “<strong>separation of concerns</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*au7V9XbaJ-aKd32j6KdGUA.png" /></figure><p>Frequently during a project’s inception, distinguishing concerns are primarily focused on the most broad aspects of bringing a product to market. The development and planning regarding technology is centered around how devices will present the product, where and how the services will be delivered to the devices, and how artifacts and data produced by the application will be stored and retrieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*-gDadcTHKfOQZr-j9F0mwQ.png" /></figure><p>While these ‘<em>macro</em>’ structure concerns are usually the domain of a development operations team, the ‘<em>micro</em>’ decision regarding how the code will be structured for optimal scalability are made by developers who create and maintain the code base.</p><h4>He is all pine and I am apple orchard.</h4><p>Keeping business logic separate from the visual aspects of the user interface is essential to building a scalable, nimble application, loosely coupled to each of its major parts. In fact, from my experiences the number one reason many application development efforts fall into a continual state of refactoring, becoming big monolithic waste lands, is due to global State data and business processes becoming conflated with the code used to implement the visual aspects of components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*VLOXe7bTN5m0n6wzxEIp3A.png" /><figcaption>Model View Controller</figcaption></figure><p>Most seasoned developers are familiar with the concept of <strong>Model View Control</strong> ( MVC ). Perhaps the proliferation of this pattern is due to its seemingly simplistic approach of separating abstract concerns into a perceptible structure of directories of each concern, often labeled Model(<strong>data-layer</strong>), Views(<strong>presentation-layer</strong>), and Controller (<strong>service-layer</strong>). However, the use of MVC as a universal methodology for structuring code is often the cause of quite a few foundational mishaps. If the <strong>service-layer</strong> is the sole mechanism for bridging a <strong>view-layer</strong> with a <strong>data-layer, </strong>it often begins to inherit the responsibility of implementing business rules as well. Problems arise when logic used for processing cross-cutting concerns or business rules in a <strong>service-layer </strong>become intrinsic to a particular service. It is often the case that the logic inevitably needs to be shared with other services. Usually this means a direct references between the services or logic in one services is duplicated in other services as a short cut for sharing. These compromises will eventually<strong> </strong>detract or even prevent scalability.</p><p>The first and best choice for the placement of business logic is in the back-end where it is closest to the origination of the data. Here, all subscribers to the data, no matter how they intend on consuming the data, will consume the same results of a business process. If placement of business logic in the back-end is not possible, then processing these concerns in a <strong>business-layer</strong> in the front-end is the next best option.</p><p>Most modern back-end application frameworks, especially ones providing asynchronous RESTful api services do not have to contend with the same nuances of State as browser based applications. Back-end applications have a singular responsibility when handling a change request to the current State. Often these responsibilities, do not included ensuring all connected consumers are aware of the change. Even when this is so and a back-end application has been extended to encompass the responsibility of broadcasting State, it handles the duties in a disinterested manner, unconcerned for how or even if the changes are applied by the consumers. Maintaining a division of concerns in applications on the back-end is important. However, the challenge is often based upon separating the implementation of business rules for re-use by multiple consumers. Keeping the <strong>service-layer</strong> DRY (don’t repeat yourself), while efficiently suppling access to cross-cutting concerns to enable a fluid processing of request.</p><p>Concerns for interacting with a data-storage system should be segregated to a ‘<strong>data layer</strong>’. Cross-cutting concerns, such as security and data accessibility needs, often impervious to strict separation, should reside with in the <strong>business-layer</strong>. Controllers<strong> </strong>in the<strong> service-layer </strong>are best kept as thin processors directing traffic based on simple conditions derived from the <strong>business-layer </strong>and the<strong> data-layer</strong>.</p><p>In many front-end JavaScript browser based applications, business logic is implemented in controllers that can easily become sources of monolithic code structures. Controllers with unique responsibilities become intrinsically connected to other controllers with an entirely different set of responsibilities for the sole purpose of sharing global State or business processes. The first step in developing a solution in front-end applications, is to place the processes for managing shared State in separate services that can be injected or imported into controllers.</p><p>However, it is often not enough for controllers just to have a reference to a service that can supply global state on instantiation. Depending on when the controller is instantiated, it may not be able to harness the latest changes to State or if the State changes occur while the controller is instantiated it will not be able to update its components unless some apparatus has been created to provide constant awareness of the changes. If the apparatus providing State awareness is implemented as a service with a direct reference to a <strong>data-layer, </strong>then the component<strong> </strong>can not stand alone, but must be deployed with the <strong>data-layer</strong> as well. When this occurs, it becomes increasingly difficult to maintain and expand the capabilities of an application without constant refactoring or branching of the code. This intractable complexity not only stifles time to market, but in the worst case it can cause catastrophic failure.</p><h4>Something there is that doesn’t love a wall</h4><p>With the rise of <strong>Single Page Applications</strong> written in JavaScript and built for browser consumption, developers are often susceptible to the bad practices of conflating concerns. Tools such as <a href="https://mustache.github.io/"><strong>Mustache Templates</strong></a> and <a href="http://handlebarsjs.com/"><strong>Handle Bars</strong></a><strong> </strong>support the process of conditional logic in the markup which encourages short-term gains in convenience over long term viability. Press for time constraints or just a lack of foresight, developers inject functional programming process in HTML and manipulate CSS to expedite a course of business logic. This behavior seems to have increased exponentially with the adoption of Angular 1.</p><p>As many Angular developers took to the concept of <strong>Model-View-View Model</strong> (MVVM ), which often turned out to be <strong>Model-View-Whatever? </strong>(MVW). Not only did business logic make its way into template markup but scalability problems became compounded by the concept of Angular 1’s <a href="https://docs.angularjs.org/guide/scope"><strong>$scope </strong></a><strong>.</strong></p><blockquote>“Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events..”</blockquote><p>In the worst architectural practices, <strong>$scope </strong>becomes the repository of global model data needed across the application rather than just localized data sets between a view and a controller or directive. Components and Services become inextricably linked in order to get access to specific $<strong>scope</strong>.</p><p>While Angular 1 offered conditional logic for markup and provided synchronization of the data State between a controller and a view, it did not offer an equivalent feature for propagating global state across an application. Encapsulating presentational components and services that are able to maintain cognizance of an application’s changing global State became the preoccupation of most Angular developers.</p><h4>We have to use a spell to make them balance:</h4><p>In time, many Angular 1 developers began developing various procedures for creating synchronicity between global data State and the controllers and directives of the <strong>service-layer.</strong> One remedy, that I adopted with great success in several architectural efforts, is a structure that projects an independent component (<em>controller/directive/template</em>) by using a <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern"><strong>Publish and Subscribe</strong></a> (<strong>PubSub</strong>) pattern. Utilizing this type of ‘<a href="https://github.com/google/guava/wiki/EventBusExplained"><strong>eventbus</strong></a>’ system to decouple components from direct references to global State data services, the creation of a <strong>view-layer</strong> made up of encapsulated components can be facilitated. Using this approach, a <strong>business-layer</strong> contains <strong>PubSub</strong> apparatus which is the only reference a <strong>view-layer </strong>has to interacting with global State data. The <strong>view-layer</strong> has no direct reference to services in the <strong>data-layer </strong>or services in the <strong>business-layer. </strong>The<strong> data-layer </strong>is<strong> </strong>relegated to handling data transactions to a remote server and managing the global State of data, which is only accessible by the <strong>business-layer</strong>. The requirements for standing up a <strong>view-layer</strong> component are only dependent on a reference to the <strong>PubSub </strong>and only have the expectation of making simple request and receiving vanilla objects from the <strong>PubSub.</strong></p><p>With the popularity of <a href="https://facebook.github.io/react/"><strong>ReactJ</strong></a><strong>S </strong>over the last several years, a paradigm shift in the way developers structure single page JavaScript applications has occurred. ReactJS garnered much attention through its implementation of a <a href="https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom"><strong>Shadow DO</strong></a><strong>M</strong> (virtual DOM) that works in tandem with <a href="https://jsx.github.io/"><strong>JSX</strong></a> ( a javascript extension syntax responsible for rendering elements in the browser’s DOM.) However, I believe a greater contribution has manifested in the way ReactJS has promoted and formalized the process by which <a href="https://en.wikipedia.org/wiki/Web_Components"><strong>web components</strong></a> transact with the global state.</p><blockquote>Properties, a set of immutable values, are passed to a component’s renderer as properties in its HTML tag. A component cannot directly modify any properties passed to it, but can be passed callback functions that do modify values. This mechanism’s promise is expressed as “properties flow down; actions flow up”</blockquote><p>Some of the problems discussed earlier with regard to the detriments of <strong>view-layers </strong>becoming strictly coupled with <strong>data-layer</strong> are remedied with ReactJS adoption of <a href="http://redux.js.org/"><strong>Redux</strong></a><strong>, </strong>which<strong> </strong>has really served as a catalyst for a shifting developers approach to JavaScript application architecture. The Redux pattern implements a Store of immutable objects residing in a <strong>data-layer</strong>. The objects in the Store can only be changed by <strong><em>actions flowing up</em></strong><em> </em>from components, while the components attributes associated with the Store object can only reflect new values by <strong><em>properties flowing down</em></strong><em>. </em>Even though <strong>PubSub</strong> in Angular 1 architecture is an adequate solution for separating <strong>view-layer</strong> from a <strong>data-layer</strong>, the unformalized approach to both publishing and subscribing to changes of global state as well how the state is managed in a <strong>data-layer</strong> can inject a cumbersome level of complexity for developers as the application grows. Thankfully, with the release of a new modern <a href="https://angular.io/"><strong>Angular X</strong> ( at the time of this writing the version is 4.4.1)</a>, much of this complexity has been reduced.</p><p>Some key features of Angular X are the inevitable removal of <strong>$scope</strong> and the Controller class along with the addition of a Components class (the concept of Components was implemented in Angular 1.6). However, the most important new feature is the adoption of <a href="http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html"><strong>Observables</strong></a>, the focal point for working with <a href="http://reactivex.io/rxjs/"><strong>ReactiveX (RxJS)</strong></a>. The concept of Observables seems to be an out growth of JavaScript’s built-in-object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"><strong>Proxy</strong></a>, formally <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe"><em>Object.observe</em></a>. Other frameworks, such as <a href="http://www.javascriptmvc.com/"><strong>JavaScriptMVC</strong> </a>(<a href="https://canjs.com/"><strong>CanJS</strong></a> / <a href="https://donejs.com/"><strong>DoneJS</strong></a>), <a href="https://www.emberjs.com/"><strong>Ember</strong></a>, and <a href="http://knockoutjs.com/"><strong>KnockoutJs</strong></a>, were early proponents of the ‘<strong>observable</strong>’ concept, implementing a method of constantly observing a model data set. Using Observables in Angular X, allows components to stay up to date with global data without demanding an implementation of an apparatus such as Promises and routing resolves. Even more exciting is the adoption of a Redux pattern for managing global data State using the <a href="https://github.com/ngrx"><strong>NGRx</strong></a> library. Listed as resource in the <a href="https://angular.io/resources/">Data Libraries section of the Angular website</a>, I believe NGRx’s set of tools will become such a prominent feature of Angular X applications that it may eventually become integrated as a standard part of the framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*yGVvi-zglu6bmcX66Udonw.png" /></figure><p>While NGRx and Observables add a monumental boost to the architecture of Angular X applications, I still believe using <strong>PubSub</strong> in conjunction with NGRx and Observables can offer substantial gains toward a more definitive “<strong>separation of concerns</strong>”, especially between the <strong>view-layer</strong> and <strong>data-layer.</strong></p><h3>Lessons learned and Practices adopted</h3><p>I have experimented with many front-end javascript frameworks over the years. Dabbling with Dojo, bending over backwards with BackBone, following to the mercy of JQuery with JavascriptMVC, finding salvation with CanJS/DoneJS and Zepto, and getting onboard with Angular. No matter how familiar I am with a framework and the expected final deliverable of a development effort, taking the time upfront to assess how the “<strong>separation of concerns</strong>” will be applied to a given framework before coding has served me well. It has enabled me to become quite adept at building prototypes which progress into productions applications conducive to growth without refactoring.</p><p>More importantly, as I have gained experience and assumed responsibility in developing and managing teams as a Principal front-end developer and a Web Architect, I must approach application architecture with the assumption that I will not be the only developer to maintain and expand the application. I must consider how the division of architectural concerns will be associated with the various skill sets of individual developers so as to maximize their output. It is often the desire, or precisely the demand, for new developers to begin contributing immediately. Of course “on boarding” becomes much smoother and successful when good documentation exist and an integrated working environment can easily be replicated. Even still, a factor probably the most consequential to overall team development, is the time it takes new developer to accurately assess how data flows and connects each “<strong>separation of concern</strong>” within the application architecture. The larger and more monolithic an application the longer it takes to perceive the inherent dependencies. With decoupled modules, code development can occur without a developer having to know all the intricacies of an entire application architecture. This is especially useful when on boarding new developers, regardless of their skill level. When a new developer has to spend the first 6 weeks figuring out the entire breath of an application’s code base just to modify model data and html markup in component, the arrival of a new developer can become stultifying for both the team and the new developer.</p><p>Over the next couple of articles, I will present examples of how I have implemented the concept of a “<strong>separation of concerns</strong>” in a browser based application and NodeJS application. I will also demonstrate a method of crafting an integrated development environment with <strong>Docker</strong> that is easily adaptable.</p><p><a href="https://medium.com/@will.streeter/docker-is-my-i-d-e-d6dc84cca26d"><strong>Docker is my {I.D.E} </strong></a><strong>:</strong> demonstrate how the front-end, back-end, database, and web server (NGINX) are bundled together with Docker Compose to facilitate a FullStack i<strong>ntegrate development environment</strong>.</p><p><a href="https://medium.com/@will.streeter/optimal-angular-pubsub-with-ngrx-4faab11eb293"><strong>Optimal Angular : PubSub With NGRx</strong></a> : A simple front-end application enabling a user to register, login, and view protected content. This is accomplished using the<strong> Angular (4.1.x)</strong> , a <strong>PubSubBrok</strong>er apparatus and the <strong>NGRx (Redux pattern).</strong></p><p><a href="https://medium.com/@will.streeter/swagger-nodejs-typescript-tsoa-15a3f10fabaf"><strong>Swagger, NodeJS, &amp; TypeScript : TSOA</strong></a><strong>: </strong>A back-end application built with the latest <strong>NodeJS (7.9.+)</strong> utilizing <strong>Express</strong>, developed with <strong>TypeScript</strong>, employing <strong>TSOA</strong> for generating <strong>Swagger UI</strong>, and retrieving and storing data in a <strong>Mongo</strong> data-store through <strong>Mongoose</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a37d04c10f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/willsonic/practical-web-development-and-architecture-26a37d04c10f">Practical Web Development and Architecture</a> was originally published in <a href="https://medium.com/willsonic">will.streeter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger, NodeJS, & TypeScript : TSOA]]></title>
            <link>https://medium.com/willsonic/swagger-nodejs-typescript-tsoa-15a3f10fabaf?source=rss-ce37b550d506------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a3f10fabaf</guid>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Willie Streeter]]></dc:creator>
            <pubDate>Mon, 12 Jun 2017 01:08:14 GMT</pubDate>
            <atom:updated>2017-06-13T21:42:07.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuxeW6aUbG0UtbJF52JFEw.png" /></figure><p>The following exposition is part of a series of articles concerning, <a href="https://medium.com/@will.streeter/practical-web-development-and-architecture-26a37d04c10f"><strong>Practical Web Development and Architecture</strong></a>. This article continues to focus on the theme, ‘<strong>separation of concerns</strong>’, demonstrating how the concept can be applied to a NodeJS server application development using the example <a href="https://github.com/WillStreeter/ws-node-demo"><strong>ws-node-demo</strong></a>. The development of the front-end application <a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a>, a consumer of the NodeJs application is explained in the the article <a href="https://medium.com/@will.streeter/optimal-angular-pubsub-with-ngrx-4faab11eb293"><strong>Optimal Angular : PubSub With NGRx</strong></a><strong>. </strong>Both front-end and back-end applications are bundled as a <strong>FullStack</strong> integrated development environment using <a href="https://www.docker.com/"><strong>Docker</strong></a>, which is delineated in the article<a href="https://medium.com/@will.streeter/docker-is-my-i-d-e-d6dc84cca26d"> <strong>Docker is my {I.D.E}.</strong></a></p><p>The <strong>ws-node-demo</strong> application reviewed in the article was written in TypeScript, utilizing the <a href="https://expressjs.com/"><strong>Express</strong></a> framework to establish a web server infrastructure. It supports User authentication with <a href="https://github.com/auth0/node-jsonwebtoken"><strong>JWT (jsonwebtokens</strong></a><strong> ) </strong>and communicates with a Mongo database by way of the <a href="http://mongoosejs.com/"><strong>Mongoose</strong></a> object modeling services. Documentation for the REST API is created with <a href="https://github.com/lukeautry/tsoa"><strong>tsoa</strong></a><strong>,</strong> a tool providing scaffolding of code and generation of <a href="https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/json/petstore.json"><strong>Swagger JSON</strong></a><strong> </strong>for showing RESTful documentation of the application with <a href="http://petstore.swagger.io/"><strong>Swagger UI tools</strong></a>.</p><p><em>I developed the back-end with NodeJS and a Mongo data store, using a series of Docker containers with Docker Compose. If you are unfamiliar with Docker or want to run the application without Docker, you can do so by cloning it and building with standard NPM commands found in the </em><a href="https://github.com/WillStreeter/ws-node-demo/blob/master/package.json"><strong>package.json</strong></a><em> file. However, you must install Mongo on your client machine in order for the application to properly function. If you roll with Docker, then grab the entire ecosystem from </em><a href="https://github.com/WillStreeter/basic-ng2-docker-dev"><strong><em>here</em></strong><em>.</em></a></p><h3><strong>Why use TypeScript ?</strong></h3><p>Using TypeScript to develop a NodeJS application provides the same type of code base across the entire stack. There are many nuances and ‘<em>out of the norm</em>’ steps needed to develop JavaScript in the classical object-oriented manner offered in languages such as Java , Python, C++, Visual Basic .NET, Ruby, and ActionScript. TypeScript provides “strongly typed” declarations, which provide better precision and performance than writing in JavaScript. As s a superset of JavaScript, TypeScript must be compiled in order to be loaded as JavaScript in the browser and/or the NodeJS ecosystem.</p><p>One important concept to remain cognizant of when developing with TypeScript for browser and/or NodeJs, is how 3rd party libraries are imported. NPM library packages needed in a typical NodeJS application can often be located by creating a search term that proceeds the name of the package with ‘<strong><em>@types/’</em></strong>, as in ‘<strong><em>@types/express</em></strong>’ on the NPM site. Many of the most popular NPM packages written in JavaScript like <strong>Express</strong> can be imported in the<strong> package.json</strong>’s <strong>dependencies</strong> listing, which should also be included in the <strong>devDependencies.</strong></p><p>Remember, the final distributed version of the <strong>NodeJs</strong> application will be consumed as<strong> Javascript </strong>not <strong>TypeScript.</strong></p><pre><strong>&quot;dependencies&quot;</strong>: {<br>  <strong>&quot;express&quot;</strong>: <strong>&quot;^4.14.0”,<br>  </strong>...<br>}</pre><p><em>Added to the package.json </em><strong><em>devDependencies</em></strong></p><pre>&quot;devDependencies&quot;: {<br>    &quot;@types/express&quot;: &quot;^4.0.30&quot;,<br>  ...<br>}</pre><p>With the advent of the <a href="https://github.com/DefinitelyTyped/DefinitelyTyped"><strong>DefinitelyTyped</strong></a> library, the number of developers using TypeScript has gained momentum over the past year, and thus, the <strong>DefinitelyTyped </strong>repo, which anyone can contribute to0, contains hundreds if not thousands of directories that are used to wrap existing libraries written in JavaScript. The <strong><em>@types/express </em></strong>package used in the application can be found <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express"><strong>here</strong></a> (<a href="https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express">https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express</a>)</p><h3>Itinerary</h3><ul><li><strong>Development Set Up: </strong>Summarize the development tools and configuration.</li><li><strong>App Directory Configuration:</strong> Comprehensive description of the contents and approach to the structure of the application directories.</li><li><strong>Processing Data</strong>: Brief summation on the code pattern and how it can support optimal developer output.</li><li><strong>Document Generation</strong>: using ‘<strong>tsoa</strong>’ to scaffold the application and generate documentation.</li></ul><h3>Development Set Up</h3><p><a href="http://swagger.io/"><strong>Swagger</strong></a><strong>,</strong> a part of the <a href="https://www.openapis.org/#"><strong>Open API Initiative</strong></a><strong>, </strong>provides a set of tools to describe and document a RESTful api. In theory, the idea of code generation sounds great, but thus far I continue to find it somewhat lacking. While the generation of code may not be a fruitful endeavor, the documentation, <a href="http://petstore.swagger.io/"><strong>Swagger UI</strong></a><strong>,</strong> produced from the Swagger Schema <strong>( swagger-api.yaml/swagger-api.json)</strong> is an invaluable resource.</p><p>Over the last several years there have been a number of open-source projects created to unify the orchestration Swagger documentation and code scaffolding, such as <a href="http://apigee-127/swagger-tools"><strong>swagger-tools</strong></a>. Like other initiatives of this sort, the process always begins and ends with the proficiency of the Swagger schema created from the outset of the project. Quite frequently, I find, as the nuances of the Swagger schema become more complex, accurate code generation becomes hampered if not impossible.</p><p>Thus, I was pleasantly surprised to discover <a href="https://github.com/lukeautry/tsoa"><strong>tsoa</strong></a>, created by Luke Autry. Instead of first creating a Swagger Schema in order to generate the code scaffolding, <strong>tsoa</strong> reverses the process by generating the final Swagger Schema from the code created. Some code generation or updating does take place, but the majority of the code is created by the developer. This process provides the most valuable asset: sound documentation and testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*ESIJQ5ZI4hvjcHWXp2JvhA.png" /><figcaption>Top Level Root NodeJs and 2nd Level directory</figcaption></figure><h3><strong>App Directory Configuration</strong></h3><p>The directory structure of the application emphasizes an architectural approach based on a “<strong>separation of concerns</strong>”:</p><p><strong>src/data-layer/ </strong>: responsible for organizing how the data will be stored and accessed.</p><ul><li><strong>adapters</strong> : implements the set up of <a href="http://mongoosejs.com/">Mongoose</a> for connecting to a Mongo database.</li><li><strong>data-abstracts </strong>: delineates both the Schemas representing the structure of each Mongo Collection and the Documents representing each set of data in the Collection.</li><li><strong>data-agents </strong>: implements the query transactions against the data store for each particular collection</li><li><strong>model </strong>: contains a Typescript class representing the definition of the data portrayed by the Document.</li></ul><p><strong>src/business-layer/ </strong>: implementation of business logic and other resources need by the <strong>service-layer </strong>and/or <strong>middleware</strong></p><ul><li><strong>security : </strong>contains apparatus for creating tokens and processing security checks on specific API request.</li><li><strong>validators : </strong>contains schema and processing logic for validating data sent with API request.</li></ul><p><strong>src/service-layer/ </strong>: contains the processes for establishing API endpoints in the form of routes which will facilitate responses to data request.</p><ul><li><strong>controllers : </strong>serve as the basis for processing data request associated with <strong>routes</strong>. The custom controllers (<strong>User</strong> and <strong>Authorization</strong>) extend <strong>tsoa</strong> controllers, using decorators to associate router endpoints to specific functions exposed in each of the controllers. These functions, commonly referred to as <strong>C.R.U.D. </strong>(create, read, update, and delete) implement the basic <strong>GET, POST, PUT, PATCH, and DELETE</strong> processes for transacting with RESTful api.</li><li><strong>request : </strong>contains TypeScript <strong>interfaces</strong> representing the attributes that make up each of the various types of <strong>request</strong>.</li><li><strong>response : </strong>contains TypeScript <strong>interfaces</strong> representing the attributes that make up various types of <strong>responses</strong>.</li></ul><p><strong>src/presentation-layer/ </strong>: contains the presentational views offered by the application.</p><ul><li><strong>documentation</strong> : contains the <strong>Swagger-UI</strong> files and directories facilitating the display and mechanisms for making REST based API calls and presenting the responses.</li></ul><p><em>*Since the responsibility of this NodeJs application is essentially providing data against request, there are no other views but documentation.</em></p><p><strong>src/middleware/ </strong>: contains resources to establish the server configuration as well as a place to store utility processes shared across the application.</p><ul><li><strong>common</strong> : currently contains the instantiation of the ‘logger’ that can be shared across the application</li><li><strong>server-config</strong> : contains vendor specific implementation of the node server framework vendor, ‘<strong>Express</strong>’ as well as the all important ‘<strong>routes’ </strong>configuration<strong> </strong>organizing the REST API endpoints.</li></ul><p><strong>A brief explanation on configuration files</strong></p><p><strong>src/server.ts</strong> : initializes our web server with our chosen NodeJs framework, <strong>Express</strong>.</p><p><strong>package.json</strong> : serves as the manifest in all NodeJs application, specifically delineating external libraries required for building the application in the ‘<strong>dependencies</strong>’ and ‘<strong>devDependencies</strong>’ section and providing a ‘<strong>scripts’</strong> section provides commands necessary for <strong>building</strong>, <strong>running</strong>, and <strong>packaging.</strong></p><p><strong>src/types.ts</strong> : As previously mentioned, <strong>package.json</strong> external libraries should accurately portray what will be included in both development and production modes. However, it may be the case that a TypeScript definition does not exist for a desired JavaScript package. In such cases, the <strong>types.ts </strong>file can be used to declare libraries we would like to use as is the case with ‘<strong>express-winston’</strong> used with in the logging apparatus.</p><p><strong>tsconfig.json</strong> : provides options for TypeScript when it performs the task of compiling to JavaScript.</p><p><strong>tslint.json</strong> : provides a listing of rules that can be applied against the code to maintain formatting standards.</p><p><strong>src/server-config</strong>: contains the core infrastructure for instantiating the web-server.</p><p><strong>tsoa.json</strong> : establishes the various locations of files needed to generate the <strong>swagger.json</strong>, which will eventually be used to by the <strong>Swagger UI</strong> to represent the API documentation. A couple of key configurations are</p><ul><li>listing the Security definitions which will be used to signify protected data access</li><li>hosting and domain configurations, the directory path to place the output of our TypeScript compilation, as well as the label ‘/api’ used to signify the handling and processing of request data rather than other kinds of resources.</li><li>the all important route configuration is use to identify the file used to stand up the web-server application, the location of the directory where the <strong>routes.ts</strong> can be found, and finally where the file(s) reside used in conjunction with our security apparatus are located.</li></ul><h3>Processing Data:</h3><p>The primary responsibility of most web-servers is to accept and process request from clients; to this end the data flow in our application request reflects this purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*mVANZPVjG2Vd-qn-0nkBxg.png" /><figcaption>High-level flow of an API request to the NodeJs application</figcaption></figure><p>1 API request to <strong>GET</strong> a specific User based on the id of the User is sent to the server:</p><pre>http://localhost:8080/api/Users/591cc1bc2b9622b151c9a68a</pre><p>The <strong>routes.ts</strong> file located in the middleware directory captures the request base on the URI <strong>‘/api/Users/:userId’</strong></p><pre>//middleware/routes.ts<br>....<br>app.get(<strong>&#39;/api/Users/:userId&#39;</strong>, <em>authenticateMiddleware</em>(<strong>&#39;api_key&#39; </strong>),<br>    <strong>function</strong>(request: <strong>any</strong>, response: <strong>any</strong>, next: <strong>any</strong>) {<br>        <strong>const </strong>args = {<br>            <strong>userId</strong>: {      <strong>&quot;in&quot;</strong>: <strong>&quot;path&quot;</strong>, <br>                         <strong>&quot;name&quot;</strong>: <strong>&quot;userId&quot;</strong>, <br>                     <strong>&quot;required&quot;</strong>: <strong>true</strong>, <br>                     <strong>&quot;typeName&quot;</strong>: <strong>&quot;string&quot; <br>                    </strong>},<br>           <strong>authentication</strong>: { <br>                          <strong>&quot;in&quot;</strong>: <strong>&quot;header&quot;</strong>, <br>                        <strong>&quot;name&quot;</strong>: <strong>&quot;x-access-token&quot;</strong>, <br>                    <strong>&quot;required&quot;</strong>: <strong>true</strong>, <strong>&quot;typeName&quot;</strong>: <strong>&quot;string&quot;<br>                    </strong>}<br>        };<br><br>        <strong>let </strong>validatedArgs: <strong>any</strong>[] = [];<br>        <strong>try </strong>{<br>            validatedArgs = <em>getValidatedArgs</em>(args, request);<br>        } <strong>catch </strong>(err) {<br>            <strong>return </strong>next(err);<br>        }<br><br>        <strong>const </strong>controller = <strong>new </strong>UsersController();<br><br><br>        <strong>const </strong>promise = controller.GetUserById.apply(<br>                    controller, validatedArgs);</pre><pre>        <strong>let </strong>statusCode = undefined;</pre><pre>        <strong>if </strong>(controller <strong>instanceof </strong>Controller) {<br>            statusCode = (controller as Controller).getStatus();<br>        }</pre><pre><em>promiseHandler</em>(promise, statusCode, response, next);<br>    });<br>....</pre><pre><strong>function </strong><em>authenticateMiddleware</em>(name: <strong>string</strong>, scopes: <strong>string</strong>[] = []) {<br>    <strong>return </strong>(request: <strong>any</strong>, response: <strong>any</strong>, next: <strong>any</strong>) =&gt; {<br>        <em>expressAuthentication</em>(request, name, scopes).then(<br>         (user: <strong>any</strong>) =&gt; {<br>            set(request, <strong>&#39;user&#39;</strong>, user);<br>            next();<br>          }).catch((error: <strong>any</strong>) =&gt; {<br>                response.<strong>status</strong>(401);<br>                next(error)<br>            });<br>    }<br>}</pre><pre><strong>function </strong><em>promiseHandler</em>(promise: <strong>any</strong>, statusCode: <strong>any</strong>, response: <strong>any</strong>, next: <strong>any</strong>) {<br>    <strong>return </strong>promise<br>        .then((data: <strong>any</strong>) =&gt; {<br>                  ...<br>        })<br>        .catch((error: <strong>any</strong>) =&gt; next(error));<br>}<br><br><strong>function </strong><em>getValidatedArgs</em>(args: <strong>any</strong>, request: <strong>any</strong>): <strong>any</strong>[] {<br>  <strong>return <em>Object</em></strong>.keys(args).map(key =&gt; {<br>     <strong>const </strong>name = args[key].<strong>name</strong>;<br>     <strong>switch </strong>(args[key].<strong>in</strong>) {<br>        <strong>case &#39;request&#39;</strong>:<br>          <strong>return </strong>request;<br>        <strong>case &#39;query&#39;</strong>:<br>           <strong>return </strong><em>ValidateParam</em>(args[key], <br>                                request.query[name], <br>                                models, name)<br>   ....<br>}</pre><p>2 Since access of the data provided by this URI demands a User to have been Authenticated (logged in and allocated a token), the function <em>authenticateMiddleware(..).</em>.is executed first</p><pre><em><br></em><strong>function </strong><em>authenticateMiddleware</em>(name: <strong>string</strong>, scopes: <strong>string</strong>[] = []) {<br>    <strong>return </strong>(request: <strong>any</strong>, response: <strong>any</strong>, next: <strong>any</strong>) =&gt; {<br>        <em>expressAuthentication</em>(request, name, scopes) ..<br>          ...<br>   }<br>}</pre><p>calling the <em>expressAuthentication() method </em>which resides in the <strong>business-layer/security/Authentication.ts</strong> file. Using the new “<a href="https://medium.com/@tsmith18256/async-await-in-node-js-v7-a9386b44e115"><strong>async</strong></a>” capabilities of NodeJs, the method is established as Promise chain and will thus return a Promise indicating whether the User has a valid token.</p><pre><strong>await </strong>authService.getAuthById(payload.<strong>userId</strong>);</pre><p>While the token can be verified without the use of a Promise, in order to ensure the User Id is valid and is associated with a logged in User, a request must be sent to the <strong>data store</strong>, which does require a Promise.</p><pre><strong>import </strong>{ AuthServiceCheck} <strong>from &#39;../../data-layer/data-agents/UserDataAgent&#39;</strong>;<br><strong>import </strong>{ IUserDocument } <strong>from &#39;../../data-layer/data-abstracts/repositories/user/IUserDocument&#39;<br>import </strong>{ <em>verifyToken </em>} <strong>from &#39;./token-helpers&#39;<br></strong><br><strong>let </strong>authService = <strong>new </strong>AuthServiceCheck();</pre><pre><strong>async function </strong><em>expressAuthentication</em>(request: express.Request, securityName: <strong>string</strong>, scopes?: <strong>string</strong>[]): Promise&lt;<strong>any</strong>&gt; {<br>  <strong>const </strong>token =  request.headers[<strong>&#39;x-access-token&#39;</strong>];<br>....<br>   <strong>const </strong>payload = <em>verifyToken</em>(token);<br>  ....<br>     <strong>let </strong>authResult = <strong>await </strong>authService.getAuthById(payload.<strong>userId</strong>);<br>     <strong>if</strong>(authResult &amp;&amp; !(authResult <strong>instanceof <em>Error</em></strong>)){<br>             ...<br>              <strong>return <em>Promise</em></strong>.resolve({ <strong>authorizedUser</strong>:<strong>true  </strong>});<br>          }<br>           ...<br>          <strong>return <em>Promise</em></strong>.reject( <strong>new <em>Error</em></strong>(<strong>&#39;jwt token malformed&#39;</strong>));<br>      }<br>};</pre><p>3 The <strong>UserDataAgent.ts</strong> located in the <strong>data-layer/data-agents</strong> provides all transactional access the data-store for storing and processing User based data.</p><pre><strong>async </strong>getUserById( userId:<strong>string</strong>):Promise&lt;<strong>any</strong>&gt;{<br>   ... <br>  return result<br>}</pre><pre><strong>export class </strong>AuthServiceCheck {<br><br>   <strong>userDataAgent </strong>=  <strong>new </strong>UserDataAgent();<br><br>   <strong>async </strong>getAuthById(userId:<strong>string</strong>):Promise&lt;<strong>any</strong>&gt;{<br>     <strong>return await this</strong>.<strong>userDataAgent</strong>.getUserById(userId);<br>  }<br>}</pre><p>4 If the User does not have a valid token or the User’s id can not be validated, the request will no longer progress through the rest of the application and a response indicating an error due to the lack of authenticity will be returned. However, if the authentication is valid, the request will continue to progress through the <strong>routes.ts</strong>, by next establishing an ‘<strong>args</strong>’ Object delineating the structure of the parameters that must accompany the URI request. This ‘<strong>args</strong>’ object will be verified by the ‘<em>getValidatedArgs(…)’ </em>method, which basically wraps ‘<em>ValidateParam(…)’ : </em>a function exposed by the ‘<strong>tsoa’ </strong>library.</p><pre><strong>function </strong><em>getValidatedArgs</em>(args: <strong>any</strong>, request: <strong>any</strong>): <strong>any</strong>[] {<br>  <strong>return <em>Object</em></strong>.keys(args).map(key =&gt; {<br>     <strong>const </strong>name = args[key].<strong>name</strong>;<br>     <strong>switch </strong>(args[key].<strong>in</strong>) {<br>        <strong>case &#39;request&#39;</strong>:<br>            <strong>return </strong>request;<br>        <strong>case &#39;query&#39;</strong>:<br>           <strong>return </strong>ValidateParam(args[key], request.query[name], models, name)</pre><pre> ...<br>}</pre><p><em>ValidateParam </em>method, essentially matches the<strong> ‘args’ </strong>object against the parameters delineated in th<strong>e swagger.json . </strong>If the parameters are deemed invalid, progress ceases and an error response is generated<strong>. </strong>When the parameters have been deemed valid, the request continues on to a controller (<strong>UserController</strong>.ts) in the <strong>service-layer.</strong></p><pre><strong>....<br>try </strong>{<br>    validatedArgs = <em>getValidatedArgs</em>(args, request);<br>} <strong>catch </strong>(err) {<br>    <strong>return </strong>next(err);<br>}</pre><pre><strong>const </strong>controller = <strong>new </strong>UsersController();<br><strong>const </strong>promise = controller.GetUserById.apply(controller, validatedArgs);<br>....</pre><p>5 The controller, in this case <strong>UserController.ts</strong>, calls the <strong>UserDataAgent.ts</strong>’s method<em> ‘getUserById(… )’</em> in the <strong>data-layer</strong> in order to retrieve data from the data-store (<strong>Mongo</strong>)<strong> </strong>associated with this particular User Id.</p><pre>@<em>Security</em>(<strong>&#39;api_key&#39;</strong>)<br>@<em>Get</em>(<strong>&#39;{userId}&#39;</strong>)<br><strong>public async </strong>GetUserById(userId: <strong>string</strong>, @<em>Header</em>(<strong>&#39;x-access-token&#39;</strong>) authentication: <strong>string </strong>): Promise&lt;IUserResponse&gt; {<br>   <strong>let </strong>result = <strong>await this</strong>.<strong>userDataAgent</strong>.getUserById(userId);<br>   <strong>if</strong>( result &amp;&amp; result.<strong>username</strong>){<br>          <strong>var </strong>aUser = <strong>new </strong>UserModel(result);<br>           <strong>return </strong>&lt;IUserResponse&gt;(aUser.getClientUserModel());<br>   }<strong>else</strong>{<br>      <strong>if</strong>(result){<br>          <strong>throw </strong>result;<br>      }<strong>else</strong>{<br>          <strong>throw</strong>{<br>               <strong>thrown</strong>:<strong>true</strong>,<br>               <strong>status</strong>: 404,<br>               <strong>message</strong>: <strong>&#39;no such user exist&#39;<br>          </strong>}<br>      }<br>   }<br>}</pre><p>Controllers in the <strong>service-layer</strong> not only provide access to the <strong>data-layer </strong>through <strong>Agents </strong>used for negotiating queries against the data-store, but controllers also can provide point of access to the<strong> business-layer</strong> to process business rules. While not used in the above method, one such case can be reviewed in the<strong> UserController.ts </strong>method <em>RegisterNewUser()</em></p><pre>@<em>Post</em>()<br><strong>public async </strong>RegisterNewUser(@<em>Body</em>()  request: IUserCreateRequest): Promise&lt;IUserResponse&gt; {</pre><pre><strong>let </strong>vaildationErrors:<strong>any</strong>[] = <strong>await     <br>                                </strong><em>validateUserRegistration</em>(request);<br>       .....<br>}</pre><p>Although the initial validation of necessary parameters is performed in the <strong>routes.ts</strong> implementation, a second round of validation is used to ensure the data defining the parameters for a new User passes specific standards. The ‘request’ parameter, which contains the data defining a new User, is processed by <em>validateUserRegistration(…) method </em>found in the <strong>UserValidation Processor.ts</strong> implementation located in the <strong>business-layer/validators</strong> directory.</p><pre><strong>async function </strong><em>validateUserRegistration</em>(userReqObj:<strong>any</strong>): Promise&lt;<strong>any</strong>&gt;{<br>  <strong>let </strong>validUserRegData = <strong>new </strong>UserValidationSchema(userReqObj);<br>  <strong>var </strong>regex = <strong>new <em>RegExp</em></strong>(<strong>&#39;^[A-Za-z0-9$]+$&#39;</strong>);<br>  <strong>let </strong>validationResults =  <strong>await </strong><em>validate</em>(validUserRegData);<br>  <strong>const </strong>badPW = regex.test(userReqObj.<strong>password</strong>);<br>  <strong>let </strong>constraints =[]<br>   <strong>if</strong>(validationResults &amp;&amp;  validationResults.<strong>length </strong>&gt; 0 || !badPW){<br>      <strong>if</strong>(!badPW){<br>        constraints.push({<br>          <strong>constraints</strong>: {<strong>isAlphanumeric</strong>: <strong>&quot;password must contain only<br>                                        letters and numbers and $&quot;  <br>                        </strong>},<br>            <strong>property</strong>:<strong>&quot;password&quot; </strong>});<br>        }<br>    forEach(validationResults, (item)=&gt;{<br>        constraints.push(pick(item, <strong>&#39;constraints&#39;</strong>, <strong>&#39;property&#39;</strong>));<br>     });<br>   }<br>   <strong>return </strong>constraints;<br>}</pre><p>6As previously described in <strong>step</strong> <strong>3</strong>, the <strong>UserDataAgents.ts</strong> method returns the results of the query on the User collection to find the User with the id initially supplied in the URI api request. Unlike the previous invocation of this method during the authentication process, we are looking for User ‘<em>id’</em> supplied as a parameter in the request rather than the User ‘<em>id’</em> of the entity making the request.</p><p>7 After completing the transaction with the data-store in the <strong>UserDataAgent.ts</strong>, a Promise in the form of a vanilla object is returned to the <strong>UserController.ts</strong> indicating failure or success. When a successful retrieval of a User with the given ‘id’ is achieved, the data associated with said User is constructed as a <strong>UserModel</strong> that will be resolved as an <strong>IUserResponse</strong> Promise to the <strong>routes.ts</strong>.</p><pre>@<em>Security</em>(<strong>&#39;api_key&#39;</strong>)<br>@<em>Get</em>(<strong>&#39;{userId}&#39;</strong>)<br><strong>public async </strong>GetUserById(....){</pre><pre><strong>if</strong>( result &amp;&amp; result.<strong>username</strong>){<br>       <strong>var </strong>aUser = <strong>new </strong>UserModel(result);<br>        <strong>return </strong>&lt;IUserResponse&gt;(aUser.getClientUserModel());<br>}<strong>else</strong>{</pre><pre>....</pre><p>If some mishap occurs in the processing of the query in the <strong>UserDataAgent.ts,</strong> such as a broken connection to the data-store, a result without the intrinsic ‘<strong>username</strong>’ will be returned which indicates an <strong>Error</strong> should be returned as the response. A similar <strong>Error</strong> response is created when the supplied ‘id’ does not exist for any User in the data-store. In either case, an <strong>Error</strong> will be <strong>thrown</strong>.</p><pre><strong>public async </strong>GetUserById(....){</pre><pre><strong>if</strong>( result &amp;&amp; result.<strong>username</strong>){<br>    ...<br>} <strong>if</strong>(result){<br>       <strong>throw </strong>result;<br>   }<strong>else</strong>{<br>        <strong>throw</strong>{<br>            <strong>thrown</strong>:<strong>true</strong>,<br>            <strong>status</strong>: 404,<br>            <strong>message</strong>: <strong>&#39;no such user exist&#39;<br>       </strong>}<br>   }<br>}</pre><pre>....</pre><p>8 Whether the <strong>UserController.ts</strong> result of processing the original request <strong>throws</strong> an <strong>Error</strong> or it is is successful, the <strong>routes.ts</strong> will handle the result in the <em>promiseHandler(…) </em>function<em>.</em></p><pre>app.<strong>get</strong>(<strong>&#39;/api/Users/:userId&#39;</strong>,<br>    <em>authenticateMiddleware</em>(<strong>&#39;api_key&#39;<br>    </strong>),<br>    <strong>function(...){</strong></pre><pre><strong>const </strong>promise = controller.GetUserById.apply(controller,       <br>                                              validatedArgs);<br><strong>...</strong></pre><pre><em>promiseHandler</em>(promise, statusCode, response, next);</pre><pre><strong>function </strong><em>promiseHandler</em>(promise: <strong>any</strong>, statusCode: <strong>any</strong>, response: <strong>any</strong>, next: <strong>any</strong>) {<br>    <strong>return </strong>promise<br>        .then((data: <strong>any</strong>) =&gt; {<br>        //handle successful responses <br>             <strong>if </strong>(data) {<br>                response.<strong>json</strong>(data);<br>                response.<strong>status</strong>(statusCode || 200);<br>            } <strong>else </strong>{<br>                response.<strong>status</strong>(statusCode || 204);<br>                response.<strong>end</strong>();<br>            }<br>         })<br>        //process thrown errors<br>        .catch((error: <strong>any</strong>) =&gt; next(error));<br>}</pre><p>9 If the response was successful, it is returned and no further process is implemented. However, if an Error exist and was thrown, the next(error) in the catch block pass the response to <em>clientErrorHandler(…) e</em>stablished in the <strong>server.ts</strong> as part of the node frame work initializing process.</p><pre><strong>function </strong><em>clientErrorHandler </em>(err, req, res, next) {<br>  <strong>if </strong>(err.hasOwnProperty(<strong>&#39;thrown&#39;</strong>) &amp;&amp; err.<strong>thrown</strong>) {<br>      res.<strong>status</strong>(err.<strong>status</strong>).<strong>send</strong>({ <strong>error</strong>: err.<strong>message</strong>})<br>  } <strong>else </strong>{<br>      next(err)<br>  }<br>}<br><br>nodeFrameWork.<strong>app</strong>.<strong>use</strong>(<em>clientErrorHandler</em>);</pre><p>This completes an example of how data flows through application and is processed base on a RESTful api request. Inherent in many back-end web server applications, is the inevitable <a href="https://en.wikipedia.org/wiki/Cross-cutting_concern"><strong>cross-cutting</strong></a>.</p><blockquote>Cross-cutting concerns are parts of a program that rely on or must affect many other parts of the system. They form the basis for the development of <a href="https://en.wikipedia.org/wiki/Aspect_(computer_science)">aspects</a>. Such cross-cutting concerns do not fit cleanly into <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented programming</a> or <a href="https://en.wikipedia.org/wiki/Procedural_programming">procedural programming</a>.</blockquote><p>Such is the case with the authentication process in the<strong> business-laye</strong>r that deviates from strictly accessing the <strong>data-layer</strong> from the <strong>service-layer</strong>. Perhaps, the <strong>routes.ts</strong> file may be suited for the <strong>service-layer</strong>, but as it seems to be a core structure in standing the server up it also makes sense for it location in the <strong>middleware</strong> directory. While delineation of a “<strong>separation of concerns</strong>” is not as emphatic, as might be achieved in a browser client application, a focus on specific processes is still plausible through the various layers and facilitates a more intuitive approach as the features of the application expand.</p><h3><strong>Document Generation</strong></h3><p>Creating the documentation of the RESTful api produced by the <strong>swagger.json</strong> and presented in the <strong>Swagger UI </strong>tool is automated through using the ‘npm run’ commands in the <strong>package.json</strong> .</p><p>To run the entire process:</p><pre><strong>$ npm run start</strong></pre><p>This will invoke p<strong>ackage.json</strong> “<strong>start</strong>” command in the ‘<em>script</em>’ section</p><pre><strong>&quot;start&quot;</strong>: <strong>&quot;npm-run-all -s clean build start:simple&quot;</strong>,</pre><p><strong>1st</strong> it wilrun the “<em>clean</em>” scripts:</p><pre><strong>&quot;clean&quot;</strong>: <strong>&quot;npm-run-all -p clean:*&quot;</strong>,<br><strong>&quot;clean:dist&quot;</strong>: <strong>&quot;rimraf dist&quot;</strong>,<br><strong>&quot;clean:cov&quot;</strong>: <strong>&quot;rimraf coverage&quot;</strong>,</pre><p><strong>2nd</strong> it will run the “build’ scripts,</p><pre><strong>&quot;build&quot;</strong>: <strong>&quot;npm-run-all -s build:swagger&quot;</strong>,<br><strong>&quot;build:swagger&quot;</strong>: <strong>&quot;npm run swagger-gen &amp;&amp; npm run routes-gen &amp;&amp; tsc &amp;&amp; npm run copy-swagger-ui&quot;</strong>,<br><strong>...</strong><br><strong>&quot;swagger-gen&quot;</strong>: <strong>&quot;tsoa swagger&quot;</strong>,<br><strong>&quot;routes-gen&quot;</strong>: <strong>&quot;tsoa routes&quot;</strong>,<br><strong>&quot;copy-swagger-ui&quot;</strong>: <strong>&quot;ncp ./src/swagger-ui ./dist/swagger-ui&quot;</strong>,</pre><ul><li>creating the <strong>swagger.json</strong> from the ‘<strong>swagger-gen</strong>’ command,</li><li>invoke the <strong>‘routes-gen</strong>’ command to reappraise the <strong>routes.ts</strong> file ensuring it has been configured correctly and the RESTful endpoint associations with particular controllers is valid.</li><li>the ‘<strong>tsc</strong>’ command will compile the TypeScript files into Javascript files using the <strong>“outputDirectory”</strong>: <strong>“./dist”</strong> attribute in the<strong> tsoa.json </strong>file to identify where resulting JavaScript files should be placed.</li><li>Finally the <strong>SwaggerUI</strong> directory implementing the client documentation portal, which resides in the <strong>presentation-layer/documentation,</strong> will be copied to the ‘<em>dist</em>’ directory that was created in the previous ‘<strong>tsc</strong>’ command.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*hk_BSOzfxWcmKmK0LoEZNA.png" /></figure><p>The Swagger UI client can be accessed at ‘http:localhost:8080/docs’, which was previously established in the <strong>tsoa</strong>.<strong>json</strong> file.</p><pre><strong>//tsoa.json<br>&quot;outputDirectory&quot;</strong>: <strong>&quot;./dist&quot;</strong>,<br><strong>&quot;entryFile&quot;</strong>: <strong>&quot;./src/server.ts&quot;</strong>,<br><strong>&quot;host&quot;</strong>: <strong>&quot;localhost:8080&quot;</strong>,<br><strong>&quot;basePath&quot;</strong>: <strong>&quot;/api&quot;</strong></pre><p>Once the page is Swagger UI can be loaded in the browser, a listing of t the available API commands can be viewed by clicking on the ‘<strong>default</strong>’ link. The result is presented below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*acNdIsbogZZmJyPCDJO7Bw.png" /></figure><p>To test the validity of an API request, select an api request such as<strong> POST /Users</strong>. The window should appear as below. In the request text box, the following object should process correctly as a valid user</p><pre>{<br>  &quot;username&quot;: &quot;taosing&quot;,<br>  &quot;password&quot;: &quot;password&quot;,<br>  &quot;firstname&quot;: &quot;fifty&quot;,<br>  &quot;lastname&quot;: &quot;cents&quot;,<br>  &quot;email&quot;: &quot;zip-zap@ez.com&quot;,<br>  &quot;admin&quot;: false,<br>  &quot;isLoggedIn&quot;: false<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*PFiitDVaG9KEsCPPVR10zw.png" /></figure><p>While running the single command is the easoest path toward correctly building and structuring the application, it is useful to review the process on the <a href="https://github.com/lukeautry/tsoa"><strong>‘tsoa’ GitHub</strong></a> page. As is the case in many development efforts, the tools rarely produce seamless results. It may be necessary to run <strong>tsoa</strong> commands individually in the beginning to understand exactly what is produced.</p><pre><strong>$ npm run swagger-gen</strong></pre><pre><strong>$ npm run routes-en</strong></pre><p>Hopefully, this article has provided insight regarding how a “<strong>separation of concerns</strong>” can be achieved in a NodeJS application. Thin Controllers in a <strong>service-layer</strong> relying on references to the <strong>business-layer </strong>and<strong> data-layer </strong>for<strong> </strong>implementing<strong> </strong>process demonstrates how such a structure can eliminate code duplication and enable the sharing of services between controllers. I also demonstrated the value of <strong>tsoa</strong> and how easily this tool facilitates a use of the <strong>Swagger UI</strong> for generating documentation is accomplished.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a3f10fabaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/willsonic/swagger-nodejs-typescript-tsoa-15a3f10fabaf">Swagger, NodeJS, &amp; TypeScript : TSOA</a> was originally published in <a href="https://medium.com/willsonic">will.streeter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker is my {I.D.E}]]></title>
            <link>https://medium.com/willsonic/docker-is-my-i-d-e-d6dc84cca26d?source=rss-ce37b550d506------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6dc84cca26d</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Willie Streeter]]></dc:creator>
            <pubDate>Mon, 12 Jun 2017 01:00:57 GMT</pubDate>
            <atom:updated>2017-06-13T21:41:43.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5a2BX2s6A1UhZ-up2MhXeQ.png" /></figure><h4>from a developer’s perspective</h4><p>In this post, I will describe how the <a href="https://www.docker.com/"><strong>Docker</strong></a> eco-system can be used to project an <a href="https://en.wikipedia.org/wiki/Integrated_development_environment"><strong>Integrated Development Environment</strong></a><strong> (IDE)</strong>. For readers, whose position in a software shop is that of Development and Operations (<strong>DevOps</strong>), please except my apologies for the brief definition of Docker and perhaps my tardiness with respect to the latest features. I am writing this from the perspective of <strong>FullStack</strong> developer, whose focus is primarily getting front-end applications , back-end applications , and various resources connected to facilitate code development. I will begin by using the <a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/Dockerfile.dev"><strong>Dockerfile</strong></a> in <a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a><strong> </strong>GitHub repository<strong> </strong>to provide an example for analyzing the configuration and reviewing the commands use to build and run it as a container. By the end of the article, I will demonstrate how Docker Compose is used in the <a href="https://github.com/WillStreeter/ws-dev-docker-example"><strong>ws-dev-docker-example</strong></a> GitHub repository to bundle multiple containers.</p><p>As delineated in <a href="https://medium.com/@will.streeter/practical-web-development-and-architecture-26a37d04c10f"><strong>Practical Web Development and Architecture</strong></a><strong>,</strong> the introduction posting to this series, one of the most consequential aspects of on-boarding developers is the amount of time it takes new developers to get an IDE in place for interacting with code. The progression of this initial introduction to a development team has improved greatly thanks to Docker; the <a href="https://blog.containership.io/a-history-of-container-technology">current manifestation of an initiative</a> started some twenty years ago and promoted by companies like Google around the concept <a href="https://en.wikipedia.org/wiki/Operating-system-level_virtualization"><strong>Operating-system-level virtualization</strong></a><strong>. </strong>Offering an implementation of this concept, <strong>Docker</strong> provides a machine<strong> (docker-machine) </strong>to install an engine <strong>(docker-engine) </strong>on host operating system, which enables the host to share its kernel with isolated containers (<strong>docker containers</strong>). Docker containers are the destination of an application like NodeJS and the various libraries need to support installation as well as run-time resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GUqa3XXaydHfVLXKkXiY9A.png" /></figure><p>The orchestration and scaffolding of Docker enables a local client ecosystem to be deployed to a production system with few modifications to the configuration of the local docker containers. Rather than drilling down in to specifics about what makes this possible, I am going to focus on implementing an ecosystem for development purposes on a client machine (<strong>MAC</strong>).</p><h3>Itinerary</h3><p><strong>Docker Set Up:</strong> summarize Docker installation and briefly explain a few configuration commands used in Docker file. Using Docker commands to build an image and run the image as a container.</p><p><strong>Helpful tips for debugging docker </strong>: briefly describe several ways of using docker-commands to debug the docker eco-system.</p><p><strong>Multiple Container Orchestration</strong>: demonstrate how a docker-compose file is configure to aggregate multiple containers running simultaneously.</p><p><em>As mention in the beginning of this post, this article was written to support an example of developing a FullStack application using NodeJs and Angular X (4.1.0 at the time of this writing). Each of the applications have their own Docker container. The entire set up of the environment employs a container of NGINX as well as a container for Mongo. For the purpose of this article, I will mostly focus on how, docker is configured and utilized for building the front-end Angular client.</em></p><h3><strong>Docker Set Up</strong></h3><p><strong><em>(The proceeding instructions are based on developing with Docker on a Mac.)</em></strong></p><p>To set up Docker on your client machine, visit the Docker site and go to the <a href="https://www.docker.com/community-edition"><strong>community edition</strong></a> page where you can download the appropriate version for your machine’s operating system. Upon your selection, you will have the choice of the ‘<strong>stable</strong>’ or ‘<strong>edge</strong>’. I suggest using the <strong>stable</strong> version. Information provided on the page will show you how to verify installation.</p><p><strong>From Docker Images to a Docker Container:</strong></p><p>Docker containers are built with Docker images, which is the case with the <a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a> that will be used to demonstrate this Docker based development. The images are publicly accessible on the <a href="https://hub.docker.com/u/willsonic/"><strong>Docker-Hub registry site</strong></a> but can be reviewed in my <a href="https://github.com/WillStreeter?tab=repositories"><strong>GitHub repositories</strong></a><strong> </strong>as well.</p><p>Those familiar with developing front-end applications will recognize that NodeJs needs to be used in a development environment for task running and to express a view of the application in a browser. There is often a need for libraries and <strong>SDKs </strong>to be installed in the actual operating system as well, and our Docker eco-system should be able to accommodate these needs. While those running the Docker container for <a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a> do not have to worry about how and what other images are accumulated to create the final image, offering insight into the process will serve as a good start to understanding how the Docker system functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GvOet0ZMyvo4Sz_AQMAE8w.png" /></figure><p>As NodeJs is a requirement, I begin with an image from Michael Hart, which can be found at <a href="https://github.com/mhart/alpine-node"><strong>mhart/alpine-node</strong></a> GitHub repo. Hart seems to keep relatively update with the latest NodeJs builds involving the <a href="https://alpinelinux.org/">Alpine linux distribution</a>.</p><ul><li><a href="https://github.com/WillStreeter/ws-node-alpine"><strong>ws-node-alpine</strong></a>: Use the the mhart/alpine image as a base in the Dockerfile, it will be customized by adding libraries not included with mhart/alpine. This image will be used in various other containers utilizing NodeJs.</li><li><a href="https://github.com/WillStreeter/ws-typescript-development"><strong>ws-typescript-devolpment</strong></a>: utilizing the base image produced by the <strong>ws-node-alpine, </strong>and adding several libraries to be globally installed such as the TypeScript compiler (tsc), Gulp, Yarn,Typings, and TSlint will form the base image of <a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a><strong>. </strong>Creating a new image this way, allows <strong>ws-node-alpine </strong>the possibility of being used by other containers that do not need these global libraries.</li><li><a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a>: contains our Dockerfile of concern, using the base image produced by <strong>ws-typescript-development, </strong>which is the accumulation of the previous images. Here is where the configuration of the front-end client will be implemented.</li></ul><p>Some may think <strong>ws-typescript-devolpment</strong> is an unnecessary step adding bloat, since TypeScript, Gulp and the other libraries can be globally installed on the client machine and then orchestrated with Docker to mount the results of task running. However, I have found it saves cycles by freeing up the dependency on developers to accurately set up client machines, ensuring global libraries are accessible with proper permissions. Even if the resulting image is large during development, it will not be the same image used in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OujbWwt6BTzvkvhemEL_0Q.png" /><figcaption>ws-ngrx-login-rep + Dockerfile.dev</figcaption></figure><p>While it is typical to find just one Dockerfile in a repositories, I have become accustom to creating Dockerfile.dev for development and a Dockerfile for production. A Dockerfile for production does not currently exits, as the intention is to demonstrate a development practice with Docker.</p><p><a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/Dockerfile.dev"><strong>Dockerfile.dev</strong></a><strong> break down</strong>:</p><pre>FROM willsonic/ws-ngx-development:v0.0.1</pre><p>Informs the Docker instance what image will be used to build the current effort.</p><pre>ENV UI_CLIENT_PORT 5555<br>ENV LIVERELOAD_UI_CLIENT_PORT 3001<br><br>EXPOSE $UI_CLIENT_PORT<br>EXPOSE $LIVERELOAD_UI_CLIENT_PORT</pre><p>Here we set up some environments variables and request the Docker container make certain ports available to the outside world.</p><ul><li><strong>UI_CLIENT_PORT</strong>: will provide the port used to view our application on client machine browser. <a href="http://localhost:5555/">http://localhost:5555</a></li><li><strong>LIVERELOAD_UI_CLIENT_PORT</strong>: will provide the <a href="https://www.browsersync.io/"><strong>BrowserSync</strong></a> Port http://localhost:3001 . Part of the BrowserSync implementation incorporates the ability for LiveReload in the browser. (as side note, BrowserSync is used to serve the html, css, images assets, and JavaScript files performing the duties which will be the responsibility of NGINX in a production environment)</li></ul><p>It is important to note that ENV variables are used in statements, which are executed while building an image. This means during run time when the image is used as a container, these variables will be of no use.</p><pre>RUN mkdir -p /app/dist \<br>  &amp;&amp; mkdir -p /app/tools \<br>  &amp;&amp; mkdir -p /app/resources \<br>  &amp;&amp; mkdir -p /app/node_modules \<br>  &amp;&amp; mkdir -p /app/src</pre><p>RUN is used to execute shell commands. Directories are created with <strong>mkdir</strong> command and will be preserved in the Docker container after completing the build process.</p><pre>COPY test-config.js /app/test-config.js<br>COPY test-main.js /app/test-main.js<br>COPY karma.conf.js /app/karma.conf.js<br>COPY protractor.conf.js /app/protractor.conf.js<br>COPY tslint.json /app/tslint.json<br>COPY package.json /app/package.json<br>COPY tsconfig.json /app/tsconfig.json<br>COPY tools /app/tools<br>COPY gulpfile.ts /app/gulpfile.ts<br>COPY src /app/src</pre><p><strong>COPY</strong> command copies files and directories from the client into the Docker image we are building. Without creating these directories in the previous <strong>RUN</strong> command, the files and directories created by the build process would not be present when running the image. The process of the <strong>COPY</strong> command facilitates mounting directories and files enabling changes to them on the client machine to propagate to the Docker container.</p><pre>WORKDIR /app</pre><p>This command establishes a directory that will serve as the root directory of the Docker container.</p><pre>RUN npm install &amp;&amp; gulp build.bundle.rxjs</pre><p>This command applies the ubiquitous ‘npm install’; the first step necessary to install packages needed to develop and run client side JavaScript frameworks. One of the critical task that also needs to be completed during set up of development environment is the placement of t<a href="http://reactivex.io/rxjs/">he <strong>ReactiveX Rxjs</strong></a> library. This is specific to our client application and the need for SystemJS to become aware of the the location of the <strong>Rxjs</strong> package. ( the double ampersands (&amp;&amp;) are used to chain <strong>RUN</strong> commands)</p><pre>CMD [&quot;npm&quot;,  &quot;start&quot;]<br><em>#ENTRYPOINT [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;while true; do sleep 1; done&quot;]</em></pre><p>The CMD command executes the package.json script</p><pre><strong>&quot;start&quot;</strong>: <strong>&quot;gulp serve.dev --color&quot;</strong>,</pre><p>The <strong>ENTRYPOINT</strong> command is currently commented out with the prefix “#”. The usage of this command will be explained later, when debugging methods are described.</p><p>A more detail explanation of these build process as well as other commands not used here can be found on the <a href="https://docs.docker.com/engine/reference/builder/"><strong>Docker commands reference page</strong></a>.</p><p><strong>Building and Running:</strong></p><p>Before we can run the images as a container, we must create an image. When we installed the Docker client, a command line interface (cli) was also installed. Execute the following command from the root of <strong>ws-ngx-login-demo-dev to </strong>build an image.</p><pre>$ docker build -t local-ws-ngx-login-demo-dev -f Dockerfile.dev .</pre><ul><li><strong>-t</strong> : uses ‘local-ws-ngx-login-demo-dev’ as a tag name for the image we are building.( <em>Since we could eventually have many images on our machine, possibly </em><strong><em>ws-ngx-login-demo-prod</em></strong><em> for production or staging etc, I like to create a </em><strong><em>tag</em></strong><em> (-t) name that accurately describes the image purpose.</em> )</li><li><strong>-f </strong>: points to the Dockerfile used to build the image <em>(Without the </em><strong><em>file</em></strong><em> (-f) option, Docker would assume the file name is the default </em><strong><em>Dockerfile</em></strong><em> . Since the production version of the file would be different, I have create a</em><strong><em> Dockerfile.dev</em></strong><em>. )</em></li><li><strong>. </strong>: the dot signifies that the image will be loaded into the registry on our client machine rather than a remote repository.</li></ul><p>After running the build command, we should eventually see a message suggesting the positive or negative result of the build execution.</p><pre>...<br>---&gt; 6e0d6dee5cbf<br>Removing intermediate container 8b8ae8cff7e1<br>Step 19/19 : CMD npm start<br>---&gt; Running in 52442749c401<br>---&gt; bf87702e0178<br>Removing intermediate container 52442749c401<br>Successfully built bf87702e0178<br>$</pre><p>(<em> note: it may take several minutes depending the speed of your connection, as we must download the other base images used by the ws-ngx-login-demo as well the current libraries listed in the packag.json</em>)</p><p>Executing the following command ‘<strong> docker images </strong>‘, we can see the resulting images we have created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*PSdmzYi7fu7R_OgiHe4v6A.png" /><figcaption>output from docker images</figcaption></figure><p>Now that the images necessary for running <strong>ws-ngx-login-demo</strong> have been constructed, we are prepared to run the image as a container. Before I run the image as a container, I will issue the <strong>‘docker ps -a</strong>’ command to see what containers are currently running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*z5WjqfPKFcJeCz02L0zmGw.png" /><figcaption>Before run containers..</figcaption></figure><p>The output demonstrates there are currently no containers running. This will change when we execute the following command:</p><pre>$ docker run --name ws-ngx-login-demo-container  -d -p 5555:5555  local-ws-ngx-login-demo-dev</pre><p>using the following options:</p><ul><li><strong>— name </strong>: a label to provide an identification of the container</li><li><strong>-d</strong> : enables the container to stop running or exit when the process that start the container ceases.</li><li><strong>-p</strong>: represent the ports we will use to access the container, which is also the port that the NodeJS will use to allow access to the web-server.</li><li><strong>local-ws-ngix-login-demo-dev</strong> : the name of the image we are running as a container.</li></ul><p>More information regarding the execution of the ‘docker run’ command can be found on the <a href="https://docs.docker.com/engine/reference/run/"><strong>Docker website</strong></a>. When we execute the command ‘<strong>docker ps -a</strong>’, we should see the following container running. While the CONTAINER_ID ( <strong>e2f045a6ae86</strong> ) may be different, the NAMES (<strong> ws-ngx-login-demo-container </strong>) should be the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*99BgL8rM7BApqIe282qIWw.png" /><figcaption>After executing command to run the image as a container.</figcaption></figure><p>Now if you open the browser to ‘ <a href="http://localhost:5555/#/"><strong>http://localhost:5555 </strong></a>’ the web application should appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3yzF9R6Ryb06HsEY9C0tVA.png" /><figcaption>ws-ngx-login-demo browser view</figcaption></figure><p>While the container is up an running, the LiveReload is <strong>not</strong> accessible. We are unable to get the browser to reload when we make changes to our code. There are different ways to accomplish this task. We will use a docker-compose.yml.</p><p>First stop the current container and then remove the container.</p><pre>$ docker stop ws-ngx-login-demo-container &amp;&amp; docker rm ws-ngx-login-demo-container</pre><p>When that is complete, run the container by executing the following command.</p><pre>$ docker-compose up</pre><p>This will enable us to run the application using the package.json ‘npm run start’ command, which executes our gulp task. Now we get the following</p><ul><li>application logging output</li><li>LiveReload facilitates the restarting of the application after making and saving changes to our code.</li><li>access to the BrowserSync portal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*tVTq7uc_fgHeFaS2YJut-w.png" /></figure><p>We can stop the container by simply pressing ‘Ctrl + C’ in the terminal, however the container will still be present. To both stop and remove the container, we either issues the previous ‘stop and rm(remove)’ or just execute the command:</p><pre>$ docker-compose down</pre><p>This command can be executed in the terminal after ‘Crtl + C’ or by opening another terminal and executing ‘docker-compose down’. ( I usually have 2 terminals open, one for bringing up a bundle of containers and another for taking them down.)</p><p>Before expounding on how docker-compose is used to orchestrate the entire suite of applications for developing on a <strong>FullStack</strong>, I will review some process I use for debugging Docker creation when my efforts go astray.</p><h3><strong>Helpful tips for debugging Docker</strong></h3><p><strong>Docker Image Building: </strong>I find it is necessary to remove images before rebuilding them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*5UkHCKdMbVTMz8-CzVUGgg.png" /></figure><p>Above is a view of my terminal after executing ‘docker images’. The ‘&lt;none&gt;’ under REPOSITORY is the output of an image that is broken or did not complete the process of building. We should remove the image by using the IMAGE ID ‘<strong>2d2fd0396d56</strong> ‘ and executing the following command.</p><pre>$ docker rmi 2d2fd0396d56</pre><p>Sometimes we may find the ‘rmi’ command will not respect our wishes and we need to prepend the image id with (‘ <strong>-f</strong> ’) a force option ‘docker rmi -f 2d2fd0396d56’. At other times we may be left with images that are impervious to our request, which are said to be ‘dangling’. To remove these images we can execute</p><pre>$ docker rmi $( docker images -q -f dangling=true)</pre><p><strong>Docker Container running: </strong>I have often found that if things go awry it will happen during this process. The first and most obvious choice is to simply review the log output displayed when we execute ‘docker-compose up’. If log output did not appear when executing the <strong>compose</strong> command or you want the logs from a specific container, try using the ‘docker logs command’</p><pre><em>$ docker logs [container id or name] </em></pre><p>If the logs are not accessible or offer no help, I have found the easiest way to figure out what is happening is to rebuild the image after changing the Docker files final <strong>CMD</strong> or <strong>RUN</strong> command with an <strong>‘<em>ENTRYPOINT</em>’ </strong>command. This will enable standing up the container in a stasis mode<strong>. </strong>When we execute the ‘<em>docker run’</em> command and it fails to start or exits immediately, we need to run the container without executing a final <strong>CMD </strong>or<strong> RUN </strong>command<strong>, </strong>which is more often than not the culprit of the failures<strong>.</strong> As I mentioned earlier, the Dockerfile.dev of this project, has a commented out line:</p><pre><em>ENTRYPOINT [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;while true; do sleep 1; done&quot;]</em></pre><p>This command will get the container running, in place of the <strong>CMD</strong> allowing us to access it and start investigating what may be breaking or not working correctly in our set up. To use this command, take the following steps:</p><p>1- Stop and Remove all the offending container</p><pre><em>docker stop [container id or name] &amp;&amp; docker rm [container id or name]</em></pre><p>2- When the offending container is no longer present, remove the image that was used to create the container by using the ‘<strong>docker rmi</strong> ‘ command. Once the image has been successfully purged, update the Docker file commenting out the <strong>CMD</strong> and uncommenting or inserting the <strong>ENTRYPOINT</strong> command with the instructions below</p><pre># Dockerfile.dev<br>...<br>#CMD [&quot;npm&quot;,  &quot;start&quot;]<br><em>ENTRYPOINT [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;while true; do sleep 1; done&quot;]</em></pre><p>3- After updating the Docker file, execute the build command to create the image. Once the image has been created, use the run command we initially executed to start the container, <strong>not the docker-compose up command.</strong></p><pre>$ docker run --name ws-ngx-login-demo-container  -d -p 5555:5555  local-ws-ngx-login-demo-dev</pre><p>4- To make sure the container has started, execute the ‘docker ps -a’ command and view the <strong>STATUS</strong> of the container. It should not say ‘<strong>exited</strong> ….’ but rather ‘<strong>Up</strong> ….’ . Now that the container is up, we can issue the following command to ‘<strong>ssh</strong>’ or way into the container, where we can start to do a better analysis of missing files or directories errors, etc.</p><pre>$ docker exec -it ws-ngx-login-demo-container sh</pre><p><strong>Short Cuts:</strong></p><p>I have found it is often a good idea to create <strong>Makefile</strong> of the Docker execution commands. Not only does this help in cutting down incorrect inputs and constantly searching history for previously used commands, but when working with a team who may not be as familiar with the Docker paradigm it can be a tremendous help.</p><pre>//Makefile for ws-ngx-login-demo<br>all:<br><br>CONTAINER_NAME = ws-ngx-login-demo-container<br>IMAGE_NAME = local-ws-ngx-login-demo-dev<br><br><br>build-dev:<br>   docker build -t $(IMAGE_NAME) -f Dockerfile.dev .<br><br>run-container:<br>   docker run --name $(CONTAINER_NAME) -d -p 5555:5555  $(IMAGE_NAME)<br><br>start:<br>   docker start $(CONTAINER_NAME)<br><br>stop:<br>   docker stop $(CONTAINER_NAME)<br><br>rm:<br>   docker rm $(CONTAINER_NAME)<br><br>up:<br>   docker-compose up<br><br>down:<br>   docker-compose down<br><br>logs:<br>   docker logs -f  $(CONTAINER_NAME)</pre><h3><strong>Multiple Container Orchestration:</strong></h3><p>This article is part of a series written to demonstrate an approach to FullStack development, <a href="https://medium.com/p/26a37d04c10f/edit"><strong>Practical Web Development and Architecture</strong></a>, which can facilitate optimal output with respect to both a scalable architecture as well as the coordination of efforts among the members of a development team.</p><p>Thus far, I covered building a single image for running a single container,using <strong>ws-ngx-login-demo </strong>as an example<strong>. </strong>I also demonstrated how to use Docker commands ‘<strong>docker-compose</strong>’ to run the container, while performing code development to instantly propagate the results of your efforts. In this section we will expand on how ‘docker-compose’ can be used to orchestrate development of several containers representing a <strong>FullStack</strong>. To this end, the bundling of the various containers can be found in the <a href="https://github.com/WillStreeter/ws-dev-docker-example"><strong>ws-dev-docker-example</strong></a>.</p><p>The bundle includes 4 GitHub repositories, which have been added as submodules.</p><ul><li><strong>ws-ngx-login-demo </strong>: an implementation of a front-end client built with TypeScript. A detail description of the architecture can be reviewed in the article,<a href="https://medium.com/@will.streeter/optimal-angular-pubsub-with-ngrx-4faab11eb293"> <strong>Optimal Angular : PubSub With NGRx</strong></a>.</li><li><strong>ws-node-demo </strong>: an implementation of back-end web-server using NodeJS, written with TypeScript. A detail description of the architecture can be reviewed in the article, <a href="https://medium.com/@will.streeter/swagger-nodejs-typescript-tsoa-15a3f10fabaf"><strong>Swagger, NodeJS, &amp; TypeScript : TSOA</strong></a>.</li><li><a href="https://github.com/WillStreeter/ws-mongo-demo"><strong>ws-mongo-demo </strong>:</a> a Dockerfile used to containerized instance of a Mongo Database used by <strong>ws-node-demo</strong> to store and retrieve data.</li><li><a href="https://github.com/WillStreeter/ws-nginx-demo"><strong>ws-nginx-demo</strong></a><strong> </strong>: contains an implementation of a NGINX web-server, providing a representation of how a <strong>FullStack</strong> application would be accessed in production. The name of each ‘service’ in the docker-compose file is proxied as a host in the <a href="https://github.com/WillStreeter/ws-nginx-demo/blob/master/etc-dev/nginx.conf"><strong>nginx.conf</strong> file.</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*dsNFrM_PS4EyPQ1eeQdLQg.png" /><figcaption>root directory for ws-dev-docker-exmaple and partial docker-compose.yml</figcaption></figure><p>The <em>docker-compose.yml</em> defines how multiple containers can be orchestrated to perform in unison with each other. For the purposes of this series and the example application provided, I have only using the <a href="https://docs.docker.com/compose/overview/#common-use-cases"><strong>Docker Compose</strong></a> process for building an integrated development environment. However, the entire ecosystem of the <em>docker-compose.yml</em> file and associated Docker files in each repo can be repurposed and packaged as a production deployable bundle.</p><h4>dock-compose.yml break down:</h4><p>As a <a href="https://en.wikipedia.org/wiki/YAML"><strong>YAML</strong></a> file type, docker-compose files must adhere to the YAML syntax rules, such as new line and tabs. The <a href="https://github.com/WillStreeter/ws-dev-docker-example/blob/master/docker-compose.yml"><strong>ws-dev-docker-example/docker-compose.yml</strong></a> declares Docker Compose format <strong>version</strong> ‘<strong>3</strong>’, which associates the process of the file to a specific version of the Docker Engine.</p><pre><strong>version: &#39;3&#39;<br>services:<br>  mongo:<br>        ...<br>  ws-node-demo:<br>        ...<br>  ws-ngx-login-demo:<br>        ...<br>  ws-nginx-demo:<br>        ...</strong></pre><p><strong>version: </strong>directs the docker-compose file to be process in association with a specific version of the Docker Engine.</p><p><strong>services</strong> : serves as a list in YAML parlance will be used to define each of the containers that will become a service. Services is 1 of 3 possibilities to create top level Docker Compose list (<a href="/service/ttps://docs.docker.com/compose/compose-file/#service-configuration-reference"> <strong>services</strong>, <strong>networks</strong>, and <strong>volumes</strong></a>).</p><p><strong>mongo</strong> , <strong>ws-node-demo, ws-ngx-login-demo , ws-nginx-demo: </strong>represent a second level YAML list of titles. Each perspective title in the list is used to express a set of definitions that will be applied to each instance of the associated container.</p><pre>//contents of the docker-compose service node for <strong>ws-ngx-login-demo</strong></pre><pre><strong>ws-ngx-login-demo:<br>  restart: </strong>always<br>  <strong>container_name: </strong>ws-ngx-login-demo-container<br>  <strong>build:<br>    context: </strong>./ws-ngx-login-demo<br>    <strong>dockerfile: </strong>./Dockerfile.dev<br>  <strong>image: </strong>local-ws-ngx-login-demo-dev:latest<br>  <strong>command: </strong>[<strong>&#39;npm&#39;</strong>, <strong>&#39;run&#39;</strong>, <strong>&#39;start&#39;</strong>]<br>  <strong>volumes:<br>    </strong>- ./ws-ngx-login-demo/dist:/app/dist<br>    - ./ws-ngx-login-demo/tools:/app/tools<br>    - ./ws-ngx-login-demo/src:/app/src<br>    - ./ws-ngx-login-demo/yarn.lock:/app/yarn.lock:rw<br>    - ./ws-ngx-login-demo/tsconfig.json:/app/tsconfig.json<br>    - ./ws-ngx-login-demo/package.json:/app/package.json:rw<br>    - ./ws-ngx-login-demo/gulpfile.ts:/app/gulpfile.ts:rw<br>  <strong>links:<br>      </strong>- <strong>&quot;ws-node-demo&quot;<br>  ports:<br>    </strong>- <strong>&#39;5555:5555&#39;<br>    </strong>- <strong>&#39;3001:3001&#39;</strong></pre><p><a href="https://docs.docker.com/compose/compose-file/#restart"><strong>restart</strong></a><strong> : </strong>option specifies an action for restarting the container when it stops running due to a failure. One such scenario would be if a NodeJS application fails to instantiate when a reference to database is undefined because the container has not completed instantiation.</p><p><a href="https://docs.docker.com/compose/compose-file/#container_name"><strong>container_name</strong></a>: allows for the creation of a custom name other than the default.</p><p><a href="https://docs.docker.com/compose/compose-file/#build"><strong>build</strong></a>: provides a list of custom configuration to create a Docker image before running. While we may use the commands previously described in the <strong>Building and Running </strong>to facilitate the creation of images during initial development, it is easier to enable the entire process with just the ‘docker-compose up’ command once images and containers seem to be accurately standing up.</p><p><a href="https://docs.docker.com/compose/compose-file/#image"><strong>image</strong></a>: denotes the name and version of the Docker image made from the build process or one that is already created and accessible that can be used to facilitate creating the container.</p><p><a href="https://docs.docker.com/compose/compose-file/#command"><strong>command</strong></a>: provides the same behavior as the <strong>CMD</strong> option in Dockerfiles. However, when it is part of the docker-compose configuration it will override the <strong>CMD</strong> option in a Dockerfile.</p><p><a href="https://docs.docker.com/compose/compose-file/#volumes"><strong>volumes</strong></a>: allows for the creation of a key pair list of files or directories to be mounted on the host path. While the <strong>volumes</strong> option in the DockerFile performs the same operation, the retention of the files and directories is different. Previously, described in the configuration of a Dockerfile, the RUN option was used to make directories that would retain the mounted data even after the image was constructed. If we had not done this step, our data would not be present during the ‘<strong>running</strong>’ of a container. Using the <strong>volumes</strong> options with docker-compose, mounting data can actually be placed in the directories created during the build process without the <strong>COPY</strong> command in Dockerfiles.</p><p><a href="https://docs.docker.com/compose/compose-file/#links"><strong>links</strong></a>: option enables the creation of a list of dependencies that the current container depends on, and thus, offering the capability of determining the order in which services are created. Just as the services names are used in the <a href="https://github.com/WillStreeter/ws-nginx-demo/blob/master/etc-dev/nginx.conf"><strong>nginx.conf</strong></a><strong> </strong>as proxied hostnames to identify a container, so to does the links option offer service name recognition.</p><p><a href="https://docs.docker.com/compose/compose-file/#ports"><strong>ports</strong></a>: option allows for defining ports. If the definition of the port does not include the second port, as in ‘first:second” (HOST:CONTAINER), the container will be supplied with a default port.</p><p>While not listed in the <strong>ws-ngx-login-demo </strong>services configuration above, another useful option is the <a href="https://docs.docker.com/compose/compose-file/#environment"><strong>environment</strong></a> option, which can be used to provide environment settings directly available in a container.</p><pre>//docker-compose<br>    environment:<br>      DB_USER: baby<br>      DB_PASSWORD: indacorner</pre><pre>//ws-node-demo  some database adapter.ts<br>  process.env.DB_USER<br>  process.env.DB_PASSWORD</pre><p>The option <a href="https://docs.docker.com/compose/compose-file/#args"><strong>args</strong></a><strong> </strong>is also quite useful for specifying values for <strong>ENV </strong>in a Dockerfile during the build process<strong>.</strong></p><pre>//docker-compose<br>  build:<br>    args:<br>      MONGODB_VERSION: 3.2.8<br>      MONGODB_PORT: 27017<br>      DB_STORAGE_ENGINE: mmapv1<br>      DB_JOURNALING: nojournal<br>      DB_MOUNTPOINT: /mongodb/data</pre><pre>//DockerFile for Mongo</pre><pre>CMD rm /mongodb/data/mongod.lock || true &amp;&amp; \<br>  /usr/bin/mongod \<br>  --dbpath $DB_MOUNTPOINT \<br>  --port $MONGODB_PORT \<br>  --storageEngine $DB_STORAGE_ENGINE \<br>  --$DB_JOURNALING</pre><p>I have only described a few of the options that I frequently used. There a lot more options and recipes for working with <strong>Dockerfiles</strong> and <strong>Docker Compose</strong>. If you are new to <strong>Docker</strong> and are just getting started, hopefully this article and the other articles that make up this series can help you get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6dc84cca26d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/willsonic/docker-is-my-i-d-e-d6dc84cca26d">Docker is my {I.D.E}</a> was originally published in <a href="https://medium.com/willsonic">will.streeter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimal Angular : PubSub With NGRx]]></title>
            <link>https://medium.com/willsonic/optimal-angular-pubsub-with-ngrx-4faab11eb293?source=rss-ce37b550d506------2</link>
            <guid isPermaLink="false">https://medium.com/p/4faab11eb293</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Willie Streeter]]></dc:creator>
            <pubDate>Mon, 12 Jun 2017 00:55:25 GMT</pubDate>
            <atom:updated>2017-06-13T21:42:39.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkv1PXjyW38wcUrtNJRoIQ.png" /></figure><p>The concepts and practices presented in this article are delineated in a previous article, <a href="https://medium.com/@will.streeter/practical-web-development-and-architecture-26a37d04c10f"><strong>Practical Web Development and Architecture</strong></a>. The development of a front-end application base on those concepts will be explained in the following exposition, which was constructed in concert with a NodeJS server application and a Mongo data store. A review of the server application is offered in the article <a href="https://medium.com/@will.streeter/swagger-nodejs-typescript-tsoa-15a3f10fabaf"><strong>Swagger, NodeJS, &amp; TypeScript : TSOA</strong></a><strong>. </strong>The code can be reviewed in the<strong> </strong><a href="https://github.com/WillStreeter/ws-ngx-login-demo"><strong>ws-ngx-login-demo</strong></a><strong> </strong>GitHub repository<strong>. </strong>Both front-end and back-end applications are bundled as a FullStack integrated development environment using <a href="https://www.docker.com/"><strong>Docker</strong></a>, delineated in the article <a href="https://medium.com/@will.streeter/docker-is-my-i-d-e-d6dc84cca26d"><strong>Docker is my {I.D.E}</strong></a><strong> . </strong>To run this application with in the FullStack clone the<a href="https://github.com/WillStreeter/ws-dev-docker-example"><strong> ws-dev-docker-example</strong></a><strong> .</strong></p><p><em>For those not interested in using Docker, but wanting to clone, build, and run the application, I have create branch in the GitHub repository, called</em><strong><em> </em></strong><a href="https://github.com/WillStreeter/ws-ngx-login-demo/tree/serverless"><strong>serverless</strong></a><strong> </strong><em>, which can standup without the use of Docker, the NodeJS server application, or Mongo.</em></p><h3><strong>Itinerary</strong></h3><p>The following article demonstrates a use of the latest Angular 4.1.0( at the time of this writing) and NGRX ( Redux) implementation to show a registration and login flow, with guarded content.</p><ul><li><strong>Development Set Up: </strong>Summarize the development apparatus tools and configuration</li><li><strong>App Directory Configuration:</strong> Highlight the contents and approach to the structure of the application directories.</li><li><strong>Data Management and Processing</strong>: Detailed explanation of how a data flows and is processed with in the ‘s<strong>eparations of concerns’.</strong> The means of providing a User’s profile view will be used to generalized the process.</li></ul><p>In the section<strong> DataManagement and Processing, </strong>a more detailed break down of several areas is covered with regard to <strong>PubSubBroker</strong> and the use of <strong>NGRx</strong>:</p><ul><li><strong>Generating a User Profile View in 7 Steps</strong> : specific code snippets showing how the <strong>ProfileComponent</strong> in the <strong>view-layer</strong> interact with the <strong>PubSubBroker</strong> in the <strong>business-layer </strong>to facilitate communication with the <strong>data-layer</strong>.</li><li><strong>Deconstructing PubSubBroker &amp; Brokerage : </strong>details the construction of the object oriented approach to crafting <strong>PubSubBroker</strong> and <strong>Brokerage</strong> to facilitate decoupling the <strong>view-layer</strong> from the<strong> data-layer.</strong></li><li><strong>Processing global State data with NGRx</strong> : a brief synopsis on how data is processed with the <strong>NGRx</strong>’s implementation of <strong>Redux</strong>.</li><li><strong>Encapsulated Services</strong> : is an example of how <strong>business-layer</strong> services outside of the <strong>PubSubBroker</strong>, can be shared across the view-layer components as an encapsulated processes. This will be achieved by delineating how <a href="https://angular.io/docs/ts/latest/guide/reactive-forms.html">Angular’s Reactive Forms</a> are extended with <strong>validator.js </strong>to customize validations with the<strong> view-layer’s RegistrationComponent.</strong></li></ul><h3><strong>Development Set Up</strong></h3><p>Scaffolding of the source code for this project is accomplished with Minko Gechev’s <a href="https://github.com/mgechev/angular-seed"><strong>angular-seed</strong></a>, which uses <strong>j</strong><a href="http://jspm.io/"><strong>spm’s</strong></a> <a href="https://github.com/systemjs/systemjs">SystemJS</a> universal module loader. Currently, the latest Angular X uses <a href="https://webpack.github.io/"><strong>WebPack</strong></a> through the<strong> </strong><a href="https://github.com/angular/angular-cli"><strong>angular-cli</strong></a> tool. WebPack relies on an accumulation of plugins to handle bundling strategies and task maintenance such as preprocessor css compiling, minifying, and other scaffolding nuisances. <a href="https://github.com/systemjs/systemjs"><strong>SystemJS</strong></a> is a strictly for aggregating and packaging modules:</p><blockquote>“Universal dynamic module loader — loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS”</blockquote><p>Implementing the minutia of task running is accomplished by other tools, such as <a href="http://gulpjs.com/"><strong>Gulp</strong></a>. While WebPack may seem like an “auto magic” one stop shop approach, I have found this blissful simplicity can turn into an epic meltdown, when things go awry. I have used both tools, and for now I am sticking with SystemJS.</p><p>Minko Gechev’s <a href="https://github.com/mgechev/angular-seed"><strong>angular-seed</strong></a><strong> </strong>provides a productive<strong> </strong><a href="https://github.com/mgechev/angular-seed#tools-documentation"><strong>tool set</strong></a> that is fairly stable and well documented. Whenever I have a need to make modifications for configuring certain task or including 3rd party libraries the process has been for the most part mundane. Part of the tool set includes BrowserSync for running the app in a browser with ‘live-reload’.</p><p>I downloaded the Gechev’s angular-seed as a zip file, and copied files over to as needed for my project folder. The root directory appears as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*lrE55w6Hklxo_7BcuPx47g.png" /></figure><p>Most of my customizations for SASS and inclusion of libraries all takes place in the <strong><em>tools/config/</em></strong><a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/tools/config/seed.config.ts"><strong><em>seedconfig.ts</em></strong></a> and <strong><em>tools/config/</em></strong><a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/tools/config/project.config.ts"><strong><em>project.config.ts</em></strong></a>. However, I did find it necessary to create a task for unit testing, <strong><em>tools/tasks/seed/build.js.mockdata.ts</em></strong><em>, </em>which instructs the scaffolding to compile and copy the testing data to the eventual “dist” directory for unit testing. I also added some attributes to the<strong><em> tools/env/env-config.interface.ts</em></strong>, to provide values for host, api name identifier, and ports, which are mostly used in my Docker eco-system.</p><h3><strong>App Directory Configuration</strong></h3><p>The Gechev’s angular-seed is a vanilla starter kit for modern Angular project, and thus, does not include a couple of resources that I will use in this project.</p><ul><li><a href="https://github.com/ngrx"><strong>NGRx</strong></a><strong> (resources) : </strong>handles the redux plumbing for modern Angular Projects.</li><li><a href="https://github.com/angular/material2"><strong>angular-material2</strong></a><strong> : </strong>Google’s Material design for modern Angular projects.</li><li><a href="https://github.com/angular/flex-layout"><strong>angular/flex-layout</strong></a> : a library of directives for using css flex.</li><li><a href="https://www.npmjs.com/package/@types/validator"><strong>@types/validator</strong></a>: providing some extra validations attributes for our reactive forms. (this is a Definitively Typed package, which is a TypeScript wrapper around a javascript library, in this case<a href="https://github.com/chriso/validator.js"><strong> validator.js</strong></a> )</li></ul><p>After adding these resource as dependencies in our <strong>package.json </strong>and including them in our <strong>seed.config.ts </strong>we<strong> </strong>are good to go.</p><p><strong>src/client </strong>: contains all directories and files formulating the functional representation of application.</p><p><strong>src/e2e</strong> : contains e2e (End To End) testing with protractor.</p><p><strong>src/test-artifacts</strong> : contains data and ancillary files used for unit testing.</p><p><strong>src/vendor</strong> : contains third party code that does not fit into the paradigm of our <strong>tools</strong> structure. In this case, I have included the direct download of <a href="https://github.com/tgdev/animate-sass">Animate-sass</a> library from GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*5k2WMfUqv2HzLF16IGNy4g.png" /><figcaption>src/ directory and file structure and src/client / directory and file structure</figcaption></figure><p>The <strong>src/client/app/ </strong>directory represents the procedural code base of the application, and it is here where we will instantiate our Angular framework by bootstrapping the root module.</p><p><strong>src/client/app/app-stage: </strong>centralizing the files necessary for standing up the entire application.</p><p><strong>src/client/app/shared-utils/app-env: </strong>contains file(s) implementing the specifics of the environment in which the application instantiates. It works in conjunction with the files in the<a href="https://github.com/WillStreeter/ws-ngx-login-demo/tree/master/tools/env"> <strong>tools/env</strong>.</a></p><p><strong>src/client/assets </strong>: contains any artifacts and images used with in the application.</p><p><strong>src/client/scss</strong>: contains customized sass (ex: variables, mixins, abstract classes, etc.,) used to augment css styling, which is for the most part structured with in the angular-material2 theme included as a dependency in our application.</p><p><strong>src/client/css </strong>: contains are <strong>seed-main.css</strong> file, implementing reset, and is imported by the <strong>main.scss </strong>file which acts as the staging for importing files in <strong>src/client/scss</strong>. The basis for this approach laid by Gechev in a Wiki, <a href="https://github.com/mgechev/angular-seed/wiki/Working-with-SASS"><strong>Working with SASS</strong></a>.</p><p>Separating the various concerns of the application as discussed in the article <a href="https://medium.com/p/26a37d04c10f/edit"><strong>Practical Web Development and Architecture</strong></a>, the structure of the client is grouped accordingly.</p><h4><strong>View Layer</strong></h4><p><a href="/service/ttps://github.com/WillStreeter/ws-ngx-login-demo/tree/master/src/client/app/view-layer"><strong>src/client/app/view-layer</strong></a><strong> : </strong>contains files implementing the presentational concerns of the applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*omFC7PHd2XxP2HBfbFNw0w.png" /><figcaption>Directory structure of the view-layer</figcaption></figure><p><strong>~/view-layer/modules-by-route :</strong> each directory aggregating files needed for a single module that serves as the base for perspective route (URL view). Modules from <strong>modules-by-route </strong>that are not included in the <strong>app.stage.module</strong> are self contained units that are loaded when requested through a ‘lazy loading’ approach.</p><p><strong>~/view-layer/common-views : </strong>each top level directory represents the aggregation of files for a single view component that can shared across the application.</p><h4><strong>Data Layer</strong></h4><p><a href="https://github.com/WillStreeter/ws-ngx-login-demo/tree/master/src/client/app/data-layer"><strong>src/client/app/data-layer</strong></a><strong> : </strong>implementation of services for remote (HTTP) data transactions as well as the infrastructure for scaffolding our data models in a <strong>Redux</strong> paradigm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*hqYZyobgw9Ba24C7QYuZxw.png" /><figcaption>Directory structure of the data-layer</figcaption></figure><p><strong>~/data-layer/api-services :</strong> contains a wrapper (<strong> http.wrapper.services</strong>) for abstracting the repeated orchestration of HTTP C.R.U.D implementation from each services ( such as <strong>user.services</strong> ) api request.</p><p><strong>~/data-layer/ngrx-data :</strong> implements <strong>Redux</strong> facilitated through <strong>NRGx</strong>.</p><ul><li><strong>reducers</strong> : are the immutable data objects representing our <strong>Redux Store.</strong></li><li><strong>actions, guards, </strong>and<strong> effects</strong> contain procedures for interacting with the <strong>Store</strong>.</li><li><strong>ngrx.data.module.ts : </strong>aggregates these resources for export into our <strong>app.stage.module</strong>.</li></ul><p><em>*For a more detailed and nuanced understanding of how NGRx facilitates Redux in Angular, the ng-book blog tutorial, “</em><a href="http://blog.ng-book.com/introduction-to-redux-with-typescript-and-angular-2/"><strong><em>Introduction to Redux with TypeScript and Angular 2</em></strong></a><strong><em>”</em></strong><em>, offers one of the best overviews I have come across. Even though it is a bit dated, the principals still apply. To keep up to date with how the progressive versions of Angular as applied to NGRx, follow the </em><a href="https://github.com/ngrx/example-app"><strong><em>example-app</em></strong></a><strong><em> </em></strong><em>Mike Ryan maintains on GitHub.</em></p><h4><strong>Business Layer</strong></h4><p><a href="https://github.com/WillStreeter/ws-ngx-login-demo/tree/master/src/client/app/business-layer"><strong>src/client/app/business-layer</strong></a><strong> : </strong>implements a <strong>Publish</strong> and <strong>Subscribe</strong> process for brokering request between the <strong>view-layer</strong> and<strong> data-layer</strong>, resulting in no direct exchanges between presentational components and the <strong>NGRx Redux</strong> orchestration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*mgHSIbZ6M-ulUAoV_a9HdA.png" /><figcaption>Directory structure of the business layer</figcaption></figure><p><strong>~/business-layer/brokerage :</strong> implements transactions with the <strong>data-layer </strong>by registering as a <strong>consumer</strong> with the <strong>pubsub-broker</strong>.</p><p><strong>~/business-layer/pubsub-broker :</strong> implements a Publish and Subscribe system for interacting with the <strong>data-layer</strong>.</p><p><strong>~/business-layer/models :</strong> contains files representing data schemas used by both the<strong> view-laye</strong>r and <strong>data-layer</strong>.</p><p><strong>~/business-layer/shared-types :</strong> contains files listing the various action types implemented in the <strong>data-layer/ngrx-data/actions</strong> against the Store and used by stubs in the <strong>brokerage/ngrx-stubs.</strong></p><p><strong>~/business-layer/validator :</strong> contains an encapsulated service implementation for validation of User input with in forms surfacing in the v<strong>iew-layer</strong>.</p><h3><strong>Data Management and Processing</strong></h3><p><strong>data-layer:</strong> Implements all HTTP processing for requesting and responding to data from the server . It also manages the State of the data using a Redux pattern imposed by NGRx, which formalizes the way data is accessed through <strong>Actions</strong> and <strong>Selectors.</strong></p><p><strong>business-layer:</strong> Uses <strong>PubSubBroker</strong> in conjunction with a <strong>Brokerage </strong>to respond to <strong>view-layer</strong> demands for access to the <strong>data-layer, </strong>thus<strong> </strong>removing any references to the <strong>data-layer’s </strong>Redux <strong>Store </strong>in the<strong> view-layer. The Brokerage </strong>stubs<strong> </strong>limit what each <strong>view-layer</strong> component can consume from the <strong>Store</strong>.<strong> </strong>This layer is also where encapsulated services for <strong>Non-Store </strong>related data processing are located.</p><p><strong>view-layer </strong>: Contains viewable components created with the singular responsibility of presenting data output and consuming User input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*bQht2tZmD_R7JhIvRRtJQg.png" /></figure><h4><strong>Generating a User Profile View in 7 Steps</strong></h4><p>The following scenario captures the flow of requesting a User’s profile data for display in the <strong>view-layer’s</strong> <strong>ProfileComponen</strong>t. It demonstrates a typical scenario a <strong>view-laye</strong>r employs with the <strong>PubSubBroker</strong> in the <strong>business-layer</strong> to observe and request action against global State <strong>data</strong> from the <strong>data-layer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhNTizhtEBb35O2QKt3Xsg.png" /><figcaption>data flow from from view-layer to business-layer t0 data-layer</figcaption></figure><p>1When a<strong> view-layer</strong> component such as the <strong>ProfileComponent</strong> with data dependencies is instantiated, it send the named identity of a <strong>Broker</strong> <strong>Stub</strong>, <strong>BROKER_PROFILE_STORE, </strong>by way of the <strong>PubSubBroker’s , </strong><a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/src/client/app/business-layer/pubsub-broker/services/broker.dispatcher.service.ts"><strong>BrokerDispatcherService </strong>function<strong> dispatchBrokerSelector().</strong></a></p><pre><strong>export class </strong>ProfileComponent <strong>implements </strong>OnInit, OnDestroy {<br> <strong>subscribeHandler</strong>:<strong>any</strong>;<br> <strong>userProfile$</strong>:Observable&lt;<strong>any</strong>&gt;;<br> <strong>brokerRef</strong>:<strong>any</strong>;<br>  //BrokerDispatcherService <br> <strong>constructor</strong>( <strong>private </strong>activatedRoute:ActivatedRoute,<br>              <strong>private </strong>bDS:BrokerDispatcherService) {<br><br>    <strong>var </strong>brokerResponse:BrokerResponse =         <br><strong>this</strong>.bDS.dispatchBrokerSelector(BrokerList.<strong>BROKER_PROFILE_STORE</strong>);</pre><pre>   <strong>this</strong>.<strong>brokerRef </strong>= brokerResponse.<strong>brokerRequested</strong>;<br>                 <br>}<br>....</pre><p>2 <strong>BrokerDispatcherService </strong>shares an established relationship with a<strong> Broker Consumer, </strong>such as<strong> NGRxBrokerConsumer,</strong> through a<strong> BrokerPublisher. </strong>In this case, the <strong>NGRxBrokerConsumer</strong> function <strong>ReceivedBrokerSelectorRequest() </strong>uses<strong> </strong>the named identity to reference the broker stub, <strong>BrokerProfileStore.</strong></p><pre><strong>export class </strong>NGRxBrokerConsumer <strong>implements </strong>IConsumer{</pre><pre>  <strong>constructor</strong>( <strong>private </strong>brokerDialogStore: BrokerDialogStore,<br>               <strong>private </strong>brokerLoginStore: BrokerLoginStore,<br>               <strong>private </strong>brokerNavStore: BrokerNavStore,<br>               <strong>private </strong>brkrRgstrtnStore: BrokerRegistrationStore,<br>               <strong>private </strong>brokerProfileStore: BrokerProfileStore   ){ }<br><br>            ....<br> <br> public ReceivedBrokerSelectorRequest(brokerType:<strong>string</strong>):     <br>        BrokerResponse{</pre><pre>        <strong>var </strong>brokerResponse = <strong>new </strong>BrokerResponse();<br>        <strong>switch</strong>(brokerType){<br>             ....</pre><pre>            <strong>case this</strong>.brokerProfileStore.<strong>brokerLabel</strong>:<br>                  brokerResponse.<strong>brokerRequested =<br>                    this</strong>.brokerProfileStore.getComponentSupplies();<br>            <strong>break</strong>;</pre><pre>        }<br>        <strong>return </strong>brokerResponse;<br>    }<br><br>}</pre><p>3 The BrokerProfileStore stub responds to the function call <strong>getComponentSupplies</strong>() by returning object containing properties for ‘<strong><em>storeObs’ </em></strong><em>and</em><strong><em> </em>‘<em>storeDsp</em>’. </strong>The<strong> <em>storeObs</em></strong><em> </em>contains<em> </em><strong>Observables </strong>that<strong> </strong>are derived from the <strong>NGRx Store</strong> S<strong>electors. </strong>The<strong> <em>storeDsp </em></strong>contains a set of <strong>BrokerActions </strong>to dispatch<strong> </strong>actions against the <strong>Store</strong>.</p><pre><strong>export class </strong>BrokerProfileStore {<br>    <strong>brokerLabel</strong>:<strong>string </strong>= BrokerList.<strong>BROKER_PROFILE_STORE</strong>;<br>    <strong>constructor</strong>( <strong>private </strong>store: Store&lt;fromRoot.State&gt;,<br>                 <strong>private </strong>brkrActnBuilder:BrokerActionBuilder ) { } </pre><pre>    getComponentSupplies():<strong>any</strong>{ <strong>return  <br>      <em>Object</em></strong>.assign({</pre><pre>        <strong>brokerLabel</strong>: <strong>this</strong>.<strong>brokerLabel</strong>,</pre><pre>        <strong>storeObs</strong>:{ <strong>userProfile$</strong>: <strong>this</strong>.store.<br>                             <strong>select</strong>(fromRoot.getSelectedProfile)  <br>                  },</pre><pre>        <strong>storeDsp</strong>:{ <strong>GET_USER_PROFILE_ATTEMPT</strong>: <strong>this</strong>.brkrActnBuilder.<br>               create( ProfileActionTypes.GET_USER_PROFILE_ATTEMPT,<br>                       <strong>this</strong>.<strong>brokerLabel</strong>, <strong>null</strong>)<br>                  }<br>       });<br>    }<br><br><br>}</pre><p><strong>4 </strong>Upon receiving the <strong>BrokerResponse, </strong>the <strong>view-layer</strong> component extracts a subscriptions to the <strong>Observables</strong> contained in the ‘<strong><em>storeObs’</em></strong> property, which provides a continual awareness of the the <strong>State</strong> of the <strong>userProfile$</strong> attribute in the <strong>Store</strong>.</p><pre>//Profile Component continued..<br>ngOnInit() {<br>         <br>  <strong>this</strong>.<strong>userProfile$ </strong>= <strong>this</strong>.<strong>brokerRef</strong>.<strong>storeObs</strong>.<strong>userProfile$</strong>;<br>    .....</pre><pre>}</pre><p>5 <strong>Actions</strong> against the <strong>Store</strong> that the ProfileComponent can perform are contained in the ‘<strong><em>storeDsp</em></strong>’. Request are<strong> </strong>sent through the <strong>PubSubBroker’s BrokerDispatcherService </strong>method<strong> dispatchBrokerAction</strong>()<strong> .</strong> In this case, the name of a User, supplied as a parameter attribute with in the URL, is sent as an Action.</p><pre>//Profile Component continued..<br>ngOnInit() {<br>         ...<br> <strong>this</strong>.<strong>subscribeHandler </strong>= <strong>this</strong>.activatedRoute.<strong>params</strong>.<br>      subscribe(params =&gt; {<br>        <strong>var </strong>note = <strong>this</strong>.<strong>brokerRef</strong>.<strong>storeDsp</strong>.<strong>GET_USER_PROFILE_ATTEMPT</strong>;<br>        note.<strong>payLoad </strong>=  params[<strong>&#39;username&#39;</strong>];<br>        <strong>this</strong>.bDS.dispatchBrokerAction(note);<br>      });<br>}</pre><p>6 Once again <strong>NGRxBrokerConsumer </strong>will<strong> </strong>consume the request. However, as it is a demand for <strong>Action, </strong>the request<strong> </strong>will be received by the <strong>ReceiveBrokerAction</strong> method, which will then pass the request on to the <strong>BrokerProfileStore stub </strong>using its <strong>dispatchAction</strong>() function.</p><pre><strong>export class </strong>NGRxBrokerConsumer <strong>implements </strong>IConsumer{<br><br>            ....<br> <br><strong>public </strong>ReceiveBrokerAction( brokerAction:BrokerAction){<br>    <strong>switch</strong>(brokerAction.<strong>brokerType</strong>){<br>           ...<br>        <strong>case this</strong>.brokerProfileStore.<strong>brokerLabel</strong>:<br>              <strong>this</strong>.brokerProfileStore.dispatchAction(brokerAction);<br>        <strong>break</strong>;<br>    }<br>}</pre><p>7 The <strong>Broker</strong> will use its established reference to the <strong>Store</strong> to dispatch a new Action ‘<strong>profileActions.GetUserProfileAttempt</strong> ’ against the State of the Store.</p><pre>@Injectable()<br><strong>export class </strong>BrokerProfileStore {<br>    <strong>brokerLabel</strong>:<strong>string </strong>= BrokerList.<strong>BROKER_PROFILE_STORE</strong>;<br>    <strong>constructor</strong>( <strong>private </strong>store: Store&lt;fromRoot.State&gt;,<br>                 <strong>private </strong>brkrActnBuilder:BrokerActionBuilder ) { }</pre><pre>dispatchAction(brokerAction:BrokerAction):<strong>void </strong>{<br>  <strong>switch</strong>(brokerAction.<strong>actionType</strong>){<br>    <strong>case </strong>ProfileActionTypes.GET_USER_PROFILE_ATTEMPT:<br>      t<strong>his</strong>.store.dispatch(<strong>new <br>                    </strong>profileActions.GetUserProfileAttempt(        <br>                            brokerAction.<strong>payLoad</strong>));  <br>            <strong>break</strong>;<br>   }<br>}</pre><p>Exact implementation of what happens once the ProfileAction GetUserProfileAttempt() functions is invoked will be detailed later in the section <strong><em>Processing global State data with NGRx.</em></strong></p><h4>Deconstructing PubSubBroker &amp; Brokerage</h4><p>Within the <strong>business-layer</strong>, the <strong>PubSubBroker</strong> and <strong>Brokerage</strong> module work to process communication from components in the <strong>view-layer</strong> to the core data objects in the <strong>data-layer</strong>. Processing communication between the two separate layers with <strong>PubSub Broker</strong> facilitates a total decoupling of the mechanisms for handling the <strong>State</strong> of our data object. If our <strong>data-layer</strong> should change to a different pattern for maintaining <strong>State, </strong>perhaps no longer using a <strong>Redux Store,</strong> none of the visual components need to change as long as the new <strong>data-layer</strong> provides <strong>Observables </strong>for subscription to the<strong> State of </strong>data objects,<strong> </strong>and implement a mechanism for updating the<strong> State</strong> of data object with some semblance of an <strong>Action</strong> object<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*10VuOvVONqXEUYehTMPQ_g.png" /></figure><p>The <a href="https://github.com/WillStreeter/ws-ngx-login-demo/tree/master/src/client/app/business-layer/pubsub-broker"><strong>PubSubBroker </strong><em>(README.md)</em></a><strong> </strong>module is implemented through the object oriented facilities of TypeScript.</p><ol><li>An Abstract class,<a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/src/client/app/business-layer/pubsub-broker/outlet/abstract.broker.trader.ts"> <strong>AbstractBrokerTrader</strong></a><strong>,</strong> extends <strong>ISupplier</strong> and has an array attribute of type <strong>IConsumer</strong>.</li><li>As an abstract class, <strong>AbstractBrokerTrader</strong>, can not be instantiated, but must be extended by another class which is performed <a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/src/client/app/business-layer/pubsub-broker/outlet/broker.publisher.ts"><strong>BrokerPublisher</strong> .</a></li><li>Since <strong>BrokerPublisher </strong>extends <strong>AbstractBrokerTrader,</strong> it is not only an<strong> ISupplier, </strong>but also<strong> </strong>possesses an awareness of the <strong>IConsumer </strong>array attribute type<strong>.</strong></li><li>The <strong>Brokerage </strong>module has a ‘<strong>registries’</strong> directory, that contains services like <strong>NGRxBrokerRegistrationService. </strong>These services implement a registration<strong> </strong>between<strong> Brokerage IConsumers </strong>like<strong> NGRxBrokerConsumer , </strong>whose class definition<strong> implements IConsumer, </strong>and<strong> </strong>the<strong> BrokerPublisher.</strong></li><li>This registration is performed when <strong>NGRxBrokerRegistrationService, </strong>calls the <strong>BrokerPublisher </strong>function<strong> RegisterBrokerConsumer</strong>(). The <strong>BrokerPublisher </strong>function pushes instances of <strong>IConsumer </strong>types<strong> </strong>like <strong>NGRxBrokerConsumer </strong>into its<strong> IConsumer </strong>array.</li><li>The<strong> BrokerDispatchService </strong>injected into components<strong> </strong>residing in the <strong>view-layer </strong>contains a reference to the <strong>BrokerPublisher, </strong>and thus can<strong> </strong>invoke<strong> BrokerPublisher </strong>functions that can reference any of the <strong>IConsumer</strong> array entities functions like <strong>ReceiveBrokerAction().</strong></li></ol><p>The only <strong>Brokers</strong> that currently exist are used to supply the <strong>State</strong> and provide <strong>Actions</strong> against the <strong>NGRx</strong> state management apparatus in the <strong>data-layer,</strong> other <strong>Brokers</strong> could be created in the same manner if an alternative pattern or management system is desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3euHszX8VhaKeGkEYSFy_A.png" /></figure><p>The <strong>Brokerage</strong> module directory, <strong>ngrx-stubs, </strong>contains the various <strong>Broker</strong> <strong>stubs</strong> used to gather the <strong>Selectors</strong> and <strong>Actions </strong>needed by particular components in the<strong> view-layer</strong>. Each <strong>stub</strong> has a a direct reference to the NGRx <strong>Store</strong> in the <strong>data-layer </strong>and is instantiated in the<strong> business-layer </strong>by th<strong>e</strong> <strong>NGRxBrokerConsumer</strong>.</p><h4>Processing global State data with NGRx</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*Tc49WDfvixYRGXFA1BzN0A.png" /><figcaption>Flow of Data between actions &gt; reducers &gt; effects</figcaption></figure><p><em>(each step is represent by a number is a yellow circle)</em></p><p>0 Components subscribe to changes in a<strong> Store’s</strong> object <strong>State</strong>, (often called <strong>Smart Component</strong> or <strong>Containers</strong>) through the use <strong>Selectors</strong> to establish an <strong>Observable</strong>, which in the above diagram is label <strong>Target</strong>.</p><pre><strong>// </strong>While this is often place in the<strong> </strong>ngOnInit() or constructor() of // Angular components, this call resides in <br>// brokerage/ngrx-stubs/broker.profile.store </pre><pre><strong>this</strong>.store.<strong>select</strong>(fromRoot.getSelectedProfile)</pre><p>1The initiation of the data cycle begins when a new <strong>Action</strong> is dispatched.</p><pre><strong>this</strong>.store.dispatch(<br>     <strong>new </strong>profileActions.CheckUserProfileNameAttempt(&#39;wilSonic&#39;)<br>           );</pre><p>In the ‘<strong>this.store.dispatch’</strong> statement above , the <strong>new</strong> Object created is configured in an <strong>Action</strong> declaration file,<strong> </strong><a href="https://github.com/WillStreeter/ws-ngx-login-demo/blob/master/src/client/app/data-layer/ngrx-data/actions/profile.actions.ts"><strong>profile.action.ts</strong> .</a></p><pre><strong>export class </strong>CheckUserProfileNameAttempt <strong>implements </strong>Action {<br> <strong>public readonly type </strong>= ProfileActionTypes.CHECK_USER_PROFILE_NAME_ATTEMPT;<br>  <strong>constructor</strong>(<strong>public </strong>payload:<strong>string</strong>) {  }<br>}</pre><p>2 Dispatching<strong> </strong>the<strong> Action </strong>to the <strong>Store, </strong>it<strong> </strong>first passes through a <strong>Reducer</strong> checking for a<strong> ‘case’ </strong>to interact with the <strong>Action </strong>type. If the <strong>State</strong> of the <strong>Reducer</strong> changes base on the conditions set within the <strong>case</strong> , all <strong>Observable</strong> actively subscribing by way of <strong>Selectors, will </strong>notified of the change. (<em>… such an Observable was set up in step zero</em>)</p><p>The specific action ‘<strong>CHECK_USER_PROFILE_NAME_ATTEMPT</strong>’ , which initiated our course of action does not have a case in any of the <strong>Reducers. </strong>However, it will eventually get picked up by an<strong> Effect </strong>described in the third step<strong>.</strong></p><pre><strong>export  interface </strong>State {<br>  <strong>ids</strong>: <strong>string</strong>[];<br>  <strong>entities</strong>: { [<strong>id</strong>: <strong>string</strong>]: UserModel };<br>  <strong>selectedProfileId</strong>: <strong>string </strong>| <strong>null</strong>;<br>  <strong>validUserName</strong>:<strong>string</strong>;<br>}<br><br><strong>export const </strong>initialState: State = {<br>  <strong>ids</strong>: [],<br>  <strong>entities</strong>: {},<br>  <strong>selectedProfileId</strong>: <strong>null</strong>,<br>  <strong>validUserName</strong>:<strong>null<br></strong>};</pre><pre><strong>export function </strong><em>reducer</em>(state = initialState, action:   <br>                               profileActions.Actions): State {</pre><pre><strong>switch </strong>(action.<strong>type</strong>) {<br>        .....</pre><pre><br>      <strong>case </strong>ProfileActionTypes.SET_SELECTED_PROFILE_ID:{<br>          <strong>if </strong>(state.<strong>ids</strong>.indexOf(action.<strong>payload</strong>) &gt; -1) {<br>             <strong>return <em>Object</em></strong>.assign({}, <br>                              state, <br>                             { <strong>selectedProfileId</strong>:action.<strong>payload </strong>});<br>          }<strong>else </strong>{<br>             <strong>return </strong>state;<br>          }<br>      }<br><br>     <strong>default</strong>: {<br>         <strong>return </strong>state;<br>     }<br>}</pre><p>3Like <strong>Reducers</strong>, <strong>Effects</strong> can register a request to interact with specific <strong>Action</strong> types as well. Thus, our originally dispatched <strong>Action</strong> continues its course as <strong>ProfileEffects</strong> has registered a request to interact with the <strong>Action</strong> type <strong>CHECK_USER_PROFILE_NAME_ATTEMPT</strong>.</p><pre><strong>export class </strong>ProfileEffects {</pre><pre>@<em>Effect</em>() <strong>getUserByName$ </strong>= <strong>this</strong>.actions$<br> .ofType(profileActions.ProfileTypes.<strong>CHECK_USER_PROFILE_NAME_ATTEMPT</strong>) .<strong>map</strong>(action =&gt; action.<strong>payload</strong>)<br> .<strong>switchMap</strong>(payload =&gt; <br>    <strong>this</strong>.userServices.getUserByName( <br>      payload,<br>      errorActions.ErrorTypes.REPORT_ERROR,<br>      profileActions.ProfileTypes.CHECK_USER_PROFILE_NAME_FAILURE,<br>      profileActions.ProfileTypes.CHECK_USER_PROFILE_NAME_SUCCESS)<br>  );</pre><pre><br> <strong>constructor</strong>( <strong>private </strong>store:Store&lt;fromRoot.State&gt;,<br>              <strong>private </strong>userServices: UserServices,<br>              <strong>private </strong>actions$: Actions<br>             ) {  }<br>}</pre><p>4While simplistic processing of business rules can be applied through manipulation of the <strong>Observable</strong> using the <a href="https://xgrommx.github.io/rx-book/why_rx.html"><strong>RxJs reactive library</strong></a> , it is often the case that mapping the <strong>Observable</strong> to a separate service for processing is a better approach. This is especially true when asynchronous services are need. We use such a service in the above <strong>Effect</strong> by implementing the <strong>UserService</strong> ( <strong>this.userServices.getUserByName</strong>(…) ) to request API information.</p><pre><strong>export class </strong>UserServices {<br><br>  <strong>constructor</strong>(<strong>private </strong>httpWrapperService: HttpWrapperService) { }<br><br>     getUserByName( payload:<strong>string</strong>,<br>                    ErrorActionType:<strong>string</strong>, <br>                    SpecificErrorType:<strong>string</strong>, <br>                    SuccessType:<strong>string</strong>) {</pre><pre>         <strong>let </strong>getParams: HttpParams = {<br>            <strong>auth</strong>: <strong>false</strong>,<br>            <strong>errorActionType</strong>: ErrorActionType,<br>            <strong>specificErrorType</strong>:SpecificErrorType,<br>            <strong>payload</strong>: payload,<br>            <strong>responseObject</strong>: <strong>&#39;user&#39;</strong>,<br>            <strong>successActionType</strong>:SuccessType,<br>            <strong>uri</strong>: <strong>&#39;Users/username/&#39;</strong>+payload<br>         };</pre><pre>         <strong>return this</strong>.httpWrapperService.get(getParams);<br>       }</pre><pre>}</pre><p>While <strong>UserService</strong> methods request HTTP transactions, the actual <strong>AJAX</strong> is defined in the a wrapper <strong>HttpWrapperService</strong>(). The results of a successful HTTP request is mapped to the current <strong>Observable</strong> being processed by the <strong>ProfileEffect</strong>. In other words, the <strong>Observable</strong> stream is still active when a successful result from the HTTP request occurs. When there is an error, the current Observable is no longer viable. Like resolving a <strong>Promise</strong> by creating a Promise.reject, a new Observable must defined as is the case in the catch() statement where Observable.of() is used map the resulting ‘<strong>error action.type</strong>’.</p><pre><strong>export class </strong>HttpWrapperService {<br><em><br>  </em><strong>constructor</strong>(<strong>private </strong>http: Http) { }</pre><pre>...</pre><pre><strong>public </strong>get(params: HttpParams) {<br>    <strong>let </strong>{apiUrl, options} = <br>           <strong>this</strong>.configRequest(params.<strong>uri</strong>, params.<strong>auth</strong>);</pre><pre><strong>     return this</strong>.http.get(apiUrl, options)<br>           .<strong>map</strong>(res =&gt; ({<br>                <strong>type</strong>: params.<strong>successActionType</strong>,<br>                <strong>payload</strong>: res.json()[params.<strong>responseObject</strong>]<br>             }))<br>           .<strong>catch</strong>(res =&gt; Observable.<em>of</em>({<br>              <strong>type</strong>: params.<strong>errorActionType</strong>,<br>               <strong>payload</strong>: {<br>               <strong>action_type</strong>: params.<strong>specificErrorType</strong>,<br>               <strong>message</strong>: res.json()<br>             }<br>      }));<br>  }</pre><pre>...</pre><p>5No matter what kinds of procedures occur during the course of the <strong>Effects </strong>task, the result of the process will be an <strong>Action</strong> object <strong>Observable, </strong>which<strong> </strong>will once again go through the cycle of <strong>Redux</strong> .</p><pre>.<strong>map</strong>(res =&gt; ({<br>                <strong>type</strong>: params.<strong>successActionType</strong>,<br>                <strong>payload</strong>: res.json()[params.<strong>responseObject</strong>]<br>             }))</pre><p>The above snippet of code demonstrates mapping the result to an a <strong>Profile Action</strong> type ‘<strong>CHECK_USER_PROFILE_NAME_SUCCESS</strong>’, which creates the <strong>Action</strong> object below:</p><pre><strong>export class </strong>CheckUserProfileNameSuccess <strong>implements </strong>Action {<br> <strong>public readonly type </strong>=  <br>               ProfileActionTypes.CHECK_USER_PROFILE_NAME_SUCCESS;<br>  <strong>constructor</strong>(<strong>public </strong>payload:UserModel) {  }<br>}</pre><p>While the unsuccessful attempt, will result in the <strong>Error Action Type</strong> : ‘<strong>REPORT_ERROR</strong>’ which will create the following Action object:</p><pre><strong>export class </strong>ReportError <strong>implements </strong>Action {<br>  <strong>public readonly type </strong>= ErrorActionTypes.REPORT_ERROR;<br>  <strong>constructor</strong>(<strong>public </strong>payload: ErrorModel) {  }<br>}<br></pre><h4>Encapsulated Services:</h4><p>Finally, there is an instance of <a href="https://angular.io/docs/ts/latest/guide/reactive-forms.html">Angular’s Reactive Forms</a> used with in the application when the user inputs data in the registration form. The process of validating a user’s input data has been augmented by a set of validation schemas from <a href="https://github.com/chriso/validator.js"><strong>validator.js</strong></a><strong>. </strong>This ‘<em>micro</em>’ process does not utilize<strong> NGRx Redux </strong>in any significant way other than to check if the ‘username’ is already in use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*HxOTyw4qSx33QRE6JVahDA.png" /><figcaption>Processing data input through validation services</figcaption></figure><p>In short, the<strong> Registration</strong> module imports the <strong>Control Message Components</strong> and <strong>Validation services </strong>to display <em>Error Messages</em> below input boxes. Upon entering text and hitting the tab button or just moving focus to the next input box, the data from the previous input box is processed by the <strong>validation services</strong>. If an error is captured during the validation process,</p><pre><strong>*ngIf=&quot;errorMessage !== null&quot;</strong></pre><p>Angular’s <strong>*ngIf </strong>conditional in the <strong>Control Message Component</strong> template becomes true, and will displays the message.</p><p>Hopefully this application demonstrates how a modern Angular project can be structured based on a “<strong>separation of concerns</strong>”. While the architecture may seem a bit complex for the menial tasks performed (registration and log in), the goal of this effort is to provide an example of a structure for large applications. Whether created and maintained by one developer or a few developers, the concepts outlined in this article can provide an example of a constructive approach toward developing a foundation for maximum scalability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4faab11eb293" width="1" height="1" alt=""><hr><p><a href="https://medium.com/willsonic/optimal-angular-pubsub-with-ngrx-4faab11eb293">Optimal Angular : PubSub With NGRx</a> was originally published in <a href="https://medium.com/willsonic">will.streeter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>