rjweb-server
Version:
Easy and Robust Way to create a Web Server with Many Easy-to-use Features in NodeJS
108 lines (107 loc) • 2.41 kB
JavaScript
class Reference {
/**
* Create a new reference to use with the server
* @example
* ```
* const controller = new Server({ })
*
* const ref = new Reference('Hello')
*
* controller.path('/', (path) => path
* .ws('/echo', (ws) => ws
* .onConnect((ctr) => {
* ctr.printRef(ref) // Will not emit the current state, only when the ref changes
* })
* .onMessage((ctr) => {
* ref.set(ctr.rawMessage, {
* emit: true // When disabled will not emit the current state to subscribers
* }) // Will automatically end up echoing it because of the subscription & that to all listeners
* })
* )
* )
* ```
* @since 7.2.0
*/
constructor(initialValue) {
this.processDataFn = (v) => v;
this.listeners = [];
this.state = initialValue;
}
/**
* Process data before sending it to listeners
* @example
* ```
* const ref = new Reference('Hello')
*
* ref.processData((data) => {
* return data + ', yes'
* })
*
* ref.set('Nice')
*
* // Will emit 'Nice, yes' to listeners instead of 'Nice'
* ```
*/
processData(callback) {
this.processDataFn = callback;
return this;
}
/**
* Set the State of a Reference
* @example
* ```
* const ref = new Reference('Hello')
*
* ref.set('Moin')
* ref.set((prev) => `${prev}!`)
*
* ref.get() // 'Moin!'
* ```
* @since 7.2.0
*/
set(value, options = {}) {
const emit = options?.emit ?? true;
if (typeof value === "function")
this.state = value(this.state);
else
this.state = value;
if (emit) {
const data = this.processDataFn(this.state);
for (const listener of this.listeners) {
if (listener)
listener(data);
}
}
return this;
}
/**
* Get the Current State of the Reference
* @since 7.2.0
*/
get() {
return this.state;
}
/**
* Listen for Changes (when actually emitted)
* @since 7.2.0
*/
onChange(listener) {
this.listeners.push(listener);
return {
index: listener
};
}
/**
* Remove a Listener by index
* @since 7.2.0
*/
removeOnChange(listener) {
const index = this.listeners.findIndex((l) => Object.is(l, listener));
if (index !== -1)
this.listeners.splice(index, 1);
return this;
}
}
export {
Reference as default
};