@openhps/core
Version:
Open Hybrid Positioning System - Core component
91 lines • 3.02 kB
JavaScript
import { __decorate, __metadata } from "tslib";
import { SerializableObject } from '../data/decorators';
import { v4 as uuidv4 } from 'uuid';
import { Node } from '../Node';
import { PushPromise } from '../graph/PushPromise';
/**
* Sink node
*
* ## Usage
*
* ### Creating a SinkNode
* When creating a sink node, you have to implement an ```onPush``` method that provides you with the pushed data frame.
* Sink nodes are the final nodes in the model and have no outlets. Once the onPush is resolved, data objects in that frame
* are stored in a {@link DataObjectService}.
* ```typescript
* import { DataFrame, SinkNode } from '@openhps/core';
*
* export class CustomSink<In extends DataFrame> extends SinkNode<In> {
* // ...
* public onPush(data: In, options?: GraphOptions): Promise<void> {
* return new Promise<void>((resolve, reject) => {
*
* });
* }
* }
* ```
* @category Sink node
*/
let SinkNode = class SinkNode extends Node {
constructor(options) {
super(options);
this.options.completedEvent = this.options['completedEvent'] === undefined ? true : this.options.completedEvent;
this.options.persistence = this.options['persistence'] === undefined ? true : this.options.persistence;
}
push(data, options) {
return new PushPromise((resolve, reject) => {
if (data === null || data === undefined) {
return reject();
}
// Push the frame to the sink node
this.onPush(data, options).then(() => {
const persistPromise = [];
if (data instanceof Array) {
data.forEach(f => {
if (this.options.persistence) {
persistPromise.push(this.persistDataObject(f));
}
});
} else {
if (this.options.persistence) {
persistPromise.push(this.persistDataObject(data));
}
}
return Promise.all(persistPromise);
}).then(() => {
resolve();
// Fire a completed event
if (this.options.completedEvent) {
if (data instanceof Array) {
data.forEach(f => {
this.emit('completed', {
frameUID: f.uid
});
});
} else {
this.emit('completed', {
frameUID: data.uid
});
}
}
}).catch(reject);
});
}
persistDataObject(frame) {
return new Promise((resolve, reject) => {
const servicePromises = [];
const objects = frame.getObjects();
for (const object of objects) {
if (object.uid === null) {
object.uid = uuidv4();
}
// Queue the storage of the object in a data service
const service = this.model.findDataService(object);
servicePromises.push(service.insert(object.uid, object));
}
Promise.all(servicePromises).then(() => resolve()).catch(reject);
});
}
};
SinkNode = __decorate([SerializableObject(), __metadata("design:paramtypes", [Object])], SinkNode);
export { SinkNode };