[
  {
    "path": ".dependency-cruiser.js",
    "content": "/** @type {import('dependency-cruiser').IConfiguration} */\n\n// https://github.com/Sairyss/domain-driven-hexagon#enforcing-architecture\n\nconst apiLayerPaths = [\n  'controller',\n  'dtos',\n  'request',\n  'response',\n  'dto\\\\.ts$',\n  'controller\\\\.ts$',\n  'resolver\\\\.ts$',\n];\n\nconst applicationLayerPaths = ['application', '\\\\.service\\\\.ts$'];\n\nconst infrastructureLayerPaths = [\n  'infrastructure',\n  'infra',\n  'database',\n  'repository',\n];\n\nconst domainLayerPaths = [\n  'domain',\n  'entity\\\\.ts$',\n  'aggregate\\\\.ts$',\n  'domain-event\\\\.ts$',\n  'value-object\\\\.ts$',\n];\n\nmodule.exports = {\n  forbidden: [\n    /* user defined rules */\n    {\n      name: 'no-domain-to-api-deps',\n      comment: 'Domain layer cannot depend on api layer',\n      severity: 'error',\n      from: { path: domainLayerPaths },\n      to: {\n        path: apiLayerPaths,\n      },\n    },\n    {\n      name: 'no-domain-to-app-deps',\n      comment: 'Domain layer cannot depend on application layer',\n      severity: 'error',\n      from: { path: domainLayerPaths },\n      to: {\n        path: applicationLayerPaths,\n        pathNot: ['AppRequestContext\\\\.ts'],\n      },\n    },\n    {\n      name: 'no-domain-to-infra-deps',\n      comment: 'Domain layer cannot depend on infrastructure layer',\n      severity: 'error',\n      from: { path: domainLayerPaths },\n      to: {\n        path: infrastructureLayerPaths,\n        pathNot: ['port\\\\.ts$'],\n      },\n    },\n    {\n      name: 'no-infra-to-api-deps',\n      comment: 'Infrastructure layer cannot depend on api layer',\n      severity: 'error',\n      from: { path: infrastructureLayerPaths },\n      to: {\n        path: apiLayerPaths,\n      },\n    },\n    {\n      name: 'no-command-query-to-api-deps',\n      comment: 'Commands and Queries cannot depend on api layer',\n      severity: 'error',\n      from: {\n        path: [\n          'query-handler\\\\.ts$',\n          'command-handler\\\\.ts$',\n          'command\\\\.ts$',\n          'service\\\\.ts$',\n        ],\n      },\n      to: {\n        path: apiLayerPaths,\n      },\n    },\n\n    /* rules from the 'recommended' preset: */\n    // {\n    //   name: 'no-circular',\n    //   severity: 'warn',\n    //   comment:\n    //     'This dependency is part of a circular relationship. You might want to revise ' +\n    //     'your solution (i.e. use dependency inversion, make sure the modules have a single responsibility) ',\n    //   from: {},\n    //   to: {\n    //     circular: true,\n    //   },\n    // },\n    {\n      name: 'no-orphans',\n      comment:\n        \"This is an orphan module - it's likely not used (anymore?). Either use it or \" +\n        \"remove it. If it's logical this module is an orphan (i.e. it's a config file), \" +\n        'add an exception for it in your dependency-cruiser configuration. By default ' +\n        'this rule does not scrutinize dot-files (e.g. .eslintrc.js), TypeScript declaration ' +\n        'files (.d.ts), tsconfig.json and some of the babel and webpack configs.',\n      severity: 'error',\n      from: {\n        orphan: true,\n        pathNot: [\n          '(^|/)\\\\.[^/]+\\\\.(js|cjs|mjs|ts|json)$', // dot files\n          '\\\\.d\\\\.ts$', // TypeScript declaration files\n          '(^|/)tsconfig\\\\.json$', // TypeScript config\n          '(^|/)(babel|webpack)\\\\.config\\\\.(js|cjs|mjs|ts|json)$', // other configs\n        ],\n      },\n      to: {},\n    },\n    {\n      name: 'no-deprecated-core',\n      comment:\n        'A module depends on a node core module that has been deprecated. Find an alternative - these are ' +\n        \"bound to exist - node doesn't deprecate lightly.\",\n      severity: 'error',\n      from: {},\n      to: {\n        dependencyTypes: ['core'],\n        path: [\n          '^(v8/tools/codemap)$',\n          '^(v8/tools/consarray)$',\n          '^(v8/tools/csvparser)$',\n          '^(v8/tools/logreader)$',\n          '^(v8/tools/profile_view)$',\n          '^(v8/tools/profile)$',\n          '^(v8/tools/SourceMap)$',\n          '^(v8/tools/splaytree)$',\n          '^(v8/tools/tickprocessor-driver)$',\n          '^(v8/tools/tickprocessor)$',\n          '^(node-inspect/lib/_inspect)$',\n          '^(node-inspect/lib/internal/inspect_client)$',\n          '^(node-inspect/lib/internal/inspect_repl)$',\n          '^(async_hooks)$',\n          '^(punycode)$',\n          '^(domain)$',\n          '^(constants)$',\n          '^(sys)$',\n          '^(_linklist)$',\n          '^(_stream_wrap)$',\n        ],\n      },\n    },\n    {\n      name: 'not-to-deprecated',\n      comment:\n        'This module uses a (version of an) npm module that has been deprecated. Either upgrade to a later ' +\n        'version of that module, or find an alternative. Deprecated modules are a security risk.',\n      severity: 'error',\n      from: {},\n      to: {\n        dependencyTypes: ['deprecated'],\n      },\n    },\n    {\n      name: 'no-non-package-json',\n      severity: 'error',\n      comment:\n        \"This module depends on an npm package that isn't in the 'dependencies' section of your package.json. \" +\n        \"That's problematic as the package either (1) won't be available on live (2 - worse) will be \" +\n        'available on live with an non-guaranteed version. Fix it by adding the package to the dependencies ' +\n        'in your package.json.',\n      from: {},\n      to: {\n        dependencyTypes: ['npm-no-pkg', 'npm-unknown'],\n      },\n    },\n    {\n      name: 'not-to-unresolvable',\n      comment:\n        \"This module depends on a module that cannot be found ('resolved to disk'). If it's an npm \" +\n        'module: add it to your package.json. In all other cases you likely already know what to do.',\n      severity: 'error',\n      from: {},\n      to: {\n        couldNotResolve: true,\n      },\n    },\n    {\n      name: 'no-duplicate-dep-types',\n      comment:\n        \"Likely this module depends on an external ('npm') package that occurs more than once \" +\n        'in your package.json i.e. bot as a devDependencies and in dependencies. This will cause ' +\n        'maintenance problems later on.',\n      severity: 'error',\n      from: {},\n      to: {\n        moreThanOneDependencyType: true,\n        // as it's pretty common to have a type import be a type only import\n        // _and_ (e.g.) a devDependency - don't consider type-only dependency\n        // types for this rule\n        dependencyTypesNot: ['type-only'],\n      },\n    },\n\n    /* rules you might want to tweak for your specific situation: */\n    {\n      name: 'not-to-test',\n      comment:\n        \"This module depends on code within a folder that should only contain tests. As tests don't \" +\n        \"implement functionality this is odd. Either you're writing a test outside the test folder \" +\n        \"or there's something in the test folder that isn't a test.\",\n      severity: 'error',\n      from: {\n        pathNot: '^(tests)',\n      },\n      to: {\n        path: '^(tests)',\n      },\n    },\n    {\n      name: 'not-to-spec',\n      comment:\n        'This module depends on a spec (test) file. The sole responsibility of a spec file is to test code. ' +\n        \"If there's something in a spec that's of use to other modules, it doesn't have that single \" +\n        'responsibility anymore. Factor it out into (e.g.) a separate utility/ helper or a mock.',\n      severity: 'error',\n      from: {},\n      to: {\n        path: '\\\\.(spec|test)\\\\.(js|mjs|cjs|ts|ls|coffee|litcoffee|coffee\\\\.md)$',\n      },\n    },\n    {\n      name: 'not-to-dev-dep',\n      severity: 'error',\n      comment:\n        \"This module depends on an npm package from the 'devDependencies' section of your \" +\n        'package.json. It looks like something that ships to production, though. To prevent problems ' +\n        \"with npm packages that aren't there on production declare it (only!) in the 'dependencies'\" +\n        'section of your package.json. If this module is development only - add it to the ' +\n        'from.pathNot re of the not-to-dev-dep rule in the dependency-cruiser configuration',\n      from: {\n        path: '^(src)',\n        pathNot:\n          '\\\\.(spec|test)\\\\.(js|mjs|cjs|ts|ls|coffee|litcoffee|coffee\\\\.md)$',\n      },\n      to: {\n        dependencyTypes: ['npm-dev'],\n      },\n    },\n    {\n      name: 'optional-deps-used',\n      severity: 'info',\n      comment:\n        'This module depends on an npm package that is declared as an optional dependency ' +\n        \"in your package.json. As this makes sense in limited situations only, it's flagged here. \" +\n        \"If you're using an optional dependency here by design - add an exception to your\" +\n        'dependency-cruiser configuration.',\n      from: {},\n      to: {\n        dependencyTypes: ['npm-optional'],\n      },\n    },\n    {\n      name: 'peer-deps-used',\n      comment:\n        'This module depends on an npm package that is declared as a peer dependency ' +\n        'in your package.json. This makes sense if your package is e.g. a plugin, but in ' +\n        'other cases - maybe not so much. If the use of a peer dependency is intentional ' +\n        'add an exception to your dependency-cruiser configuration.',\n      severity: 'error',\n      from: {},\n      to: {\n        dependencyTypes: ['npm-peer'],\n      },\n    },\n  ],\n  options: {\n    /* conditions specifying which files not to follow further when encountered:\n       - path: a regular expression to match\n       - dependencyTypes: see https://github.com/sverweij/dependency-cruiser/blob/master/doc/rules-reference.md#dependencytypes-and-dependencytypesnot\n       for a complete list\n    */\n    doNotFollow: {\n      path: 'node_modules',\n    },\n\n    /* conditions specifying which dependencies to exclude\n       - path: a regular expression to match\n       - dynamic: a boolean indicating whether to ignore dynamic (true) or static (false) dependencies.\n          leave out if you want to exclude neither (recommended!)\n    */\n    // exclude : {\n    //   path: '',\n    //   dynamic: true\n    // },\n\n    /* pattern specifying which files to include (regular expression)\n       dependency-cruiser will skip everything not matching this pattern\n    */\n    // includeOnly : '',\n\n    /* dependency-cruiser will include modules matching against the focus\n       regular expression in its output, as well as their neighbours (direct\n       dependencies and dependents)\n    */\n    // focus : '',\n\n    /* list of module systems to cruise */\n    // moduleSystems: ['amd', 'cjs', 'es6', 'tsd'],\n\n    /* prefix for links in html and svg output (e.g. 'https://github.com/you/yourrepo/blob/develop/'\n       to open it on your online repo or `vscode://file/${process.cwd()}/` to \n       open it in visual studio code),\n     */\n    // prefix: '',\n\n    /* false (the default): ignore dependencies that only exist before typescript-to-javascript compilation\n       true: also detect dependencies that only exist before typescript-to-javascript compilation\n       \"specify\": for each dependency identify whether it only exists before compilation or also after\n     */\n    tsPreCompilationDeps: true,\n\n    /* \n       list of extensions to scan that aren't javascript or compile-to-javascript. \n       Empty by default. Only put extensions in here that you want to take into\n       account that are _not_ parsable. \n    */\n    // extraExtensionsToScan: [\".json\", \".jpg\", \".png\", \".svg\", \".webp\"],\n\n    /* if true combines the package.jsons found from the module up to the base\n       folder the cruise is initiated from. Useful for how (some) mono-repos\n       manage dependencies & dependency definitions.\n     */\n    // combinedDependencies: false,\n\n    /* if true leave symlinks untouched, otherwise use the realpath */\n    // preserveSymlinks: false,\n\n    /* TypeScript project file ('tsconfig.json') to use for\n       (1) compilation and\n       (2) resolution (e.g. with the paths property)\n\n       The (optional) fileName attribute specifies which file to take (relative to\n       dependency-cruiser's current working directory). When not provided\n       defaults to './tsconfig.json'.\n     */\n    tsConfig: {\n      fileName: 'tsconfig.json',\n    },\n\n    /* Webpack configuration to use to get resolve options from.\n\n       The (optional) fileName attribute specifies which file to take (relative\n       to dependency-cruiser's current working directory. When not provided defaults\n       to './webpack.conf.js'.\n\n       The (optional) `env` and `args` attributes contain the parameters to be passed if\n       your webpack config is a function and takes them (see webpack documentation\n       for details)\n     */\n    // webpackConfig: {\n    //  fileName: './webpack.config.js',\n    //  env: {},\n    //  args: {},\n    // },\n\n    /* Babel config ('.babelrc', '.babelrc.json', '.babelrc.json5', ...) to use\n      for compilation (and whatever other naughty things babel plugins do to\n      source code). This feature is well tested and usable, but might change\n      behavior a bit over time (e.g. more precise results for used module \n      systems) without dependency-cruiser getting a major version bump.\n     */\n    // babelConfig: {\n    //   fileName: './.babelrc'\n    // },\n\n    /* List of strings you have in use in addition to cjs/ es6 requires\n       & imports to declare module dependencies. Use this e.g. if you've\n       re-declared require, use a require-wrapper or use window.require as\n       a hack.\n    */\n    // exoticRequireStrings: [],\n    /* options to pass on to enhanced-resolve, the package dependency-cruiser\n       uses to resolve module references to disk. You can set most of these\n       options in a webpack.conf.js - this section is here for those\n       projects that don't have a separate webpack config file.\n\n       Note: settings in webpack.conf.js override the ones specified here.\n     */\n    enhancedResolveOptions: {\n      /* List of strings to consider as 'exports' fields in package.json. Use\n         ['exports'] when you use packages that use such a field and your environment\n         supports it (e.g. node ^12.19 || >=14.7 or recent versions of webpack).\n\n         If you have an `exportsFields` attribute in your webpack config, that one\n         will have precedence over the one specified here.\n      */\n      exportsFields: ['exports'],\n      /* List of conditions to check for in the exports field. e.g. use ['imports']\n         if you're only interested in exposed es6 modules, ['require'] for commonjs,\n         or all conditions at once `(['import', 'require', 'node', 'default']`)\n         if anything goes for you. Only works when the 'exportsFields' array is\n         non-empty.\n\n        If you have a 'conditionNames' attribute in your webpack config, that one will\n        have precedence over the one specified here.\n      */\n      conditionNames: ['import', 'require', 'node', 'default'],\n      /*\n         The extensions, by default are the same as the ones dependency-cruiser\n         can access (run `npx depcruise --info` to see which ones that are in\n         _your_ environment. If that list is larger than what you need (e.g. \n         it contains .js, .jsx, .ts, .tsx, .cts, .mts - but you don't use \n         TypeScript you can pass just the extensions you actually use (e.g. \n         [\".js\", \".jsx\"]). This can speed up the most expensive step in \n         dependency cruising (module resolution) quite a bit.\n       */\n      // extensions: [\".js\", \".jsx\", \".ts\", \".tsx\", \".d.ts\"],\n      /* \n         If your TypeScript project makes use of types specified in 'types'\n         fields in package.jsons of external dependencies, specify \"types\"\n         in addition to \"main\" in here, so enhanced-resolve (the resolver\n         dependency-cruiser uses) knows to also look there. You can also do\n         this if you're not sure, but still use TypeScript. In a future version\n         of dependency-cruiser this will likely become the default.\n       */\n      mainFields: ['main', 'types'],\n    },\n    reporterOptions: {\n      dot: {\n        /* pattern of modules that can be consolidated in the detailed\n           graphical dependency graph. The default pattern in this configuration\n           collapses everything in node_modules to one folder deep so you see\n           the external modules, but not the innards your app depends upon.\n         */\n        collapsePattern: 'node_modules/[^/]+',\n\n        /* Options to tweak the appearance of your graph.See\n           https://github.com/sverweij/dependency-cruiser/blob/master/doc/options-reference.md#reporteroptions\n           for details and some examples. If you don't specify a theme\n           don't worry - dependency-cruiser will fall back to the default one.\n        */\n        // theme: {\n        //   graph: {\n        //     /* use splines: \"ortho\" for straight lines. Be aware though\n        //       graphviz might take a long time calculating ortho(gonal)\n        //       routings.\n        //    */\n        //     splines: \"true\"\n        //   },\n        //   modules: [\n        //     {\n        //       criteria: { matchesFocus: true },\n        //       attributes: {\n        //         fillcolor: \"lime\",\n        //         penwidth: 2,\n        //       },\n        //     },\n        //     {\n        //       criteria: { matchesFocus: false },\n        //       attributes: {\n        //         fillcolor: \"lightgrey\",\n        //       },\n        //     },\n        //     {\n        //       criteria: { matchesReaches: true },\n        //       attributes: {\n        //         fillcolor: \"lime\",\n        //         penwidth: 2,\n        //       },\n        //     },\n        //     {\n        //       criteria: { matchesReaches: false },\n        //       attributes: {\n        //         fillcolor: \"lightgrey\",\n        //       },\n        //     },\n        //     {\n        //       criteria: { source: \"^src/model\" },\n        //       attributes: { fillcolor: \"#ccccff\" }\n        //     },\n        //     {\n        //       criteria: { source: \"^src/view\" },\n        //       attributes: { fillcolor: \"#ccffcc\" }\n        //     },\n        //   ],\n        //   dependencies: [\n        //     {\n        //       criteria: { \"rules[0].severity\": \"error\" },\n        //       attributes: { fontcolor: \"red\", color: \"red\" }\n        //     },\n        //     {\n        //       criteria: { \"rules[0].severity\": \"warn\" },\n        //       attributes: { fontcolor: \"orange\", color: \"orange\" }\n        //     },\n        //     {\n        //       criteria: { \"rules[0].severity\": \"info\" },\n        //       attributes: { fontcolor: \"blue\", color: \"blue\" }\n        //     },\n        //     {\n        //       criteria: { resolved: \"^src/model\" },\n        //       attributes: { color: \"#0000ff77\" }\n        //     },\n        //     {\n        //       criteria: { resolved: \"^src/view\" },\n        //       attributes: { color: \"#00770077\" }\n        //     }\n        //   ]\n        // }\n      },\n      archi: {\n        /* pattern of modules that can be consolidated in the high level\n          graphical dependency graph. If you use the high level graphical\n          dependency graph reporter (`archi`) you probably want to tweak\n          this collapsePattern to your situation.\n        */\n        collapsePattern:\n          '^(packages|src|lib|app|bin|test(s?)|spec(s?))/[^/]+|node_modules/[^/]+',\n\n        /* Options to tweak the appearance of your graph.See\n           https://github.com/sverweij/dependency-cruiser/blob/master/doc/options-reference.md#reporteroptions\n           for details and some examples. If you don't specify a theme\n           for 'archi' dependency-cruiser will use the one specified in the\n           dot section (see above), if any, and otherwise use the default one.\n         */\n        // theme: {\n        // },\n      },\n      text: {\n        highlightFocused: true,\n      },\n    },\n  },\n};\n// generated: dependency-cruiser@12.10.0 on 2023-02-27T15:40:08.936Z\n"
  },
  {
    "path": ".eslintrc.js",
    "content": "/**\n * eslint config\n * https://github.com/Sairyss/backend-best-practices#static-code-analysis\n */\n\nmodule.exports = {\n  parser: '@typescript-eslint/parser',\n  parserOptions: {\n    project: 'tsconfig.json',\n    tsconfigRootDir: __dirname,\n    sourceType: 'module',\n  },\n  plugins: ['@typescript-eslint/eslint-plugin'],\n  extends: [\n    'plugin:@typescript-eslint/recommended',\n    'plugin:prettier/recommended',\n  ],\n  root: true,\n  env: {\n    node: true,\n    jest: true,\n  },\n  ignorePatterns: ['.eslintrc.js'],\n  rules: {\n    '@typescript-eslint/interface-name-prefix': 'off',\n    '@typescript-eslint/no-explicit-any': 'off',\n\n    // TS errors\n    '@typescript-eslint/no-misused-new': 'error',\n    '@typescript-eslint/explicit-module-boundary-types': 'error',\n    '@typescript-eslint/no-non-null-assertion': 'error',\n    '@typescript-eslint/no-unused-vars': 'error',\n\n    // Eslint off\n    'import/extensions': 'off',\n    'import/prefer-default-export': 'off',\n    'class-methods-use-this': 'off',\n    'no-useless-constructor': 'off',\n    'import/no-unresolved': 'off',\n    'no-control-regex': 'off',\n    'no-shadow': 'off',\n    'import/no-cycle': 'off',\n    'consistent-return': 'off',\n    'no-underscore-dangle': 'off',\n    'max-classes-per-file': 'off',\n\n    // Eslint errors\n    'no-restricted-syntax': [\n      'error',\n      {\n        selector: 'LabeledStatement',\n        message:\n          'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',\n      },\n      {\n        selector: 'WithStatement',\n        message:\n          '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.',\n      },\n      {\n        selector: \"MethodDefinition[kind='set']\",\n        message: 'Property setters are not allowed',\n      },\n    ],\n  },\n};\n"
  },
  {
    "path": ".gitignore",
    "content": "# Environment variables\n.env\n\n# compiled output\n/dist\n/node_modules\n/package-lock.json\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\npnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# OS\n.DS_Store\n\n# Tests\n/coverage\n/.nyc_output\n\n# IDEs and editors\n/.idea\n.project\n.classpath\n.c9/\n*.launch\n.settings/\n*.sublime-workspace\n\n# IDE - VSCode\n# .vscode/*\n# !.vscode/settings.json\n# !.vscode/tasks.json\n# !.vscode/launch.json\n# !.vscode/extensions.json\n"
  },
  {
    "path": ".jestrc.json",
    "content": "{\n  \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n  \"rootDir\": \".\",\n  \"testEnvironment\": \"node\",\n  \"coverageDirectory\": \"../tests/coverage\",\n  \"setupFilesAfterEnv\": [\"./tests/setup/jestSetupAfterEnv.ts\"],\n  \"globalSetup\": \"<rootDir>/tests/setup/jestGlobalSetup.ts\",\n  \"testRegex\": \".spec.ts$\",\n  \"moduleNameMapper\": {\n    \"@src/(.*)$\": \"<rootDir>/src/$1\",\n    \"@modules/(.*)$\": \"<rootDir>/src/modules/$1\",\n    \"@config/(.*)$\": \"<rootDir>/src/configs/$1\",\n    \"@libs/(.*)$\": \"<rootDir>/src/libs/$1\",\n    \"@exceptions$\": \"<rootDir>/src/libs/exceptions\",\n    \"@tests/(.*)$\": \"<rootDir>/tests/$1\"\n  },\n  \"transform\": {\n    \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n  }\n}"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}"
  },
  {
    "path": ".vscode/ltex.dictionary.en-US.txt",
    "content": "DTOs\nDTO\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n  \"cucumberautocomplete.steps\": [\"tests/**/*.ts\"],\n  \"cucumberautocomplete.strictGherkinCompletion\": true,\n  \"cSpell.words\": [\"instanceof\", \"Slonik\"]\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Sairyss\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Domain-Driven Hexagon\n\n**Check out my other repositories**:\n\n- [Backend best practices](https://github.com/Sairyss/backend-best-practices) - Best practices, tools and guidelines for backend development.\n- [System Design Patterns](https://github.com/Sairyss/system-design-patterns) - list of topics and resources related to distributed systems, system design, microservices, scalability and performance, etc.\n- [Full Stack starter template](https://github.com/Sairyss/fullstack-starter-template) - template for full stack applications based on TypeScript, React, Vite, ChakraUI, tRPC, Fastify, Prisma, zod, etc.\n\n---\n\nThe main emphasis of this project is to provide recommendations on how to design software applications. This readme includes techniques, tools, best practices, architectural patterns and guidelines gathered from different sources.\n\nCode examples are written using [NodeJS](https://nodejs.org/en/), [TypeScript](https://www.typescriptlang.org/), [NestJS](https://docs.nestjs.com/) framework and [Slonik](https://github.com/gajus/slonik) for the database access.\n\nPatterns and principles presented here are **framework/language agnostic**. Therefore, the 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.\n\n**Note**: code examples are adapted to TypeScript and frameworks mentioned above. <br/>\n(Implementations in other languages will look differently)\n\n**Everything below is provided as a recommendation, not a rule**. Different projects have different requirements, so any pattern mentioned in this readme should be adjusted to project needs or even skipped entirely if it doesn't fit. In real world production applications, you will most likely only need a fraction of those patterns depending on your use cases. More info in [this](#general-recommendations-on-architectures-best-practices-design-patterns-and-principles) section.\n\n---\n\n- [Domain-Driven Hexagon](#domain-driven-hexagon)\n- [Architecture](#architecture)\n      - [Pros](#pros)\n      - [Cons](#cons)\n- [Diagram](#diagram)\n- [Modules](#modules)\n- [Application Core](#application-core)\n- [Application layer](#application-layer)\n  - [Application Services](#application-services)\n  - [Commands and Queries](#commands-and-queries)\n    - [Commands](#commands)\n    - [Queries](#queries)\n  - [Ports](#ports)\n- [Domain Layer](#domain-layer)\n  - [Entities](#entities)\n  - [Aggregates](#aggregates)\n  - [Domain Events](#domain-events)\n  - [Integration Events](#integration-events)\n  - [Domain Services](#domain-services)\n  - [Value objects](#value-objects)\n  - [Domain Invariants](#domain-invariants)\n    - [Replacing primitives with Value Objects](#replacing-primitives-with-value-objects)\n    - [Make illegal states unrepresentable](#make-illegal-states-unrepresentable)\n      - [Validation at compile time](#validation-at-compile-time)\n      - [Validation at runtime](#validation-at-runtime)\n    - [Guarding vs validating](#guarding-vs-validating)\n  - [Domain Errors](#domain-errors)\n  - [Using libraries inside Application's core](#using-libraries-inside-applications-core)\n- [Interface Adapters](#interface-adapters)\n  - [Controllers](#controllers)\n    - [Resolvers](#resolvers)\n  - [DTOs](#dtos)\n    - [Request DTOs](#request-dtos)\n    - [Response DTOs](#response-dtos)\n    - [Additional recommendations](#additional-recommendations)\n    - [Local DTOs](#local-dtos)\n- [Infrastructure layer](#infrastructure-layer)\n  - [Adapters](#adapters)\n  - [Repositories](#repositories)\n  - [Persistence models](#persistence-models)\n  - [Other things that can be a part of Infrastructure layer](#other-things-that-can-be-a-part-of-infrastructure-layer)\n- [Other recommendations](#other-recommendations)\n  - [General recommendations on architectures, best practices, design patterns and principles](#general-recommendations-on-architectures-best-practices-design-patterns-and-principles)\n  - [Recommendations for smaller APIs](#recommendations-for-smaller-apis)\n  - [Behavioral Testing](#behavioral-testing)\n  - [Folder and File Structure](#folder-and-file-structure)\n    - [File names](#file-names)\n  - [Enforcing architecture](#enforcing-architecture)\n  - [Prevent massive inheritance chains](#prevent-massive-inheritance-chains)\n- [Additional resources](#additional-resources)\n  - [Articles](#articles)\n  - [Websites](#websites)\n  - [Blogs](#blogs)\n  - [Videos](#videos)\n  - [Books](#books)\n\n# Architecture\n\nThis is an attempt to combine multiple architectural patterns and styles together, such as:\n\n- [Domain-Driven Design (DDD)](https://en.wikipedia.org/wiki/Domain-driven_design)\n- [Hexagonal (Ports and Adapters) Architecture](https://en.wikipedia.org/wiki/Hexagonal_architecture_(software))\n- [Secure by Design](https://www.manning.com/books/secure-by-design)\n- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)\n- [Onion Architecture](https://herbertograca.com/2017/09/21/onion-architecture/)\n- [SOLID Principles](https://en.wikipedia.org/wiki/SOLID)\n- [Software Design Patterns](https://refactoring.guru/design-patterns/what-is-pattern)\n\nAnd many others (more links below in every chapter).\n\nBefore we begin, here are the PROS and CONS of using a complete architecture like this:\n\n#### Pros\n\n- Independent of external frameworks, technologies, databases, etc. Frameworks and external resources can be plugged/unplugged with much less effort.\n- Easily testable and scalable.\n- More secure. Some security principles are baked in design itself.\n- The solution can be worked on and maintained by different teams, without stepping on each other's toes.\n- Easier to add new features. As the system grows over time, the difficulty in adding new features remains constant and relatively small.\n- If the solution is properly broken apart along [bounded context](https://martinfowler.com/bliki/BoundedContext.html) lines, it becomes easy to convert pieces of it into microservices if needed.\n\n#### Cons\n\n- 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.\n\n- Some 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](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) applications and could over-complicate such solutions. Some principles which are described below can be used in smaller sized applications, but must be implemented only after analyzing and understanding all pros and cons.\n\n# Diagram\n\n![Domain-Driven Hexagon](assets/images/DomainDrivenHexagon.png)\n<sup>Diagram is mostly based on [this one](https://github.com/hgraca/explicit-architecture-php#explicit-architecture-1) + others found online</sup>\n\nIn short, data flow looks like this (from left to right):\n\n- Request/CLI command/event is sent to the controller using plain DTO;\n- Controller parses this DTO, maps it to a Command/Query object format and passes it to an Application service;\n- Application service handles this Command/Query; it executes business logic using domain services and entities/aggregates and uses the infrastructure layer through ports(interfaces);\n- Infrastructure layer maps data to a format that it needs, retrieves/persists data from/to a database, uses adapters for other I/O communications (like sending an event to an external broker or calling external APIs), maps data back to domain format and returns it back to Application service;\n- After the Application service finishes doing its job, it returns data/confirmation back to Controllers;\n- Controllers return data back to the user (if application has presenters/views, those are returned instead).\n\nEach layer is in charge of its own logic and has building blocks that usually should follow a [Single-responsibility principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) when possible and when it makes sense (for example, using `Repositories` only for database access, using `Entities` for business logic, etc.).\n\n**Keep in mind** that different projects can have more or less steps/layers/building blocks than described here. Add more if the application requires it, and skip some if the application is not that complex and doesn't need all that abstraction.\n\nGeneral 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.\n\nMore in details on each step below.\n\n# Modules\n\nThis project's code examples use separation by modules (also called components). Each module's name should reflect an important concept from the Domain and have its own folder with a dedicated codebase. Each business use case inside that module gets its own folder to store most of the things it needs (this is also called _Vertical Slicing_). It's easier to work on things that change together if those things are gathered relatively close to each other. Think of a module as a \"box\" that groups together related business logic.\n\nUsing modules is a great way to [encapsulate](<https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)>) parts of highly [cohesive](<https://en.wikipedia.org/wiki/Cohesion_(computer_science)>) business domain rules.\n\nTry to make every module independent and keep interactions between modules minimal. Think of each module as a mini application bounded by a single context. Consider module internals private and try to avoid direct imports between modules (like importing a class `import SomeClass from '../SomeOtherModule'`) since this creates [tight coupling](<https://en.wikipedia.org/wiki/Coupling_(computer_programming)>) and can turn your code into a [spaghetti](https://en.wikipedia.org/wiki/Spaghetti_code) and application into a [big ball of mud](https://en.wikipedia.org/wiki/Big_ball_of_mud).\n\nFew advices to avoid coupling:\n\n- Try not to create dependencies between modules or use cases. Instead, move shared logic into a separate files and make both depend on that instead of depending on each other.\n- Modules can cooperate through a [mediator](https://en.wikipedia.org/wiki/Mediator_pattern#:~:text=In%20software%20engineering%2C%20the%20mediator,often%20consist%20of%20many%20classes.) or a public [facade](https://en.wikipedia.org/wiki/Facade_pattern), hiding all private internals of the module to avoid its misuse, and giving public access only to certain pieces of functionality that meant to be public.\n- Alternatively modules can communicate with each other by using messages. For example, you can send commands using a commands bus or subscribe to events that other modules emit (more info on events and commands bus below).\n\nThis ensures [loose coupling](https://en.wikipedia.org/wiki/Loose_coupling), refactoring of a module internals can be done easier because outside world only depends on module's public interface, 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 or major refactoring.\n\nKeep your modules small. You should be able to rewrite a module in a relatively short period of time. This applies not only to modules pattern, but to software development in general: objects, functions, microservices, processes, etc. Keep them small and composable. This is incredibly powerful in a constantly changing environments of software development, since when your requirements change, changing small modules is much easier than changing a big program. You can just delete a module and rewrite it from scratch in a matter of days. This idea is further described in this talk: [Greg Young - The art of destroying software](https://youtu.be/Ed94CfxgsCA).\n\nCode Examples:\n\n- Check [src/modules](src/modules) directory structure.\n- [src/modules/user/commands](src/modules/user/commands) - \"commands\" directory in a user module includes business use cases (commands) that a module can execute, each with its own Vertical Slice.\n\nRead more:\n\n- [Modular programming: Beyond the spaghetti mess](https://www.tiny.cloud/blog/modular-programming-principle/).\n- [What are Modules in Domain Driven Design?](https://www.culttt.com/2014/12/10/modules-domain-driven-design/)\n- [How to Implement Vertical Slice Architecture](https://garywoodfine.com/implementing-vertical-slice-architecture/)\n\nEach module consists of layers described below.\n\n# Application Core\n\nThis is the core of the system which is built using [DDD building blocks](https://dzone.com/articles/ddd-part-ii-ddd-building-blocks):\n\n**Domain layer**:\n\n- Entities\n- Aggregates\n- Domain Services\n- Value Objects\n- Domain Errors\n\n**Application layer**:\n\n- Application Services\n- Commands and Queries\n- Ports\n\n**Note**: different implementations may have slightly different layer structures depending on applications needs. Also, more layers and building blocks may be added if needed.\n\n---\n\n# Application layer\n\n## Application Services\n\nApplication Services (also called \"Workflow Services\", \"Use Cases\", \"Interactors\", etc.) are used to orchestrate the steps required to fulfill the commands imposed by the client.\n\nApplication services:\n\n- Typically used to orchestrate how the outside world interacts with your application and performs tasks required by the end users;\n- Contain no domain-specific business logic;\n- 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;\n- Uses ports to declare dependencies on infrastructural services/adapters required to execute domain logic (ports are just interfaces, we will discuss this topic in details below);\n- Fetch domain `Entities`/`Aggregates` (or anything else) from database/external APIs (through ports/interfaces, with concrete implementations injected by the [DI](https://en.wikipedia.org/wiki/Dependency_injection) library);\n- Execute domain logic on those `Entities`/`Aggregates` (by invoking their methods);\n- In case of working with multiple `Entities`/`Aggregates`, use a `Domain Service` to orchestrate them;\n- Execute other out-of-process communications through Ports (like event emits, sending emails, etc.);\n- Services can be used as a `Command`/`Query` handlers;\n- Should not depend on other application services since it may cause problems (like cyclic dependencies);\n\nOne service per use case is considered a good practice.\n\n<details>\n<summary>What are \"Use Cases\"?</summary>\n\n[wiki](https://en.wikipedia.org/wiki/Use_case):\n\n> 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.\n\nUse cases are, simply said, list of actions required from an application.\n\n---\n\n</details>\n\nExample file: [create-user.service.ts](src/modules/user/commands/create-user/create-user.service.ts)\n\nMore about services:\n\n- [Domain-Application-Infrastructure Services pattern](https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/domain-application-infrastructure-services-pattern.html)\n- [Services in DDD finally explained](https://developer20.com/services-in-ddd-finally-explained/)\n\n## Commands and Queries\n\nThis principle is called [Command–Query Separation(CQS)](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation). When possible, methods should be separated into `Commands` (state-changing operations) and `Queries` (data-retrieval operations). To make a clear distinction between those two types of operations, input objects can be represented as `Commands` and `Queries`. Before DTO reaches the domain, it's converted into a `Command`/`Query` object.\n\n### Commands\n\n`Command` is an object that signals user intent, for example `CreateUserCommand`. It describes a single action (but does not perform it).\n\n`Commands` 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.\n\nData retrieval is responsibility of `Queries`, so `Command` methods should not return business data.\n\nSome CQS purists may say that a `Command` shouldn't return anything at all. But you will need at least an ID of a created item to access it later. To achieve that you can let clients generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) (more info here: [CQS versus server generated IDs](https://blog.ploeh.dk/2014/08/11/cqs-versus-server-generated-ids/)).\n\nThough, violating this rule and returning some metadata, like `ID` of a created item, redirect link, confirmation message, status, or other metadata is a more practical approach than following dogmas.\n\n**Note**: `Command` is similar but not the same as described here: [Command Pattern](https://refactoring.guru/design-patterns/command). There are multiple definitions across the internet with similar but slightly different implementations.\n\nTo execute a command you can use a `Command Bus` instead of importing a service directly. This will decouple a command Invoker from a Receiver, so you can send your commands from anywhere without creating coupling.\n\nAvoid command handlers executing other commands in this fashion: Command → Command. Instead, use events for that purpose, and execute next commands in a chain in an Event handler: Command → Event → Command.\n\nExample files:\n\n- [create-user.command.ts](src/modules/user/commands/create-user/create-user.command.ts) - a command Object\n- [create-user.message.controller.ts](src/modules/user/commands/create-user/create-user.message.controller.ts) - controller executes a command using a command bus. This decouples it from a command handler.\n- [create-user.service.ts](src/modules/user/commands/create-user/create-user.service.ts) - a command handler.\n\nRead more:\n\n- [What is a command bus and why should you use it?](https://barryvanveen.nl/blog/49-what-is-a-command-bus-and-why-should-you-use-it)\n- [Why You Should Avoid Command Handlers Calling Other Commands?](https://www.rahulpnath.com/blog/avoid-commands-calling-commands/)\n\n### Queries\n\n`Query` is similar to a `Command`. It belongs to a read model and signals user intent to find something and describes how to do it.\n\n`Query` is just a data retrieval operation and should not make any state changes (like writes to the database, files, third party APIs, etc.). For this reason, in read model we can bypass a domain and repository layers completely and query database directly from a query handler.\n\nSimilarly to Commands, Queries can use a `Query Bus` if needed. This way you can query anything from anywhere without importing classes directly and avoid coupling.\n\nExample files:\n\n- [find-users.query-handler.ts](src/modules/user/queries/find-users/find-users.query-handler.ts) - a query handler. Notice how we query the database directly, without using domain objects or repositories (more info [here](https://codeopinion.com/should-you-use-the-repository-pattern-with-cqrs-yes-and-no/)).\n\n---\n\nBy enforcing `Command` and `Query` separation, the code becomes simpler to understand. One changes something, another just retrieves data.\n\nAlso, following CQS from the start will facilitate separating write and read models into different databases if someday in the future the need for it arises.\n\n**Note**: this repo uses [NestJS CQRS](https://docs.nestjs.com/recipes/cqrs) package that provides a command/query bus.\n\nRead more about CQS and CQRS:\n\n- [Command Query Segregation](https://khalilstemmler.com/articles/oop-design-principles/command-query-segregation/).\n- [Exposing CQRS Through a RESTful API](https://www.infoq.com/articles/rest-api-on-cqrs/)\n- [What is the CQRS pattern?](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs)\n- [CQRS and REST: the perfect match](https://lostechies.com/jimmybogard/2016/06/01/cqrs-and-rest-the-perfect-match/)\n\n---\n\n## Ports\n\nPorts are interfaces that define contracts that should be implemented by adapters. For example, a port can abstract technology details (like what type of database is used to retrieve some data), and infrastructure layer can implement an adapter in order to execute some action more related to technology details rather than business logic. Ports act like [abstractions](<https://en.wikipedia.org/wiki/Abstraction_(computer_science)>) for technology details that business logic does not care about. Name \"port\" most actively is used in [Hexagonal Architecture](<https://en.wikipedia.org/wiki/Hexagonal_architecture_(software)>).\n\nIn Application Core **dependencies point inwards**. Outer layers can depend on inner layers, but inner layers never depend on outer layers. Application Core shouldn't depend on frameworks or access external resources directly. Any external calls to out-of-process resources/retrieval of data from remote processes should be done through `ports` (interfaces), with class implementations created somewhere in infrastructure layer and injected into application's core ([Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and [Dependency Inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle)). This makes business logic independent of technology, facilitates testing, allows to plug/unplug/swap any external resources easily making application modular and [loosely coupled](https://en.wikipedia.org/wiki/Loose_coupling).\n\n- Ports are basically just interfaces that define what has to be done and don't care about how it's done.\n- Ports can be created to abstract side effects like I/O operations and database access, technology details, invasive libraries, legacy code etc. from the Domain.\n- By abstracting side effects, you can test your application logic in isolation by [mocking](https://en.wikipedia.org/wiki/Mock_object) the implementation. This can be useful for [unit testing](https://en.wikipedia.org/wiki/Unit_testing).\n- Ports should be created to fit the Domain needs, not simply mimic the tools APIs.\n- Mock implementations can be passed to ports while testing. Mocking makes your tests faster and independent of the environment.\n- Abstraction provided by ports can be used to inject different implementations to a port if needed ([polymorphism](<https://en.wikipedia.org/wiki/Polymorphism_(computer_science)>)).\n- When designing ports, remember the [Interface segregation principle](https://en.wikipedia.org/wiki/Interface_segregation_principle). Split large interfaces into smaller ones when it makes sense, but also keep in mind to not overdo it when not necessary.\n- Ports can also help to delay decisions. The Domain layer can be implemented even before deciding what technologies (frameworks, databases etc.) will be used.\n\n**Note**: 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 the Domain Layer's business logic depends on executing some external resource, in such cases those ports can be put in a Domain Layer.\n\n**Note**: abusing ports/interfaces may lead to [unnecessary abstractions](https://mortoray.com/2014/08/01/the-false-abstraction-antipattern/) and overcomplicate your application. In a lot of cases it's totally fine to depend on a concrete implementation instead of abstracting it with an interface. Think carefully if you really need an abstraction before using it.\n\nExample files:\n\n- [repository.port.ts](src/libs/ddd/repository.port.ts) - generic port for repositories\n- [user.repository.port.ts](src/modules/user/database/user.repository.port.ts) - a port for user repository\n- [find-users.query-handler.ts](src/modules/user/queries/find-users/find-users.query-handler.ts) - notice how query handler depends on a port instead of concrete repository implementation, and an implementation is injected\n- [logger.port.ts](src/libs/ports/logger.port.ts) - another example of a port for application logger\n\nRead more:\n\n- [A Color Coded Guide to Ports and Adapters](https://8thlight.com/blog/damon-kelley/2021/05/18/a-color-coded-guide-to-ports-and-adapters.html)\n\n---\n\n# Domain Layer\n\nThis layer contains the application's business rules.\n\nDomain should operate using domain objects described by [ubiquitous language](https://martinfowler.com/bliki/UbiquitousLanguage.html). Most important domain building blocks are described below.\n\n- [Developing the ubiquitous language](https://medium.com/@felipefreitasbatista/developing-the-ubiquitous-language-1382b720bb8c)\n\n## Entities\n\nEntities 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.\n\nEntities 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.\n\nEntities must always protect their [invariant](https://en.wikipedia.org/wiki/Class_invariant):\n\n> 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.\n\nEntities:\n\n- Contain Domain business logic. Avoid having business logic in your services when possible, this leads to [Anemic Domain Model](https://martinfowler.com/bliki/AnemicDomainModel.html) (Domain Services are an exception for business logic that can't be put in a single entity).\n- Have an identity that defines it and makes it distinguishable from others. Its identity is consistent during its life cycle.\n- Equality between two entities is determined by comparing their identificators (usually its `id` field).\n- Can contain other objects, such as other entities or value objects.\n- Are responsible for collecting all the understanding of state and how it changes in the same place.\n- Responsible for the coordination of operations on the objects it owns.\n- Know nothing about upper layers (services, controllers etc.).\n- Domain entities data should be modelled to accommodate business logic, not some database schema.\n- 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 `validate()` method that checks if business rules are not violated by update).\n- Must be consistent on creation. Validate Entities and other domain objects on creation and throw an error on first failure. [Fail Fast](https://en.wikipedia.org/wiki/Fail-fast).\n- Avoid no-arg (empty) constructors, accept and validate all required properties in a constructor (or in a [factory method](https://en.wikipedia.org/wiki/Factory_method_pattern) like `create()`).\n- For optional properties that require some complex setting up, [Fluent interface](https://en.wikipedia.org/wiki/Fluent_interface) and [Builder Pattern](https://refactoring.guru/design-patterns/builder) can be used.\n- Make Entities partially immutable. Identify what properties shouldn't change after creation and make them `readonly` (for example `id` or `createdAt`).\n\n**Note**: A lot 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.\n\nExample files:\n\n- [user.entity.ts](src/modules/user/domain/user.entity.ts)\n- [wallet.entity.ts](src/modules/wallet/domain/wallet.entity.ts)\n\nRead more:\n\n- [Domain Entity pattern](https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/domain-entity-pattern.html)\n- [Secure by design: Chapter 6 Ensuring integrity of state](https://livebook.manning.com/book/secure-by-design/chapter-6/)\n\n---\n\n## Aggregates\n\n[Aggregate](https://martinfowler.com/bliki/DDD_Aggregate.html) 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.\n\n- Aggregates help to simplify the domain model by gathering multiple domain objects under a single abstraction.\n- Aggregates should not be influenced by the data model. Associations between domain objects are not the same as database relationships.\n- Aggregate root is an entity that contains other entities/value objects and all logic to operate them.\n- Aggregate root has global identity ([UUID / GUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) / primary key). Entities inside the aggregate boundary have local identities, unique only within the Aggregate.\n- Aggregate root is a gateway to entire aggregate. Any references from outside the aggregate should **only** go to the aggregate root.\n- Any operations on an aggregate must be [transactional operations](https://en.wikipedia.org/wiki/Database_transaction). Either everything gets saved/updated/deleted or nothing.\n- Only Aggregate Roots can be obtained directly with database queries. Everything else must be done through traversal.\n- Similar to `Entities`, 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. Simply said, all objects in an aggregate must be consistent, meaning that if one object inside an aggregate changes state, this shouldn't conflict with other domain objects inside this aggregate (this is called _Consistency Boundary_).\n- Objects within the Aggregate can reference other Aggregate roots via their globally unique identifier (id). Avoid holding a direct object reference.\n- Try to avoid aggregates that are too big, this can lead to performance and maintaining problems.\n- Aggregates can publish `Domain Events` (more on that below).\n\nAll of these 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.\n\nIn summary, if you combine multiple related entities and value objects inside one root `Entity`, this root `Entity` becomes an `Aggregate Root`, and this cluster of related entities and value objects becomes an `Aggregate`.\n\nExample files:\n\n- [aggregate-root.base.ts](src/libs/ddd/aggregate-root.base.ts) - abstract base class.\n- [user.entity.ts](src/modules/user/domain/user.entity.ts) - aggregates are just entities that have to follow a set of specific rules described above.\n\nRead more:\n\n- [Understanding Aggregates in Domain-Driven Design](https://dzone.com/articles/domain-driven-design-aggregate)\n- [What Are Aggregates In Domain-Driven Design?](https://www.jamesmichaelhickey.com/domain-driven-design-aggregates/) <- this is a series of multiple articles, don't forget to click \"Next article\" at the end.\n- [Effective Aggregate Design Part I: Modeling a Single Aggregate](https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf)\n- [Effective Aggregate Design Part II: Making Aggregates Work Together](https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_2.pdf)\n\n---\n\n## Domain Events\n\nDomain Event indicates that something happened in a domain that you want other parts of the same domain (in-process) to be aware of. Domain events are just messages pushed to an in-memory Domain Event dispatcher.\n\nFor example, if a user buys something, you may want to:\n\n- Update his shopping cart;\n- Withdraw money from his wallet;\n- Create a new shipping order;\n- Perform other domain operations that are not a concern of an aggregate that executes a \"buy\" command.\n\nThe typical approach involves executing all this logic in a service that performs a \"buy\" operation. However, this creates coupling between different subdomains.\n\nAn alternative approach would be publishing a `Domain Event`. If executing a command related to one aggregate instance requires additional domain rules to be run on one or more additional aggregates, you can design and implement those side effects to be triggered by Domain Events. Propagation of state changes across multiple aggregates within the same domain model can be performed by subscribing to a concrete `Domain Event` and creating as many event handlers as needed. This prevents coupling between aggregates.\n\nDomain Events may be useful for creating an [audit log](https://en.wikipedia.org/wiki/Audit_trail) to track all changes to important entities by saving each event to the database. Read more on why audit logs may be useful: [Why soft deletes are evil and what to do instead](https://jameshalsall.co.uk/posts/why-soft-deletes-are-evil-and-what-to-do-instead).\n\nAll changes caused by Domain Events across multiple aggregates in a single process can be saved in a single database [transaction](https://en.wikipedia.org/wiki/Database_transaction). This approach ensures consistency and integrity of your data. Wrapping an entire flow in a transaction or using patterns like [Unit of Work](https://java-design-patterns.com/patterns/unit-of-work/) or similar can help with that.\n**Keep in mind** that abusing transactions can create bottlenecks when multiple users try to modify single record concurrently. Use it only when you can afford it, otherwise go for other approaches (like [eventual consistency](https://en.wikipedia.org/wiki/Eventual_consistency)).\n\nThere are multiple ways on implementing an event bus for Domain Events, for example by using ideas from patterns like [Mediator](https://refactoring.guru/design-patterns/mediator) or [Observer](https://refactoring.guru/design-patterns/observer).\n\nExamples:\n\n- [user-created.domain-event.ts](src/modules/user/domain/events/user-created.domain-event.ts) - simple object that holds data related to published event.\n- [create-wallet-when-user-is-created.domain-event-handler.ts](src/modules/wallet/application/event-handlers/create-wallet-when-user-is-created.domain-event-handler.ts) - this is an example of Domain Event Handler that executes some actions when a domain event is raised (in this case, when user is created it also creates a wallet for that user).\n- [sql-repository.base.ts](src/libs/db/sql-repository.base.ts) - repository publishes all domain events for execution when it persists changes to an aggregate.\n- [create-user.service.ts](src/modules/user/commands/create-user/create-user.service.ts) - in a service we execute a global transaction to make sure all the changes done by Domain Events across the application are stored atomically (all or nothing).\n\nTo have a better understanding on domain events and implementation read this:\n\n- [Domain Event pattern](https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/domain-event-pattern.html)\n- [Domain events: design and implementation](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation)\n\n**Additional notes**:\n\n- When using only events for complex workflows with a lot of steps, it will be hard to track everything that is happening across the application. One event may trigger another one, then another one, and so on. To track the entire workflow you'll have to go multiple places and search for an event handler for each step, which is hard to maintain. In this case, using a service/orchestrator/mediator might be a preferred approach compared to only using events since you will have an entire workflow in one place. This might create some coupling, but is easier to maintain. Don't rely on events only, pick the right tool for the job.\n\n- In some cases you will not be able to save all changes done by your events to multiple aggregates in a single transaction. For example, if you are using microservices that span transaction between multiple services, or [Event Sourcing pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) that has a single stream per aggregate. In this case saving events across multiple aggregates can be eventually consistent (for example by using [Sagas](https://microservices.io/patterns/data/saga.html) with compensating events or a [Process Manager](https://www.enterpriseintegrationpatterns.com/patterns/messaging/ProcessManager.html) or something similar).\n\n## Integration Events\n\nOut-of-process communications (calling microservices, external APIs) are called `Integration Events`. If sending a Domain Event to external process is needed then domain event handler should send an `Integration Event`.\n\nIntegration Events usually should be published only after all Domain Events finished executing and saving all changes to the database.\n\nTo handle integration events in microservices you may need an external message broker / event bus like [RabbitMQ](https://www.rabbitmq.com/) or [Kafka](https://kafka.apache.org/) together with patterns like [Transactional outbox](https://microservices.io/patterns/data/transactional-outbox.html), [Change Data Capture](https://en.wikipedia.org/wiki/Change_data_capture), [Sagas](https://microservices.io/patterns/data/saga.html) or a [Process Manager](https://www.enterpriseintegrationpatterns.com/patterns/messaging/ProcessManager.html) to maintain [eventual consistency](https://en.wikipedia.org/wiki/Eventual_consistency).\n\nRead more:\n\n- [Domain Events vs. Integration Events in Domain-Driven Design and microservices architectures](https://devblogs.microsoft.com/cesardelatorre/domain-events-vs-integration-events-in-domain-driven-design-and-microservices-architectures/)\n\nFor integration events in distributed systems here are some patterns that may be useful:\n\n- [Saga distributed transactions](https://docs.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga)\n- [Saga vs. Process Manager](https://blog.devarchive.net/2015/11/saga-vs-process-manager.html)\n- [The Outbox Pattern](https://www.kamilgrzybek.com/design/the-outbox-pattern/)\n- [Event Sourcing pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)\n\n---\n\n## Domain Services\n\nEric Evans, Domain-Driven Design:\n\n> 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\"\n\n- Domain Service is a specific type of domain layer class that is used to execute domain logic that relies on two or more `Entities`.\n- Domain Services are used when putting the logic on a particular `Entity` would break encapsulation and require the `Entity` to know about things it really shouldn't be concerned with.\n- Domain services are very granular, while application services are a facade purposed with providing an API.\n- 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.\n\n---\n\n## Value objects\n\nSome Attributes and behaviors can be moved out of the entity itself and put into `Value Objects`.\n\nValue Objects:\n\n- Have no identity. Equality is determined through structural property.\n- Are immutable.\n- Can be used as an attribute of `entities` and other `value objects`.\n- Explicitly defines and enforces important constraints (invariants).\n\nValue 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.\n\nImagine you have a `User` entity which needs to have an `address` 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 `country`, `street`, `postalCode` etc., so it can be modeled and treated as a `Value Object` with its own business logic.\n\n`Value object` isn’t just a data structure that holds values. It can also encapsulate logic associated with the concept it represents.\n\nExample files:\n\n- [address.value-object.ts](src/modules/user/domain/value-objects/address.value-object.ts)\n\nRead more about Value Objects:\n\n- [Martin Fowler blog](https://martinfowler.com/bliki/ValueObject.html)\n- [Value Objects to the rescue](https://medium.com/swlh/value-objects-to-the-rescue-28c563ad97c6).\n- [Value Object pattern](https://badia-kharroubi.gitbooks.io/microservices-architecture/content/patterns/tactical-patterns/value-object-pattern.html)\n\n## Domain Invariants\n\nDomain [invariants](<https://en.wikipedia.org/wiki/Invariant_(mathematics)#Invariants_in_computer_science>) are the policies and conditions that are always met for the Domain in particular context. Invariants determine what is possible or what is prohibited in the context.\n\nInvariants enforcement is the responsibility of domain objects (especially of the entities and aggregate roots).\n\nThere are a certain number of invariants for an object that should always be true. For example:\n\n- When sending money, amount must always be a positive integer, and there always must be a receiver credit card number in a correct format;\n- Client cannot purchase a product that is out of stock;\n- Client's wallet cannot have less than 0 balance;\n- etc.\n\nIf the business has some rules similar to described above, the domain object should not be able to exist without following those rules.\n\nBelow we will discuss some validation techniques for your domain objects.\n\nExample files:\n\n- [wallet.entity.ts](src/modules/wallet/domain/wallet.entity.ts) - notice `validate` method. This is a simplified example of enforcing a domain invariant.\n\nRead more:\n\n- [Design validations in the domain model layer](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-model-layer-validations)\n- [Why Domain Invariants are critical to build good software?](https://no-kill-switch.ghost.io/why-domain-invariants-are-critical-to-build-good-software/)\n\n### Replacing primitives with Value Objects\n\nMost of the code bases operate on primitive types – `strings`, `numbers` etc. In the Domain Model, this level of abstraction may be too low.\n\nSignificant business concepts can be expressed using specific types and classes. `Value Objects` can be used instead primitives to avoid [primitives obsession](https://refactoring.guru/smells/primitive-obsession).\nSo, for example, `email` of type `string`:\n\n```typescript\nconst email: string = 'john@gmail.com';\n```\n\ncould be represented as a `Value Object` instead:\n\n```typescript\nexport class Email extends ValueObject<string> {\n  constructor(value: string) {\n    super({ value });\n  }\n\n  get value(): string {\n    return this.props.value;\n  }\n}\n```\n\n```typescript\nconst email: Email = new Email('john@gmail.com');\n```\n\nNow the only way to make an `email` is to create a new instance of `Email` class first, this ensures it will be validated on creation and a wrong value won't get into `Entities`.\n\nAlso, 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.\n\nCreating 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.\n\nUsing `Value Objects` for primitive types is also called a `domain primitive`. The concept and naming are proposed in the book [\"Secure by Design\"](https://www.manning.com/books/secure-by-design).\n\nUsing `Value Objects` instead of primitives:\n\n- Makes code easier to understand by using ubiquitous language instead of just `string`.\n- Improves security by ensuring invariants of every property.\n- Encapsulates specific business rules associated with a value.\n\n`Value Object` can represent a typed value in domain (a _domain primitive_). 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 `Value Objects` first. This object only accepts values which make sense in its context.\n\nIf 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.\n\n> 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\n> 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\n> 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.\n\nQuote from: [Secure by design: Chapter 5.3 Standing on the shoulders of domain primitives](https://livebook.manning.com/book/secure-by-design/chapter-5/96)\n\nAlso, an alternative for creating an object may be a [type alias](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases) (ideally using [nominal types](https://betterprogramming.pub/nominal-typescript-eee36e9432d2)) just to give this primitive a semantic meaning.\n\n**Warning**: Don't include Value Objects in objects that can be sent to other processes, like dtos, events, database models etc. Serialize them to primitive types first.\n\n**Note**: In languages like TypeScript, creating value objects for single values/primitives adds some extra complexity and boilerplate code, since you need to access an underlying value by doing something like `email.value`. Also, it can have performance penalties due to creation of so many objects. This technique works best in languages like [Scala](https://www.scala-lang.org/) with its [value classes](https://docs.scala-lang.org/overviews/core/value-classes.html) that represents such classes as primitives at runtime, meaning that object `Email` will be represented as `String` at runtime.\n\n**Note**: if you are using nodejs, [Runtypes](https://www.npmjs.com/package/runtypes) is a nice library that you can use instead of creating your own value objects for primitives.\n\n**Note**: Some people say that _primitive obsession_ is a code smell, some people consider making a class/object for every primitive may be overengineering (unless you are using Scala with its value classes). For less complex and smaller projects it's definitely an overkill. For bigger projects, there are people who advocate for and against this approach. If you notice that creating a class for every primitive doesn't give you much benefit, 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: [From Primitive Obsession to Domain Modelling - Over-engineering?](https://blog.ploeh.dk/2015/01/19/from-primitive-obsession-to-domain-modelling/#7172fd9ca69c467e8123a20f43ea76c2).\n\nRecommended reading:\n\n- [Primitive Obsession — A Code Smell that Hurts People the Most](https://medium.com/the-sixt-india-blog/primitive-obsession-code-smell-that-hurt-people-the-most-5cbdd70496e9)\n- [Domain Primitives: what they are and how you can use them to make more secure software](https://freecontent.manning.com/domain-primitives-what-they-are-and-how-you-can-use-them-to-make-more-secure-software/)\n- [Value Objects Like a Pro](https://medium.com/@nicolopigna/value-objects-like-a-pro-f1bfc1548c72)\n- [\"Secure by Design\" Chapter 5: Domain Primitives](https://livebook.manning.com/book/secure-by-design/chapter-5/) (a full chapter of the article above)\n\n### Make illegal states unrepresentable\n\nUse Value Objects/Domain Primitives and Types ([Algebraic Data Types (ADT)](https://en.wikipedia.org/wiki/Algebraic_data_type)) to make illegal states impossible to represent in your program.\n\nSome people recommend using objects for every value:\n\nQuote from [John A De Goes](https://twitter.com/jdegoes):\n\n> 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.\n\nLet's distinguish two types of protection from illegal states: at **compile time** and at **runtime**.\n\n#### Validation at compile time\n\nTypes 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 compile time, so IDE will show type errors right away.\n\nThe 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 the IDE will show a type error:\n\n```typescript\nexport enum UserRoles {\n  admin = 'admin',\n  moderator = 'moderator',\n  guest = 'guest',\n}\n\nconst userRole: UserRoles = 'some string'; // <-- error\n```\n\nOr, for example, imagine that business logic requires to have contact info of a person by either having `email`, or `phone`, or both. Both `email` and `phone` could be represented as optional, for example:\n\n```typescript\ninterface ContactInfo {\n  email?: Email;\n  phone?: Phone;\n}\n```\n\nBut what happens if both are not provided by a programmer? Business rule violated. Illegal state allowed.\n\nSolution: this could be presented as a [union type](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types)\n\n```typescript\ntype ContactInfo = Email | Phone | [Email, Phone];\n```\n\nNow only either `Email`, or `Phone`, or both must be provided. If nothing is provided, the IDE will show a type error right away. Now business rule validation is moved from runtime to **compile time**, which makes the application more secure and gives a faster feedback when something is not used as intended.\n\nThis is called a _typestate pattern_.\n\n> The typestate pattern is an API design pattern that encodes information about an object’s run-time state in its compile-time type.\n\nRead more:\n\n- [Making illegal states unrepresentable](https://v5.chriskrycho.com/journal/making-illegal-states-unrepresentable-in-ts/)\n- [Typestates Would Have Saved the Roman Republic](https://blog.yoavlavi.com/state-machines-would-have-saved-the-roman-republic/)\n- [The Typestate Pattern](https://cliffle.com/blog/rust-typestate/)\n- [Make illegal states unrepresentable — but how? The Typestate Pattern in Erlang](https://erszcz.medium.com/make-illegal-states-unrepresentable-but-how-the-typestate-pattern-in-erlang-16b37b090d9d)\n\n#### Validation at runtime\n\nData 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.\n\nThings that can't be validated at compile time (like user input) are validated at runtime.\n\nFirst line of defense is validation of user input DTOs.\n\nSecond line of defense are Domain Objects. Entities and value objects have to protect their invariants. Having some validation rules here will protect their state from corruption. You can use techniques like [Design by contract](https://en.wikipedia.org/wiki/Design_by_contract) by defining preconditions in object constructors and checking postconditions and invariants before saving an object to the database.\n\nEnforcing self-validation of your domain objects will inform immediately when data is corrupted. Not validating domain objects allows them to be in an incorrect state, this leads to problems.\n\nBy combining compile and runtime validations, using objects instead of primitives, enforcing self-validation and invariants of your domain objects, using Design by contract, [Algebraic Data Types (ADT)](https://en.wikipedia.org/wiki/Algebraic_data_type) and typestate pattern, and other similar techniques, you can achieve an architecture where it's hard, or even impossible, to end up in illegal states, thus improving security and robustness of your application dramatically (at a cost of extra boilerplate code).\n\n**Recommended to read**:\n\n- [Backend Best Practices: Data Validation](https://github.com/Sairyss/backend-best-practices#data-validation)\n\n### Guarding vs validating\n\nYou may have noticed that we do validation in multiple places:\n\n1. First when user input is sent to our application. In our example we use DTO decorators: [create-user.request-dto.ts](src/modules/user/commands/create-user/create-user.request.dto.ts).\n2. Second time in domain objects, for example: [address.value-object.ts](src/modules/user/domain/value-objects/address.value-object.ts).\n\nSo, why are we validating things twice? Let's call a second validation \"_guarding_\", and distinguish between guarding and validating:\n\n- Guarding is a failsafe mechanism. Domain layer views it as invariants to comply with always-valid domain model.\n- Validation is a filtration mechanism. Outside layers view them as input validation rules.\n\n> This difference leads to different treatment of violations of these business rules. An invariant violation in the domain model is an exceptional situation and should be met with throwing an exception. On the other hand, there’s nothing exceptional in external input being incorrect.\n\nThe input coming from the outside world should be filtered out before passing it further to the domain model. It’s the first line of defense against data inconsistency. At this stage, any incorrect data is denied with corresponding error messages.\nOnce the filtration has confirmed that the incoming data is valid it's passed to a domain. When the data enters the always-valid domain boundary, it's assumed to be valid and any violation of this assumption means that you’ve introduced a bug.\nGuards help to reveal those bugs. They are the failsafe mechanism, the last line of defense that ensures data in the always-valid boundary is indeed valid. Guards comply with the [Fail Fast principle](https://enterprisecraftsmanship.com/posts/fail-fast-principle) by throwing runtime exceptions.\n\nDomain classes should always guard themselves against becoming invalid.\n\nFor preventing null/undefined values, empty objects and arrays, incorrect input length etc. a library of [guards](<https://en.wikipedia.org/wiki/Guard_(computer_science)>) can be created.\n\nExample file: [guard.ts](src/libs/guard.ts)\n\n**Keep in mind** that not all validations/guarding can be done in a single domain object, 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.\n\nRead more:\n\n- [Refactoring: Guard Clauses](https://medium.com/better-programming/refactoring-guard-clauses-2ceeaa1a9da)\n- [Always-Valid Domain Model](https://enterprisecraftsmanship.com/posts/always-valid-domain-model/)\n\n<details>\n<summary><b>Note</b>: Using validation library instead of custom guards</summary>\n\nInstead of using custom _guards_ you could use an external validation library, but it's not a good practice to tie domain to external libraries and is not usually recommended.\n\nAlthough 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 `Value Objects` 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 `Value Object` in case when old library is no longer maintained, contains critical bugs or is compromised by hackers etc.\n\nThough, it's fine to do full sanity checks using validation framework or library **outside** the domain (for example [class-validator](https://www.npmjs.com/package/class-validator) decorators in `DTOs`), and do only some basic checks (guarding) inside of domain objects (besides business rules), like checking for `null` or `undefined`, checking length, matching against simple regexp etc. to check if value makes sense and for extra security.\n\n<details>\n<summary>Note about using regexp</summary>\n\nBe careful with custom regexp validations for things like validating `email`, only use custom regexp for some very simple rules and, if possible, let validation library do its job on more difficult ones to avoid problems in case your regexp is not good enough.\n\nAlso, 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.\n\nFor example, value can be accepted as valid by a validation library, but `Value Object` may throw an error because custom regexp is not good enough (validating `email` 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 `email` must contain an `@`). Try finding and validating only patterns that won't cause conflicts.\n\n---\n\n</details>\n\nAlthough there are other strategies on how to do validation inside domain, like passing validation schema as a dependency when creating new `Value Object`, but this creates extra complexity.\n\nEither 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.\n\nFor some projects, especially smaller ones, it might be easier and more appropriate to just use validation library/framework.\n\n</details>\n\n## Domain Errors\n\nApplication's core and domain layers shouldn't throw HTTP exceptions or statuses since it shouldn't know in what context it's used, since it can be used by anything: HTTP controller, Microservice event handler, Command Line Interface etc. A better approach is to create custom error classes with appropriate error codes.\n\nExceptions are for exceptional situations. Complex domains usually have a lot of errors that are not exceptional, but a part of a business logic (like \"seat already booked, choose another one\"). Those errors may need special handling. In those cases returning explicit error types can be a better approach than throwing.\n\nReturning an error instead of throwing explicitly shows a type of each exception that a method can return so you can handle it accordingly. It can make an error handling and tracing easier.\n\nTo help with that you can create an [Algebraic Data Types (ADT)](https://en.wikipedia.org/wiki/Algebraic_data_type) for your errors and use some kind of Result object type with a Success or a Failure condition (a [monad](<https://en.wikipedia.org/wiki/Monad_(functional_programming)>) like [Either](https://typelevel.org/cats/datatypes/either.html) from functional languages similar to Haskell or Scala). Unlike throwing exceptions, this approach allows defining types (ADTs) for every error and will let you see and handle them explicitly instead of using `try/catch` and avoid throwing exceptions that are invisible at compile time. For example:\n\n```typescript\n// User errors:\nclass UserError extends Error {\n  /* ... */\n}\n\nclass UserAlreadyExistsError extends UserError {\n  /* ... */\n}\n\nclass IncorrectUserAddressError extends UserError {\n  /* ... */\n}\n\n// ... other user errors\n```\n\n```typescript\n// Sum type for user errors\ntype CreateUserError = UserAlreadyExistsError | IncorrectUserAddressError;\n\nfunction createUser(\n  command: CreateUserCommand,\n): Result<UserEntity, CreateUserError> {\n  // ^ explicitly showing what function returns\n  if (await userRepo.exists(command.email)) {\n    return Err(new UserAlreadyExistsError()); // <- returning an Error\n  }\n  if (!validate(command.address)) {\n    return Err(new IncorrectUserAddressError());\n  }\n  // else\n  const user = UserEntity.create(command);\n  await this.userRepo.save(user);\n  return Ok(user);\n}\n```\n\nThis approach gives us a fixed set of expected error types, so we can decide what to do with each:\n\n```typescript\n/* in HTTP context we want to convert each error to an \nerror with a corresponding HTTP status code: 409, 400 or 500 */\nconst result = await this.commandBus.execute(command);\nreturn match(result, {\n  Ok: (id: string) => new IdResponse(id),\n  Err: (error: Error) => {\n    if (error instanceof UserAlreadyExistsError)\n      throw new ConflictHttpException(error.message);\n    if (error instanceof IncorrectUserAddressError)\n      throw new BadRequestException(error.message);\n    throw error;\n  },\n});\n```\n\nThrowing makes errors invisible for the consumer of your functions/methods (until those errors happen at runtime, or until you dig deeply into the source code and find them). This means those errors are less likely to be handled properly.\n\nReturning errors instead of throwing them adds some extra boilerplate code, but can make your application robust and secure since errors are now explicitly documented and visible as return types. You decide what to do with each error: propagate it further, transform it, add extra metadata, or try to recover from it (for example, by retrying the operation).\n\n**Warning**: Some errors/exceptions are non-recoverable and should be thrown, not returned. If you return technical Exceptions (like connection failed, process out of memory, etc.), It may cause some security issues and goes against [Fail-fast](https://en.wikipedia.org/wiki/Fail-fast) principle. Instead of terminating a program flow immediately and logging the error, returning an exception continues program execution and allows it to run in an incorrect state, which may lead to more unexpected errors, so it's generally better to throw an Exception in those cases rather than returning it. Analyze if the error is \"likely recoverable\" or \"likely unrecoverable\". If an error is most likely a recoverable error, it's a great candidate for using it in a Result object. If an error is most likely unrecoverable, throw it.\n\nLibraries you can use:\n\n- [oxide.ts](https://www.npmjs.com/package/oxide.ts) - this is a nice npm package if you want to use a Result object\n- [@badrap/result](https://www.npmjs.com/package/@badrap/result) - alternative\n\nExample files:\n\n- [user.errors.ts](src/modules/user/domain/user.errors.ts) - user errors\n- [create-user.service.ts](src/modules/user/commands/create-user/create-user.service.ts) - notice how `Err(new UserAlreadyExistsError())` is returned instead of throwing it.\n- [create-user.http.controller.ts](src/modules/user/commands/create-user/create-user.http.controller.ts) - in a user http controller we match an error and decide what to do with it. If an error is `UserAlreadyExistsError` we throw a `Conflict Exception` which a user will receive as `409 - Conflict`. If an error is unknown we just throw it and our framework will return it to the user as `500 - Internal Server Error`.\n- [create-user.cli.controller.ts](src/modules/user/commands/create-user/create-user.cli.controller.ts) - in a CLI controller we don't care about returning a correct status code so we just `.unwrap()` a result, which will just throw in case of an error.\n- [exceptions](src/libs/exceptions) folder contains some generic app exceptions (not domain specific)\n\nRead more:\n\n- [Flexible Error Handling w/ the Result Class](https://khalilstemmler.com/articles/enterprise-typescript-nodejs/handling-errors-result-class/)\n- [Advanced error handling techniques](https://enterprisecraftsmanship.com/posts/advanced-error-handling-techniques/)\n- [\"Secure by Design\" Chapter 9.2: Handling failures without exceptions](https://livebook.manning.com/book/secure-by-design/chapter-9/51)\n- [\"Functional Programming in Scala\" Chapter 4. Handling errors without exceptions](https://livebook.manning.com/book/functional-programming-in-scala/chapter-4/)\n\n## Using libraries inside Application's core\n\nWhether to use libraries in application core 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 working with numbers).\n\nMain recommendations to keep in mind is that libraries imported in application's core **shouldn't** expose:\n\n- Functionality to access any out-of-process resources (http calls, database access etc);\n- Functionality not relevant to domain (frameworks, technology details like ORMs, Logger etc.).\n- Functionality that brings randomness (generating random IDs, timestamps etc.) since this makes tests unpredictable (though in TypeScript world it's not that big of a deal since this can be mocked by a test library without using DI);\n- If a library changes often or has a lot of dependencies of its own it most likely shouldn't be used in domain layer.\n\nTo use such libraries consider creating an `anti-corruption` layer by using [adapter](https://refactoring.guru/design-patterns/adapter) or [facade](https://refactoring.guru/design-patterns/facade) patterns.\n\nWe sometimes tolerate libraries in the center, but be careful with general purpose libraries that may scatter across many domain objects. It will be hard to replace those libraries if needed. Tying only one or just a few domain objects to some single-responsibility library should be fine. It's way easier to replace a specific library that is tied to one or few objects than a general purpose library that is everywhere.\n\nIn addition to different libraries there are Frameworks. Frameworks can be a real nuisance, because by definition they want to be in control, and it's hard to replace a Framework later when your entire application is glued to it. It's fine to use Frameworks in outside layers (like infrastructure), but keep your domain clean of them when possible. You should be able to extract your domain layer and build a new infrastructure around it using any other framework without breaking your business logic.\n\nNestJS does a good job, as it uses decorators which are not very intrusive, so you could use decorators like `@Inject()` without affecting your business logic at all, and it's relatively easy to remove or replace it when needed. Don't give up on frameworks completely, but keep them in boundaries and don't let them affect your business logic.\n\nOffload as much of irrelevant responsibilities as possible from the core, especially from domain layer. In addition, try to minimize usage of dependencies in general. More dependencies your software has means more potential errors and security holes. One technique for making software more robust is to minimize what your software depends on - the less that can go wrong, the less will go wrong. On the other hand, removing all dependencies would be counterproductive as replicating that functionality would require huge amount of work and would be less reliable than just using a popular, battle-tested library. Finding a good balance is important, this skill requires experience.\n\nRead more:\n\n- [Referencing external libs](https://khorikov.org/posts/2019-08-07-referencing-external-libs/).\n- [Anti-corruption Layer — An effective Shield](https://medium.com/@malotor/anticorruption-layer-a-effective-shield-caa4d5ba548c)\n\n---\n\n# Interface Adapters\n\nInterface 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/command handlers) 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.\n\nContains `Controllers` and `Request`/`Response` DTOs (can also contain `Views`, like backend-generated HTML templates, if required).\n\n## Controllers\n\n- Controller is a user-facing API that is used for parsing requests, triggering business logic and presenting the result back to the client.\n- One controller per use case is considered a good practice.\n- In [NestJS](https://docs.nestjs.com/) world controllers may be a good place to use [OpenAPI/Swagger decorators](https://docs.nestjs.com/openapi/operations) for documentation.\n\nOne controller per trigger type can be used to have a clearer separation. For example:\n\n- [create-user.http.controller.ts](src/modules/user/commands/create-user/create-user.http.controller.ts) for http requests ([NestJS Controllers](https://docs.nestjs.com/controllers)),\n- [create-user.cli.controller.ts](src/modules/user/commands/create-user/create-user.cli.controller.ts) for command line interface access ([NestJS Console](https://www.npmjs.com/package/nestjs-console))\n- [create-user.message.controller.ts](src/modules/user/commands/create-user/create-user.message.controller.ts) for external messages ([NestJS Microservices](https://docs.nestjs.com/microservices/basics)).\n- etc.\n\n### Resolvers\n\nIf you are using [GraphQL](https://graphql.org/) instead of controllers, you will use [Resolvers](https://docs.nestjs.com/graphql/resolvers).\n\nOne of the main benefits of a layered architecture is separation of concerns. As you can see, it doesn't matter if you use [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) or GraphQL, the only thing that changes is user-facing API layer (interface-adapters). All the application Core stays the same since it doesn't depend on technology you are using.\n\nExample files:\n\n- [create-user.graphql-resolver.ts](src/modules/user/commands/create-user/graphql-example/create-user.graphql-resolver.ts)\n\n---\n\n## DTOs\n\nData that comes from external applications should be represented by a special type of classes - Data Transfer Objects ([DTO](https://en.wikipedia.org/wiki/Data_transfer_object) for short).\nData Transfer Object is an object that carries data between processes. It defines a contract between your API and clients.\n\n### Request DTOs\n\nInput data sent by a user.\n\n- Using Request DTOs gives a contract that a client of your API has to follow to make a correct request.\n\nExamples:\n\n- [create-user.request.dto.ts](src/modules/user/commands/create-user/create-user.request.dto.ts)\n\n### Response DTOs\n\nOutput data returned to a user.\n\n- 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).\n\nExamples:\n\n- [user.response.dto.ts](src/modules/user/dtos/user.response.dto.ts)\n\n---\n\nDTO contracts protect your clients from internal data structure changes that may happen in your API. When internal data models change (like renaming variables or splitting tables), they can still be mapped to match a corresponding DTO to maintain compatibility for anyone using your API.\n\nWhen updating DTO interfaces, a new version of API can be created by prefixing an endpoint with a version number, for example: `v2/users`. This will make transition painless by preventing breaking compatibility for users that are slow to update their apps that uses your API.\n\nYou may have noticed that our [create-user.command.ts](src/modules/user/commands/create-user/create-user.command.ts) contains the same properties as [create-user.request.dto.ts](src/modules/user/commands/create-user/create-user.request.dto.ts).\nSo why do we need DTOs if we already have Command objects that carry properties? Shouldn't we just have one class to avoid duplication?\n\n> Because commands and DTOs are different things, they tackle different problems. Commands are serializable method calls - calls of the methods in the domain model. Whereas DTOs are the data contracts. The main reason to introduce this separate layer with data contracts is to provide backward compatibility for the clients of your API. Without the DTOs, the API will have breaking changes with every modification of the domain model.\n\nMore info on this subject here: [Are CQRS commands part of the domain model?](https://enterprisecraftsmanship.com/posts/cqrs-commands-part-domain-model/) (read \"_Commands vs DTOs_\" section).\n\n### Additional recommendations\n\n- DTOs should be data-oriented, not object-oriented. Its properties should be mostly primitives. We are not modeling anything here, just sending flat data around.\n- When returning a `Response` prefer _whitelisting_ properties over _blacklisting_. 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.\n- If you use the same DTOs in multiple apps (frontend and backend, or between microservices), you can keep them somewhere in a shared directory instead of module directory and create a git submodule or a separate package for sharing them.\n- `Request`/`Response` DTO classes may be a good place to use validation and sanitization decorators like [class-validator](https://www.npmjs.com/package/class-validator) and [class-sanitizer](https://www.npmjs.com/package/class-sanitizer) (make sure that all validation errors are gathered first and only then return them to the user, this is called [Notification pattern](https://martinfowler.com/eaaDev/Notification.html). Class-validator does this by default).\n- `Request`/`Response` DTO classes may also be a good place to use Swagger/OpenAPI library decorators that [NestJS provides](https://docs.nestjs.com/openapi/types-and-parameters).\n- If DTO decorators for validation/documentation are not used, DTO can be just an interface instead of a class.\n- Data can be transformed to DTO format using a separate mapper or right in the constructor of a DTO class.\n\n### Local DTOs\n\nAnother thing that can be seen in some projects is local DTOs. Some people prefer to never use domain objects (like entities) outside its domain (in `controllers`, for example) and return a plain DTO object instead. This project doesn't use this technique, to avoid extra complexity and boilerplate code like interfaces and data mapping.\n\n[Here](https://martinfowler.com/bliki/LocalDTO.html) are Martin Fowler's thoughts on local DTOs, in short (quote):\n\n> 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.\n\nThough you may want to introduce Local DTOs when you need to decouple modules properly. For example, when querying from one module to another you don't want to leak your entities between modules. In that case using a Local DTO may be justified.\n\n---\n\n# Infrastructure layer\n\nThe Infrastructure layer is responsible for encapsulating technology. You can find there the implementations of database repositories for storing/retrieving business entities, message brokers to emit messages/events, I/O services to access external resources, framework related code and any other code that represents a replaceable detail for the architecture.\n\nIt'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 to make changes or swap one component for another.\n\nInfrastructure layer can contain `Adapters`, database related files like `Repositories`, `ORM entities`/`Schemas`, framework related files etc.\n\n## Adapters\n\n- 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).\n- Adapters also can be used to interact with different domains inside single process to avoid coupling between those domains.\n- Adapters are essentially an implementation of ports. They are not supposed to be called directly in any point in code, only through ports(interfaces).\n- Adapters can be used as Anti-Corruption Layer (ACL) for legacy code.\n\nRead more on ACL: [Anti-Corruption Layer: How to Keep Legacy Support from Breaking New Systems](https://www.cloudbees.com/blog/anti-corruption-layer-how-keep-legacy-support-breaking-new-systems)\n\nAdapters should have:\n\n- a `port` somewhere in application/domain layer that it implements;\n- a mapper that maps data **from** and **to** domain (if it's needed);\n- a DTO/interface for received data;\n- a validator to make sure incoming data is not corrupted (validation can reside in DTO class using decorators, or it can be validated by `Value Objects`).\n\n## Repositories\n\nRepositories are abstractions over collections of entities that are living in a database.\nThey centralize common data access functionality and 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, in a file, or some other source.\n\nWe use repositories to decouple the infrastructure or technology used to access databases from the domain model layer.\n\nMartin Fowler describes a repository as follows:\n\n> A repository performs the tasks of an intermediary between the domain model layers and data mapping, acting similarly 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.\n\nThe data flow here looks something like this: repository receives a domain `Entity` from application service, maps it to database schema/ORM format, does required operations (saving/updating/retrieving etc), then maps it back to domain `Entity` format and returns it back to service.\n\nApplication's core usually is not allowed to depend on repositories directly, instead it depends on abstractions (ports/interfaces). This makes data retrieval technology-agnostic.\n\n**Note**: in theory, most publications out there recommend abstracting a database with interfaces. In practice, it's not always useful. Most of the projects out there never change database technology (or rewrite most of the code anyway if they do). Another downside is that if you abstract a database you are more likely not using its full potential. This project abstracts repositories with a generic port to make a practical example [repository.port.ts](src/libs/ddd/repository.port.ts), but this doesn't mean you should do that too. Think carefully before using abstractions. More info on this topic: [Should you Abstract the Database?](https://enterprisecraftsmanship.com/posts/should-you-abstract-database/)\n\nExample files:\n\nThis project contains abstract repository class that allows to make basic CRUD operations: [sql-repository.base.ts](src/libs/db/sql-repository.base.ts). This base class is then extended by a specific repository, and all specific operations that an entity may need are implemented in that specific repo: [user.repository.ts](src/modules/user/database/user.repository.ts).\n\nRead more:\n\n- [Design the infrastructure persistence layer](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design)\n- [Should you use the Repository Pattern? With CQRS, Yes and No!](https://codeopinion.com/should-you-use-the-repository-pattern-with-cqrs-yes-and-no/) - in a read model / query handlers it is not required to use a repository pattern.\n\n## Persistence models\n\nUsing a single entity for domain logic and database concerns leads to a database-centric architecture. In DDD world domain model and persistence model should be separated.\n\nSince domain `Entities` have their data modeled so that it best accommodates domain logic, it may be not in the best shape to save in a database. For that purpose `Persistence models` can be created that have a shape that is better represented in a particular database that is used. Domain layer should not know anything about persistence models, and it should not care.\n\nThere can be multiple models optimized for different purposes, for example:\n\n- Domain with its own models - `Entities`, `Aggregates` and `Value Objects`.\n- Persistence layer with its own models - ORM ([Object–relational mapping](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping)), schemas, read/write models if databases are separated into a read and write db ([CQRS](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation)) etc.\n\nOver time, when the amount of data grows, there may be a need to make some changes in the database like improving performance or data integrity by re-designing some tables or even changing the database entirely. Without an explicit separation between `Domain` and `Persistance` models any change to the database will lead to change in your domain `Entities` or `Aggregates`. For example, when performing a database [normalization](https://en.wikipedia.org/wiki/Database_normalization) data can spread across multiple tables rather than being in one table, or vice-versa for [denormalization](https://en.wikipedia.org/wiki/Denormalization). This may force a team to do a complete refactoring of a domain layer which may cause unexpected bugs and challenges. Separating Domain and Persistence models prevents that.\n\n**Note**: separating domain and persistence models may be overkill for smaller applications. It requires a lot of effort creating and maintaining boilerplate code like mappers and abstractions. Consider all pros and cons before making this decision.\n\nExample files:\n\n- [user.repository.ts](src/modules/user/database/user.repository.ts) <- notice `userSchema` and `UserModel` type that describe how user looks in a database\n- [user.mapper.ts](src/modules/user/user.mapper.ts) <- Persistence models should also have a corresponding mapper to map from domain to persistence and back.\n\nFor smaller projects you could use [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) libraries like [Typeorm](https://typeorm.io/) for simplicity. But for projects with more complexity ORMs are not flexible and performant enough. For this reason, this project uses raw queries with a [Slonik](https://github.com/gajus/slonik) client library.\n\nRead more:\n\n- [Stack Overflow question: DDD - Persistence Model and Domain Model](https://stackoverflow.com/questions/14024912/ddd-persistence-model-and-domain-model)\n- [Just Stop It! The Domain Model Is Not The Persistence Model](https://blog.sapiensworks.com/post/2012/04/07/Just-Stop-It!-The-Domain-Model-Is-Not-The-Persistence-Model.aspx)\n- [Comparing SQL, query builders, and ORMs](https://www.prisma.io/dataguide/types/relational/comparing-sql-query-builders-and-orms)\n- [Secure by Design: Chapter 6.2.2 ORM frameworks and no-arg constructors](https://livebook.manning.com/book/secure-by-design/chapter-6/40)\n\n## Other things that can be a part of Infrastructure layer\n\n- Framework related files;\n- Application logger implementation;\n- Infrastructure related events ([Nest-event](https://www.npmjs.com/package/nest-event))\n- Periodic cron jobs or tasks launchers ([NestJS Schedule](https://docs.nestjs.com/techniques/task-scheduling));\n- Other technology related files.\n\n---\n\n# Other recommendations\n\n## General recommendations on architectures, best practices, design patterns and principles\n\nDifferent projects most likely will have different requirements. Some principles/patterns in such projects can be implemented in a simplified form, some can be skipped. Follow [YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it) principle and don't overengineer.\n\nSometimes complex architecture and principles like [SOLID](https://en.wikipedia.org/wiki/SOLID) can be incompatible with [YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it) and [KISS](https://en.wikipedia.org/wiki/KISS_principle). A good programmer should be pragmatic and has to be able to combine his skills and knowledge with a common sense to choose the best solution for the problem.\n\n> You need some experience with object-oriented software development in real world projects before they are of any use to you. Furthermore, they don’t tell you when you have found a good solution and when you went too far. Going too far means that you are outside the “scope” of a principle and the expected advantages don’t appear.\n> Principles, Heuristics, ‘laws of engineering’ are like hint signs, they are helpful when you know where they are pointing to and you know when you have gone too far. Applying them requires experience, that is trying things out, failing, analyzing, talking to people, failing again, fixing, learning and failing some more. There is no shortcut as far as I know.\n\n**Before implementing any pattern always analyze if benefit given by using it worth extra code complexity**.\n\n> Effective design argues that we need to know the price of a pattern is worth paying - that's its own skill.\n\nDon't blindly follow practices, patterns and architectures just because books and articles say so. Sometimes rewriting a software from scratch is the best solution, and all your efforts to fit in all the patterns and architectural styles you know into the project will be a waste of time. Try to evaluate the cost and benefit of every pattern you implement and avoid overengineering. Remember that architectures, patterns and principles are your tools that may be useful in certain situations, not dogmas that you have to follow blindly.\n\nHowever, remember:\n\n> It's easier to refactor over-design than it's to refactor no design.\n\nRead more:\n\n- [Which Software Architecture should you pick?](https://youtu.be/8B445kqSKwg)\n- [SOLID Principles and the Arts of Finding the Beach](https://sebastiankuebeck.wordpress.com/2017/09/17/solid-principles-and-the-arts-of-finding-the-beach/)\n- [Martin Fowler blog: Yagni](https://martinfowler.com/bliki/Yagni.html)\n- [7 Software Development Principles That Should Be Embraced Daily](https://betterprogramming.pub/7-software-development-principles-that-should-be-embraced-daily-c26a94ec4ecc?gi=3b5b298ddc23)\n\n## Recommendations for smaller APIs\n\nBe careful when implementing any complex architecture in small-medium sized projects with not a lot of business logic. Some building blocks/patterns/principles may fit well, but others may be an overengineering.\n\nFor example:\n\n- 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.\n- But practices like creating an object for every primitive, using `Value Objects` to separate business logic into smaller classes, separating `Domain Models` from `Persistence Models` 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, maintenance overheads etc. without adding much benefit.\n\n[DDD](https://en.wikipedia.org/wiki/Domain-driven_design) and other practices described here are mostly about creating software with complex business logic. But what would be a better approach for simpler applications?\n\nFor applications with not a lot of business logic, where code mostly exists as a glue between database and a client, consider other architectures. The most popular is probably [MVC](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller). _Model-View-Controller_ is better suited for [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) applications with little business logic since it tends to favor designs where software is mostly the view of the database.\n\nAdditional resources:\n\n- [Do you have enough Complexity for a Domain Model (Domain Driven Design)?](https://youtu.be/L1foFiqopIc)\n\n## Behavioral Testing\n\nBehavioral Testing (and also [BDD](https://en.wikipedia.org/wiki/Behavior-driven_development)) is a testing of the external behavior of the program, also known as black box testing.\n\nDomain-Driven Design with its ubiquitous language plays nicely with Behavioral tests.\n\nFor BDD tests [Cucumber](https://cucumber.io/) with [Gherkin](https://cucumber.io/docs/gherkin/reference/) syntax can give a structure and meaning to your tests. This way even people not involved in a development can define steps needed for testing. In node.js world [cucumber](https://www.npmjs.com/package/@cucumber/cucumber) or [jest-cucumber](https://www.npmjs.com/package/jest-cucumber) are nice packages to achieve that.\n\nExample files:\n\n- [create-user.feature](tests/user/create-user/create-user.feature) - feature file that contains human-readable Gherkin steps\n- [create-user.e2e-spec.ts](tests/user/create-user/create-user.e2e-spec.ts) - e2e / behavioral test\n\nRead more:\n\n- [Backend best practices - Testing](https://github.com/Sairyss/backend-best-practices#testing)\n\n## Folder and File Structure\n\nSome typical approaches are:\n\n- **Layered architecture**: split an entire application into directories divided by functionality, like `controllers`, `services`, `repositories`, etc. For example:\n\n```text\n- Controllers\n  - UserController\n  - WalletController\n  - OtherControllers...\n- Services\n  - UserService\n  - WalletService\n  - OtherServices...\n- Repositories\n  - ...\n```\n\nThis approach makes navigation harder. Every time you need to change some feature, instead of having all related files in the same place (in a module), you have to jump multiple directories to find all related files. This approach usually leads to tight coupling and spaghetti code.\n\n- **Divide application by modules** and split each module by some business domain:\n\n```text\n- User\n  - UserController\n  - UserService\n  - UserRepository\n- Wallet\n  - WalletController\n  - WalletService\n  - WalletRepository\n  ...\n```\n\nThis looks better. With this approach each module is encapsulated and only contains its own business logic. The only downside is: over time those controllers and services can end up hundreds of lines long, making it difficult to navigate and merge conflicts harder to manage.\n\n- **Divide a module by subcomponents:** use modular approach discussed above and divide each module by slices and use cases. We divide a module further into smaller components:\n\n```text\n- User\n  - CreateUser\n    - CreateUserController\n    - CreateUserService\n    - CreateUserDTO\n  - UpdateUser\n    - UpdateUserController\n    - UpdateUserService\n    - UpdateUserDTO\n  - UserRepository\n  - UserEntity\n- Wallet\n  - CreateWallet\n    - CreateWalletController\n    - CreateWalletService\n    - CreateWalletDto\n  ...\n```\n\nThis way each module is further split into highly cohesive subcomponents (by feature). Now when you open the project, instead of just seeing directories like `controllers`, `services`, `repositories`, etc. you can see right away what features application has from just reading directory names.\n\nThis approach makes navigation and maintaining easier since all related files are close to each other. It also makes every feature properly encapsulated and gives you an ability to make localized decisions per component, based on each particular feature's needs.\n\nShared files like domain objects (entities/aggregates), repositories, shared DTOs, interfaces, etc. can be stored outside of feature directory since they are usually reused by multiple subcomponents.\n\nThis is called [The Common Closure Principle (CCP)](https://ericbackhage.net/clean-code/the-common-closure-principle/). Folder/file structure in this project uses this principle. Related files that usually change together (and are not used by anything else outside that component) are stored close together.\n\n> The aim here should be to be strategic and place classes that we, from experience, know often changes together into the same component.\n\nKeep in mind that this project's folder/file structure is an example and might not work for everyone. The main recommendations here are:\n\n- Separate your application into modules;\n- Keep files that change together close to each other (_Common Closure Principle_ and _Vertical Slicing_);\n- Group files by their behavior that changes together, not by a type of functionality that file provides;\n- Keep files that are reused by multiple components apart;\n- Respect boundaries in your code, keeping files together doesn't mean inner layers can import outer layers;\n- Try to avoid a lot of nested folders;\n- [Move files around until it feels right](https://dev.to/dance2die/move-files-around-until-it-feels-right-2lek).\n\nThere are different approaches to file/folder structuring, choose what suits better for the project/personal preference.\n\nExamples:\n\n- [user](src/modules/user) module.\n- [create-user](src/modules/user/commands/create-user) subcomponent.\n\n- [Commands](src/modules/user/commands) directory contains all state changing use cases and each use case inside it contains most of the things that it needs: controller, service, DTOs, command, etc.\n- [Queries](src/modules/user/queries) directory is structured in the same way as commands but contains data retrieval use cases.\n\nRead more:\n\n- [Out with the Onion, in with Vertical Slices](https://medium.com/@jacobcunningham/out-with-the-onion-in-with-vertical-slices-c3edfdafe118)\n- [[YouTube] Tired of Layers? Vertical Slice Architecture to the rescue!](https://youtu.be/lsddiYwWaOQ)\n- [Vertical Slice Architecture](https://jimmybogard.com/vertical-slice-architecture/)\n- [Why I don’t like layered architecture for microservices](https://garywoodfine.com/why-i-dont-like-layered-architecture-for-microservices/) - this explains more in details what disadvantages a typical horizontal Layered Architecture have compared to Modular / Vertical Slice architectures.\n\n### File names\n\nConsider giving a descriptive type names to files after a dot \"`.`\", like `*.service.ts` or `*.entity.ts`. This makes it easier to differentiate what files do what and makes it easier to find those files using [fuzzy search](https://en.wikipedia.org/wiki/Approximate_string_matching) (`CTRL+P` for Windows/Linux and `⌘+P` for MacOS in VSCode to try it out).\n\nAlternatively you could use class names as file names, but consider adding descriptive suffixes like `Service` or `Controller`, etc.\n\nRead more:\n\n- [Angular Style Guides: Separate file names with dots and dashes](https://angular.io/guide/styleguide#separate-file-names-with-dots-and-dashes).\n\n## Enforcing architecture\n\nTo make sure everyone in the team adheres to defined architectural practices, use tools and libraries that can analyze and validate dependencies between files and layers.\n\nFor example:\n\n```typescript\n  // Dependency cruiser example\n  {\n    name: 'no-domain-deps',\n    comment: 'Domain layer cannot depend on api or database layers',\n    severity: 'error',\n    from: { path: ['domain', 'entity', 'aggregate', 'value-object'] },\n    to: { path: ['api', 'controller', 'dtos', 'database', 'repository'] },\n  },\n```\n\nSnippet of code above will prevent your domain layer to depend on the API layer or database layer. Example config: [.dependency-cruiser.js](.dependency-cruiser.js)\n\nYou can also generate graphs like this:\n\n<details>\n<summary>Click to see dependency graph</summary>\n <img src=\"assets/dependency-graph.svg\" alt=\"Dependency graph\">\n</details>\n<br>\n\nExample tools:\n\n- [Dependency cruiser](https://github.com/sverweij/dependency-cruiser) - Validate and visualize dependencies for JavaScript / TypeScript.\n- [ArchUnit](https://www.archunit.org/) - library for checking the architecture of Java applications\n\nRead more:\n\n- [Validate Dependencies According to Clean Architecture](https://betterprogramming.pub/validate-dependencies-according-to-clean-architecture-743077ea084c)\n- [Clean Architecture Boundaries with Spring Boot and ArchUnit](https://reflectoring.io/java-components-clean-boundaries/)\n\n## Prevent massive inheritance chains\n\nClasses that can be extended should be designed for extensibility and usually should be `abstract`. If class is not designed to be extended, prevent extending it by making class `final`. Don't create inheritance more than 1-2 levels deep since this makes refactoring harder and leads to a bad design. You can use [composition](https://en.wikipedia.org/wiki/Composition_over_inheritance) instead.\n\n**Note**: in TypeScript, unlike other languages, there is no default way to make class `final`. But there is a way around it using a custom decorator.\n\nExample file: [final.decorator.ts](src/libs/decorators/final.decorator.ts)\n\nRead more:\n\n- [When to declare classes final](https://ocramius.github.io/blog/when-to-declare-classes-final/)\n- [Final classes by default, why?](https://matthiasnoback.nl/2018/09/final-classes-by-default-why/)\n- [Prefer Composition Over Inheritance](https://medium.com/better-programming/prefer-composition-over-inheritance-1602d5149ea1)\n\n---\n\n# Additional resources\n\n- [Backend best practices](https://github.com/Sairyss/backend-best-practices) - more best practices that are used here\n- [System Design Patterns](https://github.com/Sairyss/system-design-patterns) - learn system design\n\n## Articles\n\n- [DDD, Hexagonal, Onion, Clean, CQRS, … How I put it all together](https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together)\n- [Hexagonal Architecture](https://www.qwan.eu/2020/08/20/hexagonal-architecture.html)\n- [Hexagonal (Ports and Adapters) Architecture](https://medium.com/idealo-tech-blog/hexagonal-ports-adapters-architecture-e3617bcf00a0)\n- [Clean architecture series](https://medium.com/@pereiren/clean-architecture-series-part-1-f34ef6b04b62)\n- [Clean architecture for the rest of us](https://pusher.com/tutorials/clean-architecture-introduction)\n- [An illustrated guide to 12 Factor Apps](https://www.redhat.com/architect/12-factor-app)\n\n## Websites\n\n- [The Twelve-Factor App](https://12factor.net/)\n- [Refactoring guru - Catalog of Design Patterns](https://refactoring.guru/design-patterns/catalog)\n\n## Blogs\n\n- [Vladimir Khorikov](https://enterprisecraftsmanship.com/)\n- [Derek Comartin](https://codeopinion.com/)\n- [Kamil Grzybek](https://www.kamilgrzybek.com/)\n- [Martin Fowler](https://martinfowler.com/)\n- [Khalil Stemmler](https://khalilstemmler.com)\n- [Herberto Graca](https://herbertograca.com/)\n\n## Videos\n\n- [More Testable Code with the Hexagonal Architecture](https://youtu.be/ujb_O6myknY)\n- [Playlist: Design Patterns Video Tutorial](https://youtube.com/playlist?list=PLF206E906175C7E07)\n- [Playlist: Design Patterns in Object Oriented Programming](https://youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc)\n- [Herberto Graca - Making architecture explicit](https://www.youtube.com/watch?v=_yoZN9Sb3PM&feature=youtu.be)\n\n## Books\n\n- [\"Domain-Driven Design: Tackling Complexity in the Heart of Software\"](https://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215) by Eric Evans\n- [\"Secure by Design\"](https://www.manning.com/books/secure-by-design) by Dan Bergh Johnsson, Daniel Deogun, Daniel Sawano\n- [\"Implementing Domain-Driven Design\"](https://www.amazon.com/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577) by Vaughn Vernon\n- [\"Clean Architecture: A Craftsman's Guide to Software Structure and Design\"](https://www.amazon.com/Clean-Architecture-Craftsmans-Software-Structure/dp/0134494164/ref=sr_1_1?dchild=1&keywords=clean+architecture&qid=1605343702&s=books&sr=1-1) by Robert Martin\n"
  },
  {
    "path": "database/getMigrator.ts",
    "content": "/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport { SlonikMigrator } from '@slonik/migrator';\nimport { createPool } from 'slonik';\nimport * as dotenv from 'dotenv';\nimport * as path from 'path';\n\n// use .env or .env.test depending on NODE_ENV variable\nconst envPath = path.resolve(\n  __dirname,\n  process.env.NODE_ENV === 'test' ? '../.env.test' : '../.env',\n);\ndotenv.config({ path: envPath });\n\nexport async function getMigrator() {\n  const pool = await createPool(\n    `postgres://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}/${process.env.DB_NAME}`,\n  );\n\n  const migrator = new SlonikMigrator({\n    migrationsPath: path.resolve(__dirname, 'migrations'),\n    migrationTableName: 'migration',\n    slonik: pool,\n  } as any);\n\n  return { pool, migrator };\n}\n"
  },
  {
    "path": "database/migrate.ts",
    "content": "/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nimport { getMigrator } from './getMigrator';\n\nexport async function run() {\n  const { migrator } = await getMigrator();\n  migrator.runAsCLI();\n  console.log('Done');\n}\n\nrun();\n"
  },
  {
    "path": "database/migrations/2022.10.07T13.49.19.users.sql",
    "content": "CREATE TABLE \"users\" (\n  \"id\" character varying NOT NULL,\n  \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),\n  \"updatedAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),\n  \"email\" character varying NOT NULL,\n  \"country\" character varying NOT NULL,\n  \"postalCode\" character varying NOT NULL,\n  \"street\" character varying NOT NULL,\n  \"role\" character varying NOT NULL,\n  CONSTRAINT \"UQ_e12875dfb3b1d92d7d7c5377e22\" UNIQUE (\"email\"),\n  CONSTRAINT \"PK_cace4a159ff9f2512dd42373760\" PRIMARY KEY (\"id\")\n)"
  },
  {
    "path": "database/migrations/2022.10.07T13.49.54.wallets.sql",
    "content": "CREATE TABLE \"wallets\" (\n  \"id\" character varying NOT NULL,\n  \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),\n  \"updatedAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),\n  \"balance\" integer NOT NULL DEFAULT '0',\n  \"userId\" character varying NOT NULL,\n  CONSTRAINT \"UQ_35472b1fe48b6330cd349709564\" UNIQUE (\"userId\"),\n  CONSTRAINT \"PK_bec464dd8d54c39c54fd32e2334\" PRIMARY KEY (\"id\")\n)"
  },
  {
    "path": "database/migrations/down/2022.10.07T13.49.19.users.sql",
    "content": "DROP TABLE \"users\""
  },
  {
    "path": "database/migrations/down/2022.10.07T13.49.54.wallets.sql",
    "content": "DROP TABLE \"wallets\""
  },
  {
    "path": "database/seed.ts",
    "content": "/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nimport { getMigrator } from './getMigrator';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n// Utility function to run a migration\nexport const seed = async (query, file) => {\n  console.log(`executing migration: ${file} ...`);\n  const { pool, migrator } = await getMigrator();\n  await migrator.up();\n  await pool.query(query);\n  console.log(`${file} migration executed`);\n};\n\nconst directoryPath = path.join(__dirname, 'seeds');\nasync function runAll() {\n  fs.readdir(directoryPath, async function (err, files) {\n    if (err) {\n      return console.log('Unable to scan directory: ' + err);\n    }\n    for (const file of files) {\n      const data = fs.readFileSync(path.resolve(directoryPath, file), {\n        encoding: 'utf8',\n        flag: 'r',\n      });\n      await seed({ sql: data, values: [], type: 'SLONIK_TOKEN_SQL' }, file);\n    }\n    console.log('done');\n    process.exit(0);\n  });\n}\n\nrunAll();\n"
  },
  {
    "path": "database/seeds/users.seed.sql",
    "content": "INSERT INTO\n  users (\n    id,\n    \"createdAt\",\n    \"updatedAt\",\n    email,\n    country,\n    \"postalCode\",\n    street,\n    \"role\"\n  )\nVALUES\n  (\n    'f59d0748-d455-4465-b0a8-8d8260b1c877',\n    now(),\n    now(),\n    'john@gmail.com',\n    'England',\n    '24312',\n    'Road Avenue',\n    'guest'\n  );"
  },
  {
    "path": "database/seeds/wallets.seed.sql",
    "content": "INSERT INTO\n  wallets (id, \"createdAt\", \"updatedAt\", balance, \"userId\")\nVALUES\n  (\n    gen_random_uuid(),\n    now(),\n    now(),\n    0,\n    'f59d0748-d455-4465-b0a8-8d8260b1c877'\n  );"
  },
  {
    "path": "docker/docker-compose.yml",
    "content": "version: '3.9'\n\nservices:\n  postgres:\n    container_name: postgres-container\n    image: postgres:alpine\n    ports:\n      - 5432:5432\n    environment:\n      POSTGRES_USER: 'user'\n      POSTGRES_PASSWORD: 'password'\n      POSTGRES_DB: 'ddh'\n    volumes:\n      - ddh-postgres:/var/lib/postgresql/data\n    networks:\n      - postgres\n\n  pgadmin:\n    container_name: pgadmin_container\n    image: dpage/pgadmin4\n    environment:\n      PGADMIN_DEFAULT_EMAIL: admin@email.com\n      PGADMIN_DEFAULT_PASSWORD: admin\n    ports:\n      - 5050:80\n    networks:\n      - postgres\n\nnetworks:\n  postgres:\n    driver: bridge\n\nvolumes:\n  ddh-postgres:"
  },
  {
    "path": "jest-e2e.json",
    "content": "{\n  \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n  \"rootDir\": \".\",\n  \"testEnvironment\": \"node\",\n  \"coverageDirectory\": \"./coverage\",\n  \"setupFilesAfterEnv\": [\"./tests/setup/jestSetupAfterEnv.ts\"],\n  \"globalSetup\": \"<rootDir>/tests/setup/jestGlobalSetup.ts\",\n  \"testRegex\": \".e2e-spec.ts$\",\n  \"moduleNameMapper\": {\n    \"@src/(.*)$\": \"<rootDir>/src/$1\",\n    \"@modules/(.*)$\": \"<rootDir>/src/modules/$1\",\n    \"@config/(.*)$\": \"<rootDir>/src/configs/$1\",\n    \"@libs/(.*)$\": \"<rootDir>/src/libs/$1\",\n    \"@exceptions$\": \"<rootDir>/src/libs/exceptions\",\n    \"@tests/(.*)$\": \"<rootDir>/tests/$1\"\n  },\n  \"transform\": {\n    \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n  }\n}\n"
  },
  {
    "path": "nest-cli.json",
    "content": "{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\"\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"domain-driven-hexagon\",\n  \"version\": \"2.0.0\",\n  \"description\": \"\",\n  \"author\": \"\",\n  \"private\": true,\n  \"license\": \"UNLICENSED\",\n  \"scripts\": {\n    \"prebuild\": \"rimraf dist\",\n    \"build\": \"nest build\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\"\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:debug\": \"nest start --debug --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"lint\": \"eslint \\\"{src,apps,libs,tests}/**/*.ts\\\" --fix\",\n    \"test\": \"jest --config .jestrc.json\",\n    \"test:watch\": \"jest --watch\",\n    \"test:cov\": \"jest --coverage\",\n    \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n    \"test:e2e\": \"jest -i --config jest-e2e.json\",\n    \"docker:env\": \"docker-compose --file docker/docker-compose.yml up --build\",\n    \"migration:create\": \"ts-node database/migrate create --name\",\n    \"migration:up\": \"ts-node database/migrate up\",\n    \"migration:up:tests\": \"NODE_ENV=test ts-node database/migrate up\",\n    \"migration:down\": \"ts-node database/migrate down\",\n    \"migration:down:tests\": \"NODE_ENV=test ts-node database/migrate down\",\n    \"migration:executed\": \"ts-node database/migrate executed\",\n    \"migration:executed:tests\": \"NODE_ENV=test ts-node database/migrate executed\",\n    \"migration:pending\": \"ts-node database/migrate pending\",\n    \"migration:pending:tests\": \"NODE_ENV=test ts-node database/migrate pending\",\n    \"seed:up\": \"ts-node database/seed\",\n    \"depcruise\": \"depcruise\",\n    \"deps:validate\": \"depcruise src --config .dependency-cruiser.js --output-type err-long\",\n    \"deps:graph\": \"depcruise src --include-only \\\"^src\\\" --config --output-type dot | dot -T svg > assets/dependency-graph.svg\"\n  },\n  \"dependencies\": {\n    \"@nestjs/apollo\": \"^10.1.3\",\n    \"@nestjs/common\": \"^9.0.0\",\n    \"@nestjs/core\": \"^9.0.0\",\n    \"@nestjs/cqrs\": \"^9.0.1\",\n    \"@nestjs/event-emitter\": \"^1.3.1\",\n    \"@nestjs/graphql\": \"^10.1.2\",\n    \"@nestjs/microservices\": \"^9.1.2\",\n    \"@nestjs/platform-express\": \"^9.0.0\",\n    \"@nestjs/swagger\": \"^6.1.2\",\n    \"@slonik/migrator\": \"^0.11.3\",\n    \"apollo-server-core\": \"^3.10.2\",\n    \"apollo-server-express\": \"^3.10.2\",\n    \"class-transformer\": \"^0.5.1\",\n    \"class-validator\": \"^0.13.2\",\n    \"dotenv\": \"^16.0.2\",\n    \"env-var\": \"^7.3.0\",\n    \"graphql\": \"^16.6.0\",\n    \"jest-cucumber\": \"^3.0.1\",\n    \"nanoid\": \"^3.3.4\",\n    \"nestjs-console\": \"^8.0.0\",\n    \"nestjs-request-context\": \"^2.1.0\",\n    \"nestjs-slonik\": \"^9.0.0\",\n    \"oxide.ts\": \"^1.0.5\",\n    \"reflect-metadata\": \"^0.1.13\",\n    \"rimraf\": \"^3.0.2\",\n    \"rxjs\": \"^7.2.0\",\n    \"slonik\": \"^31.2.4\",\n    \"uuid\": \"^9.0.0\",\n    \"zod\": \"^3.21.4\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^9.0.0\",\n    \"@nestjs/schematics\": \"^9.0.0\",\n    \"@nestjs/testing\": \"^9.0.0\",\n    \"@types/express\": \"^4.17.13\",\n    \"@types/jest\": \"28.1.8\",\n    \"@types/node\": \"^16.0.0\",\n    \"@types/supertest\": \"^2.0.11\",\n    \"@types/uuid\": \"^8.3.4\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.0.0\",\n    \"@typescript-eslint/parser\": \"^5.0.0\",\n    \"dependency-cruiser\": \"^12.10.0\",\n    \"eslint\": \"^8.0.1\",\n    \"eslint-config-prettier\": \"^8.3.0\",\n    \"eslint-plugin-prettier\": \"^4.0.0\",\n    \"jest\": \"28.1.3\",\n    \"prettier\": \"^2.3.2\",\n    \"source-map-support\": \"^0.5.20\",\n    \"supertest\": \"^6.1.3\",\n    \"ts-jest\": \"28.0.8\",\n    \"ts-loader\": \"^9.2.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"tsconfig-paths\": \"4.1.0\",\n    \"typescript\": \"^4.7.4\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\n      \"js\",\n      \"json\",\n      \"ts\"\n    ],\n    \"rootDir\": \"src\",\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": {\n      \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n    },\n    \"collectCoverageFrom\": [\n      \"**/*.(t|j)s\"\n    ],\n    \"coverageDirectory\": \"../coverage\",\n    \"testEnvironment\": \"node\"\n  },\n  \"volta\": {\n    \"node\": \"20.1.0\"\n  }\n}\n"
  },
  {
    "path": "src/app.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { CqrsModule } from '@nestjs/cqrs';\nimport { SlonikModule } from 'nestjs-slonik';\nimport { EventEmitterModule } from '@nestjs/event-emitter';\nimport { UserModule } from '@modules/user/user.module';\nimport { WalletModule } from '@modules/wallet/wallet.module';\nimport { RequestContextModule } from 'nestjs-request-context';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { ContextInterceptor } from './libs/application/context/ContextInterceptor';\nimport { ExceptionInterceptor } from '@libs/application/interceptors/exception.interceptor';\nimport { postgresConnectionUri } from './configs/database.config';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\n\nconst interceptors = [\n  {\n    provide: APP_INTERCEPTOR,\n    useClass: ContextInterceptor,\n  },\n  {\n    provide: APP_INTERCEPTOR,\n    useClass: ExceptionInterceptor,\n  },\n];\n\n@Module({\n  imports: [\n    EventEmitterModule.forRoot(),\n    RequestContextModule,\n    SlonikModule.forRoot({\n      connectionUri: postgresConnectionUri,\n    }),\n    CqrsModule,\n    GraphQLModule.forRoot<ApolloDriverConfig>({\n      driver: ApolloDriver,\n      autoSchemaFile: true,\n    }),\n\n    // Modules\n    UserModule,\n    WalletModule,\n  ],\n  controllers: [],\n  providers: [...interceptors],\n})\nexport class AppModule {}\n"
  },
  {
    "path": "src/configs/app.routes.ts",
    "content": "/**\n * Application routes with its version\n * https://github.com/Sairyss/backend-best-practices#api-versioning\n */\n\n// Root\nconst usersRoot = 'users';\nconst walletsRoot = 'wallets';\n\n// Api Versions\nconst v1 = 'v1';\n\nexport const routesV1 = {\n  version: v1,\n  user: {\n    root: usersRoot,\n    delete: `/${usersRoot}/:id`,\n  },\n  wallet: {\n    root: walletsRoot,\n    delete: `/${walletsRoot}/:id`,\n  },\n};\n"
  },
  {
    "path": "src/configs/database.config.ts",
    "content": "import { get } from 'env-var';\nimport '../libs/utils/dotenv';\n\n// https://github.com/Sairyss/backend-best-practices#configuration\n\nexport const databaseConfig = {\n  type: 'postgres',\n  host: get('DB_HOST').required().asString(),\n  port: get('DB_PORT').required().asIntPositive(),\n  username: get('DB_USERNAME').required().asString(),\n  password: get('DB_PASSWORD').required().asString(),\n  database: get('DB_NAME').required().asString(),\n};\n\nexport const postgresConnectionUri = `postgres://${databaseConfig.username}:${databaseConfig.password}@${databaseConfig.host}/${databaseConfig.database}`;\n"
  },
  {
    "path": "src/libs/api/api-error.response.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\n\nexport class ApiErrorResponse {\n  @ApiProperty({ example: 400 })\n  readonly statusCode: number;\n\n  @ApiProperty({ example: 'Validation Error' })\n  readonly message: string;\n\n  @ApiProperty({ example: 'Bad Request' })\n  readonly error: string;\n\n  @ApiProperty({ example: 'YevPQs' })\n  readonly correlationId: string;\n\n  @ApiProperty({\n    example: ['incorrect email'],\n    description: 'Optional list of sub-errors',\n    nullable: true,\n    required: false,\n  })\n  readonly subErrors?: string[];\n\n  constructor(body: ApiErrorResponse) {\n    this.statusCode = body.statusCode;\n    this.message = body.message;\n    this.error = body.error;\n    this.correlationId = body.correlationId;\n    this.subErrors = body.subErrors;\n  }\n}\n"
  },
  {
    "path": "src/libs/api/graphql/paginated.graphql-response.base.ts",
    "content": "import { Field, ObjectType, Int } from '@nestjs/graphql';\nimport { Type } from '@nestjs/common';\n\nexport interface IPaginatedType<T> {\n  data: T[];\n  count: number;\n  limit: number;\n  page: number;\n}\n\nexport function PaginatedGraphqlResponse<T>(\n  classRef: Type<T>,\n): Type<IPaginatedType<T>> {\n  @ObjectType({ isAbstract: true })\n  abstract class PaginatedType implements IPaginatedType<T> {\n    constructor(props: IPaginatedType<T>) {\n      this.count = props.count;\n      this.limit = props.limit;\n      this.page = props.page;\n      this.data = props.data;\n    }\n    @Field(() => Int)\n    page: number;\n\n    @Field(() => Int)\n    count: number;\n\n    @Field()\n    limit: number;\n\n    @Field(() => [classRef])\n    readonly data: T[];\n  }\n  return PaginatedType as Type<IPaginatedType<T>>;\n}\n"
  },
  {
    "path": "src/libs/api/id.response.dto.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\n\nexport class IdResponse {\n  constructor(id: string) {\n    this.id = id;\n  }\n\n  @ApiProperty({ example: '2cdc8ab1-6d50-49cc-ba14-54e4ac7ec231' })\n  readonly id: string;\n}\n"
  },
  {
    "path": "src/libs/api/paginated-query.request.dto.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport { Type } from 'class-transformer';\nimport { IsInt, IsOptional, Max, Min } from 'class-validator';\n\nexport class PaginatedQueryRequestDto {\n  @IsOptional()\n  @IsInt()\n  @Min(0)\n  @Max(99999)\n  @Type(() => Number)\n  @ApiProperty({\n    example: 10,\n    description: 'Specifies a limit of returned records',\n    required: false,\n  })\n  readonly limit?: number;\n\n  @IsOptional()\n  @IsInt()\n  @Min(0)\n  @Max(99999)\n  @Type(() => Number)\n  @ApiProperty({ example: 0, description: 'Page number', required: false })\n  readonly page?: number;\n}\n"
  },
  {
    "path": "src/libs/api/paginated.response.base.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport { Paginated } from '../ddd';\n\nexport abstract class PaginatedResponseDto<T> extends Paginated<T> {\n  @ApiProperty({\n    example: 5312,\n    description: 'Total number of items',\n  })\n  readonly count: number;\n\n  @ApiProperty({\n    example: 10,\n    description: 'Number of items per page',\n  })\n  readonly limit: number;\n\n  @ApiProperty({ example: 0, description: 'Page number' })\n  readonly page: number;\n\n  @ApiProperty({ isArray: true })\n  abstract readonly data: readonly T[];\n}\n"
  },
  {
    "path": "src/libs/api/response.base.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport { IdResponse } from './id.response.dto';\n\nexport interface BaseResponseProps {\n  id: string;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Most of our response objects will have properties like\n * id, createdAt and updatedAt so we can move them to a\n * separate class and extend it to avoid duplication.\n */\nexport class ResponseBase extends IdResponse {\n  constructor(props: BaseResponseProps) {\n    super(props.id);\n    this.createdAt = new Date(props.createdAt).toISOString();\n    this.updatedAt = new Date(props.updatedAt).toISOString();\n  }\n\n  @ApiProperty({ example: '2020-11-24T17:43:15.970Z' })\n  readonly createdAt: string;\n\n  @ApiProperty({ example: '2020-11-24T17:43:15.970Z' })\n  readonly updatedAt: string;\n}\n"
  },
  {
    "path": "src/libs/application/context/AppRequestContext.ts",
    "content": "import { RequestContext } from 'nestjs-request-context';\nimport { DatabaseTransactionConnection } from 'slonik';\n\n/**\n * Setting some isolated context for each request.\n */\n\nexport class AppRequestContext extends RequestContext {\n  requestId: string;\n  transactionConnection?: DatabaseTransactionConnection; // For global transactions\n}\n\nexport class RequestContextService {\n  static getContext(): AppRequestContext {\n    const ctx: AppRequestContext = RequestContext.currentContext.req;\n    return ctx;\n  }\n\n  static setRequestId(id: string): void {\n    const ctx = this.getContext();\n    ctx.requestId = id;\n  }\n\n  static getRequestId(): string {\n    return this.getContext().requestId;\n  }\n\n  static getTransactionConnection(): DatabaseTransactionConnection | undefined {\n    const ctx = this.getContext();\n    return ctx.transactionConnection;\n  }\n\n  static setTransactionConnection(\n    transactionConnection?: DatabaseTransactionConnection,\n  ): void {\n    const ctx = this.getContext();\n    ctx.transactionConnection = transactionConnection;\n  }\n\n  static cleanTransactionConnection(): void {\n    const ctx = this.getContext();\n    ctx.transactionConnection = undefined;\n  }\n}\n"
  },
  {
    "path": "src/libs/application/context/ContextInterceptor.ts",
    "content": "import {\n  Injectable,\n  NestInterceptor,\n  ExecutionContext,\n  CallHandler,\n} from '@nestjs/common';\nimport { Observable, tap } from 'rxjs';\nimport { nanoid } from 'nanoid';\nimport { RequestContextService } from './AppRequestContext';\n\n@Injectable()\nexport class ContextInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const request = context.switchToHttp().getRequest();\n\n    /**\n     * Setting an ID in the global context for each request.\n     * This ID can be used as correlation id shown in logs\n     */\n    const requestId = request?.body?.requestId ?? nanoid(6);\n\n    RequestContextService.setRequestId(requestId);\n\n    return next.handle().pipe(\n      tap(() => {\n        // Perform cleaning if needed\n      }),\n    );\n  }\n}\n"
  },
  {
    "path": "src/libs/application/interceptors/exception.interceptor.ts",
    "content": "import {\n  BadRequestException,\n  CallHandler,\n  ExecutionContext,\n  Logger,\n  NestInterceptor,\n} from '@nestjs/common';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\nimport { ExceptionBase } from '@libs/exceptions';\nimport { RequestContextService } from '../context/AppRequestContext';\nimport { ApiErrorResponse } from '@src/libs/api/api-error.response';\n\nexport class ExceptionInterceptor implements NestInterceptor {\n  private readonly logger: Logger = new Logger(ExceptionInterceptor.name);\n\n  intercept(\n    _context: ExecutionContext,\n    next: CallHandler,\n  ): Observable<ExceptionBase> {\n    return next.handle().pipe(\n      catchError((err) => {\n        // Logging for debugging purposes\n        if (err.status >= 400 && err.status < 500) {\n          this.logger.debug(\n            `[${RequestContextService.getRequestId()}] ${err.message}`,\n          );\n\n          const isClassValidatorError =\n            Array.isArray(err?.response?.message) &&\n            typeof err?.response?.error === 'string' &&\n            err.status === 400;\n          // Transforming class-validator errors to a different format\n          if (isClassValidatorError) {\n            err = new BadRequestException(\n              new ApiErrorResponse({\n                statusCode: err.status,\n                message: 'Validation error',\n                error: err?.response?.error,\n                subErrors: err?.response?.message,\n                correlationId: RequestContextService.getRequestId(),\n              }),\n            );\n          }\n        }\n\n        // Adding request ID to error message\n        if (!err.correlationId) {\n          err.correlationId = RequestContextService.getRequestId();\n        }\n\n        if (err.response) {\n          err.response.correlationId = err.correlationId;\n        }\n\n        return throwError(err);\n      }),\n    );\n  }\n}\n"
  },
  {
    "path": "src/libs/db/sql-repository.base.ts",
    "content": "import { RequestContextService } from '@libs/application/context/AppRequestContext';\nimport { AggregateRoot, PaginatedQueryParams, Paginated } from '@libs/ddd';\nimport { Mapper } from '@libs/ddd';\nimport { RepositoryPort } from '@libs/ddd';\nimport { ConflictException } from '@libs/exceptions';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { None, Option, Some } from 'oxide.ts';\nimport {\n  DatabasePool,\n  DatabaseTransactionConnection,\n  IdentifierSqlToken,\n  MixedRow,\n  PrimitiveValueExpression,\n  QueryResult,\n  QueryResultRow,\n  sql,\n  SqlSqlToken,\n  UniqueIntegrityConstraintViolationError,\n} from 'slonik';\nimport { ZodTypeAny, TypeOf, ZodObject } from 'zod';\nimport { LoggerPort } from '../ports/logger.port';\nimport { ObjectLiteral } from '../types';\n\nexport abstract class SqlRepositoryBase<\n  Aggregate extends AggregateRoot<any>,\n  DbModel extends ObjectLiteral,\n> implements RepositoryPort<Aggregate>\n{\n  protected abstract tableName: string;\n\n  protected abstract schema: ZodObject<any>;\n\n  protected constructor(\n    private readonly _pool: DatabasePool,\n    protected readonly mapper: Mapper<Aggregate, DbModel>,\n    protected readonly eventEmitter: EventEmitter2,\n    protected readonly logger: LoggerPort,\n  ) {}\n\n  async findOneById(id: string): Promise<Option<Aggregate>> {\n    const query = sql.type(this.schema)`SELECT * FROM ${sql.identifier([\n      this.tableName,\n    ])} WHERE id = ${id}`;\n\n    const result = await this.pool.query(query);\n    return result.rows[0] ? Some(this.mapper.toDomain(result.rows[0])) : None;\n  }\n\n  async findAll(): Promise<Aggregate[]> {\n    const query = sql.type(this.schema)`SELECT * FROM ${sql.identifier([\n      this.tableName,\n    ])}`;\n\n    const result = await this.pool.query(query);\n\n    return result.rows.map(this.mapper.toDomain);\n  }\n\n  async findAllPaginated(\n    params: PaginatedQueryParams,\n  ): Promise<Paginated<Aggregate>> {\n    const query = sql.type(this.schema)`\n    SELECT * FROM ${sql.identifier([this.tableName])}\n    LIMIT ${params.limit}\n    OFFSET ${params.offset}\n    `;\n\n    const result = await this.pool.query(query);\n\n    const entities = result.rows.map(this.mapper.toDomain);\n    return new Paginated({\n      data: entities,\n      count: result.rowCount,\n      limit: params.limit,\n      page: params.page,\n    });\n  }\n\n  async delete(entity: Aggregate): Promise<boolean> {\n    entity.validate();\n    const query = sql`DELETE FROM ${sql.identifier([\n      this.tableName,\n    ])} WHERE id = ${entity.id}`;\n\n    this.logger.debug(\n      `[${RequestContextService.getRequestId()}] deleting entities ${\n        entity.id\n      } from ${this.tableName}`,\n    );\n\n    const result = await this.pool.query(query);\n\n    await entity.publishEvents(this.logger, this.eventEmitter);\n\n    return result.rowCount > 0;\n  }\n\n  /**\n   * Inserts an entity to a database\n   * (also publishes domain events and waits for completion)\n   */\n  async insert(entity: Aggregate | Aggregate[]): Promise<void> {\n    const entities = Array.isArray(entity) ? entity : [entity];\n\n    const records = entities.map(this.mapper.toPersistence);\n\n    const query = this.generateInsertQuery(records);\n\n    try {\n      await this.writeQuery(query, entities);\n    } catch (error) {\n      if (error instanceof UniqueIntegrityConstraintViolationError) {\n        this.logger.debug(\n          `[${RequestContextService.getRequestId()}] ${\n            (error.originalError as any).detail\n          }`,\n        );\n        throw new ConflictException('Record already exists', error);\n      }\n      throw error;\n    }\n  }\n\n  /**\n   * Utility method for write queries when you need to mutate an entity.\n   * Executes entity validation, publishes events,\n   * and does some debug logging.\n   * For read queries use `this.pool` directly\n   */\n  protected async writeQuery<T>(\n    sql: SqlSqlToken<\n      T extends MixedRow ? T : Record<string, PrimitiveValueExpression>\n    >,\n    entity: Aggregate | Aggregate[],\n  ): Promise<\n    QueryResult<\n      T extends MixedRow\n        ? T extends ZodTypeAny\n          ? TypeOf<ZodTypeAny & MixedRow & T>\n          : T\n        : T\n    >\n  > {\n    const entities = Array.isArray(entity) ? entity : [entity];\n    entities.forEach((entity) => entity.validate());\n    const entityIds = entities.map((e) => e.id);\n\n    this.logger.debug(\n      `[${RequestContextService.getRequestId()}] writing ${\n        entities.length\n      } entities to \"${this.tableName}\" table: ${entityIds}`,\n    );\n\n    const result = await this.pool.query(sql);\n\n    await Promise.all(\n      entities.map((entity) =>\n        entity.publishEvents(this.logger, this.eventEmitter),\n      ),\n    );\n    return result;\n  }\n\n  /**\n   * Utility method to generate insert query for any objects.\n   * Use carefully and don't accept non-validated objects.\n   *\n   * Passing object with { name: string, email: string } will generate\n   * a query: INSERT INTO \"table\" (name, email) VALUES ($1, $2)\n   */\n  protected generateInsertQuery(\n    models: DbModel[],\n  ): SqlSqlToken<QueryResultRow> {\n    // TODO: generate query from an entire array to insert multiple records at once\n    const entries = Object.entries(models[0]);\n    const values: any = [];\n    const propertyNames: IdentifierSqlToken[] = [];\n\n    entries.forEach((entry) => {\n      if (entry[0] && entry[1] !== undefined) {\n        propertyNames.push(sql.identifier([entry[0]]));\n        if (entry[1] instanceof Date) {\n          values.push(sql.timestamp(entry[1]));\n        } else {\n          values.push(entry[1]);\n        }\n      }\n    });\n\n    const query = sql`INSERT INTO ${sql.identifier([\n      this.tableName,\n    ])} (${sql.join(propertyNames, sql`, `)}) VALUES (${sql.join(\n      values,\n      sql`, `,\n    )})`;\n\n    const parsedQuery = query;\n    return parsedQuery;\n  }\n\n  /**\n   * start a global transaction to save\n   * results of all event handlers in one operation\n   */\n  public async transaction<T>(handler: () => Promise<T>): Promise<T> {\n    return this.pool.transaction(async (connection) => {\n      this.logger.debug(\n        `[${RequestContextService.getRequestId()}] transaction started`,\n      );\n      if (!RequestContextService.getTransactionConnection()) {\n        RequestContextService.setTransactionConnection(connection);\n      }\n\n      try {\n        const result = await handler();\n        this.logger.debug(\n          `[${RequestContextService.getRequestId()}] transaction committed`,\n        );\n        return result;\n      } catch (e) {\n        this.logger.debug(\n          `[${RequestContextService.getRequestId()}] transaction aborted`,\n        );\n        throw e;\n      } finally {\n        RequestContextService.cleanTransactionConnection();\n      }\n    });\n  }\n\n  /**\n   * Get database pool.\n   * If global request transaction is started,\n   * returns a transaction pool.\n   */\n  protected get pool(): DatabasePool | DatabaseTransactionConnection {\n    return (\n      RequestContextService.getContext().transactionConnection ?? this._pool\n    );\n  }\n}\n"
  },
  {
    "path": "src/libs/ddd/aggregate-root.base.ts",
    "content": "import { DomainEvent } from './domain-event.base';\nimport { Entity } from './entity.base';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { LoggerPort } from '@libs/ports/logger.port';\nimport { RequestContextService } from '../application/context/AppRequestContext';\n\nexport abstract class AggregateRoot<EntityProps> extends Entity<EntityProps> {\n  private _domainEvents: DomainEvent[] = [];\n\n  get domainEvents(): DomainEvent[] {\n    return this._domainEvents;\n  }\n\n  protected addEvent(domainEvent: DomainEvent): void {\n    this._domainEvents.push(domainEvent);\n  }\n\n  public clearEvents(): void {\n    this._domainEvents = [];\n  }\n\n  public async publishEvents(\n    logger: LoggerPort,\n    eventEmitter: EventEmitter2,\n  ): Promise<void> {\n    await Promise.all(\n      this.domainEvents.map(async (event) => {\n        logger.debug(\n          `[${RequestContextService.getRequestId()}] \"${\n            event.constructor.name\n          }\" event published for aggregate ${this.constructor.name} : ${\n            this.id\n          }`,\n        );\n        return eventEmitter.emitAsync(event.constructor.name, event);\n      }),\n    );\n    this.clearEvents();\n  }\n}\n"
  },
  {
    "path": "src/libs/ddd/command.base.ts",
    "content": "import { RequestContextService } from '@libs/application/context/AppRequestContext';\nimport { ArgumentNotProvidedException } from '../exceptions';\nimport { Guard } from '../guard';\nimport { randomUUID } from 'crypto';\n\nexport type CommandProps<T> = Omit<T, 'id' | 'metadata'> & Partial<Command>;\n\ntype CommandMetadata = {\n  /** ID for correlation purposes (for commands that\n   *  arrive from other microservices,logs correlation, etc). */\n  readonly correlationId: string;\n\n  /**\n   * Causation id to reconstruct execution order if needed\n   */\n  readonly causationId?: string;\n\n  /**\n   * ID of a user who invoked the command. Can be useful for\n   * logging and tracking execution of commands and events\n   */\n  readonly userId?: string;\n\n  /**\n   * Time when the command occurred. Mostly for tracing purposes\n   */\n  readonly timestamp: number;\n};\n\nexport class Command {\n  /**\n   * Command id, in case if we want to save it\n   * for auditing purposes and create a correlation/causation chain\n   */\n  readonly id: string;\n\n  readonly metadata: CommandMetadata;\n\n  constructor(props: CommandProps<unknown>) {\n    if (Guard.isEmpty(props)) {\n      throw new ArgumentNotProvidedException(\n        'Command props should not be empty',\n      );\n    }\n    const ctx = RequestContextService.getContext();\n    this.id = props.id || randomUUID();\n    this.metadata = {\n      correlationId: props?.metadata?.correlationId || ctx.requestId,\n      causationId: props?.metadata?.causationId,\n      timestamp: props?.metadata?.timestamp || Date.now(),\n      userId: props?.metadata?.userId,\n    };\n  }\n}\n"
  },
  {
    "path": "src/libs/ddd/domain-event.base.ts",
    "content": "import { randomUUID } from 'crypto';\nimport { ArgumentNotProvidedException } from '../exceptions';\nimport { Guard } from '../guard';\nimport { RequestContextService } from '@libs/application/context/AppRequestContext';\n\ntype DomainEventMetadata = {\n  /** Timestamp when this domain event occurred */\n  readonly timestamp: number;\n\n  /** ID for correlation purposes (for Integration Events,logs correlation, etc).\n   */\n  readonly correlationId: string;\n\n  /**\n   * Causation id used to reconstruct execution order if needed\n   */\n  readonly causationId?: string;\n\n  /**\n   * User ID for debugging and logging purposes\n   */\n  readonly userId?: string;\n};\n\nexport type DomainEventProps<T> = Omit<T, 'id' | 'metadata'> & {\n  aggregateId: string;\n  metadata?: DomainEventMetadata;\n};\n\nexport abstract class DomainEvent {\n  public readonly id: string;\n\n  /** Aggregate ID where domain event occurred */\n  public readonly aggregateId: string;\n\n  public readonly metadata: DomainEventMetadata;\n\n  constructor(props: DomainEventProps<unknown>) {\n    if (Guard.isEmpty(props)) {\n      throw new ArgumentNotProvidedException(\n        'DomainEvent props should not be empty',\n      );\n    }\n    this.id = randomUUID();\n    this.aggregateId = props.aggregateId;\n    this.metadata = {\n      correlationId:\n        props?.metadata?.correlationId || RequestContextService.getRequestId(),\n      causationId: props?.metadata?.causationId,\n      timestamp: props?.metadata?.timestamp || Date.now(),\n      userId: props?.metadata?.userId,\n    };\n  }\n}\n"
  },
  {
    "path": "src/libs/ddd/entity.base.ts",
    "content": "import {\n  ArgumentNotProvidedException,\n  ArgumentInvalidException,\n  ArgumentOutOfRangeException,\n} from '../exceptions';\nimport { Guard } from '../guard';\nimport { convertPropsToObject } from '../utils';\n\nexport type AggregateID = string;\n\nexport interface BaseEntityProps {\n  id: AggregateID;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport interface CreateEntityProps<T> {\n  id: AggregateID;\n  props: T;\n  createdAt?: Date;\n  updatedAt?: Date;\n}\n\nexport abstract class Entity<EntityProps> {\n  constructor({\n    id,\n    createdAt,\n    updatedAt,\n    props,\n  }: CreateEntityProps<EntityProps>) {\n    this.setId(id);\n    this.validateProps(props);\n    const now = new Date();\n    this._createdAt = createdAt || now;\n    this._updatedAt = updatedAt || now;\n    this.props = props;\n    this.validate();\n  }\n\n  protected readonly props: EntityProps;\n\n  /**\n   * ID is set in the concrete entity implementation to support\n   * different ID types depending on your needs.\n   * For example it could be a UUID for aggregate root,\n   * and shortid / nanoid for child entities.\n   */\n  protected abstract _id: AggregateID;\n\n  private readonly _createdAt: Date;\n\n  private _updatedAt: Date;\n\n  get id(): AggregateID {\n    return this._id;\n  }\n\n  private setId(id: AggregateID): void {\n    this._id = id;\n  }\n\n  get createdAt(): Date {\n    return this._createdAt;\n  }\n\n  get updatedAt(): Date {\n    return this._updatedAt;\n  }\n\n  static isEntity(entity: unknown): entity is Entity<unknown> {\n    return entity instanceof Entity;\n  }\n\n  /**\n   *  Checks if two entities are the same Entity by comparing ID field.\n   * @param object Entity\n   */\n  public equals(object?: Entity<EntityProps>): boolean {\n    if (object === null || object === undefined) {\n      return false;\n    }\n\n    if (this === object) {\n      return true;\n    }\n\n    if (!Entity.isEntity(object)) {\n      return false;\n    }\n\n    return this.id ? this.id === object.id : false;\n  }\n\n  /**\n   * Returns entity properties.\n   * @return {*}  {Props & EntityProps}\n   * @memberof Entity\n   */\n  public getProps(): EntityProps & BaseEntityProps {\n    const propsCopy = {\n      id: this._id,\n      createdAt: this._createdAt,\n      updatedAt: this._updatedAt,\n      ...this.props,\n    };\n    return Object.freeze(propsCopy);\n  }\n\n  /**\n   * Convert an Entity and all sub-entities/Value Objects it\n   * contains to a plain object with primitive types. Can be\n   * useful when logging an entity during testing/debugging\n   */\n  public toObject(): unknown {\n    const plainProps = convertPropsToObject(this.props);\n\n    const result = {\n      id: this._id,\n      createdAt: this._createdAt,\n      updatedAt: this._updatedAt,\n      ...plainProps,\n    };\n    return Object.freeze(result);\n  }\n\n  /**\n   * There are certain rules that always have to be true (invariants)\n   * for each entity. Validate method is called every time before\n   * saving an entity to the database to make sure those rules are respected.\n   */\n  public abstract validate(): void;\n\n  private validateProps(props: EntityProps): void {\n    const MAX_PROPS = 50;\n\n    if (Guard.isEmpty(props)) {\n      throw new ArgumentNotProvidedException(\n        'Entity props should not be empty',\n      );\n    }\n    if (typeof props !== 'object') {\n      throw new ArgumentInvalidException('Entity props should be an object');\n    }\n    if (Object.keys(props as any).length > MAX_PROPS) {\n      throw new ArgumentOutOfRangeException(\n        `Entity props should not have more than ${MAX_PROPS} properties`,\n      );\n    }\n  }\n}\n"
  },
  {
    "path": "src/libs/ddd/index.ts",
    "content": "export * from './aggregate-root.base';\nexport * from './command.base';\nexport * from './domain-event.base';\nexport * from './entity.base';\nexport * from './mapper.interface';\nexport * from './repository.port';\nexport * from './value-object.base';\n"
  },
  {
    "path": "src/libs/ddd/mapper.interface.ts",
    "content": "import { Entity } from './entity.base';\n\nexport interface Mapper<\n  DomainEntity extends Entity<any>,\n  DbRecord,\n  Response = any,\n> {\n  toPersistence(entity: DomainEntity): DbRecord;\n  toDomain(record: any): DomainEntity;\n  toResponse(entity: DomainEntity): Response;\n}\n"
  },
  {
    "path": "src/libs/ddd/query.base.ts",
    "content": "import { OrderBy, PaginatedQueryParams } from './repository.port';\n\n/**\n * Base class for regular queries\n */\nexport abstract class QueryBase {}\n\n/**\n * Base class for paginated queries\n */\nexport abstract class PaginatedQueryBase extends QueryBase {\n  limit: number;\n  offset: number;\n  orderBy: OrderBy;\n  page: number;\n\n  constructor(props: PaginatedParams<PaginatedQueryBase>) {\n    super();\n    this.limit = props.limit || 20;\n    this.offset = props.page ? props.page * this.limit : 0;\n    this.page = props.page || 0;\n    this.orderBy = props.orderBy || { field: true, param: 'desc' };\n  }\n}\n\n// Paginated query parameters\nexport type PaginatedParams<T> = Omit<\n  T,\n  'limit' | 'offset' | 'orderBy' | 'page'\n> &\n  Partial<Omit<PaginatedQueryParams, 'offset'>>;\n"
  },
  {
    "path": "src/libs/ddd/repository.port.ts",
    "content": "import { Option } from 'oxide.ts';\n\n/*  Most of repositories will probably need generic \n    save/find/delete operations, so it's easier\n    to have some shared interfaces.\n    More specific queries should be defined\n    in a respective repository.\n*/\n\nexport class Paginated<T> {\n  readonly count: number;\n  readonly limit: number;\n  readonly page: number;\n  readonly data: readonly T[];\n\n  constructor(props: Paginated<T>) {\n    this.count = props.count;\n    this.limit = props.limit;\n    this.page = props.page;\n    this.data = props.data;\n  }\n}\n\nexport type OrderBy = { field: string | true; param: 'asc' | 'desc' };\n\nexport type PaginatedQueryParams = {\n  limit: number;\n  page: number;\n  offset: number;\n  orderBy: OrderBy;\n};\n\nexport interface RepositoryPort<Entity> {\n  insert(entity: Entity | Entity[]): Promise<void>;\n  findOneById(id: string): Promise<Option<Entity>>;\n  findAll(): Promise<Entity[]>;\n  findAllPaginated(params: PaginatedQueryParams): Promise<Paginated<Entity>>;\n  delete(entity: Entity): Promise<boolean>;\n\n  transaction<T>(handler: () => Promise<T>): Promise<T>;\n}\n"
  },
  {
    "path": "src/libs/ddd/value-object.base.ts",
    "content": "import { ArgumentNotProvidedException } from '../exceptions';\nimport { Guard } from '../guard';\nimport { convertPropsToObject } from '../utils';\n\n/**\n * Domain Primitive is an object that contains only a single value\n */\nexport type Primitives = string | number | boolean;\nexport interface DomainPrimitive<T extends Primitives | Date> {\n  value: T;\n}\n\ntype ValueObjectProps<T> = T extends Primitives | Date ? DomainPrimitive<T> : T;\n\nexport abstract class ValueObject<T> {\n  protected readonly props: ValueObjectProps<T>;\n\n  constructor(props: ValueObjectProps<T>) {\n    this.checkIfEmpty(props);\n    this.validate(props);\n    this.props = props;\n  }\n\n  protected abstract validate(props: ValueObjectProps<T>): void;\n\n  static isValueObject(obj: unknown): obj is ValueObject<unknown> {\n    return obj instanceof ValueObject;\n  }\n\n  /**\n   *  Check if two Value Objects are equal. Checks structural equality.\n   * @param vo ValueObject\n   */\n  public equals(vo?: ValueObject<T>): boolean {\n    if (vo === null || vo === undefined) {\n      return false;\n    }\n    return JSON.stringify(this) === JSON.stringify(vo);\n  }\n\n  /**\n   * Unpack a value object to get its raw properties\n   */\n  public unpack(): T {\n    if (this.isDomainPrimitive(this.props)) {\n      return this.props.value;\n    }\n\n    const propsCopy = convertPropsToObject(this.props);\n\n    return Object.freeze(propsCopy);\n  }\n\n  private checkIfEmpty(props: ValueObjectProps<T>): void {\n    if (\n      Guard.isEmpty(props) ||\n      (this.isDomainPrimitive(props) && Guard.isEmpty(props.value))\n    ) {\n      throw new ArgumentNotProvidedException('Property cannot be empty');\n    }\n  }\n\n  private isDomainPrimitive(\n    obj: unknown,\n  ): obj is DomainPrimitive<T & (Primitives | Date)> {\n    if (Object.prototype.hasOwnProperty.call(obj, 'value')) {\n      return true;\n    }\n    return false;\n  }\n}\n"
  },
  {
    "path": "src/libs/decorators/final.decorator.ts",
    "content": "/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Prevents other classes extending a class marked by this decorator.\n */\nexport function final<T extends { new (...args: any[]): object }>(\n  target: T,\n): T {\n  return class Final extends target {\n    constructor(...args: any[]) {\n      if (new.target !== Final) {\n        throw new Error(`Cannot extend a final class \"${target.name}\"`);\n      }\n      super(...args);\n    }\n  };\n}\n"
  },
  {
    "path": "src/libs/decorators/frozen.decorator.ts",
    "content": "/* eslint-disable @typescript-eslint/ban-types */\n/**\n * Applies Object.freeze() to a class and it's prototype.\n * Does not freeze all the properties of a class created\n * using 'new' keyword, only static properties and prototype\n * of a class.\n */\nexport function frozen(constructor: Function): void {\n  Object.freeze(constructor);\n  Object.freeze(constructor.prototype);\n}\n"
  },
  {
    "path": "src/libs/decorators/index.ts",
    "content": "export * from './final.decorator';\nexport * from './frozen.decorator';\n"
  },
  {
    "path": "src/libs/exceptions/exception.base.ts",
    "content": "import { RequestContextService } from '@libs/application/context/AppRequestContext';\n\nexport interface SerializedException {\n  message: string;\n  code: string;\n  correlationId: string;\n  stack?: string;\n  cause?: string;\n  metadata?: unknown;\n  /**\n   * ^ Consider adding optional `metadata` object to\n   * exceptions (if language doesn't support anything\n   * similar by default) and pass some useful technical\n   * information about the exception when throwing.\n   * This will make debugging easier.\n   */\n}\n\n/**\n * Base class for custom exceptions.\n *\n * @abstract\n * @class ExceptionBase\n * @extends {Error}\n */\nexport abstract class ExceptionBase extends Error {\n  abstract code: string;\n\n  public readonly correlationId: string;\n\n  /**\n   * @param {string} message\n   * @param {ObjectLiteral} [metadata={}]\n   * **BE CAREFUL** not to include sensitive info in 'metadata'\n   * to prevent leaks since all exception's data will end up\n   * in application's log files. Only include non-sensitive\n   * info that may help with debugging.\n   */\n  constructor(\n    readonly message: string,\n    readonly cause?: Error,\n    readonly metadata?: unknown,\n  ) {\n    super(message);\n    Error.captureStackTrace(this, this.constructor);\n    const ctx = RequestContextService.getContext();\n    this.correlationId = ctx.requestId;\n  }\n\n  /**\n   * By default in NodeJS Error objects are not\n   * serialized properly when sending plain objects\n   * to external processes. This method is a workaround.\n   * Keep in mind not to return a stack trace to user when in production.\n   * https://iaincollins.medium.com/error-handling-in-javascript-a6172ccdf9af\n   */\n  toJSON(): SerializedException {\n    return {\n      message: this.message,\n      code: this.code,\n      stack: this.stack,\n      correlationId: this.correlationId,\n      cause: JSON.stringify(this.cause),\n      metadata: this.metadata,\n    };\n  }\n}\n"
  },
  {
    "path": "src/libs/exceptions/exception.codes.ts",
    "content": "/**\n * Adding a `code` string with a custom status code for every\n * exception is a good practice, since when that exception\n * is transferred to another process `instanceof` check\n * cannot be performed anymore so a `code` string is used instead.\n * code constants can be stored in a separate file so they\n * can be shared and reused on a receiving side (code sharing is\n * useful when developing fullstack apps or microservices)\n */\nexport const ARGUMENT_INVALID = 'GENERIC.ARGUMENT_INVALID';\nexport const ARGUMENT_OUT_OF_RANGE = 'GENERIC.ARGUMENT_OUT_OF_RANGE';\nexport const ARGUMENT_NOT_PROVIDED = 'GENERIC.ARGUMENT_NOT_PROVIDED';\nexport const NOT_FOUND = 'GENERIC.NOT_FOUND';\nexport const CONFLICT = 'GENERIC.CONFLICT';\nexport const INTERNAL_SERVER_ERROR = 'GENERIC.INTERNAL_SERVER_ERROR';\n"
  },
  {
    "path": "src/libs/exceptions/exceptions.ts",
    "content": "import {\n  ARGUMENT_INVALID,\n  ARGUMENT_NOT_PROVIDED,\n  ARGUMENT_OUT_OF_RANGE,\n  CONFLICT,\n  INTERNAL_SERVER_ERROR,\n  NOT_FOUND,\n} from '.';\nimport { ExceptionBase } from './exception.base';\n\n/**\n * Used to indicate that an incorrect argument was provided to a method/function/class constructor\n *\n * @class ArgumentInvalidException\n * @extends {ExceptionBase}\n */\nexport class ArgumentInvalidException extends ExceptionBase {\n  readonly code = ARGUMENT_INVALID;\n}\n\n/**\n * Used to indicate that an argument was not provided (is empty object/array, null of undefined).\n *\n * @class ArgumentNotProvidedException\n * @extends {ExceptionBase}\n */\nexport class ArgumentNotProvidedException extends ExceptionBase {\n  readonly code = ARGUMENT_NOT_PROVIDED;\n}\n\n/**\n * Used to indicate that an argument is out of allowed range\n * (for example: incorrect string/array length, number not in allowed min/max range etc)\n *\n * @class ArgumentOutOfRangeException\n * @extends {ExceptionBase}\n */\nexport class ArgumentOutOfRangeException extends ExceptionBase {\n  readonly code = ARGUMENT_OUT_OF_RANGE;\n}\n\n/**\n * Used to indicate conflicting entities (usually in the database)\n *\n * @class ConflictException\n * @extends {ExceptionBase}\n */\nexport class ConflictException extends ExceptionBase {\n  readonly code = CONFLICT;\n}\n\n/**\n * Used to indicate that entity is not found\n *\n * @class NotFoundException\n * @extends {ExceptionBase}\n */\nexport class NotFoundException extends ExceptionBase {\n  static readonly message = 'Not found';\n\n  constructor(message = NotFoundException.message) {\n    super(message);\n  }\n\n  readonly code = NOT_FOUND;\n}\n\n/**\n * Used to indicate an internal server error that does not fall under all other errors\n *\n * @class InternalServerErrorException\n * @extends {ExceptionBase}\n */\nexport class InternalServerErrorException extends ExceptionBase {\n  static readonly message = 'Internal server error';\n\n  constructor(message = InternalServerErrorException.message) {\n    super(message);\n  }\n\n  readonly code = INTERNAL_SERVER_ERROR;\n}\n"
  },
  {
    "path": "src/libs/exceptions/index.ts",
    "content": "export * from './exception.base';\nexport * from './exception.codes';\nexport * from './exceptions';\n"
  },
  {
    "path": "src/libs/guard.ts",
    "content": "export class Guard {\n  /**\n   * Checks if value is empty. Accepts strings, numbers, booleans, objects and arrays.\n   */\n  static isEmpty(value: unknown): boolean {\n    if (typeof value === 'number' || typeof value === 'boolean') {\n      return false;\n    }\n    if (typeof value === 'undefined' || value === null) {\n      return true;\n    }\n    if (value instanceof Date) {\n      return false;\n    }\n    if (value instanceof Object && !Object.keys(value).length) {\n      return true;\n    }\n    if (Array.isArray(value)) {\n      if (value.length === 0) {\n        return true;\n      }\n      if (value.every((item) => Guard.isEmpty(item))) {\n        return true;\n      }\n    }\n    if (value === '') {\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Checks length range of a provided number/string/array\n   */\n  static lengthIsBetween(\n    value: number | string | Array<unknown>,\n    min: number,\n    max: number,\n  ): boolean {\n    if (Guard.isEmpty(value)) {\n      throw new Error(\n        'Cannot check length of a value. Provided value is empty',\n      );\n    }\n    const valueLength =\n      typeof value === 'number'\n        ? Number(value).toString().length\n        : value.length;\n    if (valueLength >= min && valueLength <= max) {\n      return true;\n    }\n    return false;\n  }\n}\n"
  },
  {
    "path": "src/libs/ports/logger.port.ts",
    "content": "export interface LoggerPort {\n  log(message: string, ...meta: unknown[]): void;\n  error(message: string, trace?: unknown, ...meta: unknown[]): void;\n  warn(message: string, ...meta: unknown[]): void;\n  debug(message: string, ...meta: unknown[]): void;\n}\n"
  },
  {
    "path": "src/libs/types/deep-partial.type.ts",
    "content": "/**\n * Applies Partial utility type to all nested objects.\n */\nexport type DeepPartial<T> = {\n  [P in keyof T]?: DeepPartial<T[P]>;\n};\n"
  },
  {
    "path": "src/libs/types/index.ts",
    "content": "/** Consider creating a bunch of shared custom utility\n * types for different situations.\n * Alternatively you can use a library like\n * https://github.com/andnp/SimplyTyped\n */\nexport * from './deep-partial.type';\nexport * from './non-function-properties.type';\nexport * from './object-literal.type';\nexport * from './require-one.type';\nexport * from './mutable.type';\n"
  },
  {
    "path": "src/libs/types/mutable.type.ts",
    "content": "/**\n * Makes all properties of the type mutable\n * (removes readonly flag)\n */\nexport type Mutable<T> = {\n  -readonly [key in keyof T]: T[key];\n};\n\n/**\n * Makes all properties of the type mutable recursively\n * (removes readonly flag, including in nested objects)\n */\nexport type DeepMutable<T> = { -readonly [P in keyof T]: DeepMutable<T[P]> };\n"
  },
  {
    "path": "src/libs/types/non-function-properties.type.ts",
    "content": "export type NonFunctionPropertyNames<T> = {\n  // eslint-disable-next-line @typescript-eslint/ban-types\n  [K in keyof T]: T[K] extends Function ? never : K;\n}[keyof T];\n\n/**\n * Exclude all function properties from type.\n */\nexport type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;\n"
  },
  {
    "path": "src/libs/types/object-literal.type.ts",
    "content": "/**\n * Interface of the simple literal object with any string keys.\n */\nexport interface ObjectLiteral {\n  [key: string]: unknown;\n}\n"
  },
  {
    "path": "src/libs/types/require-one.type.ts",
    "content": "/**\n * Makes an interface with all optional values to require AT LEAST one of them.\n */\nexport type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<\n  T,\n  Exclude<keyof T, Keys>\n> &\n  {\n    [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;\n  }[Keys];\n\n/* Makes an interface with all optional values to accept ONLY one of them */\nexport type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<\n  T,\n  Exclude<keyof T, Keys>\n> &\n  {\n    [K in Keys]-?: Required<Pick<T, K>> &\n      Partial<Record<Exclude<Keys, K>, undefined>>;\n  }[Keys];\n"
  },
  {
    "path": "src/libs/utils/convert-props-to-object.util.ts",
    "content": "/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types */\nimport { Entity } from '../ddd/entity.base';\nimport { ValueObject } from '../ddd/value-object.base';\n\nfunction isEntity(obj: unknown): obj is Entity<unknown> {\n  /**\n   * 'instanceof Entity' causes error here for some reason.\n   * Probably creates some circular dependency. This is a workaround\n   * until I find a solution :)\n   */\n  return (\n    Object.prototype.hasOwnProperty.call(obj, 'toObject') &&\n    Object.prototype.hasOwnProperty.call(obj, 'id') &&\n    ValueObject.isValueObject((obj as Entity<unknown>).id)\n  );\n}\n\nfunction convertToPlainObject(item: any): any {\n  if (ValueObject.isValueObject(item)) {\n    return item.unpack();\n  }\n  if (isEntity(item)) {\n    return item.toObject();\n  }\n  return item;\n}\n\n/**\n * Converts Entity/Value Objects props to a plain object.\n * Useful for testing and debugging.\n * @param props\n */\nexport function convertPropsToObject(props: any): any {\n  const propsCopy = structuredClone(props);\n\n  // eslint-disable-next-line guard-for-in\n  for (const prop in propsCopy) {\n    if (Array.isArray(propsCopy[prop])) {\n      propsCopy[prop] = (propsCopy[prop] as Array<unknown>).map((item) => {\n        return convertToPlainObject(item);\n      });\n    }\n    propsCopy[prop] = convertToPlainObject(propsCopy[prop]);\n  }\n\n  return propsCopy;\n}\n"
  },
  {
    "path": "src/libs/utils/dotenv.ts",
    "content": "import { config } from 'dotenv';\nimport * as path from 'path';\n\n// Initializing dotenv\nconst envPath: string = path.resolve(\n  __dirname,\n  process.env.NODE_ENV === 'test' ? '../../../.env.test' : '../../../../.env',\n);\nconfig({ path: envPath });\n"
  },
  {
    "path": "src/libs/utils/index.ts",
    "content": "export * from './convert-props-to-object.util';\n"
  },
  {
    "path": "src/main.ts",
    "content": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';\nimport { ValidationPipe } from '@nestjs/common';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const options = new DocumentBuilder().build();\n\n  const document = SwaggerModule.createDocument(app, options);\n  SwaggerModule.setup('docs', app, document);\n\n  app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));\n\n  app.enableShutdownHooks();\n\n  await app.listen(3000);\n}\nbootstrap();\n"
  },
  {
    "path": "src/modules/user/commands/create-user/create-user.cli.controller.ts",
    "content": "import { Inject, Logger } from '@nestjs/common';\nimport { Command, Console } from 'nestjs-console';\nimport { CommandBus } from '@nestjs/cqrs';\nimport { CreateUserCommand } from './create-user.command';\nimport { LoggerPort } from '@libs/ports/logger.port';\n\n// Allows creating a user using CLI (Command Line Interface)\n@Console({\n  command: 'new',\n  description: 'A command to create a user',\n})\nexport class CreateUserCliController {\n  constructor(\n    private readonly commandBus: CommandBus,\n    @Inject(Logger)\n    private readonly logger: LoggerPort,\n  ) {}\n\n  @Command({\n    command: 'user <email> <country> <postalCode> <street>',\n    description: 'Create a user',\n  })\n  async createUser(\n    email: string,\n    country: string,\n    postalCode: string,\n    street: string,\n  ): Promise<void> {\n    const command = new CreateUserCommand({\n      email,\n      country,\n      postalCode,\n      street,\n    });\n\n    const result = await this.commandBus.execute(command);\n\n    this.logger.log('User created:', result.unwrap());\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/create-user.command.ts",
    "content": "import { Command, CommandProps } from '@libs/ddd';\n\nexport class CreateUserCommand extends Command {\n  readonly email: string;\n\n  readonly country: string;\n\n  readonly postalCode: string;\n\n  readonly street: string;\n\n  constructor(props: CommandProps<CreateUserCommand>) {\n    super(props);\n    this.email = props.email;\n    this.country = props.country;\n    this.postalCode = props.postalCode;\n    this.street = props.street;\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/create-user.http.controller.ts",
    "content": "import {\n  Body,\n  ConflictException as ConflictHttpException,\n  Controller,\n  HttpStatus,\n  Post,\n} from '@nestjs/common';\nimport { routesV1 } from '@config/app.routes';\nimport { ApiOperation, ApiResponse } from '@nestjs/swagger';\nimport { CommandBus } from '@nestjs/cqrs';\nimport { match, Result } from 'oxide.ts';\nimport { CreateUserCommand } from './create-user.command';\nimport { CreateUserRequestDto } from './create-user.request.dto';\nimport { UserAlreadyExistsError } from '@modules/user/domain/user.errors';\nimport { IdResponse } from '@libs/api/id.response.dto';\nimport { AggregateID } from '@libs/ddd';\nimport { ApiErrorResponse } from '@src/libs/api/api-error.response';\n\n@Controller(routesV1.version)\nexport class CreateUserHttpController {\n  constructor(private readonly commandBus: CommandBus) {}\n\n  @ApiOperation({ summary: 'Create a user' })\n  @ApiResponse({\n    status: HttpStatus.OK,\n    type: IdResponse,\n  })\n  @ApiResponse({\n    status: HttpStatus.CONFLICT,\n    description: UserAlreadyExistsError.message,\n    type: ApiErrorResponse,\n  })\n  @ApiResponse({\n    status: HttpStatus.BAD_REQUEST,\n    type: ApiErrorResponse,\n  })\n  @Post(routesV1.user.root)\n  async create(@Body() body: CreateUserRequestDto): Promise<IdResponse> {\n    const command = new CreateUserCommand(body);\n\n    const result: Result<AggregateID, UserAlreadyExistsError> =\n      await this.commandBus.execute(command);\n\n    // Deciding what to do with a Result (similar to Rust matching)\n    // if Ok we return a response with an id\n    // if Error decide what to do with it depending on its type\n    return match(result, {\n      Ok: (id: string) => new IdResponse(id),\n      Err: (error: Error) => {\n        if (error instanceof UserAlreadyExistsError)\n          throw new ConflictHttpException(error.message);\n        throw error;\n      },\n    });\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/create-user.message.controller.ts",
    "content": "import { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\nimport { CommandBus } from '@nestjs/cqrs';\nimport { CreateUserCommand } from './create-user.command';\nimport { CreateUserRequestDto } from './create-user.request.dto';\nimport { IdResponse } from '@libs/api/id.response.dto';\n\n@Controller()\nexport class CreateUserMessageController {\n  constructor(private readonly commandBus: CommandBus) {}\n\n  @MessagePattern('user.create') // <- Subscribe to a microservice message\n  async create(message: CreateUserRequestDto): Promise<IdResponse> {\n    const command = new CreateUserCommand(message);\n\n    const id = await this.commandBus.execute(command);\n\n    return new IdResponse(id.unwrap());\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/create-user.request.dto.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport {\n  IsAlphanumeric,\n  IsEmail,\n  IsString,\n  Matches,\n  MaxLength,\n  MinLength,\n} from 'class-validator';\n\nexport class CreateUserRequestDto {\n  @ApiProperty({\n    example: 'john@gmail.com',\n    description: 'User email address',\n  })\n  @MaxLength(320)\n  @MinLength(5)\n  @IsEmail()\n  readonly email: string;\n\n  @ApiProperty({ example: 'France', description: 'Country of residence' })\n  @MaxLength(50)\n  @MinLength(4)\n  @IsString()\n  @Matches(/^[a-zA-Z ]*$/)\n  readonly country: string;\n\n  @ApiProperty({ example: '28566', description: 'Postal code' })\n  @MaxLength(10)\n  @MinLength(4)\n  @IsAlphanumeric()\n  readonly postalCode: string;\n\n  @ApiProperty({ example: 'Grande Rue', description: 'Street' })\n  @MaxLength(50)\n  @MinLength(5)\n  @Matches(/^[a-zA-Z ]*$/)\n  readonly street: string;\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/create-user.service.ts",
    "content": "import { UserRepositoryPort } from '@modules/user/database/user.repository.port';\nimport { Address } from '@modules/user/domain/value-objects/address.value-object';\nimport { CommandHandler, ICommandHandler } from '@nestjs/cqrs';\nimport { Err, Ok, Result } from 'oxide.ts';\nimport { CreateUserCommand } from './create-user.command';\nimport { UserAlreadyExistsError } from '@modules/user/domain/user.errors';\nimport { AggregateID } from '@libs/ddd';\nimport { UserEntity } from '@modules/user/domain/user.entity';\nimport { ConflictException } from '@libs/exceptions';\nimport { Inject } from '@nestjs/common';\nimport { USER_REPOSITORY } from '../../user.di-tokens';\n\n@CommandHandler(CreateUserCommand)\nexport class CreateUserService implements ICommandHandler {\n  constructor(\n    @Inject(USER_REPOSITORY)\n    protected readonly userRepo: UserRepositoryPort,\n  ) {}\n\n  async execute(\n    command: CreateUserCommand,\n  ): Promise<Result<AggregateID, UserAlreadyExistsError>> {\n    const user = UserEntity.create({\n      email: command.email,\n      address: new Address({\n        country: command.country,\n        postalCode: command.postalCode,\n        street: command.street,\n      }),\n    });\n\n    try {\n      /* Wrapping operation in a transaction to make sure\n         that all domain events are processed atomically */\n      await this.userRepo.transaction(async () => this.userRepo.insert(user));\n      return Ok(user.id);\n    } catch (error: any) {\n      if (error instanceof ConflictException) {\n        return Err(new UserAlreadyExistsError(error));\n      }\n      throw error;\n    }\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/graphql-example/create-user.graphql-resolver.ts",
    "content": "import { Args, Mutation, Resolver } from '@nestjs/graphql';\nimport { CommandBus } from '@nestjs/cqrs';\nimport { CreateUserCommand } from '../create-user.command';\nimport { CreateUserGqlRequestDto } from './dtos/create-user.gql-request.dto';\nimport { IdGqlResponse } from './dtos/id.gql-response.dto';\nimport { AggregateID } from '@src/libs/ddd';\nimport { UserAlreadyExistsError } from '@src/modules/user/domain/user.errors';\nimport { Result } from 'oxide.ts';\n\n// If you are Using GraphQL you'll need a Resolver instead of a Controller\n@Resolver()\nexport class CreateUserGraphqlResolver {\n  constructor(private readonly commandBus: CommandBus) {}\n\n  @Mutation(() => IdGqlResponse)\n  async create(\n    @Args('input') input: CreateUserGqlRequestDto,\n  ): Promise<IdGqlResponse> {\n    const command = new CreateUserCommand(input);\n\n    const id: Result<AggregateID, UserAlreadyExistsError> =\n      await this.commandBus.execute(command);\n\n    return new IdGqlResponse(id.unwrap());\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/graphql-example/dtos/create-user.gql-request.dto.ts",
    "content": "import { ArgsType, Field, InputType } from '@nestjs/graphql';\nimport {\n  IsAlphanumeric,\n  IsEmail,\n  IsString,\n  Matches,\n  MaxLength,\n  MinLength,\n} from 'class-validator';\n\n@ArgsType()\n@InputType()\nexport class CreateUserGqlRequestDto {\n  @MaxLength(320)\n  @MinLength(5)\n  @IsEmail()\n  @Field()\n  readonly email: string;\n\n  @MaxLength(50)\n  @MinLength(4)\n  @IsString()\n  @Matches(/^[a-zA-Z ]*$/)\n  @Field()\n  readonly country: string;\n\n  @MaxLength(10)\n  @MinLength(4)\n  @IsAlphanumeric()\n  @Field()\n  readonly postalCode: string;\n\n  @MaxLength(50)\n  @MinLength(5)\n  @Matches(/^[a-zA-Z ]*$/)\n  @Field()\n  readonly street: string;\n}\n"
  },
  {
    "path": "src/modules/user/commands/create-user/graphql-example/dtos/id.gql-response.dto.ts",
    "content": "import { Field, ObjectType } from '@nestjs/graphql';\n\n@ObjectType()\nexport class IdGqlResponse {\n  constructor(id: string) {\n    this.id = id;\n  }\n\n  @Field()\n  readonly id: string;\n}\n"
  },
  {
    "path": "src/modules/user/commands/delete-user/delete-user.http-controller.ts",
    "content": "import {\n  Controller,\n  Delete,\n  HttpStatus,\n  NotFoundException as NotFoundHttpException,\n  Param,\n} from '@nestjs/common';\nimport { routesV1 } from '@config/app.routes';\nimport { CommandBus } from '@nestjs/cqrs';\nimport { DeleteUserCommand } from './delete-user.service';\nimport { match, Result } from 'oxide.ts';\nimport { NotFoundException } from '@libs/exceptions';\nimport { ApiOperation, ApiResponse } from '@nestjs/swagger';\nimport { ApiErrorResponse } from '@src/libs/api/api-error.response';\n\n@Controller(routesV1.version)\nexport class DeleteUserHttpController {\n  constructor(private readonly commandBus: CommandBus) {}\n\n  @ApiOperation({ summary: 'Delete a user' })\n  @ApiResponse({\n    description: 'User deleted',\n    status: HttpStatus.OK,\n  })\n  @ApiResponse({\n    status: HttpStatus.NOT_FOUND,\n    description: NotFoundException.message,\n    type: ApiErrorResponse,\n  })\n  @Delete(routesV1.user.delete)\n  async deleteUser(@Param('id') id: string): Promise<void> {\n    const command = new DeleteUserCommand({ userId: id });\n    const result: Result<boolean, NotFoundException> =\n      await this.commandBus.execute(command);\n\n    match(result, {\n      Ok: (isOk: boolean) => isOk,\n      Err: (error: Error) => {\n        if (error instanceof NotFoundException)\n          throw new NotFoundHttpException(error.message);\n        throw error;\n      },\n    });\n  }\n}\n"
  },
  {
    "path": "src/modules/user/commands/delete-user/delete-user.service.ts",
    "content": "import { NotFoundException } from '@libs/exceptions';\nimport { UserRepositoryPort } from '@modules/user/database/user.repository.port';\nimport { Inject } from '@nestjs/common';\nimport { CommandHandler } from '@nestjs/cqrs';\nimport { Err, Ok, Result } from 'oxide.ts';\nimport { USER_REPOSITORY } from '../../user.di-tokens';\n\nexport class DeleteUserCommand {\n  readonly userId: string;\n\n  constructor(props: DeleteUserCommand) {\n    this.userId = props.userId;\n  }\n}\n\n@CommandHandler(DeleteUserCommand)\nexport class DeleteUserService {\n  constructor(\n    @Inject(USER_REPOSITORY)\n    private readonly userRepo: UserRepositoryPort,\n  ) {}\n\n  async execute(\n    command: DeleteUserCommand,\n  ): Promise<Result<boolean, NotFoundException>> {\n    const found = await this.userRepo.findOneById(command.userId);\n    if (found.isNone()) return Err(new NotFoundException());\n    const user = found.unwrap();\n    user.delete();\n    const result = await this.userRepo.delete(user);\n    return Ok(result);\n  }\n}\n"
  },
  {
    "path": "src/modules/user/database/user.repository.port.ts",
    "content": "import { PaginatedQueryParams, RepositoryPort } from '@libs/ddd';\nimport { UserEntity } from '../domain/user.entity';\n\nexport interface FindUsersParams extends PaginatedQueryParams {\n  readonly country?: string;\n  readonly postalCode?: string;\n  readonly street?: string;\n}\n\nexport interface UserRepositoryPort extends RepositoryPort<UserEntity> {\n  findOneByEmail(email: string): Promise<UserEntity | null>;\n}\n"
  },
  {
    "path": "src/modules/user/database/user.repository.ts",
    "content": "import { InjectPool } from 'nestjs-slonik';\nimport { DatabasePool, sql } from 'slonik';\nimport { UserRepositoryPort } from './user.repository.port';\nimport { z } from 'zod';\nimport { UserMapper } from '../user.mapper';\nimport { UserRoles } from '../domain/user.types';\nimport { UserEntity } from '../domain/user.entity';\nimport { SqlRepositoryBase } from '@src/libs/db/sql-repository.base';\nimport { Injectable, Logger } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\n\n/**\n * Runtime validation of user object for extra safety (in case database schema changes).\n * https://github.com/gajus/slonik#runtime-validation\n * If you prefer to avoid performance penalty of validation, use interfaces instead.\n */\nexport const userSchema = z.object({\n  id: z.string().uuid(),\n  createdAt: z.preprocess((val: any) => new Date(val), z.date()),\n  updatedAt: z.preprocess((val: any) => new Date(val), z.date()),\n  email: z.string().email(),\n  country: z.string().min(1).max(255),\n  postalCode: z.string().min(1).max(20),\n  street: z.string().min(1).max(255),\n  role: z.nativeEnum(UserRoles),\n});\n\nexport type UserModel = z.TypeOf<typeof userSchema>;\n\n/**\n *  Repository is used for retrieving/saving domain entities\n * */\n@Injectable()\nexport class UserRepository\n  extends SqlRepositoryBase<UserEntity, UserModel>\n  implements UserRepositoryPort\n{\n  protected tableName = 'users';\n\n  protected schema = userSchema;\n\n  constructor(\n    @InjectPool()\n    pool: DatabasePool,\n    mapper: UserMapper,\n    eventEmitter: EventEmitter2,\n  ) {\n    super(pool, mapper, eventEmitter, new Logger(UserRepository.name));\n  }\n\n  async updateAddress(user: UserEntity): Promise<void> {\n    const address = user.getProps().address;\n    const statement = sql.type(userSchema)`\n    UPDATE \"users\" SET\n    street = ${address.street}, country = ${address.country}, \"postalCode\" = ${address.postalCode}\n    WHERE id = ${user.id}`;\n\n    await this.writeQuery(statement, user);\n  }\n\n  async findOneByEmail(email: string): Promise<UserEntity> {\n    const user = await this.pool.one(\n      sql.type(userSchema)`SELECT * FROM \"users\" WHERE email = ${email}`,\n    );\n\n    return this.mapper.toDomain(user);\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/events/user-address-updated.domain-event.ts",
    "content": "import { DomainEvent, DomainEventProps } from '@libs/ddd';\n\nexport class UserAddressUpdatedDomainEvent extends DomainEvent {\n  public readonly country: string;\n\n  public readonly street: string;\n\n  public readonly postalCode: string;\n\n  constructor(props: DomainEventProps<UserAddressUpdatedDomainEvent>) {\n    super(props);\n    this.country = props.country;\n    this.postalCode = props.postalCode;\n    this.street = props.street;\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/events/user-created.domain-event.ts",
    "content": "import { DomainEvent, DomainEventProps } from '@libs/ddd';\n\nexport class UserCreatedDomainEvent extends DomainEvent {\n  readonly email: string;\n\n  readonly country: string;\n\n  readonly postalCode: string;\n\n  readonly street: string;\n\n  constructor(props: DomainEventProps<UserCreatedDomainEvent>) {\n    super(props);\n    this.email = props.email;\n    this.country = props.country;\n    this.postalCode = props.postalCode;\n    this.street = props.street;\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/events/user-deleted.domain-event.ts",
    "content": "import { DomainEvent, DomainEventProps } from '@libs/ddd';\n\nexport class UserDeletedDomainEvent extends DomainEvent {\n  constructor(props: DomainEventProps<UserDeletedDomainEvent>) {\n    super(props);\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/events/user-role-changed.domain-event.ts",
    "content": "import { DomainEvent, DomainEventProps } from '@libs/ddd';\nimport { UserRoles } from '../user.types';\n\nexport class UserRoleChangedDomainEvent extends DomainEvent {\n  readonly oldRole: UserRoles;\n\n  readonly newRole: UserRoles;\n\n  constructor(props: DomainEventProps<UserRoleChangedDomainEvent>) {\n    super(props);\n    this.oldRole = props.oldRole;\n    this.newRole = props.newRole;\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/user.entity.ts",
    "content": "import { AggregateRoot, AggregateID } from '@libs/ddd';\nimport { UserCreatedDomainEvent } from './events/user-created.domain-event';\nimport { Address, AddressProps } from './value-objects/address.value-object';\nimport {\n  CreateUserProps,\n  UpdateUserAddressProps,\n  UserProps,\n  UserRoles,\n} from './user.types';\nimport { UserDeletedDomainEvent } from './events/user-deleted.domain-event';\nimport { UserRoleChangedDomainEvent } from './events/user-role-changed.domain-event';\nimport { UserAddressUpdatedDomainEvent } from './events/user-address-updated.domain-event';\nimport { randomUUID } from 'crypto';\n\nexport class UserEntity extends AggregateRoot<UserProps> {\n  protected readonly _id: AggregateID;\n\n  static create(create: CreateUserProps): UserEntity {\n    const id = randomUUID();\n    /* Setting a default role since we are not accepting it during creation. */\n    const props: UserProps = { ...create, role: UserRoles.guest };\n    const user = new UserEntity({ id, props });\n    /* adding \"UserCreated\" Domain Event that will be published\n    eventually so an event handler somewhere may receive it and do an\n    appropriate action. Multiple events can be added if needed. */\n    user.addEvent(\n      new UserCreatedDomainEvent({\n        aggregateId: id,\n        email: props.email,\n        ...props.address.unpack(),\n      }),\n    );\n    return user;\n  }\n\n  /* You can create getters only for the properties that you need to\n  access and leave the rest of the properties private to keep entity\n  encapsulated. To get all entity properties (for saving it to a\n  database or mapping a response) use .getProps() method\n  defined in a EntityBase parent class */\n  get role(): UserRoles {\n    return this.props.role;\n  }\n\n  private changeRole(newRole: UserRoles): void {\n    this.addEvent(\n      new UserRoleChangedDomainEvent({\n        aggregateId: this.id,\n        oldRole: this.props.role,\n        newRole,\n      }),\n    );\n\n    this.props.role = newRole;\n  }\n\n  makeAdmin(): void {\n    this.changeRole(UserRoles.admin);\n  }\n\n  makeModerator(): void {\n    this.changeRole(UserRoles.moderator);\n  }\n\n  delete(): void {\n    this.addEvent(\n      new UserDeletedDomainEvent({\n        aggregateId: this.id,\n      }),\n    );\n  }\n\n  /* Update method only changes properties that we allow, in this\n   case only address. This prevents from illegal actions, \n   for example setting email from outside by doing something\n   like user.email = otherEmail */\n  updateAddress(props: UpdateUserAddressProps): void {\n    const newAddress = new Address({\n      ...this.props.address,\n      ...props,\n    } as AddressProps);\n\n    this.props.address = newAddress;\n\n    this.addEvent(\n      new UserAddressUpdatedDomainEvent({\n        aggregateId: this.id,\n        country: newAddress.country,\n        street: newAddress.street,\n        postalCode: newAddress.postalCode,\n      }),\n    );\n  }\n\n  validate(): void {\n    // entity business rules validation to protect it's invariant before saving entity to a database\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/user.errors.ts",
    "content": "import { ExceptionBase } from '@libs/exceptions';\n\nexport class UserAlreadyExistsError extends ExceptionBase {\n  static readonly message = 'User already exists';\n\n  public readonly code = 'USER.ALREADY_EXISTS';\n\n  constructor(cause?: Error, metadata?: unknown) {\n    super(UserAlreadyExistsError.message, cause, metadata);\n  }\n}\n"
  },
  {
    "path": "src/modules/user/domain/user.types.ts",
    "content": "import { Address } from './value-objects/address.value-object';\n\n// All properties that a User has\nexport interface UserProps {\n  role: UserRoles;\n  email: string;\n  address: Address;\n}\n\n// Properties that are needed for a user creation\nexport interface CreateUserProps {\n  email: string;\n  address: Address;\n}\n\n// Properties used for updating a user address\nexport interface UpdateUserAddressProps {\n  country?: string;\n  postalCode?: string;\n  street?: string;\n}\n\nexport enum UserRoles {\n  admin = 'admin',\n  moderator = 'moderator',\n  guest = 'guest',\n}\n"
  },
  {
    "path": "src/modules/user/domain/value-objects/address.value-object.ts",
    "content": "import { ValueObject } from '@libs/ddd';\nimport { Guard } from '@libs/guard';\nimport { ArgumentOutOfRangeException } from '@libs/exceptions';\n\n/** Note:\n * Value Objects with multiple properties can contain\n * other Value Objects inside if needed.\n * */\n\nexport interface AddressProps {\n  country: string;\n  postalCode: string;\n  street: string;\n}\n\nexport class Address extends ValueObject<AddressProps> {\n  get country(): string {\n    return this.props.country;\n  }\n\n  get postalCode(): string {\n    return this.props.postalCode;\n  }\n\n  get street(): string {\n    return this.props.street;\n  }\n\n  /**\n   * Note: This is a very simplified example of validation,\n   * real world projects will have stricter rules.\n   * You can avoid this type of validation here and validate\n   * only on the edge of the application (in controllers when receiving\n   * a request) sacrificing some security for performance and convenience.\n   */\n  protected validate(props: AddressProps): void {\n    if (!Guard.lengthIsBetween(props.country, 2, 50)) {\n      throw new ArgumentOutOfRangeException('country is out of range');\n    }\n    if (!Guard.lengthIsBetween(props.street, 2, 50)) {\n      throw new ArgumentOutOfRangeException('street is out of range');\n    }\n    if (!Guard.lengthIsBetween(props.postalCode, 2, 10)) {\n      throw new ArgumentOutOfRangeException('postalCode is out of range');\n    }\n  }\n}\n"
  },
  {
    "path": "src/modules/user/dtos/graphql/user.graphql-response.dto.ts",
    "content": "import { ResponseBase } from '@libs/api/response.base';\nimport { Field, ObjectType } from '@nestjs/graphql';\n\n@ObjectType()\nexport class UserGraphqlResponseDto extends ResponseBase {\n  @Field({\n    description: \"User's identifier\",\n  })\n  id: string;\n\n  @Field({\n    description: \"User's email address\",\n  })\n  email: string;\n\n  @Field({\n    description: \"User's country of residence\",\n  })\n  country: string;\n\n  @Field({\n    description: 'Postal code',\n  })\n  postalCode: string;\n\n  @Field({\n    description: 'Street where the user is registered',\n  })\n  street: string;\n}\n"
  },
  {
    "path": "src/modules/user/dtos/graphql/user.paginated-gql-response.dto.ts",
    "content": "import { Field, ObjectType } from '@nestjs/graphql';\nimport { PaginatedGraphqlResponse } from '../../../../libs/api/graphql/paginated.graphql-response.base';\n\nimport { UserGraphqlResponseDto } from './user.graphql-response.dto';\n\n@ObjectType()\nexport class UserPaginatedGraphqlResponseDto extends PaginatedGraphqlResponse(\n  UserGraphqlResponseDto,\n) {\n  @Field(() => [UserGraphqlResponseDto])\n  data: UserGraphqlResponseDto[];\n}\n"
  },
  {
    "path": "src/modules/user/dtos/user.paginated.response.dto.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport { PaginatedResponseDto } from '@src/libs/api/paginated.response.base';\nimport { UserResponseDto } from './user.response.dto';\n\nexport class UserPaginatedResponseDto extends PaginatedResponseDto<UserResponseDto> {\n  @ApiProperty({ type: UserResponseDto, isArray: true })\n  readonly data: readonly UserResponseDto[];\n}\n"
  },
  {
    "path": "src/modules/user/dtos/user.response.dto.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport { ResponseBase } from '@libs/api/response.base';\n\nexport class UserResponseDto extends ResponseBase {\n  @ApiProperty({\n    example: 'joh-doe@gmail.com',\n    description: \"User's email address\",\n  })\n  email: string;\n\n  @ApiProperty({\n    example: 'France',\n    description: \"User's country of residence\",\n  })\n  country: string;\n\n  @ApiProperty({\n    example: '123456',\n    description: 'Postal code',\n  })\n  postalCode: string;\n\n  @ApiProperty({\n    example: 'Park Avenue',\n    description: 'Street where the user is registered',\n  })\n  street: string;\n}\n"
  },
  {
    "path": "src/modules/user/queries/find-users/find-users.graphql-resolver.ts",
    "content": "import { QueryBus } from '@nestjs/cqrs';\nimport { Args, Query, Resolver } from '@nestjs/graphql';\nimport { Result } from 'oxide.ts';\nimport { ResponseBase } from '../../../../libs/api/response.base';\nimport { Paginated } from '../../../../libs/ddd';\nimport { PaginatedParams } from '../../../../libs/ddd/query.base';\nimport { UserModel } from '../../database/user.repository';\nimport { UserPaginatedGraphqlResponseDto } from '../../dtos/graphql/user.paginated-gql-response.dto';\nimport { FindUsersQuery } from './find-users.query-handler';\n\n@Resolver()\nexport class FindUsersGraphqlResolver {\n  constructor(private readonly queryBus: QueryBus) {}\n  @Query(() => UserPaginatedGraphqlResponseDto)\n  async findUsers(\n    @Args('options', { type: () => String })\n    options: PaginatedParams<FindUsersQuery>,\n  ): Promise<UserPaginatedGraphqlResponseDto> {\n    const query = new FindUsersQuery(options);\n    const result: Result<\n      Paginated<UserModel>,\n      Error\n    > = await this.queryBus.execute(query);\n\n    const paginated = result.unwrap();\n    const response = new UserPaginatedGraphqlResponseDto({\n      ...paginated,\n      data: paginated.data.map((user) => ({\n        ...new ResponseBase(user),\n        email: user.email,\n        country: user.country,\n        street: user.street,\n        postalCode: user.postalCode,\n      })),\n    });\n    return response;\n  }\n}\n"
  },
  {
    "path": "src/modules/user/queries/find-users/find-users.http.controller.ts",
    "content": "import { Body, Controller, Get, HttpStatus, Query } from '@nestjs/common';\nimport { routesV1 } from '@config/app.routes';\nimport { QueryBus } from '@nestjs/cqrs';\nimport { ApiOperation, ApiResponse } from '@nestjs/swagger';\nimport { Result } from 'oxide.ts';\nimport { FindUsersRequestDto } from './find-users.request.dto';\nimport { FindUsersQuery } from './find-users.query-handler';\nimport { Paginated } from '@src/libs/ddd';\nimport { UserPaginatedResponseDto } from '../../dtos/user.paginated.response.dto';\nimport { PaginatedQueryRequestDto } from '@src/libs/api/paginated-query.request.dto';\nimport { UserModel } from '../../database/user.repository';\nimport { ResponseBase } from '@src/libs/api/response.base';\n\n@Controller(routesV1.version)\nexport class FindUsersHttpController {\n  constructor(private readonly queryBus: QueryBus) {}\n\n  @Get(routesV1.user.root)\n  @ApiOperation({ summary: 'Find users' })\n  @ApiResponse({\n    status: HttpStatus.OK,\n    type: UserPaginatedResponseDto,\n  })\n  async findUsers(\n    @Body() request: FindUsersRequestDto,\n    @Query() queryParams: PaginatedQueryRequestDto,\n  ): Promise<UserPaginatedResponseDto> {\n    const query = new FindUsersQuery({\n      ...request,\n      limit: queryParams?.limit,\n      page: queryParams?.page,\n    });\n    const result: Result<\n      Paginated<UserModel>,\n      Error\n    > = await this.queryBus.execute(query);\n\n    const paginated = result.unwrap();\n\n    // Whitelisting returned properties\n    return new UserPaginatedResponseDto({\n      ...paginated,\n      data: paginated.data.map((user) => ({\n        ...new ResponseBase(user),\n        email: user.email,\n        country: user.country,\n        street: user.street,\n        postalCode: user.postalCode,\n      })),\n    });\n  }\n}\n"
  },
  {
    "path": "src/modules/user/queries/find-users/find-users.query-handler.ts",
    "content": "import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';\nimport { Ok, Result } from 'oxide.ts';\nimport { PaginatedParams, PaginatedQueryBase } from '@libs/ddd/query.base';\nimport { Paginated } from '@src/libs/ddd';\nimport { InjectPool } from 'nestjs-slonik';\nimport { DatabasePool, sql } from 'slonik';\nimport { UserModel, userSchema } from '../../database/user.repository';\n\nexport class FindUsersQuery extends PaginatedQueryBase {\n  readonly country?: string;\n\n  readonly postalCode?: string;\n\n  readonly street?: string;\n\n  constructor(props: PaginatedParams<FindUsersQuery>) {\n    super(props);\n    this.country = props.country;\n    this.postalCode = props.postalCode;\n    this.street = props.street;\n  }\n}\n\n@QueryHandler(FindUsersQuery)\nexport class FindUsersQueryHandler implements IQueryHandler {\n  constructor(\n    @InjectPool()\n    private readonly pool: DatabasePool,\n  ) {}\n\n  /**\n   * In read model we don't need to execute\n   * any business logic, so we can bypass\n   * domain and repository layers completely\n   * and execute query directly\n   */\n  async execute(\n    query: FindUsersQuery,\n  ): Promise<Result<Paginated<UserModel>, Error>> {\n    /**\n     * Constructing a query with Slonik.\n     * More info: https://contra.com/p/AqZWWoUB-writing-composable-sql-using-java-script\n     */\n    const statement = sql.type(userSchema)`\n         SELECT *\n         FROM users\n         WHERE\n           ${query.country ? sql`country = ${query.country}` : true} AND\n           ${query.street ? sql`street = ${query.street}` : true} AND\n           ${query.postalCode ? sql`\"postalCode\" = ${query.postalCode}` : true}\n         LIMIT ${query.limit}\n         OFFSET ${query.offset}`;\n\n    const records = await this.pool.query(statement);\n\n    return Ok(\n      new Paginated({\n        data: records.rows,\n        count: records.rowCount,\n        limit: query.limit,\n        page: query.page,\n      }),\n    );\n  }\n}\n"
  },
  {
    "path": "src/modules/user/queries/find-users/find-users.request.dto.ts",
    "content": "import { ApiProperty } from '@nestjs/swagger';\nimport {\n  MaxLength,\n  IsString,\n  IsAlphanumeric,\n  Matches,\n  IsOptional,\n} from 'class-validator';\n\nexport class FindUsersRequestDto {\n  @ApiProperty({ example: 'France', description: 'Country of residence' })\n  @IsOptional()\n  @MaxLength(50)\n  @IsString()\n  @Matches(/^[a-zA-Z ]*$/)\n  readonly country?: string;\n\n  @ApiProperty({ example: '28566', description: 'Postal code' })\n  @IsOptional()\n  @MaxLength(10)\n  @IsAlphanumeric()\n  readonly postalCode?: string;\n\n  @ApiProperty({ example: 'Grande Rue', description: 'Street' })\n  @IsOptional()\n  @MaxLength(50)\n  @Matches(/^[a-zA-Z ]*$/)\n  readonly street?: string;\n}\n"
  },
  {
    "path": "src/modules/user/user.di-tokens.ts",
    "content": "// Tokens used for Dependency Injection\n\nexport const USER_REPOSITORY = Symbol('USER_REPOSITORY');\n"
  },
  {
    "path": "src/modules/user/user.mapper.ts",
    "content": "import { Mapper } from '@libs/ddd';\nimport { UserModel, userSchema } from './database/user.repository';\nimport { Address } from './domain/value-objects/address.value-object';\nimport { UserEntity } from './domain/user.entity';\nimport { UserResponseDto } from './dtos/user.response.dto';\nimport { Injectable } from '@nestjs/common';\n\n/**\n * Mapper constructs objects that are used in different layers:\n * Record is an object that is stored in a database,\n * Entity is an object that is used in application domain layer,\n * and a ResponseDTO is an object returned to a user (usually as json).\n */\n\n@Injectable()\nexport class UserMapper\n  implements Mapper<UserEntity, UserModel, UserResponseDto>\n{\n  toPersistence(entity: UserEntity): UserModel {\n    const copy = entity.getProps();\n    const record: UserModel = {\n      id: copy.id,\n      createdAt: copy.createdAt,\n      updatedAt: copy.updatedAt,\n      email: copy.email,\n      country: copy.address.country,\n      postalCode: copy.address.postalCode,\n      street: copy.address.street,\n      role: copy.role,\n    };\n    return userSchema.parse(record);\n  }\n\n  toDomain(record: UserModel): UserEntity {\n    const entity = new UserEntity({\n      id: record.id,\n      createdAt: new Date(record.createdAt),\n      updatedAt: new Date(record.updatedAt),\n      props: {\n        email: record.email,\n        role: record.role,\n        address: new Address({\n          street: record.street,\n          postalCode: record.postalCode,\n          country: record.country,\n        }),\n      },\n    });\n    return entity;\n  }\n\n  toResponse(entity: UserEntity): UserResponseDto {\n    const props = entity.getProps();\n    const response = new UserResponseDto(entity);\n    response.email = props.email;\n    response.country = props.address.country;\n    response.postalCode = props.address.postalCode;\n    response.street = props.address.street;\n    return response;\n  }\n\n  /* ^ Data returned to the user is whitelisted to avoid leaks.\n     If a new property is added, like password or a\n     credit card number, it won't be returned\n     unless you specifically allow this.\n     (avoid blacklisting, which will return everything\n      but blacklisted items, which can lead to a data leak).\n  */\n}\n"
  },
  {
    "path": "src/modules/user/user.module.ts",
    "content": "import { Logger, Module, Provider } from '@nestjs/common';\nimport { UserRepository } from './database/user.repository';\nimport { CreateUserHttpController } from './commands/create-user/create-user.http.controller';\nimport { DeleteUserHttpController } from './commands/delete-user/delete-user.http-controller';\nimport { CreateUserCliController } from './commands/create-user/create-user.cli.controller';\nimport { FindUsersHttpController } from './queries/find-users/find-users.http.controller';\nimport { CreateUserMessageController } from './commands/create-user/create-user.message.controller';\nimport { CreateUserGraphqlResolver } from './commands/create-user/graphql-example/create-user.graphql-resolver';\nimport { CreateUserService } from './commands/create-user/create-user.service';\nimport { DeleteUserService } from './commands/delete-user/delete-user.service';\nimport { FindUsersQueryHandler } from './queries/find-users/find-users.query-handler';\nimport { UserMapper } from './user.mapper';\nimport { CqrsModule } from '@nestjs/cqrs';\nimport { USER_REPOSITORY } from './user.di-tokens';\nimport { FindUsersGraphqlResolver } from './queries/find-users/find-users.graphql-resolver';\n\nconst httpControllers = [\n  CreateUserHttpController,\n  DeleteUserHttpController,\n  FindUsersHttpController,\n];\n\nconst messageControllers = [CreateUserMessageController];\n\nconst cliControllers: Provider[] = [CreateUserCliController];\n\nconst graphqlResolvers: Provider[] = [\n  CreateUserGraphqlResolver,\n  FindUsersGraphqlResolver,\n];\n\nconst commandHandlers: Provider[] = [CreateUserService, DeleteUserService];\n\nconst queryHandlers: Provider[] = [FindUsersQueryHandler];\n\nconst mappers: Provider[] = [UserMapper];\n\nconst repositories: Provider[] = [\n  { provide: USER_REPOSITORY, useClass: UserRepository },\n];\n\n@Module({\n  imports: [CqrsModule],\n  controllers: [...httpControllers, ...messageControllers],\n  providers: [\n    Logger,\n    ...cliControllers,\n    ...repositories,\n    ...graphqlResolvers,\n    ...commandHandlers,\n    ...queryHandlers,\n    ...mappers,\n  ],\n})\nexport class UserModule {}\n"
  },
  {
    "path": "src/modules/wallet/application/event-handlers/create-wallet-when-user-is-created.domain-event-handler.ts",
    "content": "import { UserCreatedDomainEvent } from '@modules/user/domain/events/user-created.domain-event';\nimport { WalletRepositoryPort } from '@modules/wallet/database/wallet.repository.port';\nimport { WalletEntity } from '../../domain/wallet.entity';\nimport { OnEvent } from '@nestjs/event-emitter';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { WALLET_REPOSITORY } from '../../wallet.di-tokens';\n\n@Injectable()\nexport class CreateWalletWhenUserIsCreatedDomainEventHandler {\n  constructor(\n    @Inject(WALLET_REPOSITORY)\n    private readonly walletRepo: WalletRepositoryPort,\n  ) {}\n\n  // Handle a Domain Event by performing changes to other aggregates (inside the same Domain).\n  @OnEvent(UserCreatedDomainEvent.name, { async: true, promisify: true })\n  async handle(event: UserCreatedDomainEvent): Promise<any> {\n    const wallet = WalletEntity.create({\n      userId: event.aggregateId,\n    });\n    return this.walletRepo.insert(wallet);\n  }\n}\n"
  },
  {
    "path": "src/modules/wallet/database/wallet.repository.port.ts",
    "content": "import { RepositoryPort } from '@libs/ddd';\nimport { WalletEntity } from '../domain/wallet.entity';\n\nexport type WalletRepositoryPort = RepositoryPort<WalletEntity>;\n"
  },
  {
    "path": "src/modules/wallet/database/wallet.repository.ts",
    "content": "import { InjectPool } from 'nestjs-slonik';\nimport { DatabasePool } from 'slonik';\nimport { z } from 'zod';\nimport { SqlRepositoryBase } from '@src/libs/db/sql-repository.base';\nimport { WalletRepositoryPort } from './wallet.repository.port';\nimport { WalletEntity } from '../domain/wallet.entity';\nimport { WalletMapper } from '../wallet.mapper';\nimport { Injectable, Logger } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\n\nexport const walletSchema = z.object({\n  id: z.string().min(1).max(255),\n  createdAt: z.preprocess((val: any) => new Date(val), z.date()),\n  updatedAt: z.preprocess((val: any) => new Date(val), z.date()),\n  balance: z.number().min(0).max(9999999),\n  userId: z.string().min(1).max(255),\n});\n\nexport type WalletModel = z.TypeOf<typeof walletSchema>;\n\n@Injectable()\nexport class WalletRepository\n  extends SqlRepositoryBase<WalletEntity, WalletModel>\n  implements WalletRepositoryPort\n{\n  protected tableName = 'wallets';\n\n  protected schema = walletSchema;\n\n  constructor(\n    @InjectPool()\n    pool: DatabasePool,\n    mapper: WalletMapper,\n    eventEmitter: EventEmitter2,\n  ) {\n    super(pool, mapper, eventEmitter, new Logger(WalletRepository.name));\n  }\n}\n"
  },
  {
    "path": "src/modules/wallet/domain/events/wallet-created.domain-event.ts",
    "content": "import { DomainEvent, DomainEventProps } from '@libs/ddd';\n\nexport class WalletCreatedDomainEvent extends DomainEvent {\n  readonly userId: string;\n\n  constructor(props: DomainEventProps<WalletCreatedDomainEvent>) {\n    super(props);\n  }\n}\n"
  },
  {
    "path": "src/modules/wallet/domain/wallet.entity.ts",
    "content": "import { AggregateID, AggregateRoot } from '@libs/ddd';\nimport { ArgumentOutOfRangeException } from '@libs/exceptions';\nimport { Err, Ok, Result } from 'oxide.ts';\nimport { WalletCreatedDomainEvent } from './events/wallet-created.domain-event';\nimport { WalletNotEnoughBalanceError } from './wallet.errors';\nimport { randomUUID } from 'crypto';\n\nexport interface CreateWalletProps {\n  userId: AggregateID;\n}\n\nexport interface WalletProps extends CreateWalletProps {\n  balance: number;\n}\n\nexport class WalletEntity extends AggregateRoot<WalletProps> {\n  protected readonly _id: AggregateID;\n\n  static create(create: CreateWalletProps): WalletEntity {\n    const id = randomUUID();\n    const props: WalletProps = { ...create, balance: 0 };\n    const wallet = new WalletEntity({ id, props });\n\n    wallet.addEvent(\n      new WalletCreatedDomainEvent({ aggregateId: id, userId: create.userId }),\n    );\n\n    return wallet;\n  }\n\n  deposit(amount: number): void {\n    this.props.balance += amount;\n  }\n\n  withdraw(amount: number): Result<null, WalletNotEnoughBalanceError> {\n    if (this.props.balance - amount < 0) {\n      return Err(new WalletNotEnoughBalanceError());\n    }\n    this.props.balance -= amount;\n    return Ok(null);\n  }\n\n  /**\n   * Protects wallet invariant.\n   * This method is executed by a repository\n   * before saving entity in a database.\n   */\n  public validate(): void {\n    if (this.props.balance < 0) {\n      throw new ArgumentOutOfRangeException(\n        'Wallet balance cannot be less than 0',\n      );\n    }\n  }\n}\n"
  },
  {
    "path": "src/modules/wallet/domain/wallet.errors.ts",
    "content": "import { ExceptionBase } from '@libs/exceptions';\n\nexport class WalletNotEnoughBalanceError extends ExceptionBase {\n  static readonly message = 'Wallet has not enough balance';\n\n  public readonly code = 'WALLET.NOT_ENOUGH_BALANCE';\n\n  constructor(metadata?: unknown) {\n    super(WalletNotEnoughBalanceError.message, undefined, metadata);\n  }\n}\n"
  },
  {
    "path": "src/modules/wallet/wallet.di-tokens.ts",
    "content": "export const WALLET_REPOSITORY = Symbol('WALLET_REPOSITORY');\n"
  },
  {
    "path": "src/modules/wallet/wallet.mapper.ts",
    "content": "import { Mapper } from '@libs/ddd';\nimport { Injectable } from '@nestjs/common';\nimport { WalletEntity } from './domain/wallet.entity';\nimport { WalletModel, walletSchema } from './database/wallet.repository';\n\n@Injectable()\nexport class WalletMapper implements Mapper<WalletEntity, WalletModel> {\n  toPersistence(entity: WalletEntity): WalletModel {\n    const copy = entity.getProps();\n    const record: WalletModel = {\n      id: copy.id,\n      createdAt: copy.createdAt,\n      updatedAt: copy.updatedAt,\n      userId: copy.userId,\n      balance: copy.balance,\n    };\n    return walletSchema.parse(record);\n  }\n\n  toDomain(record: WalletModel): WalletEntity {\n    const entity = new WalletEntity({\n      id: record.id,\n      createdAt: record.createdAt,\n      updatedAt: record.updatedAt,\n      props: {\n        userId: record.userId,\n        balance: record.balance,\n      },\n    });\n    return entity;\n  }\n\n  toResponse(): any {\n    throw new Error('Not implemented');\n  }\n}\n"
  },
  {
    "path": "src/modules/wallet/wallet.module.ts",
    "content": "import { Logger, Module, Provider } from '@nestjs/common';\nimport { CreateWalletWhenUserIsCreatedDomainEventHandler } from './application/event-handlers/create-wallet-when-user-is-created.domain-event-handler';\nimport { WalletRepository } from './database/wallet.repository';\nimport { WALLET_REPOSITORY } from './wallet.di-tokens';\nimport { WalletMapper } from './wallet.mapper';\n\nconst eventHandlers: Provider[] = [\n  CreateWalletWhenUserIsCreatedDomainEventHandler,\n];\n\nconst mappers: Provider[] = [WalletMapper];\n\nconst repositories: Provider[] = [\n  { provide: WALLET_REPOSITORY, useClass: WalletRepository },\n];\n\n@Module({\n  imports: [],\n  controllers: [],\n  providers: [Logger, ...eventHandlers, ...mappers, ...repositories],\n})\nexport class WalletModule {}\n"
  },
  {
    "path": "tests/setup/jestGlobalSetup.ts",
    "content": "import { databaseConfig } from '../../src/configs/database.config';\n\nmodule.exports = async (): Promise<void> => {\n  if (!databaseConfig.database.includes('test')) {\n    throw new Error(\n      `Current database name is: ${databaseConfig.database}. Make sure database includes a word \"test\" as prefix or suffix, for example: \"test_db\" or \"db_test\" to avoid writing into a main database.`,\n    );\n  }\n};\n"
  },
  {
    "path": "tests/setup/jestSetupAfterEnv.ts",
    "content": "import { Test, TestingModuleBuilder, TestingModule } from '@nestjs/testing';\nimport { AppModule } from '@src/app.module';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { createPool, DatabasePool } from 'slonik';\nimport * as request from 'supertest';\nimport { postgresConnectionUri } from '@src/configs/database.config';\nimport { ValidationPipe } from '@nestjs/common';\n\n// Setting up test server and utilities\n\nexport class TestServer {\n  constructor(\n    public readonly serverApplication: NestExpressApplication,\n    public readonly testingModule: TestingModule,\n  ) {}\n\n  public static async new(\n    testingModuleBuilder: TestingModuleBuilder,\n  ): Promise<TestServer> {\n    const testingModule: TestingModule = await testingModuleBuilder.compile();\n\n    const app: NestExpressApplication = testingModule.createNestApplication();\n\n    app.useGlobalPipes(\n      new ValidationPipe({ transform: true, whitelist: true }),\n    );\n\n    app.enableShutdownHooks();\n\n    await app.init();\n\n    return new TestServer(app, testingModule);\n  }\n}\n\nlet testServer: TestServer;\nlet pool: DatabasePool;\n\nexport async function generateTestingApplication(): Promise<{\n  testServer: TestServer;\n}> {\n  const testServer = await TestServer.new(\n    Test.createTestingModule({\n      imports: [AppModule],\n    }),\n  );\n\n  return {\n    testServer,\n  };\n}\n\nexport function getTestServer(): TestServer {\n  return testServer;\n}\n\nexport function getConnectionPool(): DatabasePool {\n  return pool;\n}\n\nexport function getHttpServer(): request.SuperTest<request.Test> {\n  const testServer = getTestServer();\n  const httpServer = request(testServer.serverApplication.getHttpServer());\n\n  return httpServer;\n}\n\n// setup\nbeforeAll(async (): Promise<void> => {\n  ({ testServer } = await generateTestingApplication());\n  pool = await createPool(postgresConnectionUri);\n});\n\n// cleanup\nafterAll(async (): Promise<void> => {\n  await pool.end();\n  testServer.serverApplication.close();\n});\n"
  },
  {
    "path": "tests/shared/shared-steps.ts",
    "content": "import { ApiErrorResponse } from '@src/libs/api/api-error.response';\nimport { TestContext } from '@tests/test-utils/TestContext';\nimport { CreateUserTestContext } from '@tests/user/user-shared-steps';\nimport { DefineStepFunction } from 'jest-cucumber';\n\n/**\n * Test steps that can be shared between all tests\n */\n\nexport const iReceiveAnErrorWithStatusCode = (\n  then: DefineStepFunction,\n  ctx: TestContext<CreateUserTestContext>,\n): void => {\n  then(\n    /^I receive an error \"(.*)\" with status code (\\d+)$/,\n    async (errorMessage: string, statusCode: string) => {\n      const apiError = ctx.latestResponse as ApiErrorResponse;\n      expect(apiError.statusCode).toBe(parseInt(statusCode));\n      expect(apiError.error).toBe(errorMessage);\n    },\n  );\n};\n"
  },
  {
    "path": "tests/test-utils/ApiClient.ts",
    "content": "import { routesV1 } from '@src/configs/app.routes';\nimport { IdResponse } from '@src/libs/api/id.response.dto';\nimport { CreateUserRequestDto } from '@src/modules/user/commands/create-user/create-user.request.dto';\nimport { UserPaginatedResponseDto } from '@src/modules/user/dtos/user.paginated.response.dto';\nimport { getHttpServer } from '@tests/setup/jestSetupAfterEnv';\n\nexport class ApiClient {\n  private url = `/${routesV1.version}/${routesV1.user.root}`;\n\n  async createUser(dto: CreateUserRequestDto): Promise<IdResponse> {\n    const response = await getHttpServer().post(this.url).send(dto);\n    return response.body;\n  }\n\n  async deleteUser(id: string): Promise<void> {\n    const response = await getHttpServer().delete(`${this.url}/${id}`);\n    return response.body;\n  }\n\n  async findAllUsers(): Promise<UserPaginatedResponseDto> {\n    const response = await getHttpServer().get(this.url);\n    return response.body;\n  }\n}\n"
  },
  {
    "path": "tests/test-utils/TestContext.ts",
    "content": "/**\n * Used for setting a context data in cucumber tests\n */\nexport class TestContext<Context> {\n  context: Context; // test specific context\n  latestResponse: unknown; // get a latest response\n  latestRequestDto: unknown; // set a request dto to send\n\n  constructor() {\n    this.context = {} as any;\n  }\n}\n"
  },
  {
    "path": "tests/test-utils/mocks/generic-model-props.mock.ts",
    "content": "export const dateMock = new Date('2020-08-07T12:29:11.214Z');\n\nexport const createdAtUpdatedAtMock = {\n  createdAt: dateMock,\n  updatedAt: dateMock,\n};\n"
  },
  {
    "path": "tests/test-utils/snapshot-base-props.ts",
    "content": "export const snapshotBaseProps = {\n  id: expect.any(String),\n  createdAt: expect.any(String),\n  updatedAt: expect.any(String),\n};\n"
  },
  {
    "path": "tests/user/create-user/create-user.artillery.yaml",
    "content": "# Load testing with Artillery.\n# Can also be good for seeding database with lots of dummy data.\n# https://github.com/Sairyss/backend-best-practices#load-testing\n# https://www.npmjs.com/package/artillery\n# https://www.npmjs.com/package/artillery-plugin-faker\nconfig:\n  target: http://localhost:3000/v1\n  phases:\n    - duration: 2\n      arrivalRate: 150\n  plugins:\n    faker:\n      locale: en\n  variables:\n    email: '$faker.internet.email'\n    country: '$faker.address.country'\n    street: '$faker.address.streetName'\nscenarios:\n  - flow:\n      - post:\n          url: '/users'\n          json:\n            email: '{{ email }}'\n            country: '{{ country }}'\n            postalCode: '12345'\n            street: '{{ street }}'\n"
  },
  {
    "path": "tests/user/create-user/create-user.e2e-spec.ts",
    "content": "import { defineFeature, loadFeature } from 'jest-cucumber';\nimport { getConnectionPool } from '../../setup/jestSetupAfterEnv';\nimport { UserResponseDto } from '@modules/user/dtos/user.response.dto';\nimport { DatabasePool, sql } from 'slonik';\nimport { TestContext } from '@tests/test-utils/TestContext';\nimport { IdResponse } from '@src/libs/api/id.response.dto';\nimport {\n  CreateUserTestContext,\n  givenUserProfileData,\n  iSendARequestToCreateAUser,\n} from '../user-shared-steps';\nimport { ApiClient } from '@tests/test-utils/ApiClient';\nimport { iReceiveAnErrorWithStatusCode } from '@tests/shared/shared-steps';\n\nconst feature = loadFeature('tests/user/create-user/create-user.feature');\n\n/**\n * e2e test implementing a Gherkin feature file\n * https://github.com/Sairyss/backend-best-practices#testing\n */\n\ndefineFeature(feature, (test) => {\n  let pool: DatabasePool;\n  const apiClient = new ApiClient();\n\n  beforeAll(() => {\n    pool = getConnectionPool();\n  });\n\n  afterEach(async () => {\n    await pool.query(sql`TRUNCATE \"users\"`);\n    await pool.query(sql`TRUNCATE \"wallets\"`);\n  });\n\n  test('I can create a user', ({ given, when, then, and }) => {\n    const ctx = new TestContext<CreateUserTestContext>();\n\n    givenUserProfileData(given, ctx);\n\n    iSendARequestToCreateAUser(when, ctx);\n\n    then('I receive my user ID', () => {\n      const response = ctx.latestResponse as IdResponse;\n      expect(typeof response.id).toBe('string');\n    });\n\n    and('I can see my user in a list of all users', async () => {\n      const res = await apiClient.findAllUsers();\n      const response = ctx.latestResponse as IdResponse;\n\n      expect(\n        res.data.some((item: UserResponseDto) => item.id === response.id),\n      ).toBe(true);\n    });\n  });\n\n  test('I try to create a user with invalid data', ({ given, when, then }) => {\n    const ctx = new TestContext<CreateUserTestContext>();\n\n    givenUserProfileData(given, ctx);\n\n    iSendARequestToCreateAUser(when, ctx);\n\n    iReceiveAnErrorWithStatusCode(then, ctx);\n  });\n});\n"
  },
  {
    "path": "tests/user/create-user/create-user.feature",
    "content": "# This is a Gherkin feature file https://cucumber.io/docs/gherkin/reference/\n\nFeature: Create a user\n\n    Scenario: I can create a user\n        Given user profile data\n            | email              | country | street      | postalCode |\n            | john.doe@gmail.com | England | Road Avenue | 29145      |\n        When I send a request to create a user\n        Then I receive my user ID\n        And I can see my user in a list of all users\n\n    Scenario Outline: I try to create a user with invalid data\n        Given user profile data\n            | email   | country   | street   | postalCode   |\n            | <Email> | <Country> | <Street> | <PostalCode> |\n        When I send a request to create a user\n        Then I receive an error \"Bad Request\" with status code 400\n\n        Examples:\n            | Email          | Country | Street      | PostalCode |\n            | johngmail.com  | England | Road Avenue | 29145      |\n            | john@gmail.com | 123     | Road Avenue | 29145      |\n            | johng@mail.com | England | 123         | 29145      |\n            | johng@mail.com | England | Road Avenue | @          |\n            | #@!$           | $#@1    | %542        | !321       |"
  },
  {
    "path": "tests/user/delete-user/delete-user.e2e-spec.ts",
    "content": "import { UserResponseDto } from '@modules/user/dtos/user.response.dto';\nimport { IdResponse } from '@src/libs/api/id.response.dto';\nimport { defineFeature, loadFeature } from 'jest-cucumber';\nimport { DatabasePool, sql } from 'slonik';\nimport { TestContext } from '@tests/test-utils/TestContext';\nimport { getConnectionPool } from '../../setup/jestSetupAfterEnv';\nimport {\n  CreateUserTestContext,\n  givenUserProfileData,\n  iSendARequestToCreateAUser,\n} from '../user-shared-steps';\nimport { ApiClient } from '@tests/test-utils/ApiClient';\n\nconst feature = loadFeature('tests/user/delete-user/delete-user.feature');\n\ndefineFeature(feature, (test) => {\n  let pool: DatabasePool;\n  const apiClient = new ApiClient();\n\n  beforeAll(() => {\n    pool = getConnectionPool();\n  });\n\n  afterEach(async () => {\n    await pool.query(sql`TRUNCATE \"users\"`);\n    await pool.query(sql`TRUNCATE \"wallets\"`);\n  });\n\n  test('I can delete a user', ({ given, when, then, and }) => {\n    const ctx = new TestContext<CreateUserTestContext>();\n\n    givenUserProfileData(given, ctx);\n\n    iSendARequestToCreateAUser(when, ctx);\n\n    then('I send a request to delete my user', async () => {\n      const response = ctx.latestResponse as IdResponse;\n      await apiClient.deleteUser(response.id);\n    });\n\n    and('I cannot see my user in a list of all users', async () => {\n      const res = await apiClient.findAllUsers();\n      const response = ctx.latestResponse as IdResponse;\n      expect(\n        res.data.some((item: UserResponseDto) => item.id === response.id),\n      ).toBe(false);\n    });\n  });\n});\n"
  },
  {
    "path": "tests/user/delete-user/delete-user.feature",
    "content": "Feature: Delete a user\n\n    Background: Existing user\n        Given user profile data\n            | email              | country | street      | postalCode |\n            | john.doe@gmail.com | England | Road Avenue | 29145      |\n        When I send a request to create a user\n\n    Scenario: I can delete a user\n        Given I send a request to delete my user\n        Then I cannot see my user in a list of all users\n"
  },
  {
    "path": "tests/user/user-shared-steps.ts",
    "content": "import { Mutable } from '@src/libs/types';\nimport { CreateUserRequestDto } from '@src/modules/user/commands/create-user/create-user.request.dto';\nimport { DefineStepFunction } from 'jest-cucumber';\nimport { TestContext } from 'tests/test-utils/TestContext';\nimport { ApiClient } from '@tests/test-utils/ApiClient';\n\n/**\n * Test steps that are shared between multiple user tests\n */\n\nexport type CreateUserTestContext = {\n  createUserDto: Mutable<CreateUserRequestDto>;\n};\n\nexport const givenUserProfileData = (\n  given: DefineStepFunction,\n  ctx: TestContext<CreateUserTestContext>,\n): void => {\n  given(/^user profile data$/, (table: CreateUserRequestDto[]) => {\n    ctx.context.createUserDto = table[0];\n  });\n};\n\nexport const iSendARequestToCreateAUser = (\n  when: DefineStepFunction,\n  ctx: TestContext<CreateUserTestContext>,\n): void => {\n  when('I send a request to create a user', async () => {\n    const response = await new ApiClient().createUser(\n      ctx.context.createUserDto,\n    );\n    ctx.latestResponse = response;\n  });\n};\n"
  },
  {
    "path": "tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"exclude\": [\"node_modules\", \"test\", \"dist\", \"**/*spec.ts\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"removeComments\": true,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strictPropertyInitialization\": false,\n    \"target\": \"es2019\",\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"baseUrl\": \"./\",\n    \"incremental\": true,\n    \"skipLibCheck\": true,\n    \"strictNullChecks\": true,\n    \"noImplicitAny\": false,\n    \"strictBindCallApply\": false,\n    \"forceConsistentCasingInFileNames\": false,\n    \"noFallthroughCasesInSwitch\": false,\n    \"paths\": {\n      \"@src/*\": [\"src/*\"],\n      \"@modules/*\": [\"src/modules/*\"],\n      \"@config/*\": [\"src/configs/*\"],\n      \"@libs/*\": [\"src/libs/*\"],\n      \"@tests/*\": [\"tests/*\"]\n    }\n  }\n}\n"
  }
]