Class RequestResponseMatch<TRequest, TResp>

Matches responses with requests, expiring requests if they do not get a response in a timely manner.

Basic usage:

const m = new RequestResponseMatch(options);
// Listen for when a response matches a request
m.addEventListener(`match`, event => {
// event: { request:Req, response:Resp}
});
// Or alternatively, listen for success and failures
m.addEventListener(`completed`, event => {
// { request:Resp, response:Req|undefined, success:boolean }
// 'response' will be data or a string error message
});
m.request(req); // Note that some request was sent
...
m.response(resp); // Call when a response is received

It's also possible to wait for specific replies:

// With a promise
const resp = await m.requestAwait(req);
// With a callback
m.requestCallback(req, (success, resp) => {
// Runs on success or failure
})

It relies on creating an id of a request/response for them to be matched up. Use the key option if the function can generate a key from either request or response. Or alternatively set both keyRequest and keyResponse for two functions that can generate a key for request and response respectively.

The easy case is if req & resp both have the same field:

const m = new RequestResponseMatch({
key: (reqOrResp) => {
// Requests has an 'id' field
// Response also has an 'id' field that corresponds to the request id
return reqOrResp.id;
}
});

A more complicated case:

const m = new RequestResponseMatch({
keyRequest: (req) => {
// Requests have an 'id' field
return req.id;
},
keyResponse: (resp) => {
// Responses have id under a different field
return resp.reply_to
}
})

By default, error will be thrown if a response is received that doesn't match up to any request.

Type Parameters

  • TRequest
  • TResp

Hierarchy (view full)

Constructors

Properties

keyRequest: ((request: TRequest) => string)
keyResponse: ((resp: TResp) => string)
timeoutMs: number
whenUnmatchedResponse: "throw" | "ignore"

Accessors

  • get isDisposed(): boolean
  • Returns boolean

Methods

  • Returns void

  • Make a request and get the outcome via a Promise

    Parameters

    Returns Promise<TResp>

  • Makes a request with a callback for the outcome

    Parameters

    • request: TRequest
    • callback: ((error: boolean, response: string | TResp) => void)
        • (error, response): void
        • Parameters

          • error: boolean
          • response: string | TResp

          Returns void

    Returns void

  • Make a request and don't wait for the outcome.

    Parameters

    Returns void

  • Response has been received

    Parameters

    • response: TResp

      Response

    • keepAlive: boolean

    Returns boolean

    True if response matched a request