It's like EventEmitter or EventTarget, but RequestTarget :}
import RequestTarget from '@kothique/request-target';
const rt = new RequestTarget;
/* Like EventEmitter.prototype.on */
rt.on('div', (a, b) => {
if (a === b && b === Infinity) {
throw new Error('how dare you?!');
}
return a / b;
});
/* Like EventEmitter.prototype.emit */
const result = rt.request('div', 42, 17);
console.log(`42 / 17 = ${result}`);
try {
rt.request('div', Infinity, Infinity);
} catch (error) {
console.log('Woops!');
}
options.callAllHandlers
boolean?
default: false
Iftrue
, call all handlers even if a result was receivedoptions.getAllResults
boolean?
default: false
Iftrue
, results from all handlers are returned as an array on a request. Also, setting this option astrue
makesoptions.callAllHandlers
true
automaticallyoptions.autoPromiseAll
boolean?
default: true
Iftrue
andoptions.getAllResults
istrue
, automatically appliesPromise.all
to the result ofRequestTarget#request
if there are any promisesoptions.byRequest
object?
The same options, but for specific requests
/* All request handlers will be evaluated except for 'first-response' request. */
const rt = new RequestTarget({
callAllHandlers: true,
byRequest: {
'first-response': { callAllHandlers: false }
}
});
options
object
Global options- Returns:
this
Shallow merge a given options object with global options.
subject
string
Request subjectoptions
object
Request options- Returns:
this
Shallow merge a given options object with the options of the request with a given subject.
Aliases: addRequestHandler
, addHandler
.
subject
string
The name of the requesthandler
(...any) => any
The handler can also return aPromise
- Returns:
this
Add a handler for a given request type. Return this
.
Aliases: removeRequestHandler
, removeHandler
.
subject
string
The name of the requesthandler
(...any) => any
The handler passed toRequestTarget#on
- Returns:
this
Remove a given request type's handler.
Aliases: removeAllRequestHandlers
, removeAllHandlers
.
[subject]
string
The name of the request- Returns:
this
Remove all handlers for a given request subject, or, if subject
is not specified, remove all handlers regardless their request name.
subject
string
The name of the request to sendargs
any[]
Payload to send with the request- Returns:
Promise
Returns the result of the request on success, or throws an error. If there are multiple request handlers, they will be evaluated until the first defined value is returned or an error is thrown (unless options.callAllHandlers
is set to true
). If options.getAllResults
is true
, all results will be returned as an array; also, if options.autoPromiseAll
is true
and there is at least one promise returned from a handler, Promise.all
will be automatically applie to the resulting array. If all handlers return undefined
, or there are no handlers at all, returns undefined
.