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/capabilities-on-included.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@thomasfosterau/effect-jsonapi": minor
---

Add `capabilitiesOnIncluded` to `Assemble.Options` (and `Assemble.RelationshipInput`, and the `ResourceHandlers` read-only, writable and related configs): `false` stamps the `capabilities` hook's result on primary data only, leaving `included` members without capability `meta`. It defaults to `true`, today's behaviour, so existing callers are unchanged. From gardeneria#1263 O5.
70 changes: 70 additions & 0 deletions src/Assemble.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,35 @@ describe("Assemble.resource", () => {
}),
);

it.effect("stamps included members unless `capabilitiesOnIncluded` is false", () =>
Effect.gen(function* () {
const stamped = { canEdit: true, canDelete: true };
const { targets } = registry([place]);
const options = {
viewer: ADMIN,
capabilities: familyCapabilities,
include: ["birthPlace"],
includable: ["birthPlace"],
targets,
};
const both = yield* Assemble.resource(person("p1"), options);
expect(both.data.meta).toEqual(stamped);
expect(both.included?.[0]?.meta).toEqual(stamped);
const explicit = yield* Assemble.resource(person("p1"), {
...options,
capabilitiesOnIncluded: true,
});
expect(explicit.included?.[0]?.meta).toEqual(stamped);
const primaryOnly = yield* Assemble.resource(person("p1"), {
...options,
capabilitiesOnIncluded: false,
});
expect(primaryOnly.data.meta).toEqual(stamped);
expect(primaryOnly.included).toHaveLength(1);
expect(primaryOnly.included?.[0]).not.toHaveProperty("meta");
}),
);

it.effect("resolves a to-many include in one loader call per level", () =>
Effect.gen(function* () {
const { calls, targets } = registry([candidate("c-1"), candidate("c-2")]);
Expand Down Expand Up @@ -575,6 +604,28 @@ describe("Assemble.collection", () => {
expect(document.included?.[0]?.meta).toEqual({ canEdit: false, canDelete: false });
}),
);

it.effect("stamps the page only when `capabilitiesOnIncluded` is false", () =>
Effect.gen(function* () {
const stamped = { canEdit: true, canDelete: true };
const { targets } = registry([place]);
const document = yield* Assemble.collection(
page,
{ totalCount: 3, offset: 0, limit: 10, baseUrl },
{
viewer: ADMIN,
capabilities: familyCapabilities,
capabilitiesOnIncluded: false,
include: ["birthPlace"],
includable: ["birthPlace"],
targets,
},
);
expect(document.data.map((resource) => resource.meta)).toEqual(page.map(() => stamped));
expect(document.included?.map((r) => r.id)).toEqual(["place-1"]);
expect(document.included?.[0]).not.toHaveProperty("meta");
}),
);
});

describe("Assemble.unpaginatedCollection", () => {
Expand Down Expand Up @@ -627,6 +678,25 @@ describe("Assemble.unpaginatedCollection", () => {
}),
);

it.effect("leaves included members unstamped when `capabilitiesOnIncluded` is false", () =>
Effect.gen(function* () {
const { targets } = registry([place]);
const document = yield* Assemble.unpaginatedCollection(whole, {
viewer: ADMIN,
capabilities: familyCapabilities,
capabilitiesOnIncluded: false,
include: ["birthPlace"],
includable: ["birthPlace"],
targets,
});
expect(document.data.map((resource) => resource.meta)).toEqual(
whole.map(() => ({ canEdit: true, canDelete: true })),
);
expect(ids(document.included)).toEqual(["places:place-1"]);
expect(document.included?.[0]).not.toHaveProperty("meta");
}),
);

it.effect("walks a nested path level by level", () =>
Effect.gen(function* () {
const { targets } = registry([election, event]);
Expand Down
41 changes: 34 additions & 7 deletions src/Assemble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,14 @@
* rung comparison), {@link ownedCapabilities} (the owner, or a moderator
* acting for them) and {@link noCapabilities} (a family with no write
* surface). No hook means no stamp: a family that publishes the pair passes
* one.
* one. Members of `included` are stamped too; pass
* `capabilitiesOnIncluded: false` to stamp the primary data only.
*
* @since 0.16.0
*/
import * as Arr from "effect/Array";
import * as Effect from "effect/Effect";
import * as HashSet from "effect/HashSet";
import * as P from "effect/Predicate";
import type * as ApiError from "./ApiError.js";
import type * as Document from "./Document.js";
Expand Down Expand Up @@ -395,6 +397,17 @@ export interface Options<V = unknown, Targets extends Handlers.IncludeTargets =
* document mixing families stamps each member honestly. Omit for no stamp.
*/
readonly capabilities?: CapabilitiesHook<V> | undefined;
/**
* Whether `included` members are stamped with the {@link capabilities}
* rule too. Defaults to `true` — every emitted resource, primary and
* included alike. `false` stamps the primary data only; `included` members
* carry no capability `meta`. A relationship document's primary data is
* linkage, which carries no `meta`, so there `false` stamps nothing.
*
* @since 0.22.0
* @category models
*/
readonly capabilitiesOnIncluded?: boolean;
}

/**
Expand Down Expand Up @@ -733,17 +746,29 @@ export const toWireSafeResource = <R extends ResourceLike>(resource: R): R =>
// ---------------------------------------------------------------------------

/** The resource-level transform every emitted resource goes through. */
const onResourceFor = <V>(options: Options<V, any>) =>
Handlers.compose(
const onResourceFor = <V>(
options: Pick<Options<V, any>, "capabilities" | "capabilitiesOnIncluded" | "viewer" | "fields">,
primary: ReadonlyArray<ResourceLike>,
) => {
// With `capabilitiesOnIncluded: false` only the primary data is stamped. The
// one transform shapes both slots, so primary membership is by `(type, id)`;
// a resource that is both is shaped once, for the primary slot (#567).
const primaryKeys =
options.capabilitiesOnIncluded === false
? HashSet.fromIterable(primary.map((r) => `${r.type}\0${r.id}`))
: undefined;
return Handlers.compose(
Handlers.withMeta((resource) =>
options.capabilities === undefined
options.capabilities === undefined ||
(primaryKeys !== undefined && !HashSet.has(primaryKeys, `${resource.type}\0${resource.id}`))
? undefined
: // The viewer is handed to the hook exactly as it was given: an
// omitted option is `undefined`, which is then what `V` is.
options.capabilities(resource as ResourceLike, options.viewer as V),
),
Handlers.project(options.fields),
);
};

// `ResourceLike`'s `relationships` values widen to `unknown`, which the
// builders' stricter `ResourceValue` rejects; the builders only read
Expand Down Expand Up @@ -855,7 +880,7 @@ export const resource = <
"included",
included === undefined ? undefined : included.map((r) => asValue(stringifyLinks(r))),
),
onResource: onResourceFor(options),
onResource: onResourceFor(options, [wired]),
});
return { ...built, jsonapi: JSONAPI_MEMBER } as unknown as ResourceDocument<R>;
}),
Expand Down Expand Up @@ -906,7 +931,7 @@ const assembleCollection = <D, V, Targets extends Handlers.IncludeTargets>(
const built = Handlers.collection(wired.map(asValue), {
...top,
included: included.map((r) => asValue(stringifyLinks(r))),
onResource: onResourceFor(options),
onResource: onResourceFor(options, wired),
});
// SAFETY: `Handlers.collection` types its value over the builders' loose
// `ResourceValue`; the value is `D` by construction — the wired, stamped
Expand Down Expand Up @@ -1123,6 +1148,8 @@ export interface RelationshipInput<R extends ResourceLike, I extends ResourceLik
readonly key: string;
readonly viewer?: V | undefined;
readonly capabilities?: CapabilitiesHook<V> | undefined;
/** As {@link Options.capabilitiesOnIncluded}: `false` leaves `included` unstamped. */
readonly capabilitiesOnIncluded?: boolean;
/**
* Resources to carry in `included`, typically the related resources the
* linkage names. Full linkage applies, and is checked: each must be
Expand Down Expand Up @@ -1210,7 +1237,7 @@ export const relationship = <R extends ResourceLike, I extends ResourceLike = R,
const included = Handlers.buildIncluded(
relationshipRefs(input.parent, input.key),
(input.included ?? []).map((r) => asValue(stringifyLinks(r))),
{ onResource: onResourceFor(input) },
{ onResource: onResourceFor(input, []) },
);
const rel = readRelationship(input.parent, input.key);
const related = rel?.links?.related === undefined ? undefined : toLinkString(rel.links.related);
Expand Down
19 changes: 18 additions & 1 deletion src/ResourceHandlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,10 @@ const seeded = () =>
// SAFETY: the stub ops read the same members the family's list query decodes.
const listQuery = peopleListQuery as ResourceHandlers.ListQuery<ListInput>;

const handlersFor = (ops: ReturnType<typeof makeOps>["ops"]) => {
const handlersFor = (
ops: ReturnType<typeof makeOps>["ops"],
extra: { readonly capabilitiesOnIncluded?: boolean } = {},
) => {
const { cache, store: cacheStore, state } = makeCache();
const { transact, opened } = makeTransact();
const handlers = ResourceHandlers.make({
Expand All @@ -231,6 +234,7 @@ const handlersFor = (ops: ReturnType<typeof makeOps>["ops"]) => {
cache,
transact,
include: { includable: PERSON_INCLUDE.paths, targets },
...extra,
});
return { handlers, cacheStore, state, opened };
};
Expand Down Expand Up @@ -879,6 +883,19 @@ describe("list", () => {
}),
);

it.effect("stamps the page only when `capabilitiesOnIncluded` is false", () =>
Effect.gen(function* () {
const { ops } = seeded();
const { handlers } = handlersFor(ops, { capabilitiesOnIncluded: false });
const document = yield* handlers
.list({ query: { include: ["birthPlace"] } })
.pipe(Effect.provide(as(Option.some(ADMIN))));
expect(document.data[0]?.meta).toEqual({ canEdit: true, canDelete: true });
expect(document.included?.map((r) => r.id)).toEqual([PLACE]);
expect(document.included?.[0]).not.toHaveProperty("meta");
}),
);

/**
* One test per axis the links have to carry, each asserting the parameter
* reaches all five links: a client paginates by `next` / `prev`, and
Expand Down
16 changes: 12 additions & 4 deletions src/ResourceHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ export interface ReadOnlyConfig<
readonly viewer?: Effect.Effect<V, never, RV> | undefined;
/** The capability rule every emitted resource is stamped with. Omit for no stamp. */
readonly capabilities?: Assemble.CapabilitiesHook<V> | undefined;
/** `false` stamps the primary data only, leaving `included` members unstamped. Defaults to `true`. */
readonly capabilitiesOnIncluded?: boolean;
/** Read-through on `get`; write-through and eviction on the writes. */
readonly cache?: Cache<TResource, RC> | undefined;
/** The `?include=` walk on `get` and `list`. */
Expand Down Expand Up @@ -521,14 +523,15 @@ export const readOnly = <
>(
config: ReadOnlyConfig<TQuery, TResource, TId, V, E, R, RV, RL, RC, Targets>,
): ReadOnlyHandlers<TResource, TId, TQuery, E, R, RV, RL, RC, Targets> => {
const { ops, segment, cache, include, capabilities } = config;
const { ops, segment, cache, include, capabilities, capabilitiesOnIncluded } = config;
const maxPageLimit = config.maxPageLimit ?? 100;
const viewer = (config.viewer ?? none) as Effect.Effect<V, never, RV>;
// Built once per family: `Query.canonicalPairs` returns the encoder-bound
// function, and nothing about it varies by request.
const linkPairs = Query.canonicalPairs(config.listQuery);
const assemble = {
...definedMember("capabilities", capabilities),
...definedMember("capabilitiesOnIncluded", capabilitiesOnIncluded),
...definedMember("includable", include?.includable),
...definedMember("targets", include?.targets),
...definedMember("depth", include?.depth),
Expand Down Expand Up @@ -689,7 +692,7 @@ export const make = <
RT,
Committed<NoInfer<HType>, TId>
> => {
const { ops, segment, cache, capabilities } = config;
const { ops, segment, cache, capabilities, capabilitiesOnIncluded } = config;
const viewer = (config.viewer ?? none) as Effect.Effect<V, never, RV>;
const transact = (config.transact ?? identityTransact) as Transact<Tx, ET, RT>;
const hidden = config.hiddenWrite;
Expand Down Expand Up @@ -745,6 +748,7 @@ export const make = <
if (cache !== undefined) yield* cache.set(result.id, reread.value);
return yield* Assemble.resource(reread.value, {
...definedMember("capabilities", capabilities),
...definedMember("capabilitiesOnIncluded", capabilitiesOnIncluded),
viewer: yield* viewer,
});
}),
Expand Down Expand Up @@ -890,6 +894,8 @@ export interface RelatedConfig<
readonly linkBase: Effect.Effect<string, never, RL>;
readonly viewer?: Effect.Effect<V, never, RV> | undefined;
readonly capabilities?: Assemble.CapabilitiesHook<V> | undefined;
/** `false` stamps the primary data only, leaving `included` members unstamped. Defaults to `true`. */
readonly capabilitiesOnIncluded?: boolean;
/** The to-many page size when the caller names none. Defaults to `50`. */
readonly defaultPageLimit?: number | undefined;
/** The most related rows one page may resolve. Defaults to `100`. */
Expand Down Expand Up @@ -992,8 +998,10 @@ export const related = <
R | RV | RL | Handlers.IncludeTargetServices<Targets>
>) => {
const viewer = (config.viewer ?? none) as Effect.Effect<V, never, RV>;
const capabilities =
config.capabilities === undefined ? {} : { capabilities: config.capabilities };
const capabilities = {
...definedMember("capabilities", config.capabilities),
...definedMember("capabilitiesOnIncluded", config.capabilitiesOnIncluded),
};
const concurrency = config.concurrency ?? 6;
const linkPairs =
config.listQuery === undefined ? undefined : Query.canonicalPairs(config.listQuery);
Expand Down
Loading