Skip to content

Commit

Permalink
feat: initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
jassix committed Aug 7, 2024
0 parents commit f3c10f4
Show file tree
Hide file tree
Showing 29 changed files with 1,034 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const {
configure,
presets
} = require("eslint-kit");

module.exports = configure({
allowDebug: process.env.NODE_ENV !== "production",

presets: [
presets.imports(),
presets.node(),
presets.prettier(),
presets.typescript()
],
});
6 changes: 6 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# These are supported funding model platforms

github: [jassix]
patreon: jassix
open_collective: jassix
buy_me_a_coffee: jassix
16 changes: 16 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: 2
updates:
# GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix:
# NodeJS
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix:
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.DS_Store

node_modules
.pnpm-debug.log
dist

.vscode
27 changes: 27 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
.git
.github
.gitignore
.prettierrc
.cjs.swcrc
.es.swcrc
.idea
.vscode
bun.lockb

node_modules
tsconfig.json
pnpm-lock.yaml
jest.config.js
nodemon.json

example
tests
test
CHANGELOG.md
.eslintrc.js
tsconfig.cjs.json
tsconfig.esm.json
tsconfig.dts.json

build.ts
src
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"quoteProps": "consistent"
}
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# 1.0.0 - 7 Aug 2024
Release
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Mikita Pitunoŭ

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
141 changes: 141 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# elysia-cqrs
Plugin for [Elysia](https://github.com/elysiajs/elysia) for using [CQRS pattern](https://en.wikipedia.org/wiki/Command_Query_Responsibility_Segregation).

CQRS Plugin for Elysia is a lightweight extension that implements the Command Query Responsibility Segregation pattern into your Elysia-based application. This plugin allows you to effectively separate read and write operations, providing better scalability, maintainability, and testability of your code.

## Installation
```bash
bun add elysia-cqrs
```

## Example

```typescript
// commands/create-user/command.ts (example)
import { ICommand } from 'elysia-cqrs'

class CreateUserCommand extends ICommand {
constructor(public name: string) {
super()
}
}

// commands/create-user/handler.ts (example)
import { ICommandHandler } from 'elysia-cqrs'
import { CreateUserCommand } from './command.ts'

class CreateUserHandler implements ICommandHandler<CreateUserCommand, string> {
execute(command: CreateUserCommand) {
return `New user with name ${command.name} was created!`
}
}

// index.ts (example)
import { Elysia } from 'elysia'
import { cqrs } from 'elysia-cqrs'
import { CreateUserCommand, CreateUserHandler } from '@/commands/create-user'

const app = new Elysia()
.use(cqrs({
commands: [
[CreateUserCommand, new CreateUserHandler()]
]
}))
.post('/user', ({ body: { name }, commandMediator }) => {
return commandMediator.send(new CreateUserCommand(name))
}, {
body: t.Object({
name: t.String(),
})
})
.listen(5000)
```

## API
This plugin decorates `commandMediator`, `eventMediator`, `queryMediator` into `Context`.

### commandMediator
The `commandMediator` implements the `CommandMediator` class with these methods and properties:

```typescript
class CommandMediator extends Mediator {
register<T>(
command: Class<ICommand>,
handler: ICommandHandler<ICommand, T>,
): void

async send<T = never>(command: ICommand): Promise<T>
}
```
###### * this is just a sample, not real code.

***

### eventMediator
The `eventMediator` implements the `EventMediator` class with these methods and properties:

```typescript
class EventMediator extends Mediator {
register(event: Class<IEvent>, handler: IEventHandler<IEvent>): void
send(event: IEvent): void
}
```
###### * this is just a sample, not real code.

***

### queryMediator
The `queryMediator` implements the `QueryMediator` class with these methods and properties:

```typescript
class QueryMediator extends Mediator {
register<T>(
query: Class<IQuery>,
handler: IQueryHandler<IQuery, T>
): void

async send<T = never>(query: IQuery): Promise<T>
}
```
###### * this is just a sample, not real code.

***

### Base Classes
The library features foundational abstract classes like `ICommand`, `IEvent`, and `IQuery`. These are essential for ensuring standardization and polymorphism.

***

### Handler interfaces
The module additionally offers a range of handler interfaces, drawing inspiration from the @nestsjs/cqrs package.

```typescript
interface ICommandHandler<
TCommand extends ICommand = never,
TResponse = never,
> {
execute(command: TCommand): TResponse
}

interface IEventHandler<TEvent extends IEvent = never> {
handle(event: TEvent): void
}

interface IQueryHandler<
TQuery extends IQuery = never,
TResponse = never,
> {
execute(query: TQuery): TResponse
}
```

## Config
Below is the configurable property for customizing the CQRS plugin.

```typescript
interface CqrsPluginParams {
commands?: Array<[Class<ICommand>, ICommandHandler<ICommand, any>]>
events?: Array<[Class<IEvent>, IEventHandler]>
queries?: Array<[Class<IQuery>, IQueryHandler<IQuery, any>]>
}
```
28 changes: 28 additions & 0 deletions build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { build, type Options } from 'tsup'

const tsupConfig: Options = {
entry: ['src/**/*.ts'],
splitting: false,
sourcemap: false,
clean: true,
bundle: true,
} satisfies Options

await Promise.all([
// ? tsup esm
build({
outDir: 'dist',
format: 'esm',
target: 'node20',
cjsInterop: false,
...tsupConfig,
}),
// ? tsup cjs
build({
outDir: 'dist/cjs',
format: 'cjs',
target: 'node20',
// dts: true,
...tsupConfig,
}),
])
Binary file added bun.lockb
Binary file not shown.
95 changes: 95 additions & 0 deletions example/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { describe, expect, it } from 'bun:test'
import { Elysia, t } from 'elysia'
import {
cqrs,
ICommand,
ICommandHandler,
IEvent,
IEventHandler,
IQuery,
IQueryHandler,
} from '../src'

// Command

class CreateUserCommand extends ICommand {
constructor(public name: string) {
super()
}
}

class CreateUserHandler implements ICommandHandler<CreateUserCommand, string> {
execute(command: CreateUserCommand): string {
return `User created "${command.name}"`
}
}

// Query

class ReceiveUserQuery extends IQuery {
constructor(public name: string) {
super()
}
}

class ReceiveUserHandler implements IQueryHandler<ReceiveUserQuery, string> {
execute(query: ReceiveUserQuery): string {
return `Found user with name "${query.name}"`
}
}

// Event

const messageBuffer: string[] = []

class UserRegisteredEvent extends IEvent {
constructor(public name: string) {
super()
}
}

class UserRegisteredHandler implements IEventHandler<UserRegisteredEvent> {
handle(event: UserRegisteredEvent) {
messageBuffer.push(`A new user registered with name "${event.name}"`)
}
}

const app = new Elysia()
.use(
cqrs({
commands: [[CreateUserCommand, new CreateUserHandler()]],
events: [[UserRegisteredEvent, new UserRegisteredHandler()]],
queries: [[ReceiveUserQuery, new ReceiveUserHandler()]],
}),
)
.get(
'/user/:name',
({ params: { name }, queryMediator }) => {
return queryMediator.send(new ReceiveUserQuery(name))
},
{
params: t.Object({
name: t.String(),
}),
},
)
.post(
'/user',
({ body: { name }, query, commandMediator, eventMediator }) => {
if (query.event) {
eventMediator.send(new UserRegisteredEvent(name))
}

return commandMediator.send(new CreateUserCommand(name))
},
{
body: t.Object({
name: t.String(),
}),

query: t.Object({
event: t.Boolean({ default: false }),
}),
},
)
.listen(8080)
Loading

0 comments on commit f3c10f4

Please sign in to comment.