4lessandrodev / rich-domain

A lib to help you create a robust project based on domain driven-design (ddd) principles with typescript and zero dependencies.
https://www.npmjs.com/package/rich-domain
MIT License
122 stars 5 forks source link

Feat/134/testing event emitter #138

Closed 4lessandrodev closed 6 months ago

4lessandrodev commented 6 months ago

[1.21.0] - 2024-04-11

Features Added

Known Issues

Future Considerations

Usage Examples


        import { Aggregate, Ok, Result, Context, EventHandler } from 'rich-domain';

        // ------------------
        // Some Context X

        const contextX = Context.events();

        // Listening global events
        contextX.subscribe('SIGNUP', (arg) => {
            console.log(arg);
        });

        // ------------------
        // User Account as Context Y

        type Props = { name: string };

        class User extends Aggregate<Props>{
            private constructor(props: Props) {
                super(props);
            }

            public static signUp(name: string): User {
                const user = new User({ name });
                // add handler according to business rule
                user.addEvent(new SignUpEvent());
                return user;
            }

            public static create(props: Props): Result<User> {
                return Ok(new User(props));
            }
        }

        const contextY = Context.events();

        class SignUpEvent extends EventHandler<User> {
            constructor() {
                super({ eventName: 'SIGNUP' })
            }

            dispatch(user: User): void {
                // dispatch to global context event manager
                contextY.dispatchEvent(this.params.eventName, user.toObject());
            };
        }

        const user = User.signUp('John Doe');

        // dispatch to call handler
        user.dispatchEvent('SIGNUP');

Acknowledgments

thanks to @mmmoli for contributions and inspirations

mmmoli commented 6 months ago

Buddy, I can take no credit for this. 100% you.