Skip to content

fix(api): correct select/populate REST format docs + tests (closes #419) - #420

Merged
Ardnived merged 3 commits into
mainfrom
fix/419-select-populate-rest-format
May 27, 2026
Merged

Ardnived merged 3 commits into
mainfrom
fix/419-select-populate-rest-format

Conversation

@Ardnived

Copy link
Copy Markdown
Contributor

Closes #419

Summary

PR #294 shipped the select / populate validation hook for API clients, but the underlying issue spec, PR tests, and in-repo docs all assumed the wrong REST query-param format — comma-separated strings instead of PayloadCMS's bracket-notation nested objects. Real clients following the documented format hit 400 "select required" because qs-esm parses the string as a plain value, failing the hook's typeof === 'object' check.

This PR is docs + tests + observability — the hook's validation logic (src/lib/usage/hooks.ts:131-174) is byte-for-byte unchanged.

What changed

  • Diagnostic logging: req.payload.logger.warn(...) calls added to both rejection branches in the hook. Logs type, top-level keys, and a 100-char preview when the value is a string — enough to identify malformed shapes from wrangler tail without leaking full payloads.
  • REST-format integration tests: new describe('REST URL format (via qs.parse + sanitize)', ...) block in client-query-validation.int.spec.ts. Uses qs-esm + Payload's exported sanitizeSelectParam / sanitizePopulateParam to exercise the full URL → args parse pipeline. Includes the reporter's exact failing URLs as a contract lock (single-level populate[collection]=true and two-level populate[collection][field]=true MUST be accepted).
  • [email protected] added as devDependency (was a transitive dep via payload).
  • API client docs (.claude/rules/api-clients.md): new "Expected REST format" subsection with correct ✅ vs wrong ❌ URL examples, pointer to the diagnostic logging, and asTrustedReq() helper reference.
  • OpenAPI parameter injection: new src/lib/openapi/clientReadParametersDocs.ts with reusable definitions for select / populate / depth / limit / page (each carrying the bracket-notation format in its description). New injectClientReadParameters() in specFilter.ts walks the spec post-merge and adds \$refs to those parameters on every collection list + findByID GET — skipping x-internal ops, /api/globals/*, and custom subpath endpoints (which have hand-authored param surfaces). .claude/rules/openapi.md updated to document the new injection. Test coverage in api-explorer.int.spec.ts (describe('Client read parameter injection (#419)', ...)).
  • JSDoc fix in src/lib/usage/hooks.ts — wrong ?select=title example corrected to ?select[title]=true.

Production investigation

The reporter retested in Postman and found that bracket-notation populate URLs also 400 in production — specifically ?populate[pages][title]=true and ?populate[images]=true.

I ran all three failing URLs through qs.parse(..., { depth: 10 }) + Payload's exported sanitizePopulateParam (the exact pipeline findHandler uses) and every one produces hasPopulate: true — the hook should accept them. Both bracket-decoded and percent-encoded variants parse identically.

This means the hook code on main is correct; the production rejection traces to one of:

  1. Deployment lag — production may not yet be running PR feat(api): require select + populate for API client reads #294's latest hook. Confirm after this PR deploys.
  2. CF Workers / OpenNext URL mangling — environmental layer changes the URL before the hook sees it.
  3. Postman serialization quirk — what's sent differs from the address-bar URL.

The diagnostic logging in this PR makes (2) and (3) self-diagnosing on the next failure — the WARN entry will print the offending populate shape (type, keys, short preview), and we can file a concrete follow-up ticket if a real server-side bug surfaces.

Test plan

  • pnpm lint — clean
  • pnpm exec vitest run tests/int/client-query-validation.int.spec.ts — 19/19 pass (existing 10 + 9 new REST-format cases including reporter's URLs)
  • pnpm exec vitest run tests/int/api-explorer.int.spec.ts — 61/61 pass (existing 54 + 7 new parameter-injection cases)
  • pnpm test — 742 passed, 6 pre-existing failures unrelated to this PR (wm-app-config.int.spec.ts and wemeditateAppStatus.int.spec.ts), confirmed reproducible on main

Test Results

  • Integration tests: 742 passed, 1 skipped, 6 pre-existing failures
  • Build: not run locally per request — relies on CI
  • Pre-existing failures: tests/int/wm-app-config.int.spec.ts (5) and tests/int/wemeditateAppStatus.int.spec.ts (1) — all unrelated to this PR (verified by checking out main and reproducing)

Post-deploy verification (reporter)

  1. Hit https://cloud.sydevelopers.com/api/openapi.json?project=wemeditate-app and confirm a collection GET (e.g. on meditations) lists select, populate, depth, limit, page parameters.
  2. Confirm Scalar UI renders them in the request-builder panel.
  3. Re-run the previously-failing Postman requests.
  4. If they still 400, fetch wrangler tail sahajcloud --format pretty filtered by the reporter's clientId — the new WARN log will print the actual populate shape the hook saw, and we open a follow-up ticket with that as evidence.

🤖 Generated with Claude Code

Ardnived and others added 3 commits May 27, 2026 22:14
PR #294 (closes #199) required API clients to declare select + populate
on every read. The hook in src/lib/usage/hooks.ts is correct, but the
underlying issue spec, PR tests, and in-repo docs all assumed the wrong
REST query-param format (comma-separated strings instead of PayloadCMS's
bracket-notation nested objects). Real clients following the documented
format hit 400 "select required" because qs-esm parses the string as a
plain value, failing the hook's typeof === 'object' check.

Changes:
- Fix misleading JSDoc example in hooks.ts (?select=title -> ?select[title]=true)
- Add diagnostic WARN logging on hook rejection — emits type, top-level
  keys, and a 100-char string preview so production 400s are traceable
  from wrangler tail without leaking full payloads
- Add REST-format integration tests using qs-esm + Payload's exported
  sanitize* utilities. Tests the full URL -> qs.parse -> sanitize -> args
  pipeline, including the reporter's exact failing URLs as a contract
  lock (populate[collection]=true and populate[collection][field]=true
  MUST be accepted)
- Add [email protected] as devDependency (was transitive via payload)
- Update .claude/rules/api-clients.md with correct/wrong format examples
  and a pointer to the diagnostic logging
- New src/lib/openapi/clientReadParametersDocs.ts with reusable parameter
  definitions for select / populate / depth / limit / page, including the
  bracket-notation format in their descriptions
- New injectClientReadParameters() in specFilter.ts that walks the spec
  post-merge and adds $refs to those parameters on every collection list
  + findByID GET (skipping x-internal ops, /api/globals/*, and custom
  subpath endpoints which have hand-authored param surfaces)
- Update .claude/rules/openapi.md to document the new injection
- Add api-explorer.int.spec.ts coverage for the parameter injection

This PR does NOT change validation semantics — the hook's "presence check"
logic in src/lib/usage/hooks.ts:131-174 is unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Ardnived
Ardnived merged commit 45bcd7a into main May 27, 2026
Ardnived added a commit that referenced this pull request May 28, 2026
Fixes 17 failing integration tests, all stale relative to intentional
source changes that landed without updating their tests (no source changes):

- API client reads (role-based-access, pages): add `depth: 0` to reads
  that only assert ids/access. Since #420, omitting `depth` defaults to
  server depth 2 and requires `populate`; these reads don't need
  relationship population.
- wm-app-config / wemeditateAppStatus: the global now has 3 tabs
  (Pages/First Meditation/Misc) with 14 required pages. Rebuild the
  required-pages helpers from APP_REQUIRED_PAGE_FIELDS (drift-proof) and
  rewrite the field-structure assertions for the live layout.
- translations-field: assert the #414 group-wrapped nested structure
  (group named after the tab slug; leaf JSON fields keep the sub-slug name).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(api): correct select/populate REST format docs + tests from #294

1 participant