GithubHelp home page GithubHelp logo

hardyscc / nestjs-cqrs-starter Goto Github PK

View Code? Open in Web Editor NEW
374.0 5.0 53.0 4.78 MB

NestJS CQRS Microservices Starter Project

JavaScript 3.42% TypeScript 96.58%
nestjs typegraphql typeorm federation cqrs ddd eventstore event-sourcing graphql nodejs

nestjs-cqrs-starter's Introduction

NestJS CQRS Microservices Starter

Description

A starter project featuring an advanced microservice pattern with GraphQL, based on Domain-Driven Design (DDD) using the command query responsibility segregation (CQRS) design pattern.

Technologies

Installation

Please use the nest-v7 branch, the master branch still not working properly.

git clone -b nest-v7 https://github.com/hardyscc/nestjs-cqrs-starter.git <Your_Project_Name>
cd <Your_Project_Name>

npm install

Usage

Start MySQL

Start MySQL docker instance.

docker run -d -e "MYSQL_ROOT_PASSWORD=Admin12345" -e "MYSQL_USER=usr" -e "MYSQL_PASSWORD=User12345" -e "MYSQL_DATABASE=development" -e "MYSQL_AUTHENTICATION_PLUGIN=mysql_native_password" -p 3306:3306 --name some-mysql bitnami/mysql:8.0.19

Connect using MySQL docker instance command line.

docker exec -it some-mysql mysql -uroot -p"Admin12345"

Create the Databases for testing

CREATE DATABASE service_user;
GRANT ALL PRIVILEGES ON service_user.* TO 'usr'@'%';

CREATE DATABASE service_account;
GRANT ALL PRIVILEGES ON service_account.* TO 'usr'@'%';
FLUSH PRIVILEGES;

Clean up all data if needed to re-testing again

DELETE FROM service_account.ACCOUNT;
DELETE FROM service_user.USER;

Start EventStore

docker run --name some-eventstore -d -p 2113:2113 -p 1113:1113 eventstore/eventstore:release-5.0.9

Create the Persistent Subscriptions

curl -L -X PUT "http://localhost:2113/subscriptions/%24svc-user/account" \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic YWRtaW46Y2hhbmdlaXQ=" \
  -d "{}"

curl -L -X PUT "http://localhost:2113/subscriptions/%24svc-account/user" \
  -H "Content-Type: application/json" \
  -H "Authorization: Basic YWRtaW46Y2hhbmdlaXQ=" \
  -d "{}"

Start the microservices

# Start the user service
nest start service-user

# Start the account service
nest start service-account

# start the gateway
nest start gateway

Testing

Goto GraphQL Playground - http://localhost:3000/graphql

Create a user with a default saving account

mutation {
  createUser(input: { name: "John" }) {
    id
    name
  }
}

OR

curl -X POST -H 'Content-Type: application/json' \
-d '{"query": "mutation { createUser(input: { name: \"John\" }) { id name } }"}' \
http://localhost:3000/graphql

You should see something like this

  1. Under service-user console

    Async CreateUserHandler... CreateUserCommand
    query: START TRANSACTION
    query: INSERT INTO `USER`(`id`, `name`, `nickName`, `status`) VALUES (?, ?, DEFAULT, DEFAULT) -- PARAMETERS: ["4d04689b-ef40-4a08-8a27-6fa420790ddb","John"]
    query: SELECT `User`.`id` AS `User_id`, `User`.`status` AS `User_status` FROM `USER` `User` WHERE `User`.`id` = ? -- PARAMETERS: ["4d04689b-ef40-4a08-8a27-6fa420790ddb"]
    query: COMMIT
    Async ActivateUserHandler... ActivateUserCommand
    query: UPDATE `USER` SET `status` = ? WHERE `id` IN (?) -- PARAMETERS: ["A","4d04689b-ef40-4a08-8a27-6fa420790ddb"]
  2. under service-account console

    Async CreateAccountHandler... CreateAccountCommand
    query: START TRANSACTION
    query: INSERT INTO `ACCOUNT`(`id`, `name`, `balance`, `userId`) VALUES (?, ?, DEFAULT, ?) -- PARAMETERS: ["57c3cc9e-4aa9-4ea8-8c7f-5d4653ee709f","Saving","4d04689b-ef40-4a08-8a27-6fa420790ddb"]
    query: SELECT `Account`.`id` AS `Account_id`, `Account`.`balance` AS `Account_balance` FROM `ACCOUNT` `Account` WHERE `Account`.`id` = ? -- PARAMETERS: ["57c3cc9e-4aa9-4ea8-8c7f-5d4653ee709f"]
    query: COMMIT

Query the users

query {
  users {
    id
    name
    accounts {
      id
      name
      balance
    }
  }
}

OR

curl -X POST -H 'Content-Type: application/json' \
-d '{"query": "query { users { id name accounts { id name balance } } }"}' \
http://localhost:3000/graphql

Output :

{
  "data": {
    "users": [
      {
        "id": "4d04689b-ef40-4a08-8a27-6fa420790ddb",
        "name": "John",
        "accounts": [
          {
            "id": "57c3cc9e-4aa9-4ea8-8c7f-5d4653ee709f",
            "name": "Saving",
            "balance": 0
          }
        ]
      }
    ]
  }
}

nestjs-cqrs-starter's People

Contributors

hardyscc avatar renovate-bot avatar renovate[bot] avatar riuqlav avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nestjs-cqrs-starter's Issues

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/nodejs.yml
  • actions/checkout v3
  • actions/setup-node v3
npm
package.json
  • @juicycleff/nestjs-event-store 3.1.18
  • @nestjs/common 8.4.7
  • @nestjs/core 8.4.7
  • @nestjs/cqrs 8.0.5
  • @nestjs/graphql 9.1.2
  • @nestjs/platform-express 8.4.7
  • @nestjs/typeorm 8.1.4
  • apollo-server-core 3.9.0
  • apollo-server-express 3.9.0
  • graphql 16.5.0
  • graphql-tools 8.2.12
  • mysql 2.18.1
  • node-eventstore-client 0.2.18
  • node-nats-streaming 0.3.2
  • reflect-metadata 0.1.13
  • rimraf 3.0.2
  • rxjs 7.5.5
  • type-graphql 1.1.1
  • typeorm 0.2.45
  • @commitlint/cli 17.0.2
  • @commitlint/config-conventional 17.0.2
  • @nestjs/cli 8.2.6
  • @nestjs/schematics 8.0.11
  • @nestjs/testing 8.4.7
  • @types/express 4.17.13
  • @types/jest 28.1.2
  • @types/node 16.11.41
  • @types/supertest 2.0.12
  • @typescript-eslint/eslint-plugin 5.29.0
  • @typescript-eslint/parser 5.29.0
  • eslint 8.18.0
  • eslint-config-prettier 8.5.0
  • eslint-plugin-import 2.26.0
  • husky 8.0.1
  • jest 28.1.1
  • lint-staged 13.0.2
  • prettier 2.7.1
  • supertest 6.2.3
  • ts-jest 28.0.5
  • ts-loader 9.3.0
  • ts-node 10.8.1
  • tsconfig-paths 4.0.0
  • typescript 4.7.4

  • Check this box to trigger a request for Renovate to run again on this repository

How to replay events?

Hi, first of all, nice repository. I've been studying Event Sourcing in the last couple weeks and this is one of the finest example I've seen so far.

However, I'm wondering, is it possible to replay events?

Let's say that I change the projection structure and want to update my states to fit it, how should I proceed?

serious problem !

hello,

I encounter this error when executing the project :

[Nest] 22613  - 07/25/2021, 4:34:24 PM     LOG [InstanceLoader] EventStoreModule dependencies initialized +1ms
[Nest] 22613  - 07/25/2021, 4:34:24 PM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the CommandBus (?). Please make sure that the argument ModuleRef at index [0] is available in the CqrsModule context.

Potential solutions:
- If ModuleRef is a provider, is it part of the current CqrsModule?
- If ModuleRef is exported from a separate @Module, is that module imported within CqrsModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })

Error: Nest can't resolve dependencies of the CommandBus (?). Please make sure that the argument ModuleRef at index [0] is available in the CqrsModule context.

Potential solutions:
- If ModuleRef is a provider, is it part of the current CqrsModule?
- If ModuleRef is exported from a separate @Module, is that module imported within CqrsModule?
  @Module({
    imports: [ /* the Module containing ModuleRef */ ]
  })

    at Injector.lookupComponentInParentModules (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/injector.js:189:19)
    at Injector.resolveComponentInstance (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/injector.js:145:33)
    at resolveParam (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/injector.js:99:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/injector.js:114:27)
    at Injector.loadInstance (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/injector.js:47:9)
    at Injector.loadProvider (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/injector.js:69:9)
    at async Promise.all (index 3)
    at InstanceLoader.createInstancesOfProviders (/home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/instance-loader.js:44:9)
    at /home/pedram/my-project/github-samples/nestjs-cqrs-starter/node_modules/@nestjs/core/injector/instance-loader.js:29:13

package.json :

{
  "name": "product-service",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "listen": "nest start --watch --config listener.json",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@akanass/nestjsx-crypto": "^2.0.0",
    "@juicycleff/nestjs-event-store": "^3.1.18",
    "@nestjs/common": "^8.0.4",
    "@nestjs/core": "^8.0.4",
    "@nestjs/cqrs": "^8.0.0",
    "@nestjs/microservices": "^8.0.4",
    "@nestjs/mongoose": "^8.0.0",
    "@nestjs/platform-express": "^8.0.4",
    "amqp-connection-manager": "^3.2.2",
    "amqplib": "^0.8.0",
    "class-validator": "^0.13.1",
    "mongoose": "^5.13.3",
    "nestjs-console": "^6.0.0",
    "node-eventstore-client": "^0.2.18",
    "node-nats-streaming": "^0.3.2",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.6.0",
    "@nestjs/schematics": "^7.3.0",
    "@nestjs/testing": "^7.6.15",
    "@types/express": "^4.17.11",
    "@types/jest": "^26.0.22",
    "@types/node": "^14.14.36",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.19.0",
    "@typescript-eslint/parser": "^4.19.0",
    "eslint": "^7.22.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "jest": "^26.6.3",
    "prettier": "^2.2.1",
    "supertest": "^6.1.3",
    "ts-jest": "^26.5.4",
    "ts-loader": "^8.0.18",
    "ts-node": "^9.1.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.2.3"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

my app.module.ts :

import { CqrsModule } from '@nestjs/cqrs';
import { ProductModule } from './product/product.module';
import { Module } from '@nestjs/common';
import { EventStoreModule } from '@juicycleff/nestjs-event-store';
@Module({
  imports: [
    CqrsModule,

    EventStoreModule.register({
      type: 'event-store',
      tcpEndpoint: {
        host: 'localhost',
        port: 1113,
      },
      options: {
        defaultUserCredentials: {
          username: 'admin',
          password: 'changeit',
        },
      },
    }),
    ProductModule,
  ],
})
export class AppModule {}

my product.module.ts :

import { Module } from '@nestjs/common';
import { ProductController } from './controllers/products.controller';
import { ProductRepository } from './repository/product.repository';
import { ProductService } from './services/products.service';
import { ProductsSagas } from './sagas/products.sagas';
import { CommandHandlers } from './commands/handlers';
import { EventHandlers } from './events/handlers';
import { ProductCreatedEvent } from './events/impl/product-created.event';
import { CqrsModule } from '@nestjs/cqrs';
import {
  EventStoreModule,
  EventStoreSubscriptionType,
} from '@juicycleff/nestjs-event-store';


@Module({
  imports: [
    CqrsModule,
    EventStoreModule.registerFeature({
      type: 'event-store',
      featureStreamName: '$svc-product',
      subscriptions: [
        {
          type: EventStoreSubscriptionType.Persistent,
          stream: '$svc-product',
          persistentSubscriptionName: 'product',
        },
      ],
      eventHandlers: {
        ProductCreatedEvent: (data) => new ProductCreatedEvent(data),
      },
    }),
  ],
  controllers: [ProductController],
  providers: [
    ProductService,
    ProductRepository,
    ProductsSagas,
    ...CommandHandlers,
    ...EventHandlers,
  ],
})
export class ProductModule {}

Graphql subscriptions

Really like the efforts you've put into this.

Does this lib support graphql subscriptions? On nestjs docs it says federation does not support subscriptions.

Any ideas how can we achieve subscriptions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.