1.0.2 • Published 7 months ago

@manuelflorezw/cqrs v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
7 months ago

CQRS

A simple JavaScript library for implementing the CQRS pattern

  • Command
  • Query

Instalación

npm install @manuelflorezw/cqrs

Clase Command

class Command {
  constructor(command) {
    if (typeof command.execute !== 'function') {
      throw new Error('Invalid function execute')
    }
    this.command = command
  }

  execute(param) {
    return this.command.execute(param)
  }
}

Clase Query

class Query {
  constructor(query) {
    if (typeof query.execute !== 'function') {
      throw new Error('Invalid function execute')
    }
    this.query = query
  }

  execute(params) {
    return this.query.execute(params)
  }
}

Example

    ├── user-repository                     # (commands, queries, models)
    |   ├── commands                        # COMMANDS
    |   |   └── createUserCommand.js        # insert new user
    |   ├── queries                         # QUERIES
    |   |   └── getUserByIdQuery.js         # find user by Id
    |   └── models                          # MODELS
    |       └── model.js                    # Modelo to access database
    └── main.js                             # main.js

model.js

Connection to database

// user-repository/models/model.js
const users = new Map()

export const UserModel = {
  findById: id => users.get(id),
  create: user => {
    const id = users.size
    users.set(id, user)
    return id
  }
}

createUserCommand.js

//user-repository/commands/createUserCommand.js
import { UserModel } from '../models/model.js'

import { Command } from '@manuelflorezw/cqrs'

const execute = user => UserModel.create(user)

export const command = new Command({ execute })

getUserByIdQuery.js

//user-repository/queries/getUserByIdQuery.js
import { UserModel } from '../models/model.js'

import { Query } from '@manuelflorezw/cqrs'

const execute = id => UserModel.findById(id)

export const query = new Query({ execute })

main.js

import { command } from './user-repository/commands/createUserCommand.js'
import { query } from './user-repository/queries/getUserByIdQuery.js'

const id = command.execute({ name: 'Jhon'})

const result = query.execute(id)

console.log(id)
console.log(result)
1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago