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/null-empty-member-detail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@thomasfosterau/effect-jsonapi": patch
---

A `null` write-body `attributes` or `relationships` member that declares no fields now answers its 400 with the detail `Expected object`, as a member that declares fields does, instead of `Expected object | array` (#286). The status and `source.pointer` are unchanged, and so is the generated OpenAPI document.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ Everything below is **derived** — never assembled by hand:
| `Article.collection()` | collection document (strict array `data`) |
| `typeof Article.Type` | the decoded TypeScript type |

**Undeclared body members.** A write body's `attributes` or `relationships` member that declares at least one field drops any member it doesn't declare. One that declares **none** rejects every member a client sends: a resource with no attributes or no relationships, or one whose attributes or relationships are all excluded from that write (`create: false`, `update: false`, `paginated`). That applies to `createPayload`, `updatePayload`, `createInput` and the atomic `add` / `update` operations, and is a 400 whose `source.pointer` names the member (`/data/attributes/isAdmin`). An empty `{}` is accepted. Either kind answers a value that isn't an object (a string, a number, a boolean, an array) with a 400 `Expected object` at the member itself (`/data/attributes`). Either way, a member the resource doesn't declare never reaches the handler.
**Undeclared body members.** A write body's `attributes` or `relationships` member that declares at least one field drops any member it doesn't declare. One that declares **none** rejects every member a client sends: a resource with no attributes or no relationships, or one whose attributes or relationships are all excluded from that write (`create: false`, `update: false`, `paginated`). That applies to `createPayload`, `updatePayload`, `createInput` and the atomic `add` / `update` operations, and is a 400 whose `source.pointer` names the member (`/data/attributes/isAdmin`). An empty `{}` is accepted. Either kind answers a value that isn't an object (a string, a number, a boolean, an array, `null`) with a 400 `Expected object` at the member itself (`/data/attributes`). Either way, a member the resource doesn't declare never reaches the handler.

Documents are not limited to one resource type — see [Heterogeneous endpoints](#heterogeneous-endpoints-search-feeds) for polymorphic collections.

Expand Down
61 changes: 57 additions & 4 deletions src/Resource.undeclared.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@
* relationship is excluded from that write) answers 400 with a
* `source.pointer` at the undeclared member, through the real middleware
* stack, instead of handing the member to the handler. A non-object member
* answers 400 `Expected object` at the member, as a struct with fields does.
* answers 400 `Expected object` at the member, as a struct with fields does,
* a `null` included (#286).
*/
import { describe, expect, it } from "vite-plus/test";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Rec from "effect/Record";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import { HttpRouter } from "effect/http";
import { HttpApi, HttpApiBuilder } from "effect/http-api";
import { HttpApi, HttpApiBuilder, OpenApi } from "effect/http-api";
import * as Atomic from "./Atomic.js";
import * as Endpoint from "./Endpoint.js";
import * as Group from "./Group.js";
Expand Down Expand Up @@ -252,8 +254,10 @@ describe("a non-object member answers 400 at the member, whether or not it decla
// A struct that declares no fields parses any non-nullish input in the
// pinned effect, so a non-object reaches its member check; that check
// answers it exactly as a struct with fields does: "Expected object" at the
// member itself. An array is not an object to either.
const values = ['"x"', "5", "true", "[]", '["a"]'] as const;
// member itself. An array is not an object to either. A `null` fails the
// empty struct's own not-nullish check before that member check runs, and
// renders "Expected object" too, not "Expected object | array" (#286).
const values = ['"x"', "5", "true", "[]", '["a"]', "null"] as const;

const sites: ReadonlyArray<
readonly [
Expand Down Expand Up @@ -445,3 +449,52 @@ describe("a member struct left empty by write projections (#270)", () => {
expect(issues).toEqual([{ path, message: "Expected no excess property" }]);
});
});

describe("a null member that declares no fields (#286)", () => {
// The issue's own reproduction, at the schema: the empty member's `null`
// renders as the fielded member's does.
it.each([
["declares none", Flag.createPayload, { data: { type: "flags", attributes: null } }],
["declares fields", Note.createPayload, { data: { type: "notes", attributes: null } }],
] as const)("%s: Expected object at the member", (_, schema, input) => {
const issues = Result.match(Schema.decodeUnknownResult(schema)(input), {
onFailure: (error) => SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues,
onSuccess: () => [],
});
expect(issues).toEqual([{ path: ["data", "attributes"], message: "Expected object" }]);
});

// The message names no OpenAPI component: the empty member stays the inline
// closed object #270 made it, with no `noMembers` component.
it("leaves the member an inline closed object in the OpenAPI document", () => {
const RequestBody = Schema.Struct({
content: Schema.Record(
Schema.String,
Schema.Struct({
schema: Schema.Struct({
properties: Schema.Struct({
data: Schema.Struct({ properties: Schema.Record(Schema.String, Schema.Unknown) }),
}),
}),
}),
),
});
const spec = OpenApi.fromApi(Api);
const members = (path: string, method: "post" | "patch") =>
Schema.decodeUnknownSync(RequestBody)(spec.paths[path]?.[method]?.requestBody).content[
MEDIA_TYPE
]?.schema.properties.data.properties;
const closed = {
not: { type: "null" },
allOf: [{ type: "object", additionalProperties: false }],
};
expect(members("/flags", "post")?.attributes).toEqual(closed);
expect(members("/flags/{id}", "patch")?.attributes).toEqual(closed);
expect(members("/notes", "post")?.relationships).toEqual(closed);
expect(Rec.keys(spec.components.schemas)).toEqual([
"BadRequestEncoded",
"UnsupportedMediaTypeEncoded",
"NotAcceptableEncoded",
]);
});
});
58 changes: 42 additions & 16 deletions src/internal/schemaExt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@
*/
// The bare `effect` barrel: the schema-only entry point reaches this module,
// and `test/entry-points.test.ts` pins `effect` as its only external.
import { JsonPointer, Option, Predicate, Record as Rec, Schema, SchemaIssue } from "effect";
import {
Array as Arr,
JsonPointer,
Option,
Predicate,
Record as Rec,
Schema,
SchemaIssue,
} from "effect";

/**
* The value an update actually **supplies** for a clearable, tri-state field
Expand Down Expand Up @@ -127,33 +135,51 @@ export const issueLeaves = (issue: SchemaIssue.Issue): ReadonlyArray<IssueLeaf>
// key of the input is an `UnexpectedKey` at its own path, the issue
// `onExcessProperty: "error"` reports for a struct with fields;
// `Reflect.ownKeys` rather than `Object.keys` so a symbol key counts too.
// The keys are grouped under a `Composite` on `Schema.Unknown`'s AST, not on
// this struct's: a formatter reads a `message` annotation on a check's issue
// as the whole check's message, so grouping them on the struct (which
// carries `nullAsObject`, below) would collapse every key into one "Expected
// object" at the member.
// No `identifier` / `title` / `description`: an identifier makes each site a
// named component (`noMembers`, `noMembers_1`, …) in every consumer's OpenAPI
// document and renders a `null` member as "Expected <identifier>", and a title
// or description would be copied into that document too.
// oxlint-disable-next-line effect/require-filter-metadata -- see above: this check must stay anonymous in consumers' OpenAPI
const noMembers = Schema.makeFilter<unknown>(
(input, ast) =>
!Predicate.isObject(input)
? "Expected object"
: Reflect.ownKeys(input)
.filter((key) => Object.prototype.propertyIsEnumerable.call(input, key))
.map((key) => ({
path: [key],
issue: new SchemaIssue.UnexpectedKey(
ast,
Object.getOwnPropertyDescriptor(input, key)?.value,
),
})),
(input, ast, options) => {
if (!Predicate.isObject(input)) return "Expected object";
const members = Reflect.ownKeys(input)
.filter((key) => Object.prototype.propertyIsEnumerable.call(input, key))
.map(
(key) =>
new SchemaIssue.Pointer(
[key],
new SchemaIssue.UnexpectedKey(ast, Object.getOwnPropertyDescriptor(input, key)?.value),
),
);
return Arr.isReadonlyArrayNonEmpty(members)
? new SchemaIssue.Composite(Schema.Unknown.ast, members, input, options)
: true;
},
{ toJsonSchema: () => ({ type: "object", additionalProperties: false }) },
);

// A `null` never reaches `noMembers`: the empty struct's own not-nullish
// check rejects it first, as an `InvalidType` whose text comes from
// `SchemaAST.Objects#getExpected`, which is "object | array" for a struct with
// no fields ("object" for one with fields). The default formatters read a
// `message` annotation on that issue's AST before the expected text, so this
// one renders the `null` the way a struct with fields does (#286). Unlike an
// `identifier`, a `message` names no OpenAPI component and is not copied into
// the JSON Schema, and it changes no parse: only the text of that issue.
const nullAsObject = { message: "Expected object" } as const;

/**
* `Schema.Struct(fields)`, closed when `fields` is empty: a struct that
* declares no fields rejects every member of its input, each as an
* `UnexpectedKey` issue at that member's path ("Expected no excess property"),
* and rejects a non-object or an array at its own path ("Expected object"),
* as a struct with fields does.
* and rejects a non-object, an array or a `null` at its own path ("Expected
* object"), as a struct with fields does.
*
* In the pinned `effect`, a struct **with** fields drops input keys it doesn't
* declare, but a struct with **no** fields is a bare not-nullish check that
Expand All @@ -166,5 +192,5 @@ export const closedStruct = <const Fields extends Schema.Struct.Fields>(
fields: Fields,
): Schema.Struct<Fields> =>
Rec.isEmptyReadonlyRecord(fields)
? Schema.Struct<Fields>(fields).check(noMembers)
? Schema.Struct<Fields>(fields).annotate(nullAsObject).check(noMembers)
: Schema.Struct(fields);
Loading