Giter Club home page Giter Club logo

remesh's Introduction

remesh

English | 中文

npm version Documentation Maintenance License: MIT Twitter: guyingjie129

A CQRS-based DDD framework for large and complex TypeScript/JavaScript applications

Features

  • DDD principles
  • CQRS Architecture
  • Event-driven Architecture
  • Incremental updates
  • Reactive programming
  • Immutable state
  • Type-friendly APIs
  • Framework-agnostic(officially supports React/Vue)
  • SSR support
  • Collaboration support(provides official yjs integration)
  • Time-Travel/Undo/Redo supports(via remesh/modules/history)

Why Remesh?

So, why Remesh? What benefits can it bring to my application?

It depends on whether you will be attracted to the following.

  • Modularity: You don't have to bring all your state together, it can be defined and processed atomically, and aggregated into other derived state with domain.query.

  • High performance: Your component will not be re-rendered by the change of the domain.query it doesn't subscribe to.

  • Maintainability: Remesh provides a set of expressive APIs to maintain your business logic with a uniform code style, enhancing code maintainability.

  • Composability: There is no needed for your pages to have just one domain, you can define as many domains as you need and simply access other domains via domain.getDomain(...). Build your application's business logic in a combinatorial way.

  • Reusability: You can write remesh custom modules like react-hooks to reuse logic across multiple domains.

  • Testability: Your Remesh code is view-independent, so you can test your business logic in a test environment more easily.

  • Predictability: Remesh divides your business logic into pure and effect parts, where the pure parts are pure functions and immutable data, which are safe and predictable and form the core of your business logic. The effect part manages side effects in a combinatorial way through rxjs, so we can easily control the flow of data.

  • Sustainability: Your business logic doesn't tie to the view layer, even if you migrate from one view library to another (e.g. from react to vue), you can still reuse all the remesh code and keep iterating without refactoring or rewriting.

Concepts

A domain is like a component of your application. But not for the UIs, it's for your business logic.

All related things are encapsuled in the domain.

A domain can have as many resources listed in below as you want.

  • Domain States: the state you want to store in the domain.
  • Domain Queries: query states or deriving another query.
  • Domain Commands: update states or emit events or do nothing.
  • Domain Effects: An observable that perform side-effect and send commands or events.
  • Domain Events: identify something happened in the domain.

For any domain, only domain-query, domain-command, domain-event can be exposed to the outside.

domain-state will not be exposed to the outside and can't be touched directly out of the domain.

For the consumers of any domain.

  • The only way to read state is through domain-query for preventing invalid read.

  • The only way to update state is through domain-command for preventing invalid update.

Installation

# Install remesh and rxjs via npm
npm install --save remesh rxjs
# Install remesh and rxjs via yarn
yarn add remesh rxjs

Usage

You can edit it in stackblitz

Define your domain

// domain.ts
import { Remesh } from 'remesh'

import { interval } from 'rxjs'
import { map, switchMap, takeUntil } from 'rxjs/operators'

type ChangeMode = 'increment' | 'decrement'

/**
 * Define your domain model
 */
export const CountDomain = Remesh.domain({
  name: 'CountDomain',
  impl: (domain) => {
    /**
     * Define your domain's related states
     */
    const CountState = domain.state({
      name: 'CountState',
      default: 0,
    })

    /**
     * Define your domain's related events
     */
    const CountChangedEvent = domain.event<number>({
      name: 'CountChangedEvent',
    })

    /**
     * Define your domain's related commands
     */
    const SetCountCommand = domain.command({
      name: 'SetCountCommand',
      impl: ({}, count: number) => {
        /**
         * Update the domain's state and emit the related event
         */
        return [CountState().new(count), CountChangedEvent(count)]
      },
    })

    /**
     * Define your domain's related queries
     */
    const CountQuery = domain.query({
      name: 'CountQuery',
      impl: ({ get }) => {
        /**
         * Get the domain's state
         */
        return get(CountState())
      },
    })

    /**
     * You can use a command in another command
     */
    const IncreaseCountCommand = domain.command({
      name: 'IncreaseCountCommand',
      impl: ({ get }, count: number = 1) => {
        return SetCountCommand(get(CountState()) + count)
      },
    })

    /**
     * You can use a command in another command
     */
    const DecreaseCountCommand = domain.command({
      name: 'DecreaseCountCommand',
      impl: ({ get }, count: number = 1) => {
        return SetCountCommand(get(CountState()) - count)
      },
    })

    const ChangeCountByModeCommand = domain.command({
      name: 'ChangeCountByModeCommand',
      impl: ({}, mode: ChangeMode) => {
        if (mode === 'increment') return IncreaseCountCommand()
        if (mode === 'decrement') return DecreaseCountCommand()
        return null
      },
    })

    /**
     * Define an event for starting increment or decrement periodically
     */
    const StartEvent = domain.event<ChangeMode>({
      name: 'StartEvent',
    })

    /**
     * Define a command to send event since event can't be sended outside of domain
     */
    const StartCommand = domain.command({
      name: 'StartCommand',
      impl: ({}, mode: ChangeMode) => {
        return StartEvent(mode)
      },
    })

    /**
     * Define an event for stopping signal
     */
    const StopEvent = domain.event({
      name: 'StopEvent',
    })

    /**
     * Define a command to send event since event can't be sended outside of domain
     */
    const StopCommand = domain.command({
      name: 'StopCommand',
      impl: () => {
        return StopEvent()
      },
    })

    /**
     * Define your domain's related effects
     */

    domain.effect({
      name: 'ChangeCountEffect',
      impl: ({ fromEvent }) => {
        return fromEvent(StartEvent).pipe(
          switchMap((mode) => {
            return interval(100).pipe(
              map(() => ChangeCountByModeCommand(mode)),
              // finished when received stop event
              takeUntil(fromEvent(StopEvent)),
            )
          }),
        )
      },
    })

    /**
     * Expose domain resources
     */
    return {
      query: {
        CountQuery,
      },
      command: {
        SetCountCommand,
        IncreaseCountCommand,
        DecreaseCountCommand,
        StartCommand,
        StopCommand,
      },
      event: {
        StartEvent,
        StopEvent,
        CountChangedEvent,
      },
    }
  },
})

Using your domain in react component

// index.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'

import * as React from 'react'

import { RemeshRoot, useRemeshDomain, useRemeshQuery, useRemeshSend, useRemeshEvent } from 'remesh-react'

import { CountDomain } from './domain'

export const Counter = () => {
  /**
   * use remesh send for sending commands
   */
  const send = useRemeshSend()

  /**
   * read domain via useRemeshDomain
   */
  const countDomain = useRemeshDomain(CountDomain())

  /**
   * read domain query via useRemeshQuery
   */
  const count = useRemeshQuery(countDomain.query.CountQuery())

  const handleIncrement = () => {
    /**
     * send command to domain
     */
    send(countDomain.command.IncreaseCountCommand())
  }

  const handleDecrement = () => {
    /**
     * send command to domain
     */
    send(countDomain.command.DecreaseCountCommand())
  }

  const handleStartIncrease = () => {
    /**
     * send command to domain
     */
    send(countDomain.command.StartCommand('increment'))
  }

  const handleStartDecrease = () => {
    /**
     * send command to domain
     */
    send(countDomain.command.StartCommand('decrement'))
  }

  const handleStop = () => {
    /**
     * send command to domain
     */
    send(countDomain.command.StopCommand())
  }

  /**
   * listen to the domain event via useRemeshEvent
   */
  useRemeshEvent(countDomain.event.CountChangedEvent, (count) => {
    console.log(count)
  })

  return (
    <div id="container" style={{ textAlign: 'center', fontSize: 28 }}>
      <h1 id="count">{count}</h1>
      <button style={{ height: 40 }} onClick={handleStartIncrease}>
        start increase
      </button> <button style={{ height: 40 }} onClick={handleIncrement}>
        +1
      </button> <button style={{ height: 40 }} onClick={handleStop}>
        stop
      </button> <button style={{ height: 40 }} onClick={handleDecrement}>
        -1
      </button> <button style={{ height: 40 }} onClick={handleStartDecrease}>
        start decrease
      </button>{' '}
    </div>
  )
}

const rootElement = document.getElementById('root')
const root = createRoot(rootElement)

root.render(
  <StrictMode>
    <RemeshRoot>
      <Counter />
    </RemeshRoot>
  </StrictMode>,
)

Packages

Inspiration

  • Domain-Driven-Design inspired the conceptual model
  • CQRS/ES inspired the architecture model
  • Redux inspired the implementation of command model
  • Recoil inspired the implementation of query model
  • Rxjs inspired the implementation of the event model

FAQ

How do I disable the esm module output of remesh?

note: from remesh v4.2, esm is not the default, cjs-first now. You still can import remesh/esm to access esm

remesh v4.0 starts to support esm module output, which may cause errors in your project due to esm/cjs dependencies for now. The solution is to disable the esm module or map it to the corresponding cjs module via bundler configuration.

For example, in webpack, you can configure aliases via resolve.alias to

  • cjs-only: maps remesh to remesh/cjs and remesh-* to remesh-*/cjs
  • esm-only: maps remesh to remesh/esm and remesh-* to remesh-*/esm.

A similar configuration is available in vite resolve.alias

Pull requests are welcome

remesh's People

Contributors

1uckyneo avatar bailnl avatar blurname avatar cijiugechu avatar dependabot[bot] avatar frankxjkuang avatar hanyi-wang-darkstardust avatar lizheming avatar lucifier129 avatar m7yue avatar moonrailgun avatar ninesunsabiu avatar richardo2016 avatar undozen avatar xufei 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

remesh's Issues

组件内部Query和Update一个状态,每次重新打开组件的时候,Query对应的State又被初始化为默认值了

每次打开 TypeGridFilterCmp 组件,值都是 空 '', 请问为什么呀?

import { Remesh } from 'remesh';

export type DataType = '' | 'MTD';

const HeaderFilterDomain = Remesh.domain({
  name: 'HeaderFilterDomain',
  impl: (domain) => {
    const DataTypeState = domain.state<DataType>({
      name: 'DataTypeState',
      default: '',
    });

    const DataTypeQuery = domain.query({
      name: 'DataTypeQuery',
      impl: ({ get }) => {
        return get(DataTypeState());
      },
    });

    const UpdateDataTypeCommand = domain.command({
      name: 'UpdateDataTypeCommand',
      impl: (_, type: DataType) => {
        return DataTypeState().new(type);
      },
    });

    return {
      query: { DataTypeQuery },
      command: { UpdateDataTypeCommand },
      event: {},
    };
  },
});

export default HeaderFilterDomain;
function TypeGridFilterCmp(props: IProps) {
  const { onClick } = props;

  const send = useRemeshSend();
  const headerFilterDomain = useRemeshDomain(HeaderFilter());
  const dataType = useRemeshQuery(headerFilterDomain.query.DataTypeQuery());
  console.log('log: dataType', dataType);
  const updateDataType = (type: DataType) => {
    send(headerFilterDomain.command.UpdateDataTypeCommand(type));
  };

  return (
    <div>
      <Grid columns={1} className="pick-type-grid">
        <Grid.Item>
          <ul>
            <li
              className={dataType === '' ? 'active' : ''}
              onClick={() => {
                updateDataType('');
              }}
            >
              1
              <div className="wait-select-icon" />
            </li>
            <li
              className={dataType === '2' ? 'active' : ''}
              onClick={() => {
                updateDataType('MTD');
              }}
            >
  2
              <div className="wait-select-icon" />
            </li>
          </ul>
        </Grid.Item>
      </Grid>
    </div>
  );
}

remesh4.0.0更新使用react useSyncExternalStore,导致无法正常使用remesh包。

脚手架:create-react-app
package.json

{
  "name": "remesh-demo",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.13",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "remesh": "^4.0.0",
    "remesh-react": "^4.0.0",
    "rxjs": "^7.5.6",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/typescript": "^2.0.0",
    "ts-node": "^10.9.1",
    "typescript": "^4.8.4"
  }
}

错误信息:
image

ListModule 暴露 event 的必要性?

在看 TodoList example 时发现event产生依赖于TodoListModulecommand,但是 command 实现细节是在remesh 内部的,需要使用者确定command确实对list产生了修改,如果ListModule对外暴露ListChangedEvent、ListItemAddedEvent等事件,外部就确定事件已发生可以直接使用。不知道有没有必要呢?如果有必要的话我想尝试提一下pr~
image

StartedEvent effect 依赖于 dom 的挂载, dom 的挂载依赖于 StartedEvent 应该怎么实现呢

场景:
视频通话开启摄像头本地展示并上传摄像头流。

第三方服务:

class CameraShareService {
  public startLocal(dom: HTMLElement): void
}

通过remesh建模如下:

OpenCameraCommand
OpenCameraStartedEvent
OpenCameraSuccessEvent

问题

OpenCameraStartedEvent 事件触发同时修改状态visible渲染摄像头 dom,但是 OpenCameraStartedEvent 的 effect 执行
cameraShareService.startLocal 时依赖这个 dom 引用,此时并不能保证 dom 是否挂载完成,应该怎么样处理比较好呢。

想了一个方法是增加一个摄像头 dom 挂载的 event: CameraDOMMountedEvent(dom),但是似乎不能保证挂载一定会发生在执行 effect 之后?还是说调用 cameraShareService.startLocal 应该放在 CameraDOMMountedEvent effect 中呢

domain.effect({
 impl: ({ fromEvent }) => 
    fromEvent(OpenCameraStartedEvent).pipe(
        switchMap(() => fromEvent(CameraDOMMountedEvent)),
        switchMap(dom => {
          cameraShareService.startLocal(dom)
          return [OpenCameraSuccessEvent()]
        })
    )
})

想问下remesh的domain可以支持继承吗?

比如 定义了一个Domain叫 AnimalDomain, 我想对它进行不同的实现,然后在另外一个ManageDomain中引用AnimalDomain, 根据注入的参数不同,让AnimalDomain呈现为不同的子实现。目前似乎我只能通过引用不同的Domain来实现,或者借助map

Remesh-js 有什么方便的调试工具吗? // Any dev tools available for remesh-js?

一些 react 的状态库有相关的 dev tools,比如:
redux -> redux-devtools
mobx -> mobx-react-devtools
remesh-js 有自己的调试工具吗?或者是有推荐用于调试的 dev tools 吗?

Some libraries are used to manage react status have their dev tools, such as:
redux -> redux-devtools
mobx -> mobx-react-devtools
Do you know if remesh-js has its dev tools? Or any other recommended dev tools to use for debugging?

可以实现多实例吗

当发布一个命令后 所有组件都会同步更新状态 状态是全局唯一的 能否实现多实例 组件不同实例下状态互不影响

event和effect的使用问题

现在有这样一个业务方法

const downloadId = downloader.startDownload(url, {
 onProgress: () => {},
 onFinish: () => {},
 onFailed: () => {},
})
download.cancelDownload(downloadId)

使用remesh定义如下模型
downloadCommand
cancelDownloadCommand
downloadStartedEvent
progressUpdatedEvent
downloadSuccessEvent
downloadFailedEvent

按我的理解 download.startDownload发生发生在downloadStartedEvent的effect,如果下载的过程中发起了cancelDownloadCommand,此时downloadId应该在state里面了但是不清楚什么时机保存的,是应该在effect触发一个额外的事件downloadIdGotEvent吗?

中文文档有误

README_zh_CN.md
特性第5:可变状态
英文版是,immutable state
应该是,不可变状态

remesh如何在vue2.6中使用

请教下,因为老项目升级成本太高,想试试看在vue 2.6下使用remesh,是否可以有demo可以提供呢

Remesh.domain 如何接收泛型

domain.ts

// 示例在 impl 中可以接收泛型 T
export interface MessageSimple {
  id: string
  [key: string]: any
}
export const MessageListDomain = Remesh.domain({
  name: 'MessageListDomain',
  impl:(domain) =>{
    const CreateItemEvent = domain.event<T>({
      name: 'MessageList.CreateItemEvent'
    })

    const CreateItemCommand = domain.command({
      name: 'MessageList.CreateItemCommand',
      impl: (_, message: T) => {
       // ...
        return [CreateItemEvent(message)]
      }
    })
  }
 })

index.ts

import { MessageListDomain } from './domain.ts'

export interface Message {
  id: string
  time: 'xxxx',
  body: 'xxxx'
}

// 如何才能像这样将 Message 传递给 MessageListDomain 中的 T?
const messageListDomain = useRemeshDomain(MessageListDomain<Message>())

一种方式是写成 iife:
domain.ts

export interface MessageSimple {
  id: string
  [key: string]: any
}
export const MessageListDomain = <T extends MessageSimple>()=> Remesh.domain({
  ...
  const CreateItemEvent = domain.event<T>....
})()

index.ts

 const messageListDomain = useRemeshDomain(MessageListDomain<Message>())

如果这样定义,那么在 index.ts 可以传入 Message,但是 Remesh.domain 变成了在外部调用 useRemeshDomain 时初始化,多次调用初始化多次

目前的解决方案是,导出时使用 memoize 缓存 MessageListDomain 执行结果防止重复执行,有更好的方式吗

feat Serializable 支持 readonly

在使用 HistoryModule 时,由于范型 T extends SerializableArray | SerializableObject 导致无法使用

image

由于我项目中是搭配使用了 @effect/schema ,从中推断出来的类型都会带上 readonly 修饰,所以如果 Serializable 能够支持 readonly 的话,应该就可用。

考虑到 readonly 修饰的数据,并不会实际对序列化的实现或者语义造成影响,所以我觉得在库层面进行支持是有理由的。

https://github.com/remesh-js/remesh/blob/7b26fbff56f70c2de8e5398e13e7c4e9d2d3ce15/packages/remesh/src/remesh.ts#L5C1-L13

export type SerializableArray = Serializable[] | ReadonlyArray<Serializable>;
export type SerializableObject = {
    [key: string]: Serializable;
} | {
    readonly [key: string]: Serializable;
};

vue 2.7.14 中 使用remesh-vue报错app.provide为undefined

          ![image](https://user-images.githubusercontent.com/32118686/221463572-ec018256-502f-42ec-96ca-6547573f154a.png)

image
试了下,在remesh-vue中的app.provide是undefined的,这块用法不对吗
因为vue2.7也没有createApp
只能Vue.use(RemeshVue(remeshStore))

如果说直接用provide而不用app.provide,那只能在setup中使用,也没法被绑到app上
这块能给的demo吗,Thanks♪(・ω・)ノ

Originally posted by @FEYeh in #72 (comment)

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.