Repository navigation
feat(core): content-references HTTP API (relation defs + entry edges) - #1535
Conversation
🦋 Changeset detectedLatest commit: 1af449e The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
All contributors have signed the CLA ✍️ ✅ |
Scope checkThis PR changes 1,516 lines across 13 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
Adds relation-definition routes and handlers (list/create/get/update/delete/translations) and content-entry reference edge routes for children and parents, with edge-read hardening and error handling.
96936ca to
b17ee59
Compare
# Conflicts: # packages/core/src/database/repositories/content.ts
There was a problem hiding this comment.
This is a well-scoped, architecture-faithful slice: it puts Zod validation and collection-agreement/ownership invariants at the HTTP boundary, keeps the repository focused on storage, adds batched group resolution to avoid N+1 reads, and includes solid dialect-agnostic tests. It matches the prior taxonomy edge pattern and respects draft-visibility rules.
I read the full diff, the changed routes/handlers/repository code, and cross-checked against packages/core/src/api/errors.ts, packages/core/src/api/openapi/document.ts, the taxonomy edge route, and RBAC permissions. No security or data-loss issues jumped out. The remaining items are completeness/consistency rather than blockers:
- New relation/reference catch-all error codes (
RELATION_*_ERROR,REFERENCES_*_ERROR) are not added to the centralErrorCodeenum, so TypeScript consumers won't see them in the typed union. - The new public endpoints are missing from the generated OpenAPI document, even though analogous taxonomy endpoints are fully documented.
ContentRepository.findManyByIdOrSlugdoesn't tolerate a missing content table the wayfindTranslationsForGroupsdoes; if a referenced child collection is later dropped (schema deletion doesn't currently cascade to relation definitions), thePOST childrenwrite path will 500 instead of returning a structuredNOT_FOUND/COLLECTION_NOT_FOUND.
A couple of ordering/style notes are minor: the children route checks content:edit_own before requireDb, which differs from sibling routes; and createRelationBody still requires parentCollection/childCollection when translationOf is supplied even though the handler ignores them.
Overall the implementation is clean and the test coverage is good; the gaps above are polish.
Findings
-
[suggestion]
packages/core/src/api/handlers/relations.ts:82Catch-all error codes introduced here (
RELATION_CREATE_ERROR, etc.) are not added to the centralErrorCodeenum inpackages/core/src/api/errors.ts. Adding them keeps the typed union complete so clients can switch on them exhaustively. -
[suggestion]
packages/core/src/api/handlers/relations.ts:170New
REFERENCES_GET_ERROR/REFERENCES_SET_ERRORcodes are also missing fromErrorCode. The handlers here use raw strings instead of the enum, which is consistent with some older handlers but still leaves the canonical enum incomplete for this domain. -
[suggestion]
packages/core/src/api/openapi/document.ts:2323The new
/_emdash/api/relationsand/_emdash/api/content/{collection}/{id}/references/{relation}/{children,parents}endpoints are not included in the generated OpenAPI document. Taxonomy endpoints are documented intaxonomyPaths, so relations should get a matchingrelationPathsspread here and a newRelationstag to keep the spec complete. -
[needs fixing]
packages/core/src/database/repositories/content.ts:1120findTranslationsForGroupshandles a missing collection table by returning[], butfindManyByIdOrSlughas no such guard. If a relation's child collection is dropped after the relation is created,POST .../references/:relation/childrenwill throw and 500 instead of returning a structured error. Consider wrapping the batch queries here and returning an empty map whenisMissingTableError(error)is true, mirroring the read path. -
[suggestion]
packages/core/src/astro/routes/api/content/[collection]/[id]/references/[relation]/children.ts:59The route checks
content:edit_ownbeforerequireDb. Sibling routes (taxonomy terms, single content) callrequireDbfirst. While the end result is acceptable, reordering to match the established pattern makes DB-unconfigured errors surface consistently for all authenticated callers.
…plete relation error enum findManyByIdOrSlug now returns an empty map on a missing content table (mirroring findTranslationsForGroups), so setting references on a relation whose child collection was dropped returns a structured NOT_FOUND instead of a 500. Adds the RELATION_*/REFERENCES_* codes to the ErrorCode enum so the typed union is complete for this domain. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed in Findings 1 & 2 (relation/reference error codes) — Added a Finding 4 (missing child-table guard) — Confirmed reachable: Finding 3 (OpenAPI docs) — Deferred out of this PR's scope. Finding 5 ( |
There was a problem hiding this comment.
Re-review of PR #1535 (content-references HTTP API).
The author has addressed the prior review's most concrete gaps: the new RELATION_*/REFERENCES_* codes are now in the central ErrorCode enum, and ContentRepository.findManyByIdOrSlug tolerates a missing child collection table so POST .../references/:relation/children returns NOT_FOUND instead of 500 after a collection is dropped.
The approach remains sound: Zod at the route, invariants (relation existence, collection agreement, ownership) in the handler, batched group resolution for reads, cursor pagination on both forward and backlink edges, and explicit locale on resolved refs. Test coverage for the happy paths, auth/ownership, draft visibility, and cursor edge cases is solid.
Still open:
- Parent-collection missing table still 500s. The new reference handlers resolve the anchor entry with
content.findByIdOrSlug(collection, entryId). If the parent collection is dropped after the relation was created, this throws; the handler catch maps it toREFERENCES_GET_ERROR/REFERENCES_SET_ERROR(500). The symmetric child-side lookup was fixed; the parent side should be treated the same way (ideally by adding the sameisMissingTableErrorguard tofindByIdOrSlugthat now exists on the new batch methods). - OpenAPI still omits the new endpoints. The public relation-definition and reference-edge routes are not documented in
packages/core/src/api/openapi/document.ts, despite the taxonomy endpoints that inspired this slice being fully covered. - Schema still requires ignored fields for translations.
createRelationBodyrequiresparentCollection/childCollectioneven whentranslationOfis supplied, but the handler ignores those fields and inherits them from the source relation. Making them conditional would avoid confusing validation failures.
No security or data-loss concerns. The remaining items are completeness/consistency polish.
Findings
-
[needs fixing]
packages/core/src/api/handlers/relations.ts:324Anchor entry lookup via
content.findByIdOrSlug(collection, entryId)will throw if the parent collection'sec_*table no longer exists (e.g., the collection was deleted after the relation was created). The handler catch turns that into aREFERENCES_GET_ERROR/REFERENCES_SET_ERROR500. The child-side batch lookup was already hardened in this PR; the parent lookup needs the same treatment. Either wrap/catchisMissingTableErrorhere or add the guard toContentRepository.findByIdOrSlugso it returnsnull, matchingfindTranslationsForGroupsandfindManyByIdOrSlug.A fix should include a reproducing test that drops
ec_postand verifies the reference endpoints returnNOT_FOUNDinstead of 500, mirroring the existingec_pagedrop test. -
[needs fixing]
packages/core/src/api/handlers/relations.ts:444Same missing-table issue as the children path:
content.findByIdOrSlug(collection, entryId)for the parents endpoint can throwno such tablewhen the child-side collection has been dropped, leading to a 500 instead of a structuredNOT_FOUND. Consistent handling with the child lookup is needed. -
[suggestion]
packages/core/src/api/openapi/document.ts:2323The PR exposes several new public endpoints (
/_emdash/api/relations,/_emdash/api/relations/{id},/_emdash/api/relations/{id}/translations, and/_emdash/api/content/{collection}/{id}/references/{relation}/{children,parents}) but they are still missing from the generated OpenAPI document. Taxonomy endpoints have a matchingtaxonomyPathsblock that is spread at this line; relations should get an equivalentrelationPathsblock and aRelationstag to keep the spec complete. -
[suggestion]
packages/core/src/api/schemas/relations.ts:18createRelationBodystill requiresparentCollectionandchildCollectioneven whentranslationOfis provided, but the handler ignores those fields and inherits them from the source relation. This forces callers to supply valid collection slugs that are then discarded. Consider making those fields optional whentranslationOfis set, or documenting the requirement, so the schema matches the actual handler semantics.
…es; relax translation relation schema findByIdOrSlug now returns null on a missing content table (matching findManyByIdOrSlug and findTranslationsForGroups), so the reference children/parents endpoints return NOT_FOUND instead of 500 when the anchor entry's collection was dropped after the relation was created. createRelationBody no longer requires parentCollection/childCollection when translationOf is set — a translation inherits its structural fields from the source relation, so those values were previously required only to be ignored. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed in Findings 1 & 2 (parent/child anchor collection dropped → 500) — Hardened the shared Finding 4 (schema requires ignored fields for translations) — Note: Finding 3 (OpenAPI docs) — Still deferred out of this PR's scope. |
There was a problem hiding this comment.
Re-review of PR #1535. The author has addressed the prior review's concrete blockers: the new reference handlers now surface NOT_FOUND (not 500) when a content table is dropped, because ContentRepository.findByIdOrSlug was hardened to catch isMissingTableError and return null; the test suite adds the symmetric parent-collection drop case; and createRelationBody no longer requires parentCollection/childCollection when translationOf is supplied.
The implementation remains sound: Zod validation at the route, collection-agreement and ownership checks in the handler, batched group resolution for reads, cursor pagination on both forward and backlink edges, and explicit locale on resolved refs. I read the updated handler, routes, schemas, repository changes, and tests statically; I did not run the test suite or linter.
One prior suggestion is still open: the public OpenAPI document does not yet cover the new relation-definition or reference-edge endpoints, despite the taxonomy surface that inspired this slice being documented. No new security, data-integrity, or convention issues were introduced by this revision.
Findings
-
[suggestion]
packages/core/src/api/openapi/document.ts:2323The PR exposes several new public endpoints (
/_emdash/api/relations,/_emdash/api/relations/{id},/_emdash/api/relations/{id}/translations,/_emdash/api/content/{collection}/{id}/references/{relation}/children, and/_emdash/api/content/{collection}/{id}/references/{relation}/parents) but they are still missing from the generated OpenAPI document. Taxonomy endpoints have a matchingtaxonomyPathsblock that is spread at this line, and aTaxonomiestag; relations should get an equivalentrelationPathsblock and aRelationstag to keep the public spec complete....taxonomyPaths, ...relationPaths,and add
{ name: "Relations", description: "Content reference relation definitions and entry edges" }to thetagsarray at the bottom of the document.
What does this PR do?
Adds the HTTP API layer over the content-references repository — the third bottom-up slice after the schema (migration
043) andRelationRepository. Two surfaces:/_emdash/api/relations— manage relationship types (editor-readable viaschema:read, admin-writable viaschema:manage), treated as schema-like structural config./_emdash/api/content/:collection/:id/references/:relation/{children,parents}— attach/read directed references on a specific entry, ownership-aware like the taxonomy edge endpoint.This is the trust boundary: Zod at the route, and the write-path invariants (relation-exists, collection-agreement, directed storage) the repository deliberately skipped. References are stored only in
_emdash_content_references, keyed bytranslation_group— noec_*column.The final commit hardens the slice against a code review:
translationOf→NOT_FOUND, name/locale collisions →CONFLICT, missing collections →COLLECTION_NOT_FOUND.INquery (chunked) instead of N+1 per edge.?cursor/?limit, default 50, max 100) returningnextCursor; the backlink (parents) side is genuinely unbounded, so this matters. Bad cursors →INVALID_CURSOR.localeof the variant returned, so the variant fallback is explicit rather than a silent wrong-locale substitution.content:edit_ownis gated before the existence lookup onPOST childrento close an existence-oracle.PATCHrelation bodies are rejected withVALIDATION_ERROR.Closes #
Type of change
Approved feature Discussion: #386
Part of the planned content-references effort tracked under the schema (#1367) and repository (#1444) slices.
Checklist
pnpm typecheckpasses — repo-wide typecheck has 5 pre-existing failures inpackages/plugin-cli/src/plugins/*from an unbuilt@emdash-cms/plugin-types(build-order, unrelated to this PR); 0 new errors introduced by these changes.pnpm lintpasses —pnpm lint:jsonis clean for all files in this PR; the only remaining diagnostics are pre-existing in unrelated demo/templateastro.config.mjsfiles.pnpm testpasses (targeted): relation/reference handler, route, and repository suites — 60 tests green.pnpm formathas been runemdash, minor)AI-generated code disclosure
Screenshots / test output