Skip to content

abort-previous ​

Whenever a new request starts, the previous in-flight one from the same client is aborted. The search-as-you-type primitive. Being stateful it's client-level; see the Plugins overview for how plugins are applied.

ts
import { 
corgi
} from '@itsy/corgi';
import {
abortPrevious
} from '@itsy/corgi/abort-previous';
const
search
=
corgi
.
create
({
plugins
: [
abortPrevious
()] });
// Each keystroke supersedes the last; the abandoned request rejects with AbortError. async function
onType
(
q
: string) {
try { return await
search
.
get
('/search', {
query
: {
q
} });
} catch (
err
) {
// In typeahead you normally ignore the expected AbortError. } }

How it works ​

  • Tagged ORDER.cancel (the outermost slot), so a superseding call cancels the entire prior chain, including any retries or timeout it had running.
  • The previous call is cut even after its response arrives, while its body is still downloading, so a stale result can't land after a newer one. Read a .raw() Response before starting the next call.
  • Keyless by design: one plugin instance is one logical stream (e.g. one search box). Create separate clients for separate streams.
  • A fresh AbortController is minted per call, so cancellation keeps working indefinitely. Reusing a single controller would leave it "aborted" forever after the first cancel.
  • The caller's own signal is merged in, so your own aborts still work, mid-body too.

Cancel without a newer call ​

When the user moves on (clears the box, presses Escape, picks a result), there's no newer request to supersede the one in flight. Keep the plugin and call its abort():

ts
import { 
corgi
} from '@itsy/corgi';
import {
abortPrevious
} from '@itsy/corgi/abort-previous';
const
previous
=
abortPrevious
();
const
search
=
corgi
.
create
({
plugins
: [
previous
] });
const
pending
=
search
.
get
('/search', {
query
: {
q
: 'corg' } });
previous
.
abort
(); // pending rejects with an AbortError
  • The call rejects as a supersede would: with an AbortError that isAbortError recognises, or with the reason you pass, as with AbortController.abort(reason).
  • It cuts a body still downloading and any retries the call still had queued. A call that has finished is left alone, and with nothing in flight it does nothing.
  • The next call goes through as usual.
  • One plugin in one client is one stream. Put into several clients (an extended child is a separate stream), abort() aborts the newest call among them.

It's stateful, so keep it client-level ​

abortPrevious stores the current request in a closure created when the client's pipeline is built. That's why it must live at the client level:

ts
const 
search
=
corgi
.
create
({
plugins
: [
abortPrevious
(),
withTimeout
(5000)] });

On the server

Because it holds state, build the client per request on a server. Never share one at module scope, or unrelated requests would cancel each other.

Released under the MIT License.