Skip to content

Latest commit

 

History

History
48 lines (32 loc) · 1.39 KB

File metadata and controls

48 lines (32 loc) · 1.39 KB
title
Event handler

Overview

Event handler — is a simple function that receives event as an argument and performs required logic. Event handlers should be stored in a <name>.handler.ts file at the resource root (e.g. resources/users/users.handler.ts). The handler file must be imported as a side-effect in the resource's index.ts barrel file (e.g. import './users.handler').

Examples

import { eventBus, InMemoryEvent } from '@paralect/node-mongo';

import ioEmitter from 'io-emitter';

import { DATABASE_DOCUMENTS } from 'app-constants';
import { Document } from 'types';

const { DOCUMENTS } = DATABASE_DOCUMENTS;

eventBus.on(`${DOCUMENTS}.created`, (data: InMemoryEvent<Document>) => {
    try {
        const document = data.doc;

        ioEmitter.publishToUser(document.userId, 'document:created', document);
    } catch (error) {
      logger.error(`${DOCUMENTS}.created handler error: ${error}`);
    }
})
import { eventBus, InMemoryEvent } from '@paralect/node-mongo';

import { DATABASE_DOCUMENTS } from 'app-constants';
import { User } from 'types';

const { USERS } = DATABASE_DOCUMENTS;

eventBus.onUpdated(USERS, ['firstName', 'lastName'], (data: InMemoryEvent<User>) => {
    const user = data.doc;
    const fullName = user.lastName ? `${user.firstName} ${user.lastName}` : user.firstName;

    console.log(`User fullName was updated: ${fullName}`)
})