Skip to content

Insert at specific place into collection #4692

Open

Description

@zoriya

Is your feature request related to a problem? Please describe.

Insert into collection in the middle, right now we can only push or unshift into a collection, i'd like to insert at the correct position using a compare function.

For an example of my use case: i have an api that returns a paginated, sorted list of movies and a websocket that sends me new movies created. I want to insert newly created movies in place in the list without invalidating and refetching all the pages.

Describe the solution you'd like

const getMovies = new RestEndpoint({
	path: "/movie",
	searchParams: {} as { sort?: string; filter?: string; query?: string },
	paginationField: "after",
	schema: {
		items: new Collection([Movie], { nonFilterArgumentKeys: ["sort"] }),
		next: "",
	},
});

// from the websocket event
ctrl.set(
	getMovies.schema.items.insert((args) =>
		args.sort?.startsWith("random") ? undefined : compareMovies(args.sort),
	),
	{},
	[movie],
);

const compareMovies = (sort = "name") => {
	const desc = sort.startsWith("-");
	const key = sort.replace(/^-/, "") as keyof Movie;
	return (a: Movie, b: Movie) => {
		const x = a[key] ?? null;
		const y = b[key] ?? null;
		if (x === y) return 0;
		if (x === null) return 1;
		if (y === null) return -1;
		const cmp = x < y ? -1 : x > y ? 1 : 0;
		return desc ? -cmp : cmp;
	};
};

This allows inserting at the correct position without having client-side sorting the rest of the time. It would also be great if this function could skip inserting if the new item was past the end of the page. It could be done implicitly via the previous proposed api or explicitly through an api like this:

getMovies.schema.items.insert((args, { hasMore }) => ({
	compare: compareMovies(args.sort),
	atEnd: hasMore ? "skip" : "insert",
}));

Describe alternatives you've considered

Use client-side sorting but this means:

  • we sort even when not needed since the api already sorts for us, i'd rather keep api order by default
  • it doesn't handle pagination so if we add an item before it's page is loaded we have duplicated items in the list
  • i'm not even sure we can use Query with a paginated collection

Additional context
Add any other context or screenshots about the feature request here.

Activity

  1. added
    enhancement
    on Nov 15, 2026
  2. ntucker commented on Nov 16, 2026

    @ntucker
    Collaborator

    Thanks for the report. Will have a new feature for this by EOW

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions