Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/events/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2018. All Rights Reserved.
Node module: @loopback/events
This project is licensed under the MIT License, full text below.

--------

MIT license

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.
40 changes: 40 additions & 0 deletions packages/events/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# @loopback/events

This module contains utilities to help developers implement the observer
pattern.

## Basic Use

### Subscribe to an event source and type

```ts
const registry: ObservableRegistry = ...;
const source = ...;

const observer = ...;
registry.subscribe(source, 'start', observer);
```

## Installation

```sh
npm install --save @loopback/events
```

## Contributions

- [Guidelines](https://github.com/strongloop/loopback-next/blob/master/docs/CONTRIBUTING.md)
- [Join the team](https://github.com/strongloop/loopback-next/issues/110)

## Tests

Run `npm test` from the root folder.

## Contributors

See
[all contributors](https://github.com/strongloop/loopback-next/graphs/contributors).

## License

MIT
11 changes: 11 additions & 0 deletions packages/events/docs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"content": [
"index.ts",
"src/decorator-factory.ts",
"src/index.ts",
"src/inspector.ts",
"src/reflect.ts",
"src/types.ts"
],
"codeSectionDepth": 4
}
6 changes: 6 additions & 0 deletions packages/events/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dist';
6 changes: 6 additions & 0 deletions packages/events/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = require('./dist');
8 changes: 8 additions & 0 deletions packages/events/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// DO NOT EDIT THIS FILE
// Add any additional (re)exports to src/index.ts instead.
export * from './src';
51 changes: 51 additions & 0 deletions packages/events/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@loopback/events",
"version": "1.0.0",
"description": "LoopBack's implementation of events pattern",
"engines": {
"node": ">=8.9"
},
"scripts": {
"acceptance": "lb-mocha \"dist/test/acceptance/**/*.js\"",
"build:apidocs": "lb-apidocs",
"build": "lb-tsc es2017 --outDir dist",
"clean": "lb-clean loopback-events*.tgz dist package api-docs",
"pretest": "npm run build",
"test": "lb-mocha \"dist/test/unit/**/*.js\" \"dist/test/acceptance/**/*.js\"",
"unit": "lb-mocha \"dist/test/unit/**/*.js\"",
"verify": "npm pack && tar xf loopback-events*.tgz && tree package && npm run clean"
},
"author": "IBM",
"copyright.owner": "IBM Corp.",
"license": "MIT",
"dependencies": {
"@loopback/metadata": "^1.0.1",
"debug": "^4.0.1",
"p-event": "^2.1.0"
},
"devDependencies": {
"@loopback/build": "^1.0.0",
"@loopback/testlab": "^1.0.0",
"@types/debug": "^0.0.30",
"@types/node": "^10.11.2"
},
"keywords": [
"LoopBack",
"Event"
],
"files": [
"README.md",
"index.js",
"index.d.ts",
"dist/src",
"dist/index*",
"src"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/strongloop/loopback-next.git"
}
}
6 changes: 6 additions & 0 deletions packages/events/src/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './listen';
20 changes: 20 additions & 0 deletions packages/events/src/decorators/listen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {MethodDecoratorFactory} from '@loopback/metadata';

/**
* Decorate a method to listen to certain events.
* For example,
* ```ts
* @listen('start')
* async function onStart() {
* }
* ```
* @param messageTypes
*/
export function listen(...messageTypes: (string | RegExp)[]) {
return MethodDecoratorFactory.createDecorator('events:listen', messageTypes);
}
26 changes: 26 additions & 0 deletions packages/events/src/event-iterator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {EventEmitter} from 'events';
const pEvent = require('p-event');

/**
* Options to create an async event iterator
*/
export type AsyncEventIteratorOptions = {
timeout?: number;
rejectionEvents?: string[];
resolutionEvents?: string[];
multiArgs?: boolean;
filter?: (event: unknown) => boolean;
};

export function createAsyncEventIterator<T>(
eventEmitter: EventEmitter,
eventName: string,
options?: AsyncEventIteratorOptions,
): AsyncIterableIterator<T> {
return pEvent.iterator(eventEmitter, eventName, options);
}
91 changes: 91 additions & 0 deletions packages/events/src/event-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {
AsyncEventEmitter,
ListenerRegistry,
EventName,
Listener,
} from './types';
import {DefaultListenerRegistry} from './listener-registry';

/**
* A class constructor accepting arbitrary arguments.
*/
export type Constructor<T> =
// tslint:disable-next-line:no-any
new (...args: any[]) => T;

export function EventSourceMixin<C extends Constructor<object>>(superClass: C) {
return class extends superClass implements AsyncEventEmitter {
readonly registry: ListenerRegistry = new DefaultListenerRegistry();

// tslint:disable-next-line:no-any
constructor(...args: any[]) {
super(...args);
}

getListeners(eventName: EventName) {
return this.registry.getListeners(this, eventName);
}

subscribe<T>(eventName: EventName<T>, listener: Listener<T>) {
return this.registry.subscribe(this, eventName, listener);
}

once<T>(eventName: EventName<T>, listener: Listener<T>) {
return this.registry.once(this, eventName, listener);
}

unsubscribe<T>(eventName: EventName<T>, listener: Listener<T>) {
return this.registry.unsubscribe(this, eventName, listener);
}

emit<T>(eventName: EventName<T>, event: T) {
return this.registry.emit<T>(this, eventName, event);
}

async notify<T>(eventName: EventName<T>, event: T) {
return this.registry.notify(this, eventName, event);
}
};
}

/**
* Event source
*/
export class EventSource implements AsyncEventEmitter {
protected readonly registry: ListenerRegistry;
protected readonly source: object;

constructor(source?: object, registry?: ListenerRegistry) {
this.source = source || this;
this.registry = registry || new DefaultListenerRegistry();
}

getListeners(eventName: EventName) {
return this.registry.getListeners(this.source, eventName);
}

subscribe<T>(eventName: EventName<T>, listener: Listener<T>) {
return this.registry.subscribe(this.source, eventName, listener);
}

once<T>(eventName: EventName<T>, listener: Listener<T>) {
return this.registry.once(this.source, eventName, listener);
}

unsubscribe<T>(eventName: EventName<T>, listener: Listener<T>) {
return this.registry.unsubscribe(this.source, eventName, listener);
}

emit<T>(eventName: EventName<T>, event: T) {
return this.registry.emit<T>(this.source, eventName, event);
}

async notify<T>(eventName: EventName<T>, event: T) {
return this.registry.notify(this.source, eventName, event);
}
}
11 changes: 11 additions & 0 deletions packages/events/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './types';
export * from './listener-registry';
export * from './event-source';
export * from './event-iterator';
export * from './listener-adapter';
export * from './decorators';
65 changes: 65 additions & 0 deletions packages/events/src/listener-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/events
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {ListenerFunction} from './types';
import {MetadataInspector} from '@loopback/metadata';

/**
* Create a listener function for an object that has methods for corresponding
* events. For example:
* ```ts
* export class MyListener {
* async start() {}
* async stop() {}
* }
* ```
* @param obj
*/
export function asListener<T>(obj: {
[method: string]: unknown;
}): ListenerFunction<T> {
return async (event, eventName) => {
const name = eventName.toString();
for (const m of findListenMethods(obj, name)) {
if (m === 'listen') {
await (obj.listen as Function)(event, eventName);
} else {
await (obj[m] as Function)(event, eventName);
}
}
};
}

function findListenMethods(
obj: {
[method: string]: unknown;
},
eventName: string,
): string[] {
const listenMethods =
MetadataInspector.getAllMethodMetadata<(string | RegExp)[]>(
'events:listen',
obj,
) || {};
const methods = [];
for (const m in listenMethods) {
if (
listenMethods[m].some(e => {
return !!eventName.match(e);
})
) {
methods.push(m);
}
}
if (methods.length === 0) {
if (typeof obj[eventName] === 'function') {
methods.push(eventName);
}
if (typeof obj['listen'] === 'function') {
methods.push('listen');
}
}
return methods;
}
Loading