<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Noah</title>
    <description>The latest articles on Forem by Noah (@ogoodness).</description>
    <link>https://forem.com/ogoodness</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F584906%2F013d0357-b5e2-4178-a067-8c21e5457ca0.png</url>
      <title>Forem: Noah</title>
      <link>https://forem.com/ogoodness</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ogoodness"/>
    <language>en</language>
    <item>
      <title>Code Design - Domain Driven Hexagon</title>
      <dc:creator>Noah</dc:creator>
      <pubDate>Tue, 02 Mar 2021 15:37:57 +0000</pubDate>
      <link>https://forem.com/ogoodness/code-design-domain-driven-hexagon-33c7</link>
      <guid>https://forem.com/ogoodness/code-design-domain-driven-hexagon-33c7</guid>
      <description>&lt;h2&gt;
  
  
  This Is A Post From the Original GitHub Repo
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Repo:&lt;/strong&gt; &lt;a href="https://github.com/Sairyss/domain-driven-hexagon" rel="noopener noreferrer"&gt;https://github.com/Sairyss/domain-driven-hexagon&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;This repo is work in progress&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Domain-Driven Hexagon
&lt;/h1&gt;

&lt;p&gt;Main emphasis of this project is to provide recommendations on how to design software applications. In this readme are presented some of the techniques, tools, best practices, architectural patterns and guidelines gathered from different sources.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Everything below should be seen as a recommendation&lt;/strong&gt;. Keep in mind that different projects have different requirements, so any pattern mentioned in this readme can be replaced or skipped if needed.&lt;/p&gt;

&lt;p&gt;Code examples are written using &lt;a href="https://nodejs.org/en/" rel="noopener noreferrer"&gt;NodeJS&lt;/a&gt;, &lt;a href="https://www.typescriptlang.org/" rel="noopener noreferrer"&gt;TypeScript&lt;/a&gt;, &lt;a href="https://docs.nestjs.com/" rel="noopener noreferrer"&gt;NestJS&lt;/a&gt; framework and &lt;a href="https://www.npmjs.com/package/typeorm" rel="noopener noreferrer"&gt;Typeorm&lt;/a&gt; for the database access.&lt;/p&gt;

&lt;p&gt;Though patterns and principles presented here are &lt;strong&gt;framework/language agnostic&lt;/strong&gt;, so above technologies can be easily replaced with any alternative. No matter what language or framework is used, any application can benefit from principles described below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: code examples are adapted to TypeScript and mentioned above frameworks so may not fit well for other languages. Also remember that code examples presented here are just examples and must be changed according to project's needs or personal preference.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Architecture&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Diagram&lt;/li&gt;
&lt;li&gt;Modules&lt;/li&gt;
&lt;li&gt;Application Core&lt;/li&gt;
&lt;li&gt;Application layer&lt;/li&gt;
&lt;li&gt;Application Services&lt;/li&gt;
&lt;li&gt;Commands and Queries&lt;/li&gt;
&lt;li&gt;Ports&lt;/li&gt;
&lt;li&gt;Domain Layer&lt;/li&gt;
&lt;li&gt;Entities&lt;/li&gt;
&lt;li&gt;Aggregates&lt;/li&gt;
&lt;li&gt;Domain Events&lt;/li&gt;
&lt;li&gt;Domain Services&lt;/li&gt;
&lt;li&gt;Value Objects&lt;/li&gt;
&lt;li&gt;Enforcing invariants of Domain Objects&lt;/li&gt;
&lt;li&gt;Using libraries inside application's core&lt;/li&gt;
&lt;li&gt;Interface Adapters&lt;/li&gt;
&lt;li&gt;Controllers&lt;/li&gt;
&lt;li&gt;DTOs&lt;/li&gt;
&lt;li&gt;Infrastructure&lt;/li&gt;
&lt;li&gt;Adapters&lt;/li&gt;
&lt;li&gt;Repositories&lt;/li&gt;
&lt;li&gt;ORM Entities&lt;/li&gt;
&lt;li&gt;Other things that can be a part of Infrastructure layer&lt;/li&gt;
&lt;li&gt;Recommendations for smaller APIs&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Other recommendations and best practices&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Error Handling&lt;/li&gt;
&lt;li&gt;Testing&lt;/li&gt;
&lt;li&gt;Configuration&lt;/li&gt;
&lt;li&gt;Logging&lt;/li&gt;
&lt;li&gt;Health monitoring&lt;/li&gt;
&lt;li&gt;Folder and File Structure&lt;/li&gt;
&lt;li&gt;File names&lt;/li&gt;
&lt;li&gt;Static Code Analysis&lt;/li&gt;
&lt;li&gt;Code formatting&lt;/li&gt;
&lt;li&gt;Documentation&lt;/li&gt;
&lt;li&gt;Make application easy to setup&lt;/li&gt;
&lt;li&gt;Seeds&lt;/li&gt;
&lt;li&gt;Migrations&lt;/li&gt;
&lt;li&gt;Rate Limiting&lt;/li&gt;
&lt;li&gt;Code Generation&lt;/li&gt;
&lt;li&gt;Custom utility types&lt;/li&gt;
&lt;li&gt;Pre-push/pre-commit hooks&lt;/li&gt;
&lt;li&gt;Prevent massive inheritance chains&lt;/li&gt;
&lt;li&gt;Conventional commits&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Additional resources&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Articles&lt;/li&gt;
&lt;li&gt;Repositories&lt;/li&gt;
&lt;li&gt;Documentation&lt;/li&gt;
&lt;li&gt;Blogs&lt;/li&gt;
&lt;li&gt;Videos&lt;/li&gt;
&lt;li&gt;Books&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h1&gt;
  
  
  Architecture
&lt;/h1&gt;

&lt;p&gt;Mainly based on:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Domain-driven_design" rel="noopener noreferrer"&gt;Domain-Driven Design (DDD)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.octo.com/en/hexagonal-architecture-three-principles-and-an-implementation-example/" rel="noopener noreferrer"&gt;Hexagonal (Ports and Adapters) Architecture &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.manning.com/books/secure-by-design" rel="noopener noreferrer"&gt;Secure by Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html" rel="noopener noreferrer"&gt;Clean Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://herbertograca.com/2017/09/21/onion-architecture/" rel="noopener noreferrer"&gt;Onion Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/SOLID" rel="noopener noreferrer"&gt;SOLID Principles&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://refactoring.guru/design-patterns/what-is-pattern" rel="noopener noreferrer"&gt;Software Design Patterns&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And many other sources (more links below in every chapter).&lt;/p&gt;

&lt;p&gt;Before we begin, here are the PROS and CONS of using a complete architecture like this:&lt;/p&gt;

&lt;h2&gt;
  
  
  Pros:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Independent of external frameworks, technologies, databases, etc. Frameworks and external resources can be plugged/unplugged with much less effort.&lt;/li&gt;
&lt;li&gt;Easily testable and scalable.&lt;/li&gt;
&lt;li&gt;More secure. Some security principles are baked in design itself.&lt;/li&gt;
&lt;li&gt;The solution can be worked on and maintained by different teams, without stepping on each other's toes.&lt;/li&gt;
&lt;li&gt;Easier to add new features. As the system grows over time, the difficulty in adding new features remains constant and relatively small.&lt;/li&gt;
&lt;li&gt;If the solution is properly broken apart along &lt;a href="https://martinfowler.com/bliki/BoundedContext.html" rel="noopener noreferrer"&gt;bounded context&lt;/a&gt; lines, it becomes easy to convert pieces of it into microservices if needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Cons:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;This is a sophisticated architecture which requires a firm understanding of quality software principles, such as SOLID, Clean/Hexagonal Architecture, Domain-Driven Design, etc. Any team implementing such a solution will almost certainly require an expert to drive the solution and keep it from evolving the wrong way and accumulating technical debt.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Some of the practices presented here are not recommended for small-medium sized applications with not a lot of business logic. There is added up-front complexity to support all those building blocks and layers, boilerplate code, abstractions, data mapping etc. thus implementing a complete architecture like this is generally ill-suited to simple CRUD applications and could over-complicate such solutions. Some of the described below principles can be used in a smaller sized applications but must be implemented only after analyzing and understanding all pros and cons.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Diagram
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/assets%2Fimages%2FDomainDrivenHexagon.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/assets%2Fimages%2FDomainDrivenHexagon.png" alt="Domain-Driven Hexagon"&gt;&lt;/a&gt;&lt;br&gt;
&lt;sup&gt;Diagram is mostly based on &lt;a href="https://github.com/hgraca/explicit-architecture-php#explicit-architecture-1" rel="noopener noreferrer"&gt;this one&lt;/a&gt; + others found online&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;In short, data flow looks like this (from left to right):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request/CLI command/event is sent to the controller using plain DTO;&lt;/li&gt;
&lt;li&gt;Controller parses this DTO, maps it to a Command/Query object format and passes it to a Application service;&lt;/li&gt;
&lt;li&gt;Application service handles this Command/Query; it executes business logic using domain services and/or entities and uses the infrastructure layer through ports;&lt;/li&gt;
&lt;li&gt;Infrastructure layer maps data to format that it needs, uses repositories to fetch/persist data and adapters to send events or do other I/O communications, maps data back to domain format and returns it back to Application service;&lt;/li&gt;
&lt;li&gt;After application service finishes doing it's job, it returns data/confirmation back to Controllers;&lt;/li&gt;
&lt;li&gt;Controllers return data back to the user (if application has presenters/views, those are returned instead).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Keep in mind&lt;/strong&gt; that different projects can have more or less steps/layers/building blocks than described here. Add more if application requires it, and skip some if application is not that complex and doesn't need all that abstraction.&lt;/p&gt;

&lt;p&gt;General recommendation for any project: analyze how big/complex the application will be, find a compromise and use as many layers/building blocks as needed for the project and skip ones that may over-complicate things.&lt;/p&gt;

&lt;p&gt;More in details on each step below.&lt;/p&gt;

&lt;h1&gt;
  
  
  Modules
&lt;/h1&gt;

&lt;p&gt;This project's code examples use separation by modules (also called components). Each module gets its own folder with a dedicated codebase, and each use case inside that module gets it's own folder to store most of the things it needs (this is also called &lt;em&gt;Vertical Slicing&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;It is easier to work on things that change together if those things are gathered relatively close to each other. Try not to create dependencies between modules or use cases, move shared logic into a separate files and make both depend on that instead of depending on each other.&lt;/p&gt;

&lt;p&gt;Try to make every module independent and keep interactions between modules minimal. Think of each module as a mini application bounded by a single context. Try to avoid direct imports between modules (like importing a service from other domain) since this creates &lt;a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)" rel="noopener noreferrer"&gt;tight coupling&lt;/a&gt;. Communication between modules can be done using events, public interfaces or through a port/adapter (more on that topic below).&lt;/p&gt;

&lt;p&gt;This approach ensures &lt;a href="https://en.wikipedia.org/wiki/Loose_coupling" rel="noopener noreferrer"&gt;loose coupling&lt;/a&gt;, and, if bounded contexts are defined and designed properly, each module can be easily separated into a microservice if needed without touching any domain logic.&lt;/p&gt;

&lt;p&gt;A lof of people tend to create one module per entity, but this approach is not very good. Each module may have multiple entities. One thing to keep in mind is that putting entities in a single module requires those entities to have related business logic, don't group unrelated entities in one module.&lt;/p&gt;

&lt;p&gt;Read more about modular programming benefits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.tiny.cloud/blog/modular-programming-principle/" rel="noopener noreferrer"&gt;Modular programming: Beyond the spaghetti mess&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each module is separated in layers described below.&lt;/p&gt;

&lt;h1&gt;
  
  
  Application Core
&lt;/h1&gt;

&lt;p&gt;This is the core of the system which is built using &lt;a href="https://dzone.com/articles/ddd-part-ii-ddd-building-blocks" rel="noopener noreferrer"&gt;DDD building blocks&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dependencies point inwards&lt;/strong&gt;. Outer layers can depend on inner layers, but inner layers never depend on outer layers.&lt;/p&gt;

&lt;p&gt;Core layers shouldn't depend on frameworks or access external resources. Any external calls to out-of-process resources/retrieval of data from remote processes should be done through &lt;code&gt;ports&lt;/code&gt; (interfaces), with class implementations created somewhere in infrastructure layer and injected into application's core (&lt;a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="noopener noreferrer"&gt;Dependency Injection&lt;/a&gt; and &lt;a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle" rel="noopener noreferrer"&gt;Dependency Inversion&lt;/a&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  Application's Core consists of:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Domain layer:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Entities&lt;/li&gt;
&lt;li&gt;Aggregates&lt;/li&gt;
&lt;li&gt;Domain Services&lt;/li&gt;
&lt;li&gt;Value Objects&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Application layer:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Application Services&lt;/li&gt;
&lt;li&gt;Commands and Queries&lt;/li&gt;
&lt;li&gt;Ports&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is just a short list the main things that may reside in here. More building blocks may be added if needed.&lt;/p&gt;




&lt;h1&gt;
  
  
  Application layer
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Application Services
&lt;/h2&gt;

&lt;p&gt;Are also called "Workflow Services", "User Cases", "Interactors" etc.&lt;br&gt;
These services orchestrate the steps required to fulfill the commands imposed by the client.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Typically used to orchestrate how the outside world interacts with your application and performs tasks required by the end users.&lt;/li&gt;
&lt;li&gt;Contain no domain-specific business logic;&lt;/li&gt;
&lt;li&gt;Operate on scalar types, transforming them into Domain types. A scalar type can be considered any type that's unknown to the Domain Model. This includes primitive types and types that don't belong to the Domain.&lt;/li&gt;
&lt;li&gt;Application services declare dependencies on infrastructural services required to execute domain logic (by using ports).&lt;/li&gt;
&lt;li&gt;Are used in order to fetch domain &lt;code&gt;Entities&lt;/code&gt; (or anything else) from database/outside world through ports;&lt;/li&gt;
&lt;li&gt;Execute other out-of-process communications through &lt;code&gt;Ports&lt;/code&gt; (like event emits, sending emails etc);&lt;/li&gt;
&lt;li&gt;In case of interacting with one Entity/Aggregate, executes its methods directly;&lt;/li&gt;
&lt;li&gt;In case of working with multiple Entities/Aggregates, uses a &lt;code&gt;Domain Service&lt;/code&gt; to orchestrate them;&lt;/li&gt;
&lt;li&gt;Are basically a &lt;code&gt;Command&lt;/code&gt;/&lt;code&gt;Query&lt;/code&gt; handlers;&lt;/li&gt;
&lt;li&gt;Should not depend on other application services since it may cause problems (like cyclic dependencies);&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One service per use case is considered a good practice.&lt;/p&gt;

&lt;p&gt;What are "Use Cases"?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Use_case" rel="noopener noreferrer"&gt;wiki&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&amp;gt; In software and systems engineering, a use case is a list of actions or event steps typically defining the interactions between a role (known in the Unified Modeling Language as an actor) and a system to achieve a goal.&lt;/p&gt;

&lt;p&gt;Use cases are, simply said, list of actions required from an application.&lt;/p&gt;



&lt;p&gt;Example file: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.service.ts" rel="noopener noreferrer"&gt;create-user.service.ts&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;More about services:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/domain-application-infrastructure-services-pattern.html" rel="noopener noreferrer"&gt;Domain-Application-Infrastructure Services pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer20.com/services-in-ddd-finally-explained/" rel="noopener noreferrer"&gt;Services in DDD finally explained&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Notes: Interfaces for each Use Case and Local DTOs&lt;/p&gt;
&lt;h3&gt;
  
  
  Interfaces for each use case
&lt;/h3&gt;

&lt;p&gt;Some people prefer having an interface for each use case (Driving Port), which &lt;code&gt;Application Service&lt;/code&gt; implements and a &lt;code&gt;Controller&lt;/code&gt; depends on. This is a viable option, but this project doesn't use interfaces for every use case for simplicity: it makes sense using interfaces when there are &lt;strong&gt;multiple&lt;/strong&gt; implementations of a workflow, but use cases are too specific and should not have multiple implementations of the same workflow (&lt;strong&gt;one&lt;/strong&gt; service per use case rule mentioned above). &lt;code&gt;Controllers&lt;/code&gt; naturally depend on a concrete implementation thus making interfaces redundant. More on this topic &lt;a href="https://stackoverflow.com/questions/62818105/interface-for-use-cases-application-services" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  Local DTOs
&lt;/h3&gt;

&lt;p&gt;Another thing that can be seen in some projects is local DTOs. Some people prefer never use domain objects (like entities) outside of core (in &lt;code&gt;controllers&lt;/code&gt;, for example), and are using DTOs instead. This project doesn't use this technique to avoid extra interfaces and data mapping. Either to use local DTOs or not is a matter of taste.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://martinfowler.com/bliki/LocalDTO.html" rel="noopener noreferrer"&gt;Here&lt;/a&gt; are Martin Fowler's thoughts on local DTOs, in short (quote):&lt;/p&gt;

&lt;p&gt;&amp;gt; Some people argue for them(DTOs) as part of a Service Layer API because they ensure that service layer clients aren't dependent upon an underlying Domain Model. While that may be handy, I don't think it's worth the cost of all of that data mapping.&lt;/p&gt;




&lt;h2&gt;
  
  
  Commands and Queries
&lt;/h2&gt;

&lt;p&gt;This principle is called &lt;a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation" rel="noopener noreferrer"&gt;Command–Query Separation(CQS)&lt;/a&gt;. When possible, methods should be separated into &lt;code&gt;Commands&lt;/code&gt; (state-changing operations) and &lt;code&gt;Queries&lt;/code&gt; (data-retrieval operations). To make a clear distinction between those two types of operations, input objects can be represented as &lt;code&gt;Commands&lt;/code&gt; and &lt;code&gt;Queries&lt;/code&gt;. Before DTO reaches the domain, it is converted into a &lt;code&gt;Command&lt;/code&gt;/&lt;code&gt;Query&lt;/code&gt; object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Commands
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Commands&lt;/code&gt; are used for state-changing actions, like creating new user and saving it to the database. Create, Update and Delete operations are considered as state-changing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Data retrieval is responsibility of &lt;code&gt;Queries&lt;/code&gt;, so &lt;code&gt;Command&lt;/code&gt; methods should not return anything. Though, if needed, returning a bare minimum (like &lt;code&gt;ID&lt;/code&gt; of a created item or a confirmation message) may not be a bad idea.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: &lt;code&gt;Command&lt;/code&gt; has nothing to do with &lt;a href="https://refactoring.guru/design-patterns/command" rel="noopener noreferrer"&gt;Command Pattern&lt;/a&gt;, it is just a convenient name to represent that this object invokes a CQS Command. Both &lt;code&gt;Commands&lt;/code&gt; and &lt;code&gt;Queries&lt;/code&gt; in this example are just simple objects with data.&lt;/p&gt;

&lt;p&gt;Example of command object: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.command.ts" rel="noopener noreferrer"&gt;create-user.command.ts&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Queries
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Query&lt;/code&gt; is used for retrieving data and should not make any state changes (like writes to the database, files etc).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Queries are usually just a data retrieval operation and have no business logic involved; so, if needed, application and domain layers can be bypassed completely. Though, if some additional non-state changing logic has to be applied before returning a query response (like calculating something), it should be done in a corresponding application service.&lt;/p&gt;

&lt;p&gt;Validation also can be skipped, since no input is persisted in query operations. But, if needed, it can be validated to tell the user that query format is incorrect (when using enums for example).&lt;/p&gt;

&lt;p&gt;Example of query bypassing application/domain layers completely: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/find-user-by-email/find-user-by-email.http.controller.ts" rel="noopener noreferrer"&gt;find-user-by-email.http.controller.ts&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Some simple cases may not need a &lt;code&gt;Command&lt;/code&gt;/&lt;code&gt;Query&lt;/code&gt; object, like find query or delete command may only need an ID so there is no point in creating an object for that.&lt;/p&gt;

&lt;p&gt;Read more about CQS:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://martinfowler.com/bliki/CommandQuerySeparation.html" rel="noopener noreferrer"&gt;Martin Fowler blog&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://khalilstemmler.com/articles/oop-design-principles/command-query-segregation/" rel="noopener noreferrer"&gt;Command Query Segregation&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Ports
&lt;/h2&gt;

&lt;p&gt;Ports (for Driven Adapters) are interfaces that define contracts which must be implemented by infrastructure adapters in order to execute some action more related to technology details rather than business logic. Ports act like abstractions for technology details that business logic does not care about.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Ports are basically just interfaces that define what has to be done and don't care about how it is done.&lt;/li&gt;
&lt;li&gt;Ports should be created to fit the Domain needs, not simply mimic the tools APIs.&lt;/li&gt;
&lt;li&gt;Mock implementations can be passed to ports while testing. Mocking makes your tests faster and independent from the environment.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: since most ports implementations are injected and executed in application service, Application Layer can be a good place to keep those ports. But there are times when Domain Layer's business logic depends on executing some external resource, in that case those ports can be put in a Domain Layer.&lt;/p&gt;

&lt;p&gt;Example file: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/ports/repository.ports.ts" rel="noopener noreferrer"&gt;repository.ports.ts&lt;/a&gt;&lt;/p&gt;




&lt;h1&gt;
  
  
  Domain Layer
&lt;/h1&gt;

&lt;p&gt;This layer contains application's business rules.&lt;/p&gt;

&lt;p&gt;Domain should only operate using domain objects, most important ones are described below.&lt;/p&gt;

&lt;h2&gt;
  
  
  Entities
&lt;/h2&gt;

&lt;p&gt;Entities are the core of the domain. They encapsulate Enterprise wide business rules and attributes. An entity can be an object with properties and methods, or it can be a set of data structures and functions.&lt;/p&gt;

&lt;p&gt;Entities represent business models and express what properties a particular model has, what it can do, when and at what conditions it can do it. An example of business model can be a User, Product, Booking, Ticket, Wallet etc.&lt;/p&gt;

&lt;p&gt;Entities must always protect it's &lt;a href="https://en.wikipedia.org/wiki/Class_invariant" rel="noopener noreferrer"&gt;invariant&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Domain entities should always be valid entities. There are a certain number of invariants for an object that should always be true. For example, an order item object always has to have a quantity that must be a positive integer, plus an article name and price. Therefore, invariants enforcement is the responsibility of the domain entities (especially of the aggregate root) and an entity object should not be able to exist without being valid.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Entities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Contain Domain business logic. Avoid having business logic in your services when possible, this leads to &lt;a href="https://martinfowler.com/bliki/AnemicDomainModel.html" rel="noopener noreferrer"&gt;Anemic Domain Model&lt;/a&gt; (domain services are exception for business logic that can't be put in a single entity).&lt;/li&gt;
&lt;li&gt;Have an identity that defines it and makes it distinguishable from others. It's identity is consistent during its life cycle.&lt;/li&gt;
&lt;li&gt;Equality between two entities is determined by comparing their identificators (usually its &lt;code&gt;id&lt;/code&gt; field).&lt;/li&gt;
&lt;li&gt;Can contain other objects, such as other entities or value objects.&lt;/li&gt;
&lt;li&gt;Are responsible for collecting all the understanding of state and how it changes in the same place.&lt;/li&gt;
&lt;li&gt;Responsible for the coordination of operations on the objects it owns.&lt;/li&gt;
&lt;li&gt;Know nothing about upper layers (services, controllers etc).&lt;/li&gt;
&lt;li&gt;Domain entities data should be modelled to accommodate business logic, not some database schema.&lt;/li&gt;
&lt;li&gt;Entities must protect their invariants, try to avoid public setters - update state using methods and execute invariant validation on each update if needed (this can be a simple &lt;code&gt;validate()&lt;/code&gt; method that checks if business rules are not violated by update).&lt;/li&gt;
&lt;li&gt;Must be consistent on creation. Validate Entities and other domain objects on creation and throw an error on first failure. &lt;a href="https://en.wikipedia.org/wiki/Fail-fast" rel="noopener noreferrer"&gt;Fail Fast&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Avoid no-arg (empty) constructors, accept and validate all required properties through a constructor.&lt;/li&gt;
&lt;li&gt;For optional properties that require some complex setting up, &lt;a href="https://en.wikipedia.org/wiki/Fluent_interface" rel="noopener noreferrer"&gt;Fluent interface&lt;/a&gt; and &lt;a href="https://refactoring.guru/design-patterns/builder" rel="noopener noreferrer"&gt;Builder Pattern&lt;/a&gt; can be used.&lt;/li&gt;
&lt;li&gt;Make Entities partially immutable. Identify what properties shouldn't change after creation and make them &lt;code&gt;readonly&lt;/code&gt; (for example &lt;code&gt;id&lt;/code&gt; or &lt;code&gt;createdAt&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/domain/entities/user.entity.ts" rel="noopener noreferrer"&gt;user.entity.ts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/domain-entity-pattern.html" rel="noopener noreferrer"&gt;Domain Entity pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-6/" rel="noopener noreferrer"&gt;Secure by design: Chapter 6 Ensuring integrity of state&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Aggregates
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://martinfowler.com/bliki/DDD_Aggregate.html" rel="noopener noreferrer"&gt;Aggregate&lt;/a&gt; is a cluster of domain objects that can be treated as a single unit. It encapsulates entities and value objects which conceptually belong together. It also contains a set of operations which those domain objects can be operated on.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Aggregates help to simplify the domain model by gathering multiple domain objects under a single abstraction.&lt;/li&gt;
&lt;li&gt;Aggregates should not be influenced by data model. Associations between domain objects are not the same as database relationships.&lt;/li&gt;
&lt;li&gt;Aggregate root is an entity that contains other entities/value objects and all logic to operate them.&lt;/li&gt;
&lt;li&gt;Aggregate root has global identity. Entities inside the boundary have local identity, unique only within the Aggregate.&lt;/li&gt;
&lt;li&gt;Aggregate root is a gateway to entire aggregate. Any references from outside the aggregate should &lt;strong&gt;only&lt;/strong&gt; go to the aggregate root.&lt;/li&gt;
&lt;li&gt;Any operations on an aggregate must be &lt;a href="https://en.wikipedia.org/wiki/Database_transaction" rel="noopener noreferrer"&gt;transactional operations&lt;/a&gt;. Either everything gets saved/updated/deleted or nothing.&lt;/li&gt;
&lt;li&gt;Only Aggregate Roots can be obtained directly with database queries. Everything else must be done through traversal.&lt;/li&gt;
&lt;li&gt;Similar to &lt;code&gt;Entities&lt;/code&gt;, aggregates must protect their invariants through entire lifecycle. When a change to any object within the Aggregate boundary is committed, all invariants of the whole Aggregate must be satisfied.&lt;/li&gt;
&lt;li&gt;Objects within the Aggregate can hold references to other Aggregate roots. Prefer references to external aggregates only by their globally unique identity, not by holding a direct object reference.&lt;/li&gt;
&lt;li&gt;Try to avoid aggregates that are too big, this can lead to performance and maintaining problems.&lt;/li&gt;
&lt;li&gt;Aggregates can publish &lt;code&gt;Domain Events&lt;/code&gt; (more on that below).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All of this rules just come from the idea of creating a boundary around Aggregates. The boundary simplifies business model, as it forces us to consider each relationship very carefully, and within a well-defined set of rules.&lt;/p&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/base-classes/aggregate-root.base.ts" rel="noopener noreferrer"&gt;aggregate-root.base.ts&lt;/a&gt; - abstract base class.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/domain/entities/user.entity.ts" rel="noopener noreferrer"&gt;user.entity.ts&lt;/a&gt; - aggregate implementations are similar to &lt;code&gt;Entities&lt;/code&gt;, with some additional rules described above.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://dzone.com/articles/domain-driven-design-aggregate" rel="noopener noreferrer"&gt;Understanding Aggregates in Domain-Driven Design&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.jamesmichaelhickey.com/domain-driven-design-aggregates/" rel="noopener noreferrer"&gt;What Are Aggregates In Domain-Driven Design?&lt;/a&gt; &amp;lt;- this is a series of multiple articles, don't forget to click "Next article" at the end.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf" rel="noopener noreferrer"&gt;Effective Aggregate Design Part I: Modeling a Single Aggregate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_2.pdf" rel="noopener noreferrer"&gt;Effective Aggregate Design Part II: Making Aggregates Work Together&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Domain Events
&lt;/h2&gt;

&lt;p&gt;Domain event indicates that something happened in a domain that you want other parts of the same domain (in-process) to be aware of.&lt;/p&gt;

&lt;p&gt;For example, if a user buys something, you may want to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Send confirmation email to that user;&lt;/li&gt;
&lt;li&gt;Send notification to a corporate slack channel;&lt;/li&gt;
&lt;li&gt;Notify shipping department;&lt;/li&gt;
&lt;li&gt;Perform other side effects that are not concern of an original buy operation domain.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Typical approach that is usually used involves executing all this logic in a service that performs a buy operation. But this creates coupling between different subdomains.&lt;/p&gt;

&lt;p&gt;A better approach would be publishing a &lt;code&gt;Domain Event&lt;/code&gt;. Any side effect operations can be performed just by subscribing to a concrete &lt;code&gt;Domain Event&lt;/code&gt; and creating as many event handlers as needed, without glueing any unrelated code to original domain's service that sends an event.&lt;/p&gt;

&lt;p&gt;Domain events are just messages pushed to a domain event dispatcher in the same process. Out-of-process communications (like microservices) are called &lt;a href="https://arleypadua.medium.com/domain-events-vs-integration-events-5eb29a34fdbc" rel="noopener noreferrer"&gt;Integration Events&lt;/a&gt;. If sending a Domain Event to external process is needed then domain event handler should send an &lt;code&gt;Integration Event&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Domain Events may be useful for creating an &lt;a href="https://en.wikipedia.org/wiki/Audit_trail" rel="noopener noreferrer"&gt;audit log&lt;/a&gt; to track all changes to important entities by saving each event to the database. Read more on why audit logs may be useful: &lt;a href="https://jameshalsall.co.uk/posts/why-soft-deletes-are-evil-and-what-to-do-instead" rel="noopener noreferrer"&gt;Why soft deletes are evil and what to do instead&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There may be different ways on implementing Domain Events, for example using some kind of internal event bus/emitter, like &lt;a href="https://www.tutorialspoint.com/nodejs/nodejs_event_emitter.htm" rel="noopener noreferrer"&gt;Event Emitter&lt;/a&gt;, or using patterns like &lt;a href="https://refactoring.guru/design-patterns/mediator" rel="noopener noreferrer"&gt;Mediator&lt;/a&gt; or slightly modified &lt;a href="https://refactoring.guru/design-patterns/observer" rel="noopener noreferrer"&gt;Observer&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/domain-events/domain-events.ts" rel="noopener noreferrer"&gt;domain-events.ts&lt;/a&gt; - this class is responsible for providing publish/subscribe functionality for anyone who needs to emit or listen to events.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/domain/events/user-created.domain-event.ts" rel="noopener noreferrer"&gt;user-created.domain-event.ts&lt;/a&gt; - simple object that holds data related to published event.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/domain-event-handlers/user-created.event-handler.ts" rel="noopener noreferrer"&gt;user-created.event-handler.ts&lt;/a&gt; - this is an example of Domain Event Handler that executes actions and side-effects when a domain event is raised (in this case, user is created). Domain event handlers belong to Application layer.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/infrastructure/database/base-classes/typeorm.repository.base.ts" rel="noopener noreferrer"&gt;typeorm.repository.base.ts&lt;/a&gt; - repository publishes all events for execution right before or right after persisting transaction.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Events can be published right before or right after insert/update/delete transaction, chose any option that is better for a particular project:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Before: to make side-effects part of that transaction. If any event fails all changes should be reverted.&lt;/li&gt;
&lt;li&gt;After: to persist transaction even if some event fails. This makes side-effects independent, but in that case &lt;a href="https://en.wikipedia.org/wiki/Eventual_consistency" rel="noopener noreferrer"&gt;eventual consistency&lt;/a&gt; should be implemented.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both options have pros and cons.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: this project uses custom implementation for Domain Events. Reason for not using &lt;a href="https://nodejs.org/api/events.html" rel="noopener noreferrer"&gt;Node Event Emitter&lt;/a&gt; is that event emitter executes events immediately when called instead of when we want it (before/after transaction), and also has no option to &lt;code&gt;await&lt;/code&gt; for all events to finish, which might be useful when making those events a part of transaction.&lt;/p&gt;

&lt;p&gt;To have a better understanding on domain events and implementation read this:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/domain-event-pattern.html" rel="noopener noreferrer"&gt;Domain Event pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation" rel="noopener noreferrer"&gt;Domain events: design and implementation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For integration events in distributed systems here are some useful patterns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.kamilgrzybek.com/design/the-outbox-pattern/" rel="noopener noreferrer"&gt;The Outbox Pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing" rel="noopener noreferrer"&gt;Event Sourcing pattern&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Domain Services
&lt;/h2&gt;

&lt;p&gt;Eric Evans, Domain-Driven Design:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Domain services are used for "a significant process or transformation in the domain that is not a natural responsibility of an ENTITY or VALUE OBJECT"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Domain Service is a specific type of domain layer class that is used to execute domain logic that relies on two or more &lt;code&gt;Entities&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Domain Services are used when putting the logic on a particular &lt;code&gt;Entity&lt;/code&gt; would break encapsulation and require the &lt;code&gt;Entity&lt;/code&gt; to know about things it really shouldn't be concerned with.&lt;/li&gt;
&lt;li&gt;Domain services are very granular where as application services are a facade purposed with providing an API.&lt;/li&gt;
&lt;li&gt;Domain services operate only on types belonging to the Domain. They contain meaningful concepts that can be found within the Ubiquitous Language. They hold operations that don't fit well into Value Objects or Entities.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Value objects
&lt;/h2&gt;

&lt;p&gt;Some Attributes and behaviors can be moved out of the entity itself and put into &lt;code&gt;Value Objects&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Value Objects:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Have no identity. Equality is determined through structural property.&lt;/li&gt;
&lt;li&gt;Are immutable.&lt;/li&gt;
&lt;li&gt;Can be used as an attribute of &lt;code&gt;entities&lt;/code&gt; and other &lt;code&gt;value objects&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Explicitly defines and enforces important constraints (invariants).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Value object shouldn’t be just a convenient grouping of attributes but should form a well-defined concept in the domain model. This is true even if it contains only one attribute. When modeled as a conceptual whole, it carries meaning when passed around, and it can uphold its constraints.&lt;/p&gt;

&lt;p&gt;Imagine you have a &lt;code&gt;User&lt;/code&gt; entity which needs to have an &lt;code&gt;address&lt;/code&gt; of a user. Usually an address is simply a complex value that has no identity in the domain and is composed of multiple other values, like &lt;code&gt;country&lt;/code&gt;, &lt;code&gt;street&lt;/code&gt;, &lt;code&gt;postalCode&lt;/code&gt; etc; so it can be modeled and treated as a &lt;code&gt;Value Object&lt;/code&gt; with it's own business logic.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Value object&lt;/code&gt; isn’t just a data structure that holds values. It can also encapsulate logic associated with the concept it represents.&lt;/p&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/domain/value-objects/address.value-object.ts" rel="noopener noreferrer"&gt;address.value-object.ts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more about Value Objects:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://martinfowler.com/bliki/ValueObject.html" rel="noopener noreferrer"&gt;Martin Fowler blog&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://medium.com/swlh/value-objects-to-the-rescue-28c563ad97c6" rel="noopener noreferrer"&gt;Value Objects to the rescue&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a href="https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/value-object-pattern.html" rel="noopener noreferrer"&gt;Value Object pattern&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Enforcing invariants of Domain Objects
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Replacing primitives with Value Objects
&lt;/h3&gt;

&lt;p&gt;Most of the code bases operate on primitive types – &lt;code&gt;strings&lt;/code&gt;, &lt;code&gt;numbers&lt;/code&gt; etc. In the Domain Model, this level of abstraction may be too low.&lt;/p&gt;

&lt;p&gt;Significant business concepts can be expressed using specific types and classes. &lt;code&gt;Value Objects&lt;/code&gt; can be used instead primitives to avoid &lt;a href="https://refactoring.guru/smells/primitive-obsession" rel="noopener noreferrer"&gt;primitives obsession&lt;/a&gt;.&lt;br&gt;
So, for example, &lt;code&gt;email&lt;/code&gt; of type &lt;code&gt;string&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;

&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kr"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;could be represented as a &lt;code&gt;Value Object&lt;/code&gt; instead:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;

&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Email&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now the only way to make an &lt;code&gt;email&lt;/code&gt; is to create a new instance of &lt;code&gt;Email&lt;/code&gt; class first, this ensures it will be validated on creation and a wrong value won't get into &lt;code&gt;Entities&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Also an important behavior of the domain primitive is encapsulated in one place. By having the domain primitive own and control domain operations, you reduce the risk of bugs caused by lack of detailed domain knowledge of the concepts involved in the operation.&lt;/p&gt;

&lt;p&gt;Creating an object for primitive values may be cumbersome, but it somewhat forces a developer to study domain more in details instead of just throwing a primitive type without even thinking what that value represents in domain.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;Value Objects&lt;/code&gt; for primitive types is also called a &lt;code&gt;domain primitive&lt;/code&gt;. The concept and naming are proposed in the book &lt;a href="https://www.manning.com/books/secure-by-design" rel="noopener noreferrer"&gt;"Secure by Design"&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;Value Objects&lt;/code&gt; instead of primitives:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Makes code easier to understand by using &lt;a href="https://martinfowler.com/bliki/UbiquitousLanguage.html" rel="noopener noreferrer"&gt;ubiquitous language&lt;/a&gt; instead of just &lt;code&gt;string&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Improves security by ensuring invariants of every property.&lt;/li&gt;
&lt;li&gt;Encapsulates specific business rules associated with a value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also an alternative for creating an object may be a &lt;a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases" rel="noopener noreferrer"&gt;type alias&lt;/a&gt; just to give this primitive a semantic meaning.&lt;/p&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/domain/value-objects/email.value-object.ts" rel="noopener noreferrer"&gt;email.value-object.ts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Recommended to read:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://medium.com/the-sixt-india-blog/primitive-obsession-code-smell-that-hurt-people-the-most-5cbdd70496e9" rel="noopener noreferrer"&gt;Primitive Obsession — A Code Smell that Hurts People the Most&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/@nicolopigna/value-objects-like-a-pro-f1bfc1548c72" rel="noopener noreferrer"&gt;Value Objects Like a Pro&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/@felipefreitasbatista/developing-the-ubiquitous-language-1382b720bb8c" rel="noopener noreferrer"&gt;Developing the ubiquitous language&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Value Objects/Domain Primitives and Types system to make illegal states unrepresentable in your program.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some people recommend using objects for &lt;strong&gt;every&lt;/strong&gt; value:&lt;/p&gt;

&lt;p&gt;Quote from &lt;a href="https://twitter.com/jdegoes" rel="noopener noreferrer"&gt;John A De Goes&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Making illegal states unrepresentable is all about statically proving that all runtime values (without exception) correspond to valid objects in the business domain. The effect of this technique on eliminating meaningless runtime states is astounding and cannot be overstated.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets distinguish two types of protection from illegal states: at &lt;strong&gt;compile time&lt;/strong&gt; and at &lt;strong&gt;runtime&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  At compile time
&lt;/h3&gt;

&lt;p&gt;Types give useful semantic information to a developer. Good code should be easy to use correctly, and hard to use incorrectly. Types system can be a good help for that. It can prevent some nasty errors at a compile time, so IDE will show type errors right away.&lt;/p&gt;

&lt;p&gt;The simplest example may be using enums instead of constants, and use those enums as input type for something. When passing anything that is not intended IDE will show a type error.&lt;/p&gt;

&lt;p&gt;Or, for example, imagine that business logic requires to have contact info of a person by either having &lt;code&gt;email&lt;/code&gt;, or &lt;code&gt;phone&lt;/code&gt;, or both. Both &lt;code&gt;email&lt;/code&gt; and &lt;code&gt;phone&lt;/code&gt; could be represented as optional, for example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;

&lt;span class="kr"&gt;interface&lt;/span&gt; &lt;span class="nx"&gt;ContactInfo&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;email&lt;/span&gt;&lt;span class="p"&gt;?:&lt;/span&gt; &lt;span class="nx"&gt;Email&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nl"&gt;phone&lt;/span&gt;&lt;span class="p"&gt;?:&lt;/span&gt; &lt;span class="nx"&gt;Phone&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;But what happens if both are not provided by a programmer? Business rule violated. Illegal state allowed.&lt;/p&gt;

&lt;p&gt;Solution: this could be presented as a &lt;a href="https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types" rel="noopener noreferrer"&gt;union type&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;ContactInfo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;Email&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="nx"&gt;Phone&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;Email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;Phone&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now only either &lt;code&gt;Email&lt;/code&gt;, or &lt;code&gt;Phone&lt;/code&gt;, or both must be provided. If nothing is provided IDE will show a type error right away. This is a business rule validation used at &lt;strong&gt;compile time&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This approach can be used to make business logic safer and get an error as fast as possible (at compile time).&lt;/p&gt;

&lt;h3&gt;
  
  
  At runtime
&lt;/h3&gt;

&lt;p&gt;Things that can't be validated at compile time (like user input) are validated at runtime.&lt;/p&gt;

&lt;p&gt;Domain objects have to protect their invariants. Having some validation rules here will protect their state from corruption.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Value Object&lt;/code&gt; can represent a typed value in domain (a &lt;em&gt;domain primitive&lt;/em&gt;). The goal here is to encapsulate validations and business logic related only to the represented fields and make it impossible to pass around raw values by forcing a creation of valid &lt;code&gt;Value Objects&lt;/code&gt; first. This object only accepts values which make sense in its context.&lt;/p&gt;

&lt;p&gt;If every argument and return value of a method is valid by definition, you’ll have input and output validation in every single method in your codebase without any extra effort. This will make application more resilient to errors and will protect it from a whole class of bugs and security vulnerabilities caused by invalid input data.&lt;/p&gt;

&lt;p&gt;Data should not be trusted. There are a lot of cases when invalid data may end up in a domain. For example, if data comes from external API, database, or if it's just a programmer error.&lt;/p&gt;

&lt;p&gt;Enforcing self-validation will inform immediately when data is corrupted. Not validating domain objects allows them to be in an incorrect state, this leads to problems.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Without domain primitives, the remaining code needs to take care of validation, formatting, comparing, and lots of other details. Entities represent long-lived objects with a distinguished identity, such as articles in a news feed, rooms in a hotel, and shopping carts in online sales. The functionality in a system often centers around changing the state of these objects: hotel rooms are booked, shopping cart contents are&lt;br&gt;
paid for, and so on. Sooner or later the flow of control will be guided to some code representing these entities. And if all the data is transmitted as generic types such as int or String , responsibilities fall on the entity code to validate, compare, and format the data, among other tasks. The entity code will be burdened with a lot of&lt;br&gt;
tasks, rather than focusing on the central business flow-of-state changes that it models. Using domain primitives can counteract the tendency for entities to grow overly complex.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Quote from: &lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-5/96" rel="noopener noreferrer"&gt;Secure by design: Chapter 5.3 Standing on the shoulders of domain primitives&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Though &lt;em&gt;primitive obsession&lt;/em&gt; is a code smell, some people consider making a class/object for every primitive may be an overengineering. For less complex and smaller projects it definitely may be. For bigger projects, there are people who advocate for and against this approach. If creating a class for every primitive is not preferred, create classes just for those primitives that have specific rules or behavior, or just validate only outside of domain using some validation framework. Here are some thoughts on this topic: &lt;a href="https://blog.ploeh.dk/2015/01/19/from-primitive-obsession-to-domain-modelling/#7172fd9ca69c467e8123a20f43ea76c2" rel="noopener noreferrer"&gt;From Primitive Obsession to Domain Modelling - Over-engineering?&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recommended to read&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://v5.chriskrycho.com/journal/making-illegal-states-unrepresentable-in-ts/" rel="noopener noreferrer"&gt;Making illegal states unrepresentable&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://freecontent.manning.com/domain-primitives-what-they-are-and-how-you-can-use-them-to-make-more-secure-software/" rel="noopener noreferrer"&gt;Domain Primitives: what they are and how you can use them to make more secure software&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-5/" rel="noopener noreferrer"&gt;"Secure by Design" Chapter 5: Domain Primitives&lt;/a&gt; (a full chapter of the article above)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How to do simple validation?
&lt;/h3&gt;

&lt;p&gt;For simple validation like checking for nulls, empty arrays, input length etc. a library of &lt;a href="https://en.wikipedia.org/wiki/Guard_(computer_science)" rel="noopener noreferrer"&gt;guards&lt;/a&gt; can be created.&lt;/p&gt;

&lt;p&gt;Example file: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/guard.ts" rel="noopener noreferrer"&gt;guard.ts&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Read more: &lt;a href="https://medium.com/better-programming/refactoring-guard-clauses-2ceeaa1a9da" rel="noopener noreferrer"&gt;Refactoring: Guard Clauses&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another solution would be using an external validation library, but it is not a good practice to tie domain to external libraries and is not usually recommended.&lt;/p&gt;

&lt;p&gt;Although exceptions can be made if needed, especially for very specific validation libraries that validate only one thing (like specific IDs, for example bitcoin wallet address). Tying only one or just few &lt;code&gt;Value Objects&lt;/code&gt; to such a specific library won't cause any harm. Unlike general purpose validation libraries which will be tied to domain everywhere and it will be troublesome to change it in every &lt;code&gt;Value Object&lt;/code&gt; in case when old library is no longer maintained, contains critical bugs or is compromised by hackers etc.&lt;/p&gt;

&lt;p&gt;Though, it is fine to do full sanity checks using validation framework or library &lt;strong&gt;outside&lt;/strong&gt; of domain (for example &lt;a href="https://www.npmjs.com/package/class-validator" rel="noopener noreferrer"&gt;class-validator&lt;/a&gt; decorators in &lt;code&gt;DTOs&lt;/code&gt;), and do only some basic checks inside of &lt;code&gt;Value Objects&lt;/code&gt; (besides business rules), like checking for &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;, checking length, matching against simple regexp etc. to check if value makes sense and for extra security.&lt;/p&gt;

&lt;p&gt;Note about using regexp&lt;/p&gt;

&lt;p&gt;Be careful with custom regexp validations for things like validating &lt;code&gt;email&lt;/code&gt;, only use custom regexp for some very simple rules and, if possible, let validation library do it's job on more difficult ones to avoid problems in case your regexp is not good enough.&lt;/p&gt;

&lt;p&gt;Also, keep in mind that custom regexp that does same type of validation that is already done by validation library outside of domain may create conflicts between your regexp and the one used by a validation library.&lt;/p&gt;

&lt;p&gt;For example, value can be accepted as valid by a validation library, but &lt;code&gt;Value Object&lt;/code&gt; may throw an error because custom regexp is not good enough (validating &lt;code&gt;email&lt;/code&gt; is more complex than just copy - pasting a regular expression found in google. Though, it can be validated by a simple rule that is true all the time and won't cause any conflicts, like every &lt;code&gt;email&lt;/code&gt; must contain an &lt;code&gt;@&lt;/code&gt;). Try finding and validating only patterns that won't cause conflicts.&lt;/p&gt;



&lt;p&gt;Although there are other strategies on how to do validation inside domain, like passing validation schema as a dependency when creating new &lt;code&gt;Value Object&lt;/code&gt;, but this creates extra complexity.&lt;/p&gt;

&lt;p&gt;Either to use external library/framework for validation inside domain or not is a tradeoff, analyze all the pros and cons and choose what is more appropriate for current application.&lt;/p&gt;

&lt;p&gt;For some projects, especially smaller ones, it might be easier and more appropriate to just use validation library/framework.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep in mind&lt;/strong&gt; that not all validations can be done in a single &lt;code&gt;Value Object&lt;/code&gt;, it should validate only rules shared by all contexts. There are cases when validation may be different depending on a context, or one field may involve another field, or even a different entity. Handle those cases accordingly.&lt;/p&gt;

&lt;h3&gt;
  
  
  Types of validation
&lt;/h3&gt;

&lt;p&gt;There are some general recommendations for validation order. Cheap operations like checking for null/undefined and checking length of data come early in the list, and more expensive operations that require calling the database come later.&lt;/p&gt;

&lt;p&gt;Preferably in this order:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;Origin - Is the data from a legitimate sender?&lt;/em&gt; When possible, accept data only from authorized users / whitelisted IPs etc. depending on the situation.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Existence - are provided data not empty?&lt;/em&gt; Further validations make no sense if data is empty. Check for empty values: null/undefined, empty objects and arrays.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Size - Is it reasonably big?&lt;/em&gt; Before any further steps, check length/size of input data, no matter what type it is. This will prevent validating data that is too big which may block a thread entirely (sending data that is too big may be a DDoS attack).&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Lexical content - Does it contain the right characters and encoding?&lt;/em&gt; For example, if we expect data that only contains digits, we scan it to see if there’s anything else. If we find anything else, we draw the conclusion that the data is either broken by mistake or has been maliciously crafted to fool our system.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Syntax - Is the format right?&lt;/em&gt; Check if data format is right. Sometimes checking syntax is as simple as using a regexp, or it may be more complex like parsing a XML or JSON.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Semantics - Does the data make sense?&lt;/em&gt; Check data in connection with the rest of the system (like database, other processes etc). For example, checking in a database if ID of item exists.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more about validation types described above:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-4/109" rel="noopener noreferrer"&gt;"Secure by Design" Chapter 4.3: Validation&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Using libraries inside application's core
&lt;/h2&gt;

&lt;p&gt;Whether or not to use libraries in application layer and especially domain layer is a subject of a lot of debates. In real world, injecting every library instead of importing it directly is not always practical, so exceptions can be made for some single responsibility libraries that help to implement domain logic (like number converting libraries etc).&lt;/p&gt;

&lt;p&gt;Main recommendations to keep in mind is that libraries imported in application's core/domain &lt;strong&gt;shouldn't&lt;/strong&gt; expose:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Functionality to access any out-of-process resources (http calls, database access etc);&lt;/li&gt;
&lt;li&gt;Functionality not relevant to domain (frameworks, technology details like ORMs etc).&lt;/li&gt;
&lt;li&gt;Functionality that brings randomness (generating random IDs, timestamps etc) since this makes tests unpredictable (though in TypeScript world it is not that big of a deal since this can be mocked by a test library without using DI);&lt;/li&gt;
&lt;li&gt;If a library changes often or has a lot of dependencies of its own it most likely shouldn't be used in domain layer.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To use such libraries consider creating an &lt;code&gt;anti-corruption&lt;/code&gt; layer by using &lt;a href="https://refactoring.guru/design-patterns/adapter" rel="noopener noreferrer"&gt;adapter&lt;/a&gt; or &lt;a href="https://refactoring.guru/design-patterns/facade" rel="noopener noreferrer"&gt;facade&lt;/a&gt; patterns.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://medium.com/@malotor/anticorruption-layer-a-effective-shield-caa4d5ba548c" rel="noopener noreferrer"&gt;Anti-corruption Layer — An effective Shield&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Be careful with general purpose libraries/frameworks that may scatter across many domain objects. It will be hard to replace those libraries if needed.&lt;/p&gt;

&lt;p&gt;Tying only one or just few domain objects to some single-responsibility library should be fine. It is way easier to replace a specific library that is tied to one or few objects than a general purpose library that is everywhere.&lt;/p&gt;

&lt;p&gt;Offload as much of irrelevant responsibilities as possible from the core, especially from domain layer.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://khorikov.org/posts/2019-08-07-referencing-external-libs/" rel="noopener noreferrer"&gt;Referencing external libs&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  Interface Adapters
&lt;/h1&gt;

&lt;p&gt;Interface adapters (also called driving/primary adapters) are user-facing interfaces that take input data from the user and repackage it in a form that is convenient for the use cases(services) and entities. Then they take the output from those use cases and entities and repackage it in a form that is convenient for displaying it back for the user. User can be either a person using an application or another server.&lt;/p&gt;

&lt;p&gt;Contains &lt;code&gt;Controllers&lt;/code&gt; and &lt;code&gt;Request&lt;/code&gt;/&lt;code&gt;Response&lt;/code&gt; DTOs (can also contain &lt;code&gt;Views&lt;/code&gt;, like backend-generated HTML templates, if required).&lt;/p&gt;

&lt;h2&gt;
  
  
  Controllers
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Controllers are used for parsing requests, triggering use cases and presenting the result back to the client.&lt;/li&gt;
&lt;li&gt;One controller per use case is considered a good practice.&lt;/li&gt;
&lt;li&gt;In &lt;a href="https://docs.nestjs.com/" rel="noopener noreferrer"&gt;NestJS&lt;/a&gt; world controllers may be a good place to use &lt;a href="https://docs.nestjs.com/openapi/operations" rel="noopener noreferrer"&gt;OpenAPI/Swagger decorators&lt;/a&gt; for documentation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One controller per trigger type can be used to have a more clear separation. For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.http.controller.ts" rel="noopener noreferrer"&gt;create-user.http.controller.ts&lt;/a&gt; for http requests (&lt;a href="https://docs.nestjs.com/controllers" rel="noopener noreferrer"&gt;NestJS Controllers&lt;/a&gt;),&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.cli.controller.ts" rel="noopener noreferrer"&gt;create-user.cli.controller.ts&lt;/a&gt; for command line interface access (&lt;a href="https://www.npmjs.com/package/nestjs-console" rel="noopener noreferrer"&gt;NestJS Console&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.event.controller.ts" rel="noopener noreferrer"&gt;create-user.event.controller.ts&lt;/a&gt; for external events (&lt;a href="https://docs.nestjs.com/microservices/basics" rel="noopener noreferrer"&gt;NetJS Microservices&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  DTOs
&lt;/h2&gt;

&lt;p&gt;Data Transfer Object (&lt;a href="https://en.wikipedia.org/wiki/Data_transfer_object" rel="noopener noreferrer"&gt;DTO&lt;/a&gt;) is an object that carries data between processes. This is a contract between your API and clients.&lt;/p&gt;

&lt;h3&gt;
  
  
  Request DTOs
&lt;/h3&gt;

&lt;p&gt;Input data sent by a user.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using Request DTOs gives a contract that a client of your API has to follow to make a correct request.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.request.dto.ts" rel="noopener noreferrer"&gt;create-user.request.dto.ts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/interface-adapters/interfaces/user/create.user.interface.ts" rel="noopener noreferrer"&gt;create.user.interface.ts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Response DTOs
&lt;/h3&gt;

&lt;p&gt;Output data returned to a user.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using Response DTOs ensures clients only receive data described in DTOs contract, not everything that your model/entity owns (which may result in data leaks).&lt;/li&gt;
&lt;li&gt;It also to some extent protects your clients from internal data structure changes that may happen in your API.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/dtos/user.response.dto.ts" rel="noopener noreferrer"&gt;user.response.dto.ts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/interface-adapters/interfaces/user/user.interface.ts" rel="noopener noreferrer"&gt;user.interface.ts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Additional recommendations:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;When returning a &lt;code&gt;Response&lt;/code&gt; prefer &lt;em&gt;whitelisting&lt;/em&gt; properties over &lt;em&gt;blacklisting&lt;/em&gt;. This ensures that no sensitive data will leak in case if programmer forgets to blacklist newly added properties that shouldn't be returned to the user.&lt;/li&gt;
&lt;li&gt;Interfaces for &lt;code&gt;Request&lt;/code&gt;/&lt;code&gt;Response&lt;/code&gt; objects should be kept somewhere in shared directory instead of module directory since they may be used by a different application (like front-end page, mobile app or microservice). Consider creating git submodule or a separate package for sharing interfaces.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Request&lt;/code&gt;/&lt;code&gt;Response&lt;/code&gt; DTO classes may be a good place to use validation and sanitization decorators like &lt;a href="https://www.npmjs.com/package/class-validator" rel="noopener noreferrer"&gt;class-validator&lt;/a&gt; and &lt;a href="https://www.npmjs.com/package/class-sanitizer" rel="noopener noreferrer"&gt;class-sanitizer&lt;/a&gt; (make sure that all validation errors are gathered first and only then return them to the user, this is called &lt;a href="https://martinfowler.com/eaaDev/Notification.html" rel="noopener noreferrer"&gt;Notification pattern&lt;/a&gt;. Class-validator does this by default).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Request&lt;/code&gt;/&lt;code&gt;Response&lt;/code&gt; DTO classes may also be a good place to use Swagger/OpenAPI library decorators that &lt;a href="https://docs.nestjs.com/openapi/types-and-parameters" rel="noopener noreferrer"&gt;NestJS provides&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;If DTO decorators for validation/documentation are not used, DTO can be just an interface instead of class + interface.&lt;/li&gt;
&lt;li&gt;Data can be transformed to DTO format using a separate mapper or right in the constructor if DTO classes are used.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  Infrastructure
&lt;/h1&gt;

&lt;p&gt;The Infrastructure is responsible strictly to keep technology. You can find there the implementations of database repositories for business entities, message brokers, I/O components, dependency injection, frameworks and any other thing that represents a detail for the architecture, mostly framework dependent, external dependencies, and so on.&lt;/p&gt;

&lt;p&gt;It's the most volatile layer. Since the things in this layer are so likely to change, they are kept as far away as possible from the more stable domain layers. Because they are kept separate, it's relatively easy make changes or swap one component for another.&lt;/p&gt;

&lt;p&gt;Infrastructure layer can contain &lt;code&gt;Adapters&lt;/code&gt;, database related files like &lt;code&gt;Repositories&lt;/code&gt;, &lt;code&gt;ORM entities&lt;/code&gt;/&lt;code&gt;Schemas&lt;/code&gt;, framework related files etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adapters
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Infrastructure adapters (also called driven/secondary adapters) enable a software system to interact with external systems by receiving, storing and providing data when requested (like persistence, message brokers, sending emails or messages, requesting 3rd party APIs etc).&lt;/li&gt;
&lt;li&gt;Adapters also can be used to interact with different domains inside single process to avoid coupling between those domains.&lt;/li&gt;
&lt;li&gt;Adapters are essentially an implementation of ports. They are not supposed to be called directly in any point in code, only through ports(interfaces).&lt;/li&gt;
&lt;li&gt;Adapters can be used as Anti-Corruption Layer (ACL) for legacy code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more on ACL: &lt;a href="https://www.cloudbees.com/blog/anti-corruption-layer-how-keep-legacy-support-breaking-new-systems" rel="noopener noreferrer"&gt;Anti-Corruption Layer: How to Keep Legacy Support from Breaking New Systems&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Adapters should have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;a &lt;code&gt;port&lt;/code&gt; somewhere in application/domain layer that it implements;&lt;/li&gt;
&lt;li&gt;a mapper that maps data &lt;strong&gt;from&lt;/strong&gt; and &lt;strong&gt;to&lt;/strong&gt; domain (if it's needed);&lt;/li&gt;
&lt;li&gt;a DTO/interface for received data;&lt;/li&gt;
&lt;li&gt;a validator to make sure incoming data is not corrupted (validation can reside in DTO class using decorators, or it can be validated by &lt;code&gt;Value Objects&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Repositories
&lt;/h2&gt;

&lt;p&gt;Repositories centralize common data access functionality. They encapsulate the logic required to access that data. Entities/aggregates can be put into a repository and then retrieved at a later time without domain even knowing where data is saved, in a database, or a file, or some other source.&lt;/p&gt;

&lt;p&gt;We use repositories to decouple the infrastructure or technology used to access databases from the domain model layer.&lt;/p&gt;

&lt;p&gt;Martin Fowler describes a repository as follows:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A repository performs the tasks of an intermediary between the domain model layers and data mapping, acting in a similar way to a set of domain objects in memory. Client objects declaratively build queries and send them to the repositories for answers. Conceptually, a repository encapsulates a set of objects stored in the database and operations that can be performed on them, providing a way that is closer to the persistence layer. Repositories, also, support the purpose of separating, clearly and in one direction, the dependency between the work domain and the data allocation or mapping.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The data flow here looks something like this: repository receives a domain &lt;code&gt;Entity&lt;/code&gt; from application service, maps it to database schema/ORM format, does required operations and maps it back to domain &lt;code&gt;Entity&lt;/code&gt; and returns it back to service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep in mind&lt;/strong&gt; that application's core is not allowed to depend on repositories directly, instead it depends on abstractions (ports/interfaces). This makes data retrieval technology-agnostic.&lt;/p&gt;

&lt;h3&gt;
  
  
  Examples
&lt;/h3&gt;

&lt;p&gt;This project contains abstract repository class that allows to make basic CRUD operations: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/infrastructure/database/base-classes/typeorm.repository.base.ts" rel="noopener noreferrer"&gt;typeorm.repository.base.ts&lt;/a&gt;. This base class is then extended by a specific repository, and all specific operations that an entity may need is implemented in that specific repo: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/database/user.repository.ts" rel="noopener noreferrer"&gt;user.repository.ts&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  ORM Entities
&lt;/h2&gt;

&lt;p&gt;Using a single entity for domain logic and database concerns leads to a database-centric architecture. In DDD world domain model and persistance model should be separated. If ORM frameworks are used, &lt;code&gt;ORM Entities&lt;/code&gt; can be created to represent domain entities in a database.&lt;/p&gt;

&lt;p&gt;Since domain &lt;code&gt;Entities&lt;/code&gt; have their data modeled so that it best accommodates domain logic, it may be not in the best shape to save in database. For that purpose &lt;code&gt;ORM Entities&lt;/code&gt; (or &lt;code&gt;Schemas&lt;/code&gt;) are used that have shape that is better represented in a particular database that is used.&lt;/p&gt;

&lt;p&gt;This approach can also be useful when amount of data in database grows and there is a need to improve performance, for example by doing a re-design of some tables, &lt;a href="https://en.wikipedia.org/wiki/Database_normalization" rel="noopener noreferrer"&gt;database normalization&lt;/a&gt;, or even changing the database entirely. Without an explicit separation between &lt;code&gt;Entities&lt;/code&gt; and &lt;code&gt;ORM Entities&lt;/code&gt;/&lt;code&gt;Schemas&lt;/code&gt; any change to the database will lead to change in your &lt;code&gt;Entities&lt;/code&gt;, since data can spread across multiple tables rather than being in one table. This may force a team to do a complete refactoring of a domain layer which may cause unexpected bugs and challenges.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: separating &lt;code&gt;Entities&lt;/code&gt; and &lt;code&gt;ORM Entities&lt;/code&gt; may be an overkill for smaller applications, consider all pros and cons before making this decision.&lt;/p&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/database/user.orm-entity.ts" rel="noopener noreferrer"&gt;user.orm-entity.ts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/database/user.orm-mapper.ts" rel="noopener noreferrer"&gt;user.orm-mapper.ts&lt;/a&gt; &amp;lt;- &lt;code&gt;ORM Entities&lt;/code&gt; should also have a corresponding mapper to map from domain to persistence and back.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://stackoverflow.com/questions/14024912/ddd-persistence-model-and-domain-model" rel="noopener noreferrer"&gt;Stack Overflow question: DDD - Persistence Model and Domain Model&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.sapiensworks.com/post/2012/04/07/Just-Stop-It!-The-Domain-Model-Is-Not-The-Persistence-Model.aspx" rel="noopener noreferrer"&gt;Just Stop It! The Domain Model Is Not The Persistence Model&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-6/40" rel="noopener noreferrer"&gt;Secure by Design: Chapter 6.2.2 ORM frameworks and no-arg constructors&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Other things that can be a part of Infrastructure layer:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Framework related files;&lt;/li&gt;
&lt;li&gt;Application logger implementation;&lt;/li&gt;
&lt;li&gt;Infrastructure related events (&lt;a href="https://www.npmjs.com/package/nest-event" rel="noopener noreferrer"&gt;Nest-event&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Periodic cron jobs or tasks launchers (&lt;a href="https://docs.nestjs.com/techniques/task-scheduling" rel="noopener noreferrer"&gt;NestJS Schedule&lt;/a&gt;);&lt;/li&gt;
&lt;li&gt;Other technology related files.&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  Recommendations for smaller APIs
&lt;/h1&gt;

&lt;p&gt;Be careful when implementing any complex architecture in small-medium sized projects with not a lot of business logic. Some of the building blocks/patterns may fit well, but others may be an overengineering.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Separating code into modules/layers/use-cases, using some building blocks like controllers/services/entities, respecting boundaries and dependency injections etc. may be a good idea for any project.&lt;/li&gt;
&lt;li&gt;But practices like creating an object for every primitive, using &lt;code&gt;Value Objects&lt;/code&gt; to separate business logic into smaller classes, dividing &lt;code&gt;Entities&lt;/code&gt; and &lt;code&gt;ORM Entities&lt;/code&gt; etc. in projects that are more data-centric and have little or no business logic may only complicate such solutions and add extra boilerplate code, data mapping etc. without adding much benefit.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some principles/patterns can be implemented in a simplified form, some can be skipped. Follow &lt;a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it" rel="noopener noreferrer"&gt;YAGNI&lt;/a&gt; principle and don't overengineer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Before implementing any pattern always analyze if benefit given by using it worth extra code complexity&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Effective design argues that we need to know the price of a pattern is worth paying - that's its own skill.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;However, remember:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It's easier to refactor over-design than it is to refactor no design.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://martinfowler.com/bliki/Yagni.html" rel="noopener noreferrer"&gt;Martin Fowler blog: Yagni&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Other recommendations and best practices
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Error Handling
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Exception types
&lt;/h3&gt;

&lt;p&gt;Consider extending &lt;code&gt;Error&lt;/code&gt; object to make custom exception types for different situations. For example: &lt;code&gt;DomainException&lt;/code&gt; etc. This is especially relevant in NodeJS world since there is no exceptions for different situations by default.&lt;/p&gt;

&lt;p&gt;Keep in mind that application's &lt;code&gt;core&lt;/code&gt; shouldn't throw HTTP exceptions or statuses since it shouldn't know in what context it is used, since it can be used by anything: HTTP controller, Microservice event handler, Command Line Interface etc.&lt;/p&gt;

&lt;p&gt;When used in HTTP context, for returning proper status code back to user an &lt;code&gt;instanceof&lt;/code&gt; check can be performed in exception interceptor or in a controller and appropriate HTTP exception can be returned depending on exception type.&lt;/p&gt;

&lt;p&gt;Exception interceptor example: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/infrastructure/interceptors/exception.interceptor.ts" rel="noopener noreferrer"&gt;exception.interceptor.ts&lt;/a&gt; - notice how custom exceptions are converted to nest.js exceptions.&lt;/p&gt;

&lt;p&gt;Adding a &lt;code&gt;name&lt;/code&gt; string with type name for every exception is a good practice, since when that exception is transferred to another process &lt;code&gt;instanceof&lt;/code&gt; check cannot be performed anymore so a &lt;code&gt;name&lt;/code&gt; string is used instead. Exception &lt;code&gt;name&lt;/code&gt; enum types can be stored in a separate file so they can be reused on a receiving side: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/exceptions/exception.types.ts" rel="noopener noreferrer"&gt;exception.types.ts&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;When using microservices, all exception types can be packed into a library and reused in each microservice for consistency.&lt;/p&gt;

&lt;h3&gt;
  
  
  Differentiate between programmer errors and operational errors
&lt;/h3&gt;

&lt;p&gt;Application should be protected not only from operational errors (like incorrect user input), but from a programmer errors as well by throwing exceptions when something is not used as intended.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Operational errors can happen when validation error is thrown by validating user input, it means that input body is incorrect and a &lt;code&gt;400 Bad Request&lt;/code&gt; exception should be returned to the user with details of what fields are incorrect (&lt;a href="https://martinfowler.com/eaaDev/Notification.html" rel="noopener noreferrer"&gt;notification pattern&lt;/a&gt;). In this case user can fix the input body and retry the request.&lt;/li&gt;
&lt;li&gt;On the other hand, programmer error means something unexpected occurs in the program. For example, when exception happens on a new domain object creation, sometimes it can mean that a class is not used as intended and some rule is violated, for example a programmer did a mistake by assigning an incorrect value to a constructor, or value got mutated at some point and is no longer valid. In this case user cannot do anything to fix this, only a programmer can, so it may be more appropriate to throw a different type of exception that should be logged and then returned to the user as &lt;code&gt;500 Internal Server Error&lt;/code&gt;, in this case without adding much additional details to the response since it may cause a leak of some sensitive data.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Error Serialization
&lt;/h3&gt;

&lt;p&gt;By default, in NodeJS Error objects serialize to JSON with output like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;ValidationError&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Consider serializing errors by creating a &lt;code&gt;toJSON()&lt;/code&gt; method so it can be easily sent to other processes as a plain object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Error metadata
&lt;/h3&gt;

&lt;p&gt;Consider adding optional &lt;code&gt;metadata&lt;/code&gt; object to exceptions (if language doesn't support anything similar by default) and pass some useful technical information about the error when throwing. This will make debugging easier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important to keep in mind&lt;/strong&gt;: never log or add to &lt;code&gt;metadata&lt;/code&gt; any sensitive information (like passwords, emails, phone or credit card numbers etc) since this information may leak into log files, and if log files are not protected properly this information can leak or be seen by developers who have access to log files. Aim adding only technical information to your logs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Other recommendations
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;If translations of error messages to other languages is needed, consider storing those error messages in a separate object/class rather than inline string literals. This will make it easier to implement localization by adding conditional getters.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/exceptions/exception.base.ts" rel="noopener noreferrer"&gt;exception.base.ts&lt;/a&gt; - Exception abstract base class&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/exceptions/domain.exception.ts" rel="noopener noreferrer"&gt;domain.exception.ts&lt;/a&gt; - Domain Exception class example&lt;/li&gt;
&lt;li&gt;Check &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/exceptions" rel="noopener noreferrer"&gt;exceptions&lt;/a&gt; folder to see more examples (some of them are exceptions from other languages like C# or Java)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://iaincollins.medium.com/error-handling-in-javascript-a6172ccdf9af" rel="noopener noreferrer"&gt;Better error handling in JavaScript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-9/" rel="noopener noreferrer"&gt;"Secure by design" Chapter 9: Handling failures securely&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Alternatives to exceptions
&lt;/h3&gt;

&lt;p&gt;There is an alternative approach of not throwing exceptions, but returning some kind of Result object type with a Success or a Failure (an &lt;code&gt;Either&lt;/code&gt; &lt;a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)" rel="noopener noreferrer"&gt;monad&lt;/a&gt; from functional languages like Haskell). Unlike throwing exceptions, this approach allows to define types for exceptional outcomes and will force us to handle those cases explicitly instead of using &lt;code&gt;try/catch&lt;/code&gt;. For example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// ...&lt;/span&gt;
  &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;createUser&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nx"&gt;Either&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;User&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;EmailInvalidException&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// ...code for creating a user&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;invalidEmail&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;EmailInvalidException&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;- returning instead of throwing&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;User&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This approach has its advantages and may work nicely in some languages, especially in functional languages which support &lt;code&gt;Either&lt;/code&gt; type natively, but is not widely used in TypeScript/Javascript world.&lt;/p&gt;

&lt;p&gt;It also has some downsides:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It goes against &lt;a href="https://en.wikipedia.org/wiki/Fail-fast" rel="noopener noreferrer"&gt;Fail-fast&lt;/a&gt; principle. Instead of terminating a program flow, this approach continues program execution and allows it to run in an incorrect state, which may lead to more unexpected errors.&lt;/li&gt;
&lt;li&gt;It adds extra complexity. Exception cases returned somewhere deep inside application have to be handled by functions in upper layers until it reaches controllers which may add a lot of extra &lt;code&gt;if&lt;/code&gt; statements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For most projects this approach may be an overkill. Use it only if you really need it and know what you are doing.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://livebook.manning.com/book/secure-by-design/chapter-9/51" rel="noopener noreferrer"&gt;"Secure by Design" Chapter 9.2: Handling failures without exceptions&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;Software Testing helps catching bugs early. Properly tested software product ensures reliability, security and high performance which further results in time saving, cost effectiveness and customer satisfaction.&lt;/p&gt;

&lt;p&gt;Lets review two types of software testing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/White-box_testing" rel="noopener noreferrer"&gt;White Box&lt;/a&gt; testing.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Black-box_testing" rel="noopener noreferrer"&gt;Black Box&lt;/a&gt; testing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Testing module/use-case internal structures (creating a test for every file/class) is called &lt;em&gt;&lt;code&gt;White Box&lt;/code&gt;&lt;/em&gt; testing. &lt;em&gt;White Box&lt;/em&gt; testing is widely used technique, but it has disadvantages. It creates coupling to implementation details, so every time you decide to refactor business logic code this may also cause a refactoring of corresponding tests.&lt;/p&gt;

&lt;p&gt;To solve this and get the most out of your tests, prefer &lt;em&gt;&lt;code&gt;Black Box&lt;/code&gt;&lt;/em&gt; testing (also called &lt;a href="https://www.codekul.com/blog/what-is-behavioral-testing/" rel="noopener noreferrer"&gt;Behavioral Testing&lt;/a&gt;). This means that tests should focus on testing user-facing behavior users care about (your code's public API, for example &lt;code&gt;createUser()&lt;/code&gt; method in &lt;code&gt;Application Service&lt;/code&gt;), not the implementation details of individual units it has inside. This avoids coupling, protects tests from changes that may happen while refactoring, makes tests easier to understand and maintain thus saving time.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Tests that are independent of implementation details are easier to maintain since they don't need to be changed each time you make a change to the implementation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Try to avoid &lt;em&gt;White Box&lt;/em&gt; testing when possible. Though, there are cases when &lt;em&gt;White Box&lt;/em&gt; testing may be needed, for example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;High complexity in implementation details that are hard to cover using &lt;em&gt;Black Box&lt;/em&gt; testing.&lt;/li&gt;
&lt;li&gt;There is a need to increase code coverage.&lt;/li&gt;
&lt;li&gt;There is a suspicion that some area of the program may be under-tested.&lt;/li&gt;
&lt;li&gt;Sometimes it makes more sense to create a separate &lt;em&gt;White Box&lt;/em&gt; unit test for a class with specific logic than cluttering a &lt;em&gt;Black Box&lt;/em&gt; test file with those test cases.&lt;/li&gt;
&lt;li&gt;Some parts of the code can't be properly tested by &lt;em&gt;Black Box&lt;/em&gt; testing.&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use &lt;em&gt;White Box&lt;/em&gt; testing only when it is really needed and as an addition to &lt;em&gt;Black Box&lt;/em&gt; testing, not the other way around.&lt;/p&gt;

&lt;p&gt;It's all about investing only in the tests that yield the biggest return on your effort.&lt;/p&gt;

&lt;p&gt;Behavioral tests can be divided in two parts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fast: Use cases tests in isolation, with all I/O mocked and injected. This makes tests fast so they can be run all the time (after each change or before every commit). This will inform you when something fails as fast as possible. Finding bugs early is critical and saves a lot of time.&lt;/li&gt;
&lt;li&gt;Slow: Full &lt;a href="https://www.guru99.com/end-to-end-testing.html" rel="noopener noreferrer"&gt;End to End&lt;/a&gt; (e2e) tests which test a use case from end-user standpoint. Instead of injecting I/O mocks those tests usually have all infrastructure up and running: like database, API routes etc. Those tests check how everything works together and are slower so can be run only before pushing/deploying. Though e2e tests live in the same project/repository, it is a good practice to have e2e tests independent from project's code. In bigger projects e2e tests are usually written by a separate QA team.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: some people try to make e2e tests faster by using in-memory or embedded databases (like &lt;a href="https://www.npmjs.com/package/sqlite3" rel="noopener noreferrer"&gt;sqlite3&lt;/a&gt;). This makes tests faster, but reduces the reliability of those tests. In real e2e testing this should be avoided. Read more: &lt;a href="https://phauer.com/2017/dont-use-in-memory-databases-tests-h2/" rel="noopener noreferrer"&gt;Don't use In-Memory Databases for Tests&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Load Testing
&lt;/h3&gt;

&lt;p&gt;For projects with a bigger user base you might want to implement some kind of &lt;a href="https://en.wikipedia.org/wiki/Load_testing" rel="noopener noreferrer"&gt;load testing&lt;/a&gt; to see how program behaves with a lot of concurrent users. &lt;a href="https://www.npmjs.com/package/artillery" rel="noopener noreferrer"&gt;Artillery&lt;/a&gt; is a nice tool for that based on NodeJS. Though, there are plenty of other tools to choose from: &lt;a href="https://medium.com/@Dickson_Mwendia/top-6-tools-for-api-load-testing-7ff51d1ac1e8" rel="noopener noreferrer"&gt;Top 6 Tools for API &amp;amp; Load Testing&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Example files: // TODO&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://enterprisecraftsmanship.com/posts/pragmatic-unit-testing/" rel="noopener noreferrer"&gt;Pragmatic unit testing&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://testing.googleblog.com/2013/08/testing-on-toilet-test-behavior-not.html" rel="noopener noreferrer"&gt;Google Blog: Test Behavior, Not Implementation &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.departmentofproduct.com/blog/writing-bdd-test-scenarios/" rel="noopener noreferrer"&gt;Writing BDD Test Scenarios&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Store all configurable variables/parameters in config files. Try to avoid using in-line literals/primitives. This will make it easier to find and maintain all configurable parameters when they are in one place.&lt;/li&gt;
&lt;li&gt;Never store sensitive configuration variables (passwords/API keys/secret keys etc) in plain text in a configuration files or source code.&lt;/li&gt;
&lt;li&gt;Store sensitive configuration variables, or variables that change depending on environment, as &lt;a href="https://en.wikipedia.org/wiki/Environment_variable" rel="noopener noreferrer"&gt;environment variables&lt;/a&gt; (&lt;a href="https://www.npmjs.com/package/dotenv" rel="noopener noreferrer"&gt;dotenv&lt;/a&gt; is a nice package for that) or as a &lt;a href="https://www.bogotobogo.com/DevOps/Docker/Docker_Kubernetes_Secrets.php" rel="noopener noreferrer"&gt;Docker/Kubernetes secrets&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Create hierarchical config files that are grouped into sections. If possible, create multiple files for different configs (like database config, API config, tasks config etc).&lt;/li&gt;
&lt;li&gt;Application should fail and provide the immediate feedback if the required environment variables are not present at start-up.&lt;/li&gt;
&lt;li&gt;For most projects plain object configs may be enough, but there are other options, for example: &lt;a href="https://docs.nestjs.com/techniques/configuration" rel="noopener noreferrer"&gt;NestJS Configuration&lt;/a&gt;, &lt;a href="https://www.npmjs.com/package/rc" rel="noopener noreferrer"&gt;rc&lt;/a&gt;, &lt;a href="https://www.npmjs.com/package/nconf" rel="noopener noreferrer"&gt;nconf&lt;/a&gt; or any other package.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/infrastructure/configs/ormconfig.ts" rel="noopener noreferrer"&gt;ormconfig.ts&lt;/a&gt; - this is typeorm database config file. Notice &lt;code&gt;process.env&lt;/code&gt; - those are environmental variables.&lt;/li&gt;
&lt;li&gt;
&lt;a href="//.env.example"&gt;.env.example&lt;/a&gt; - this is &lt;a href="https://www.npmjs.com/package/dotenv" rel="noopener noreferrer"&gt;dotenv&lt;/a&gt; example file. This file should only store dummy example secret keys, never store actual development/production secrets in it. This file later is renamed to &lt;code&gt;.env&lt;/code&gt; and populated with real keys for every environment (local, dev or prod). Don't forget to add &lt;code&gt;.env&lt;/code&gt; to &lt;a href="//.gitignore"&gt;.gitignore&lt;/a&gt; file to avoid pushing it to repo and leaking all keys.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Logging
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Try to log all meaningful events in a program that can be useful to anybody in your team.&lt;/li&gt;
&lt;li&gt;Use proper log levels: &lt;code&gt;log&lt;/code&gt;/&lt;code&gt;info&lt;/code&gt; for events that are meaningful during production, &lt;code&gt;debug&lt;/code&gt; for events useful while developing/debugging, and &lt;code&gt;warn&lt;/code&gt;/&lt;code&gt;error&lt;/code&gt; for unwanted behavior on any stage.&lt;/li&gt;
&lt;li&gt;Write meaningful log messages and include metadata that may be useful. Try to avoid cryptic messages that only you understand.&lt;/li&gt;
&lt;li&gt;Never log sensitive data: passwords, emails, credit card numbers etc. since this data will end up in log files. If log files are not stored securely this data can be leaked.&lt;/li&gt;
&lt;li&gt;Avoid default logging tools (like &lt;code&gt;console.log&lt;/code&gt;). Use mature logger libraries (for example &lt;a href="https://www.npmjs.com/package/winston" rel="noopener noreferrer"&gt;Winston&lt;/a&gt;) that support features like enabling/disabling log levels, convenient log formats that are easy to parse (like JSON) etc.&lt;/li&gt;
&lt;li&gt;Consider including user id in logs. It will facilitate investigating if user creates an incident ticket.&lt;/li&gt;
&lt;li&gt;In distributed systems a gateway can generate an unique id for each request and pass it to every system that processes this request. Logging this id will make it easier to find related logs across different systems/files.&lt;/li&gt;
&lt;li&gt;Use consistent structure across all logs. Each log line should represent one single event and contain things like timestamp, context, unique user/request id and/or id of entity/aggregate that is being modified, as well as additional metadata if required.&lt;/li&gt;
&lt;li&gt;Use log managements systems. This will allow you to track and analyze logs as they happen in real-time. Here are some short list of log managers: &lt;a href="https://sentry.io/for/node/" rel="noopener noreferrer"&gt;Sentry&lt;/a&gt;, &lt;a href="https://www.loggly.com/" rel="noopener noreferrer"&gt;Loggly&lt;/a&gt;, &lt;a href="https://www.elastic.co/logstash" rel="noopener noreferrer"&gt;Logstash&lt;/a&gt;, &lt;a href="https://www.splunk.com/" rel="noopener noreferrer"&gt;Splunk&lt;/a&gt; etc.&lt;/li&gt;
&lt;li&gt;Send notifications of important events that happen in production to a corporate chat like Slack or even by SMS.&lt;/li&gt;
&lt;li&gt;Don't write logs to a file from your program. Write all logs to &lt;a href="https://www.computerhope.com/jargon/s/stdout.htm" rel="noopener noreferrer"&gt;stdout&lt;/a&gt; (to a terminal window) and let other tools handle writing logs to a file (for example &lt;a href="https://docs.docker.com/config/containers/logging/configure/" rel="noopener noreferrer"&gt;docker supports writing logs to a file&lt;/a&gt;). Read more: &lt;a href="https://www.coreycleary.me/why-should-your-node-js-application-not-handle-log-routing/" rel="noopener noreferrer"&gt;Why should your Node.js application not handle log routing?&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Logs can be visualized by using a tool like &lt;a href="https://www.elastic.co/kibana" rel="noopener noreferrer"&gt;Kibana&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/goldbergyoni/nodebestpractices/blob/master/sections/production/smartlogging.md" rel="noopener noreferrer"&gt;Make your app transparent using smart logs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Health monitoring
&lt;/h2&gt;

&lt;p&gt;Additionally to logging tools, health monitoring tools are a good way to keep track of system performance, identify causes of crashes or downtime, monitor behavior, availability and load. Some health monitoring tools already include logging management and error tracking, as well as alerts and general performance monitoring.&lt;/p&gt;

&lt;p&gt;Here are some basic recommendation on what can be monitored:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Connectivity – Verify if user can successfully send a request to the API endpoint and get a response with expected HTTP status code. This will confirm if the API endpoint is up and running. This can be achieved by creating some kind of 'heath check' endpoint.&lt;/li&gt;
&lt;li&gt;Performance – Make sure the response time of the API is within acceptable limits. Long response times cause bad user experience.&lt;/li&gt;
&lt;li&gt;Error rate – errors immediately affect your customers, you need to know when errors happen right away and fix them.&lt;/li&gt;
&lt;li&gt;CPU and Memory usage – spikes in CPU and Memory usage can indicate that there are problems in your system, for example bad optimized code, unwanted process running, memory leaks etc. This can result in loss of money for your organization, especially when cloud providers are used.&lt;/li&gt;
&lt;li&gt;Storage usage – servers run out of storage. Monitoring storage usage is essential to avoid data loss.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Choose health monitoring tools depending on your needs, here are some examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://sematext.com/" rel="noopener noreferrer"&gt;Sematext&lt;/a&gt;, &lt;a href="https://appsignal.com/" rel="noopener noreferrer"&gt;AppSignal&lt;/a&gt;, &lt;a href="https://prometheus.io/" rel="noopener noreferrer"&gt;Prometheus&lt;/a&gt;, &lt;a href="https://www.checklyhq.com/" rel="noopener noreferrer"&gt;Checkly&lt;/a&gt;, &lt;a href="https://clinicjs.org/" rel="noopener noreferrer"&gt;ClinicJS&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://sematext.com/blog/api-monitoring/" rel="noopener noreferrer"&gt;Essential Guide to API Monitoring: Basics Metrics &amp;amp; Choosing the Best Tools&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Folder and File Structure
&lt;/h2&gt;

&lt;p&gt;So instead of using typical layered style when all application is divided into services, controllers etc, we divide everything by modules. Now, how to structure files inside those modules?&lt;/p&gt;

&lt;p&gt;A lot of people tend to do the same thing as before: create a separate folders/files for services, controllers etc and keep all module's use-cases logic there, making those controllers and services bloated with responsibilities. This is the same approach that makes navigation harder.&lt;/p&gt;

&lt;p&gt;Using this approach, every time something in a service changes, we might have to go to another folder to change controllers, and then go to dtos folder to change the corresponding dto etc.&lt;/p&gt;

&lt;p&gt;It would be more logical to separate every module by components and have all the related files close together. Now if a use-case changes, those changes are usually made in a single use-case component, not everywhere across the module.&lt;/p&gt;

&lt;p&gt;This is called &lt;a href="https://ericbackhage.net/clean-code/the-common-closure-principle/" rel="noopener noreferrer"&gt;The Common Closure Principle (CCP)&lt;/a&gt;. Folder/file structure in this project uses this principle. Related files that usually change together (and are not used by anything else outside of that component) are stored close together, in a single use-case folder. Check user &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases" rel="noopener noreferrer"&gt;use-cases&lt;/a&gt; folder for examples.&lt;/p&gt;

&lt;p&gt;And shared files (like domain objects, repositories etc) are stored apart since those are reused by multiple use-cases. Domain layer is isolated, and use-cases which are essentially wrappers around business logic are treated as components. This approach makes navigation and maintaining easier. Check &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user" rel="noopener noreferrer"&gt;user&lt;/a&gt; folder for an example.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The aim here should to be strategic and place classes that we, from experience, know often changes together into the same component.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Keep in mind that this project's folder/file structure is an example and might not work for everyone. Main recommendations here are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Separate you application into modules;&lt;/li&gt;
&lt;li&gt;Keep files that change together close to each other (Common Closure Principle);&lt;/li&gt;
&lt;li&gt;Group files by their behavior that changes together, not by type of functionality that file provides;&lt;/li&gt;
&lt;li&gt;Keep files that are reused by multiple components apart;&lt;/li&gt;
&lt;li&gt;Respect boundaries in your code, keeping files together doesn't mean inner layers can import outer layers;&lt;/li&gt;
&lt;li&gt;Try to avoid a lot of nested folders;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dev.to/dance2die/move-files-around-until-it-feels-right-2lek"&gt;Move files around until it feels right&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There are different approaches to file/folder structuring, like explicitly separating each layer into a corresponding folder. This defines boundaries more clearly but is harder to navigate. Choose what suits better for the project/personal preference.&lt;/p&gt;

&lt;h2&gt;
  
  
  File names
&lt;/h2&gt;

&lt;p&gt;Consider giving a descriptive type names to files after a dot "&lt;code&gt;.&lt;/code&gt;", like &lt;code&gt;*.service.ts&lt;/code&gt; or &lt;code&gt;*.entity.ts&lt;/code&gt;. This makes it easier to differentiate what files does what and makes it easier to find those files using &lt;a href="https://en.wikipedia.org/wiki/Approximate_string_matching" rel="noopener noreferrer"&gt;fuzzy search&lt;/a&gt; (&lt;code&gt;CTRL+P&lt;/code&gt; for Windows/Linux and &lt;code&gt;⌘+P&lt;/code&gt; for MacOS in VSCode to try it out).&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://angular.io/guide/styleguide#separate-file-names-with-dots-and-dashes" rel="noopener noreferrer"&gt;Angular Style Guides: Separate file names with dots and dashes&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Static Code Analysis
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Static code analysis is a method of debugging by examining source code before a program is run.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For JavasScript and TypeScript, &lt;a href="https://www.npmjs.com/package/eslint" rel="noopener noreferrer"&gt;Eslint&lt;/a&gt; with &lt;a href="https://www.npmjs.com/package/@typescript-eslint/eslint-plugin" rel="noopener noreferrer"&gt;typescript-eslint plugin&lt;/a&gt; and some rules (like &lt;a href="https://www.npmjs.com/package/eslint-config-airbnb" rel="noopener noreferrer"&gt;airbnb&lt;/a&gt;) can be a great tool to enforce writing better code.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;any&lt;/code&gt; type is a bad practice. Consider disallowing it (and other things that may cause problems):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;

&lt;span class="c1"&gt;// .eslintrc.js file&lt;/span&gt;
  &lt;span class="nx"&gt;rules&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;@typescript-eslint/no-explicit-any&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;error&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Also, enabling strict mode in &lt;code&gt;tsconfig.json&lt;/code&gt; is recommended:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="w"&gt;

  &lt;/span&gt;&lt;span class="nl"&gt;"compilerOptions"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"strict"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;...&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;


&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Example file: &lt;a href="//.eslintrc.js"&gt;.eslintrc.js&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker" rel="noopener noreferrer"&gt;Code Spell Checker&lt;/a&gt; may be a good addition to eslint.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.perforce.com/blog/sca/what-static-analysis" rel="noopener noreferrer"&gt;What Is Static Analysis?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.carlrippon.com/controlling-type-checking-strictness-in-typescript/" rel="noopener noreferrer"&gt;Controlling Type Checking Strictness in TypeScript&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Code formatting
&lt;/h2&gt;

&lt;p&gt;The way code looks adds to our understanding of it. Good style makes reading code a pleasurable and consistent experience.&lt;/p&gt;

&lt;p&gt;Consider using code formatters like &lt;a href="https://www.npmjs.com/package/prettier" rel="noopener noreferrer"&gt;Prettier&lt;/a&gt; to maintain same code styles in the project.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.smashingmagazine.com/2012/10/why-coding-style-matters/" rel="noopener noreferrer"&gt;Why Coding Style Matters&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Documentation
&lt;/h2&gt;

&lt;p&gt;Create documentation that may help users/other developers to use your program.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simple readme file in a git repository that describes basic app functionality, available CLI commands, how to setup a new project etc.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://swagger.io/specification/" rel="noopener noreferrer"&gt;OpenAPI&lt;/a&gt; (Swagger) or &lt;a href="https://graphql.org/" rel="noopener noreferrer"&gt;GraphQL&lt;/a&gt; specifications. Document in details every endpoint. Add description and examples of every request, response, properties and exceptions that endpoints may return or receive as body/parameters. This will help greatly to other developers and users of your API.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/dtos/user.response.dto.ts" rel="noopener noreferrer"&gt;user.response.dto.ts&lt;/a&gt; - notice &lt;code&gt;@ApiProperty()&lt;/code&gt; decorators. This is &lt;a href="https://docs.nestjs.com/openapi/types-and-parameters" rel="noopener noreferrer"&gt;NestJS Swagger&lt;/a&gt; module.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/use-cases/create-user/create-user.http.controller.ts" rel="noopener noreferrer"&gt;create-user.http.controller.ts&lt;/a&gt; - notice &lt;code&gt;@ApiOperation()&lt;/code&gt; and &lt;code&gt;@ApiResponse()&lt;/code&gt; decorators.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://medium.com/wolox/documenting-a-nodejs-rest-api-with-openapi-3-swagger-5deee9f50420" rel="noopener noreferrer"&gt;Documenting a NodeJS REST API with OpenApi 3/Swagger&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://swagger.io/blog/api-documentation/best-practices-in-api-documentation/" rel="noopener noreferrer"&gt;Best Practices in API Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Make application easy to setup
&lt;/h2&gt;

&lt;p&gt;There are a lot of projects out there which take effort to configure after downloading it. Everything has to be set up manually: database, all configs etc. If new developer joins the team he has to waste a lot of time just to make application work.&lt;/p&gt;

&lt;p&gt;This is a bad practice and should be avoided. Setting up project after downloading it should be as easy as launching one or few commands in terminal. Consider adding scripts to do this automatically:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://krishankantsinghal.medium.com/scripting-inside-package-json-4b06bea74c0e" rel="noopener noreferrer"&gt;package.json scripts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.docker.com/compose/" rel="noopener noreferrer"&gt;docker-compose file&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://opensource.com/article/18/8/what-how-makefile" rel="noopener noreferrer"&gt;Makefile&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Database seeding and migrations (described below)&lt;/li&gt;
&lt;li&gt;or any other tools.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Seeds
&lt;/h2&gt;

&lt;p&gt;To avoid manually creating data in the database, seeding is a great solution to populate database with data for development and testing purposes (e2e testing). &lt;a href="https://en.wikipedia.org/wiki/Database_seeding" rel="noopener noreferrer"&gt;Wiki description&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This project uses &lt;a href="https://www.npmjs.com/package/typeorm-seeding#-using-entity-factory" rel="noopener noreferrer"&gt;typeorm-seeding&lt;/a&gt; package.&lt;/p&gt;

&lt;p&gt;Example file: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/modules/user/database/seeding/user.seeds.ts" rel="noopener noreferrer"&gt;user.seeds.ts&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Migrations
&lt;/h2&gt;

&lt;p&gt;Migrations are used for database table/schema changes:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Database migration refers to the management of incremental, reversible changes and version control to relational database schemas. A schema migration is performed on a database whenever it is necessary to update or revert that database's schema to some newer or older version.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Source: &lt;a href="https://en.wikipedia.org/wiki/Schema_migration" rel="noopener noreferrer"&gt;Wiki&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Migrations should be generated every time database table schema is changed. When pushed to production it can be launched automatically.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BE CAREFUL&lt;/strong&gt; not to drop some columns/tables that contain data by accident. Perform data migrations before table schema migrations and always backup database before doing anything.&lt;/p&gt;

&lt;p&gt;This project uses &lt;a href="https://github.com/typeorm/typeorm/blob/master/docs/migrations.md" rel="noopener noreferrer"&gt;Typeorm Migrations&lt;/a&gt; which automatically generates sql table schema migrations like this:&lt;/p&gt;

&lt;p&gt;Example file: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/infrastructure/database/migrations/1611765824842-CreateTables.ts" rel="noopener noreferrer"&gt;1611765824842-CreateTables.ts&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Seeds and migrations belong to Infrastructure layer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rate Limiting
&lt;/h2&gt;

&lt;p&gt;By default there is no limit on how many request users can make to your API. This may lead to problems, like DDoS or brute force attacks, lags and performance issues etc.&lt;/p&gt;

&lt;p&gt;To solve this, implementing &lt;a href="https://en.wikipedia.org/wiki/Rate_limiting" rel="noopener noreferrer"&gt;Rate Limiting&lt;/a&gt; is essential for any API.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In NodeJS world, &lt;a href="https://www.npmjs.com/package/express-rate-limit" rel="noopener noreferrer"&gt;express-rate-limit&lt;/a&gt; is an option for simple APIs.&lt;/li&gt;
&lt;li&gt;Another alternative is &lt;a href="https://www.nginx.com/blog/rate-limiting-nginx/" rel="noopener noreferrer"&gt;NGINX Rate Limiting&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://konghq.com/kong/" rel="noopener noreferrer"&gt;Kong&lt;/a&gt; has &lt;a href="https://docs.konghq.com/hub/kong-inc/rate-limiting/" rel="noopener noreferrer"&gt;rate limiting plugin&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://nordicapis.com/everything-you-need-to-know-about-api-rate-limiting/" rel="noopener noreferrer"&gt;Everything You Need To Know About API Rate Limiting &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://cloud.google.com/solutions/rate-limiting-strategies-techniques" rel="noopener noreferrer"&gt;Rate-limiting strategies and techniques&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm/" rel="noopener noreferrer"&gt;How to Design a Scalable Rate Limiting Algorithm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Code Generation
&lt;/h2&gt;

&lt;p&gt;Code generation can be important when using complex architectures to avoid typing boilerplate code manually.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/hygen" rel="noopener noreferrer"&gt;Hygen&lt;/a&gt; is a great example.&lt;br&gt;
This tool can generate building blocks (or entire modules) by using custom templates. Templates can be designed to follow best practices and concepts based on Clean/Hexagonal Architecture, DDD, SOLID etc.&lt;/p&gt;

&lt;p&gt;Main advantages of automatic code generation are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Avoid manual typing or copy-pasting of boilerplate code.&lt;/li&gt;
&lt;li&gt;No hand-coding means less errors and faster implementations. Simple CRUD module can be generated and used right away in seconds without any manual code writing.&lt;/li&gt;
&lt;li&gt;Using auto-generated code templates ensures that everyone in the team uses the same folder/file structures, name conventions, architectural and code styles.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To really understand and work with generated templates you need to understand what is being generated and why, so full understanding of an architecture and patterns used is required.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Custom utility types
&lt;/h2&gt;

&lt;p&gt;Consider creating a bunch of shared custom utility types for different situations.&lt;/p&gt;

&lt;p&gt;Some examples can be found in &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/types" rel="noopener noreferrer"&gt;types&lt;/a&gt; folder.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pre-push/pre-commit hooks
&lt;/h2&gt;

&lt;p&gt;Consider launching tests/code formatting/linting every time you do &lt;code&gt;git push&lt;/code&gt; or &lt;code&gt;git commit&lt;/code&gt;. This prevents bad code getting in your repo. &lt;a href="https://www.npmjs.com/package/husky" rel="noopener noreferrer"&gt;Husky&lt;/a&gt; is a great tool for that.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://githooks.com/" rel="noopener noreferrer"&gt;Git Hooks&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Prevent massive inheritance chains
&lt;/h2&gt;

&lt;p&gt;This can be achieved by making class &lt;code&gt;final&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: in TypeScript, unlike other languages, there is no default way to make class &lt;code&gt;final&lt;/code&gt;. But there is a way around it using a custom decorator.&lt;/p&gt;

&lt;p&gt;Example file: &lt;a href="https://github.com/Sairyss/domain-driven-hexagon/tree/master/src/core/decorators/final.decorator.ts" rel="noopener noreferrer"&gt;final.decorator.ts&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://ocramius.github.io/blog/when-to-declare-classes-final/" rel="noopener noreferrer"&gt;When to declare classes final&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://matthiasnoback.nl/2018/09/final-classes-by-default-why/" rel="noopener noreferrer"&gt;Final classes by default, why?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/better-programming/prefer-composition-over-inheritance-1602d5149ea1" rel="noopener noreferrer"&gt;Prefer Composition Over Inheritance&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conventional commits
&lt;/h2&gt;

&lt;p&gt;Conventional commits add some useful prefixes to your commit messages, for example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;feat: added ability to delete user's profile&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This creates a common language that makes easier communicating the nature of changes to teammates and also may be useful for automatic package versioning and release notes generation.&lt;/p&gt;

&lt;p&gt;Read more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.conventionalcommits.org/en/v1.0.0-beta.2/" rel="noopener noreferrer"&gt;conventionalcommits.org&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716" rel="noopener noreferrer"&gt;Semantic Commit Messages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/conventional-changelog/commitlint" rel="noopener noreferrer"&gt;Commitlint&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/semantic-release/semantic-release" rel="noopener noreferrer"&gt;Semantic release&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  Additional resources
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Articles
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together" rel="noopener noreferrer"&gt;DDD, Hexagonal, Onion, Clean, CQRS, … How I put it all together&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.qwan.eu/2020/08/20/hexagonal-architecture.html" rel="noopener noreferrer"&gt;Hexagonal Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/@pereiren/clean-architecture-series-part-1-f34ef6b04b62" rel="noopener noreferrer"&gt;Clean architecture series&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pusher.com/tutorials/clean-architecture-introduction" rel="noopener noreferrer"&gt;Clean architecture for the rest of us&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.redhat.com/architect/12-factor-app" rel="noopener noreferrer"&gt;An illustrated guide to 12 Factor Apps&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Repositories
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/goldbergyoni/nodebestpractices" rel="noopener noreferrer"&gt;Node.js Best Practices&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/donnemartin/system-design-primer" rel="noopener noreferrer"&gt;The System Design Primer&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Documentation
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://12factor.net/" rel="noopener noreferrer"&gt;The Twelve-Factor App&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://refactoring.guru/design-patterns/catalog" rel="noopener noreferrer"&gt;Refactoring guru - Catalog of Design Patterns&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/index-patterns" rel="noopener noreferrer"&gt;Microsoft - Cloud Design Patterns&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Blogs
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://martinfowler.com/" rel="noopener noreferrer"&gt;Martin Fowler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.kamilgrzybek.com/" rel="noopener noreferrer"&gt;Kamil Grzybek&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://khalilstemmler.com" rel="noopener noreferrer"&gt;Khalil Stemmler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://herbertograca.com/" rel="noopener noreferrer"&gt;Herberto Graca&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Videos
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://youtu.be/ujb_O6myknY" rel="noopener noreferrer"&gt;More Testable Code with the Hexagonal Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://youtube.com/playlist?list=PLF206E906175C7E07" rel="noopener noreferrer"&gt;Playlist: Design Patterns Video Tutorial&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc" rel="noopener noreferrer"&gt;Playlist: Design Patterns in Object Oriented Programming&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=_yoZN9Sb3PM&amp;amp;feature=youtu.be" rel="noopener noreferrer"&gt;Herberto Graca - Making architecture explicit&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Books
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215" rel="noopener noreferrer"&gt;"Domain-Driven Design: Tackling Complexity in the Heart of Software" &lt;/a&gt; by Eric Evans&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.manning.com/books/secure-by-design" rel="noopener noreferrer"&gt;"Secure by Design"&lt;/a&gt; by Dan Bergh Johnsson, Daniel Deogun, Daniel Sawano&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.amazon.com/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577" rel="noopener noreferrer"&gt;"Implementing Domain-Driven Design"&lt;/a&gt; by Vaughn Vernon&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164/ref=sr_1_1?dchild=1&amp;amp;keywords=clean+architecture&amp;amp;qid=1605343702&amp;amp;s=books&amp;amp;sr=1-1" rel="noopener noreferrer"&gt;"Clean Architecture: A Craftsman's Guide to Software Structure and Design"&lt;/a&gt; by Robert Martin&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.amazon.com/Designing-Data-Intensive-Applications-Reliable-Maintainable/dp/1449373321" rel="noopener noreferrer"&gt;Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems&lt;/a&gt; by Martin Kleppmann&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>architecture</category>
      <category>design</category>
      <category>programming</category>
    </item>
    <item>
      <title>Making  A Deep Dream Twitter Bot</title>
      <dc:creator>Noah</dc:creator>
      <pubDate>Mon, 01 Mar 2021 17:51:35 +0000</pubDate>
      <link>https://forem.com/ogoodness/making-a-deep-dream-twitter-bot-1jgh</link>
      <guid>https://forem.com/ogoodness/making-a-deep-dream-twitter-bot-1jgh</guid>
      <description>&lt;h1&gt;
  
  
  &lt;strong&gt;Let's get into it!&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;This will just be a quick walkthrough of how I made a twitter bot that can grab input from replies, generate a image from the text, and then pass that image through some Trippy deep dream filters.&lt;/p&gt;

&lt;p&gt;This tutorial will assume that you are working inside of &lt;a href="https://colab.research.google.com/notebooks/intro.ipynb#recent=true" rel="noopener noreferrer"&gt;Google Colab&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GitHub:&lt;/strong&gt; &lt;a href="https://github.com/OGoodness" rel="noopener noreferrer"&gt;https://github.com/OGoodness&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Twitter:&lt;/strong&gt; &lt;a href="https://twitter.com/NoahFields_" rel="noopener noreferrer"&gt;https://twitter.com/NoahFields_&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Bot Twitter:&lt;/strong&gt; &lt;a href="https://twitter.com/WeDeepDream" rel="noopener noreferrer"&gt;https://twitter.com/WeDeepDream&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Steps:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt; &lt;a href="https://colab.research.google.com/notebooks/intro.ipynb#recent=true" rel="noopener noreferrer"&gt;Getting Setup Inside of Google Collab&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; Creating API Keys

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developer.twitter.com/en/docs/twitter-api/getting-started/guide" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://deepai.org/" rel="noopener noreferrer"&gt;DeepAI&lt;/a&gt;

&lt;ul&gt;
&lt;li&gt;Signup and then grab the provided API Key&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Code&lt;/li&gt;
&lt;li&gt;PROFIT!&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  One of my favorite outputs:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Harmful Candy&lt;/strong&gt;&lt;br&gt;
&lt;iframe class="tweet-embed" id="tweet-1339985791565512705-183" src="https://platform.twitter.com/embed/Tweet.html?id=1339985791565512705"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-1339985791565512705-183');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1339985791565512705&amp;amp;theme=dark"
  }



&lt;/p&gt;

&lt;h2&gt;
  
  
  Code!
&lt;/h2&gt;

&lt;p&gt;First, we need to make sure Google Colab is using a compatible version of Tensorflow, you need to specify this before your imports:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="n"&gt;tensorflow_version&lt;/span&gt; &lt;span class="mf"&gt;1.&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Imports
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Install Lucid and other Dependencies
&lt;/span&gt;&lt;span class="err"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pip&lt;/span&gt; &lt;span class="n"&gt;install&lt;/span&gt; &lt;span class="o"&gt;--&lt;/span&gt;&lt;span class="n"&gt;quiet&lt;/span&gt; &lt;span class="n"&gt;lucid&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;
&lt;span class="err"&gt;!&lt;/span&gt;&lt;span class="n"&gt;pip&lt;/span&gt; &lt;span class="n"&gt;install&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;
&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="n"&gt;tensorflow_version&lt;/span&gt; &lt;span class="mf"&gt;1.&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;
&lt;span class="c1"&gt;# Import libraries
&lt;/span&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google.colab&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;files&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;numpy&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;tensorflow&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;scipy.ndimage&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;nd&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cv2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sched&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google.colab.patches&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;cv2_imshow&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;PIL&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Image&lt;/span&gt;

&lt;span class="c1"&gt;# Deep Dream Libraries
&lt;/span&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;lucid.modelzoo.vision_models&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;lucid.optvis.objectives&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;objectives&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;lucid.optvis.param&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;param&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;lucid.optvis.render&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;render&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;lucid.optvis.transform&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;transform&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;lucid.misc.io&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;show&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;load&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;lucid.misc.io.reading&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;read&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Create Model
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;InceptionV1&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load_graphdef&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Get List of Words
&lt;/h4&gt;

&lt;p&gt;Since you probably wont have a lot of user interaction at first, we are going to pull our input from a wordlist!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;word_site&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;https://www.mit.edu/~ecprice/wordlist.10000&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;

&lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;word_site&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;WORDS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;splitlines&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Helper Functions
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Convert Images to Expected size/format
&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;imgToModelSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="n"&gt;W&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;image_shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
  &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;W&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="nf"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;arr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;nd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zoom&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;mode&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;nearest&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
  &lt;span class="n"&gt;dw&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dh&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;W&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;//&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;W&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;//&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;arr&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;dw&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;dw&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;W&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dh&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;dh&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;W&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="nd"&gt;@objectives.wrap_objective&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;dot_compare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;batch&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cossim_pow&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;dot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reduce_sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="n"&gt;batch&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="n"&gt;mag&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sqrt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reduce_sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="n"&gt;cossim&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dot&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;1e-6&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;mag&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dot&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;cossim&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="n"&gt;cossim_pow&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;inner&lt;/span&gt;

&lt;span class="c1"&gt;#Get DeepAI Image from Input Text
&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_generated_image_url&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="n"&gt;headers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;api-key&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;DEEPAI API KEY&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="n"&gt;url&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;https://api.deepai.org/api/text2img&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
  &lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;utf-8&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;requests&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;json&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
  &lt;span class="n"&gt;imageUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;output_url&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;imageUrl&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Twitter Interface
&lt;/h4&gt;

&lt;p&gt;Functions to interact with Twitter, decently simple, just need to get the Twitter API Key&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_tweet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;tweet_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;split&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;/&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;api&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_api&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;tweet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tweet_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;tweet&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_api&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="c1"&gt;# Authenticate to Twitter
&lt;/span&gt;    &lt;span class="n"&gt;auth&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tweepy&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;OAuthHandler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;CONSUMER KEY&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;CONSUMER SECRET&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;auth&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set_access_token&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;TOKEN KEY&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;TOKEN SECRET&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="c1"&gt;# Create API object
&lt;/span&gt;    &lt;span class="n"&gt;api&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tweepy&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;API&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;auth&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wait_on_rate_limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_replies&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tweet&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;tweet_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tweet&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;
    &lt;span class="n"&gt;user_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tweet&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;screen_name&lt;/span&gt;
    &lt;span class="n"&gt;max_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;
    &lt;span class="n"&gt;replies&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="n"&gt;cursor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tweepy&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Cursor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;search&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;to:{}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_name&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                                &lt;span class="n"&gt;since_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;tweet_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;max_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tweet_mode&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;extended&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;items&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="nb"&gt;iter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;reply&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;cursor&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="nb"&gt;iter&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
      &lt;span class="nf"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;in_reply_to_status_id&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;tweet_id&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
          &lt;span class="n"&gt;replies&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="n"&gt;max_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;
      &lt;span class="nf"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;iter&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;break&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;replies&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Image Processing
&lt;/h4&gt;

&lt;p&gt;This is where the fancy part of the app comes in, where you actually process the image nd convert it into a weird nightmare creature!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;feature_inversion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;img&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n_steps&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;512&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cossim_pow&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Graph&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;as_default&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Session&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;sess&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;img&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;imgToModelSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;img&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;objective&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;objectives&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Objective&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
        &lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nf"&gt;dot_compare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cossim_pow&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;cossim_pow&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="n"&gt;objectives&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;blur_input_each_step&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
    &lt;span class="p"&gt;])&lt;/span&gt;

    &lt;span class="n"&gt;t_input&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;placeholder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;float32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;img&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;param_f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;param&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;image&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;img&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;decorrelate&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fft&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;alpha&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;param_f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;param_f&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;t_input&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;

    &lt;span class="n"&gt;transforms&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
      &lt;span class="n"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pad&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mode&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;constant&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;constant_value&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
      &lt;span class="n"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;jitter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
      &lt;span class="n"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;random_scale&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="mf"&gt;0.9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.95&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;1.05&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;1.1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
      &lt;span class="n"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;random_rotate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
      &lt;span class="n"&gt;transform&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;jitter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="n"&gt;T&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;render&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;make_vis_T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;objective&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;param_f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;transforms&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;transforms&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;vis_op&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;t_image&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;loss&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vis_op&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;input&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;tf&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;global_variables_initializer&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n_steps&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;vis_op&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;t_input&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;img&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;

    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t_image&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;eval&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;feed_dict&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;t_input&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;img&lt;/span&gt;&lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;Image&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromarray&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;255&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;astype&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;uint8&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are loading the provided image and running it through a series of different algorithms. &lt;br&gt;
Each one provides a slightly different output, they get trippier as you go along.&lt;br&gt;
Once we have generated each image, we want to combine the images into a &lt;strong&gt;collage&lt;/strong&gt;, so that it is easier to consume on Twitter. That's what the &lt;code&gt;h_stack&lt;/code&gt; and &lt;code&gt;v_stack&lt;/code&gt; is being used for.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_deep_images&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;imageUrl&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="n"&gt;sourceImage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;imageUrl&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;collage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
  &lt;span class="n"&gt;layers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;conv2d%d&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed3a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed3b&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                                     &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed4a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed4b&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
                                                     &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed4c&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed4d&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
                                                     &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed4e&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed5a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed5b&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="n"&gt;h_stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
  &lt;span class="n"&gt;v_stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
  &lt;span class="n"&gt;image_iter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
  &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;layer&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;layers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;image_iter&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="n"&gt;processed_image&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;feature_inversion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sourceImage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;h_stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;processed_image&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;image_iter&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
      &lt;span class="n"&gt;image_iter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
      &lt;span class="n"&gt;v_stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hstack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h_stack&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
      &lt;span class="n"&gt;h_stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h_stack&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;v_stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hstack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;h_stack&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
  &lt;span class="n"&gt;collage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;vstack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v_stack&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="n"&gt;v_stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
  &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;cossim&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;2.0&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt;
    &lt;span class="n"&gt;processed_image&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;feature_inversion&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sourceImage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;layer&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;mixed4d&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cossim_pow&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;cossim&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;v_stack&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;processed_image&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;h_stack&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;vstack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v_stack&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;collage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hstack&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;collage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;h_stack&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
  &lt;span class="n"&gt;Image&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromarray&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;sourceImage&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;255&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;astype&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;uint8&lt;/span&gt;&lt;span class="p"&gt;)).&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source.png&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;Image&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fromarray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;collage&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;image.png&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;collage&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  The Actual App
&lt;/h4&gt;

&lt;p&gt;Now that we have the code to generate our image, process the image, and merge it into a collage. Let's put that all together and make our app work!&lt;br&gt;
Currently, we are just generating the text from a random list of words, but you can use the commented section to choose a random tweet on a profile and grab replies from that. &lt;br&gt;
Once we have our text, we call the above functions to generate and image, save the image, and we finally use these images in our tweet!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_deep_dream_comment_search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
  &lt;span class="nb"&gt;iter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
  &lt;span class="c1"&gt;#Here we are randomly generating the words
&lt;/span&gt;  &lt;span class="n"&gt;reply_text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;choice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;WORDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt; &lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;choice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;WORDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="c1"&gt;# Alternitively, take words from user reply: 
&lt;/span&gt;  &lt;span class="c1"&gt;# all_user_tweets = get_user_tweets(api, "WeDeepDream")
&lt;/span&gt;  &lt;span class="c1"&gt;# while (iter &amp;lt; 100 and all_replies == []):
&lt;/span&gt;  &lt;span class="c1"&gt;#   iter += 1
&lt;/span&gt;  &lt;span class="c1"&gt;#   random_tweet = random.choice(all_user_tweets)
&lt;/span&gt;  &lt;span class="c1"&gt;#   all_replies = get_replies(api, random_tweet)
&lt;/span&gt;  &lt;span class="c1"&gt;#   print "Iter: " + str(iter)
&lt;/span&gt;  &lt;span class="c1"&gt;# if (iter &amp;lt; 100):
&lt;/span&gt;  &lt;span class="c1"&gt;#   random_reply = random.choice(all_replies)
&lt;/span&gt;  &lt;span class="c1"&gt;#   reply_text = random_reply.full_text
&lt;/span&gt;  &lt;span class="c1"&gt;#   reply_user = random_reply.user.screen_name
&lt;/span&gt;  &lt;span class="c1"&gt;# api.update_status(status='@' + str(reply_user) + " Said: " + str(reply_text))
&lt;/span&gt;  &lt;span class="c1"&gt;# + str(reply_user) + " "
&lt;/span&gt;
  &lt;span class="k"&gt;print&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Generating Images from text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
  &lt;span class="n"&gt;gen_image_url&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_generated_image_url&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reply_text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;collage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_deep_images&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;gen_image_url&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="c1"&gt;# Upload images and get media_ids
&lt;/span&gt;  &lt;span class="n"&gt;filenames&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source.png&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;image.png&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
  &lt;span class="n"&gt;media_ids&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

  &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;filenames&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="n"&gt;res&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;media_upload&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="n"&gt;media_ids&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;media_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update_status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Image generated from string: &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;  &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reply_text&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;https://github.com/OGoodness&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;media_ids&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;media_ids&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;print&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Just tweeted&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
  &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;filenames&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
      &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nb"&gt;OSError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Whoops!&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
        &lt;span class="k"&gt;pass&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Run Repeatedly
&lt;/h4&gt;

&lt;p&gt;Now that we have everything working, lets set up the collab to continuously run! &lt;br&gt;
Eventually, the Collab WILL time out, but you can find ways around this, for now, a few minutes will work as a Proof Of Concept.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sched&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;scheduler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;api&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_api&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;do_something&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; 
    &lt;span class="k"&gt;print&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Doing stuff...&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
    &lt;span class="nf"&gt;run_deep_dream_comment_search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;enter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;do_something&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sc&lt;/span&gt;&lt;span class="p"&gt;,))&lt;/span&gt;

&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;enter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;do_something&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;,))&lt;/span&gt;
&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Example Outputs
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Base Michael&lt;/strong&gt;&lt;br&gt;
&lt;iframe class="tweet-embed" id="tweet-1366411043614973955-968" src="https://platform.twitter.com/embed/Tweet.html?id=1366411043614973955"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-1366411043614973955-968');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1366411043614973955&amp;amp;theme=dark"
  }



&lt;br&gt;
&lt;strong&gt;Finds Panel&lt;/strong&gt;&lt;br&gt;
&lt;iframe class="tweet-embed" id="tweet-1365382364566671361-115" src="https://platform.twitter.com/embed/Tweet.html?id=1365382364566671361"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-1365382364566671361-115');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1365382364566671361&amp;amp;theme=dark"
  }



&lt;br&gt;
&lt;strong&gt;Rabbit Ellen&lt;/strong&gt;&lt;br&gt;
&lt;iframe class="tweet-embed" id="tweet-1365347261073428482-696" src="https://platform.twitter.com/embed/Tweet.html?id=1365347261073428482"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-1365347261073428482-696');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=1365347261073428482&amp;amp;theme=dark"
  }



&lt;/p&gt;

</description>
      <category>twitter</category>
      <category>deeplearning</category>
      <category>tutorial</category>
      <category>python</category>
    </item>
  </channel>
</rss>
