Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/pagination-link-total.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@thomasfosterau/effect-jsonapi": minor
---

`Assemble.Pagination` gains `linkTotal` and `lastUnknown`, and `Assemble.edgePage`'s `input` forwards both. `linkTotal` is the total the pagination links (`last`, and whether `next` exists) are computed from, defaulting to `totalCount`; `meta.totalCount` stays `totalCount`. `lastUnknown: true` omits `links.last` (the key is absent, not `null`) while `self` / `first` / `prev` / `next` stay exact. A search with no corpus count passes `linkTotal = offset + page.length + (hasMore ? 1 : 0)` and `lastUnknown: true`. Additive; no published type changes (`LinksValue.last` was already optional). From gardeneria#1263 O8 (#569).
69 changes: 69 additions & 0 deletions src/Assemble.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,75 @@ describe("Assemble.relationship", () => {
});
});

describe("Assemble.collection linkTotal / lastUnknown (#569)", () => {
const page = [person("a"), person("b"), person("c")];
const baseUrl = "https://example.test/people";
const at = (offset: number, extra: { linkTotal?: number; lastUnknown?: boolean }, total = 42) =>
run(Assemble.collection(page, { totalCount: total, offset, limit: 3, baseUrl, ...extra }));

it("leaves the default unchanged", async () => {
const document = await at(0, {});
expect(document.links.last).toBe(`${baseUrl}?page[offset]=39&page[limit]=3`);
expect(document.links.next).toBe(`${baseUrl}?page[offset]=3&page[limit]=3`);
});

it("computes next / last from linkTotal while meta.totalCount keeps totalCount", async () => {
const document = await at(3, { linkTotal: 6 });
expect(document.meta.totalCount).toBe(42);
expect(document.links.next).toBeNull();
expect(document.links.last).toBe(`${baseUrl}?page[offset]=3&page[limit]=3`);
});

it("omits last when lastUnknown, keeping the other links exact", async () => {
const document = await at(3, { lastUnknown: true });
expect("last" in document.links).toBe(false);
expect(document.links.self).toBe(`${baseUrl}?page[offset]=3&page[limit]=3`);
expect(document.links.first).toBe(`${baseUrl}?page[offset]=0&page[limit]=3`);
expect(document.links.prev).toBe(`${baseUrl}?page[offset]=0&page[limit]=3`);
expect(document.links.next).toBe(`${baseUrl}?page[offset]=6&page[limit]=3`);
});

it("keeps last when lastUnknown is false", async () => {
expect("last" in (await at(0, { lastUnknown: false })).links).toBe(true);
});

it("omits last on an unpageable window too", async () => {
const document = await run(
Assemble.collection(page, { totalCount: 5, offset: 0, limit: 0, baseUrl, lastUnknown: true }),
);
expect("last" in document.links).toBe(false);
});

it.each([
{ hasMore: true, next: true },
{ hasMore: false, next: false },
])("serves the search formula (hasMore $hasMore)", async ({ hasMore, next }) => {
const offset = 3;
const document = await at(
offset,
{ linkTotal: offset + page.length + (hasMore ? 1 : 0), lastUnknown: true },
page.length,
);
expect(document.links.next).toBe(next ? `${baseUrl}?page[offset]=6&page[limit]=3` : null);
expect("last" in document.links).toBe(false);
expect(document.meta.totalCount).toBe(3);
});

it("carries both through edgePage", async () => {
const document = await run(
Assemble.edgePage(
"contributions",
{ items: [person("a")], totalCount: 100 },
{ limit: 1, offset: 0, linkTotal: 1, lastUnknown: true },
"https://example.test",
),
);
expect(document.meta.totalCount).toBe(100);
expect(document.links.next).toBeNull();
expect("last" in document.links).toBe(false);
});
});

describe("Assemble.edgePage", () => {
it("assembles a capability-free page under <base>/<segment>", async () => {
const document = await run(
Expand Down
76 changes: 68 additions & 8 deletions src/Assemble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,25 @@ export interface Pagination {
* link's own `page[*]` cursor replaces the pairs' rather than appending.
*/
readonly query?: ReadonlyArray<Query.Pair> | undefined;
/**
* The total the offset pagination links are computed from — `last`, and
* whether `next` exists. Defaults to {@link Pagination.totalCount}; set it
* when the reported `meta.totalCount` is not what can be paged (a search
* engine's capped window, or an estimate). `meta.totalCount` is always
* `totalCount`, whatever `linkTotal` is.
*
* @since 0.22.0
*/
readonly linkTotal?: number;
/**
* When `true`, `links.last` is omitted (the key is absent, not `null`)
* because the last page is not known. `self` / `first` / `prev` / `next`
* stay exact, computed from {@link Pagination.linkTotal}. Defaults to
* `false`.
*
* @since 0.22.0
*/
readonly lastUnknown?: boolean;
}

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -901,6 +920,20 @@ const assembleCollection = <D, V, Targets extends Handlers.IncludeTargets>(
);
};

// The pagination links of a `Pagination`: computed from `linkTotal` (default
// `totalCount`), and without a `last` key when it is unknown.
const paginationLinks = (pagination: Pagination): Handlers.LinksValue => {
const links = Handlers.offsetPaginationLinks(
pagination.baseUrl,
{ offset: pagination.offset, limit: pagination.limit },
pagination.linkTotal ?? pagination.totalCount,
pagination.query === undefined ? undefined : { query: pagination.query },
);
if (pagination.lastUnknown !== true) return links;
const { last: _last, ...withoutLast } = links;
return withoutLast;
};

/**
* Assembles a JSON:API document around a collection page: every resource
* stamped and projected as {@link resource} does, `meta.totalCount` and the
Expand All @@ -911,6 +944,11 @@ const assembleCollection = <D, V, Targets extends Handlers.IncludeTargets>(
* resolved itself (`included`) are emitted alongside. A collection served
* whole, with no page math, goes through {@link unpaginatedCollection}.
*
* `Pagination.linkTotal` decouples the links from `meta.totalCount`, and
* `Pagination.lastUnknown` omits `links.last`: a search with no corpus count
* passes `linkTotal = offset + page.length + (hasMore ? 1 : 0)` so `next`
* exists exactly when there is more (the second example).
*
* @example
* ```ts
* import { Effect } from "effect"
Expand All @@ -926,7 +964,27 @@ const assembleCollection = <D, V, Targets extends Handlers.IncludeTargets>(
* // → 42 https://example.test/people?filter[q]=ada&page[offset]=13&page[limit]=3
* ```
*
* @since 0.16.0
* @example
* ```ts
* import { Effect } from "effect"
* import { Assemble } from "@thomasfosterau/effect-jsonapi"
*
* // A search with no corpus count: `next` exists exactly when there is more,
* // and the last page is unknown.
* const offset = 0
* const hasMore = true
* const hits = [1, 2, 3].map((n) => ({ type: "people", id: `${n}`, attributes: { name: `P${n}` } }))
* const document = Effect.runSync(Assemble.collection(hits, {
* totalCount: hits.length, offset, limit: 3,
* baseUrl: "https://example.test/search",
* linkTotal: offset + hits.length + (hasMore ? 1 : 0),
* lastUnknown: true
* }))
* console.log(document.links.next, "last" in document.links)
* // → https://example.test/search?page[offset]=3&page[limit]=3 false
* ```
*
* @since 0.16.0 (`linkTotal` and `lastUnknown` since 0.22.0)
* @category constructors
*/
export const collection = <
Expand All @@ -944,12 +1002,7 @@ export const collection = <
> =>
assembleCollection<CollectionDocument<R>, V, Targets>(resources, options, {
meta: { totalCount: pagination.totalCount },
links: Handlers.offsetPaginationLinks(
pagination.baseUrl,
{ offset: pagination.offset, limit: pagination.limit },
pagination.totalCount,
pagination.query === undefined ? undefined : { query: pagination.query },
),
links: paginationLinks(pagination),
});

/**
Expand Down Expand Up @@ -1195,7 +1248,10 @@ export const relationship = <R extends ResourceLike, I extends ResourceLike = R,
* // → https://example.test/contributions?filter[role]=author&page[offset]=1&page[limit]=1
* ```
*
* @since 0.16.0 (`input.query` since 0.21.0)
* `input.linkTotal` and `input.lastUnknown` are {@link Pagination}'s, forwarded
* as given.
*
* @since 0.16.0 (`input.query` since 0.21.0, `input.linkTotal` and `input.lastUnknown` since 0.22.0)
* @category constructors
*/
export const edgePage = <R extends ResourceLike, V = unknown>(
Expand All @@ -1205,6 +1261,8 @@ export const edgePage = <R extends ResourceLike, V = unknown>(
readonly limit: number;
readonly offset: number;
readonly query?: ReadonlyArray<Query.Pair> | undefined;
readonly linkTotal?: number;
readonly lastUnknown?: boolean;
},
base: string,
viewer?: V,
Expand All @@ -1220,6 +1278,8 @@ export const edgePage = <R extends ResourceLike, V = unknown>(
limit: input.limit,
baseUrl: `${base}/${segment}`,
...definedMember("query", input.query),
...definedMember("linkTotal", input.linkTotal),
...definedMember("lastUnknown", input.lastUnknown),
},
{ viewer, capabilities: noCapabilities },
),
Expand Down
Loading