diff --git a/examples/blog/package.json b/examples/blog/package.json index 690c5a7..6749392 100644 --- a/examples/blog/package.json +++ b/examples/blog/package.json @@ -9,6 +9,7 @@ "effect": "catalog:" }, "devDependencies": { + "@effect/vitest": "catalog:", "@types/node": "catalog:", "vite-plus": "catalog:" } diff --git a/examples/blog/test/atomic.test.ts b/examples/blog/test/atomic.test.ts index 63f7310..a73cbe5 100644 --- a/examples/blog/test/atomic.test.ts +++ b/examples/blog/test/atomic.test.ts @@ -5,8 +5,9 @@ * lid-based references, relationship operations (including on `paginated` * relationships) and all-or-nothing semantics. */ +import { it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { assert, describe, expect, expectTypeOf, it } from "vite-plus/test"; +import { assert, describe, expect, expectTypeOf } from "vite-plus/test"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -36,16 +37,14 @@ const middleware = Middleware.layerWith({ extensions: [Atomic.EXTENSION_URI] }); const jsonText = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); -const run = (effect: Effect.Effect): Promise => - Effect.runPromise( - effect.pipe( - Effect.scoped, - Effect.provide(Layer.provideMerge(Layer.mergeAll(ArticlesLive, OperationsLive), middleware)), - ) as Effect.Effect, - ); +const run = (effect: Effect.Effect): Effect.Effect => + effect.pipe( + Effect.scoped, + Effect.provide(Layer.provideMerge(Layer.mergeAll(ArticlesLive, OperationsLive), middleware)), + ) as Effect.Effect; -const runExit = (effect: Effect.Effect): Promise> => - Effect.runPromiseExit( +const runExit = (effect: Effect.Effect): Effect.Effect> => + Effect.exit( effect.pipe( Effect.scoped, Effect.provide(Layer.provideMerge(Layer.mergeAll(ArticlesLive, OperationsLive), middleware)), @@ -58,550 +57,588 @@ const findFailure = (cause: Cause.Cause): E | undefined => { }; describe("atomic operations: creating with lids", () => { - it("creates an article and a comment linked to it by lid, atomically", async () => { - const { document, linkage } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const document = yield* client.operations.operations({ - payload: Atomic.request( - // 1. create an article — it has no id yet, so it declares a lid. - // `author` is a required (`one`) relationship. - Atomic.add(Article, { - lid: "a1", - attributes: { - title: "Atomic bikeshedding", - body: "Both or neither.", - createdAt: at("2024-06-01T00:00:00.000Z"), - }, - relationships: { - author: { data: Person.ref(sampleAuthor.id) }, - tags: { data: [Tag.ref(sampleTag.id)] }, - }, - }), - // 2. create a comment on it - Atomic.add(Comment, { - lid: "c1", - attributes: { body: "Witty remark" }, - relationships: { author: { data: Person.ref(sampleAuthor.id) } }, - }), - // 3. link the comment into the article's paginated comments - // relationship — both sides referenced by lid - Atomic.addToRelationship(Article, { lid: "a1" }, "comments", [Comment.lidRef("c1")]), - ), - }); - - // the paginated comments relationship is only reachable through its - // relationship endpoint — verify the linkage landed there - const articleIdData = document["atomic:results"][0].data; - assert.exists(articleIdData); - const articleId = articleIdData.id; - const linkage = yield* client.articles.commentsRelationship({ - params: { id: Article.Id.make(articleId) }, - query: {}, - }); - return { document, linkage }; - }), - ); + it.effect("creates an article and a comment linked to it by lid, atomically", () => + Effect.gen(function* () { + const { document, linkage } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const document = yield* client.operations.operations({ + payload: Atomic.request( + // 1. create an article — it has no id yet, so it declares a lid. + // `author` is a required (`one`) relationship. + Atomic.add(Article, { + lid: "a1", + attributes: { + title: "Atomic bikeshedding", + body: "Both or neither.", + createdAt: at("2024-06-01T00:00:00.000Z"), + }, + relationships: { + author: { data: Person.ref(sampleAuthor.id) }, + tags: { data: [Tag.ref(sampleTag.id)] }, + }, + }), + // 2. create a comment on it + Atomic.add(Comment, { + lid: "c1", + attributes: { body: "Witty remark" }, + relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + }), + // 3. link the comment into the article's paginated comments + // relationship — both sides referenced by lid + Atomic.addToRelationship(Article, { lid: "a1" }, "comments", [Comment.lidRef("c1")]), + ), + }); + + // the paginated comments relationship is only reachable through its + // relationship endpoint — verify the linkage landed there + const articleIdData = document["atomic:results"][0].data; + assert.exists(articleIdData); + const articleId = articleIdData.id; + const linkage = yield* client.articles.commentsRelationship({ + params: { id: Article.Id.make(articleId) }, + query: {}, + }); + return { document, linkage }; + }), + ); + + const results = document["atomic:results"]; + expect(results).toHaveLength(3); + + // results arrive in operation order; relationship operations return no data + const article = results[0]?.data; + const comment = results[1]?.data; + expect(article?.type).toBe("articles"); + expect(comment?.type).toBe("comments"); + expect(results[2]?.data).toBeUndefined(); + + assert(article?.type === "articles"); + assert(comment?.type === "comments"); + expect(article.attributes.createdAt).toBeInstanceOf(Date); + // the data union is discriminated by `type` + expectTypeOf(article.attributes.title).toEqualTypeOf(); + expectTypeOf(comment.attributes.body).toEqualTypeOf(); + // the lid-based linkage was resolved to the comment's real id + expect(linkage.data.map((ref) => ref.id)).toEqual([comment.id]); + }), + ); - const results = document["atomic:results"]; - expect(results).toHaveLength(3); - - // results arrive in operation order; relationship operations return no data - const article = results[0]?.data; - const comment = results[1]?.data; - expect(article?.type).toBe("articles"); - expect(comment?.type).toBe("comments"); - expect(results[2]?.data).toBeUndefined(); - - assert(article?.type === "articles"); - assert(comment?.type === "comments"); - expect(article.attributes.createdAt).toBeInstanceOf(Date); - // the data union is discriminated by `type` - expectTypeOf(article.attributes.title).toEqualTypeOf(); - expectTypeOf(comment.attributes.body).toEqualTypeOf(); - // the lid-based linkage was resolved to the comment's real id - expect(linkage.data.map((ref) => ref.id)).toEqual([comment.id]); - }); + it.effect("the created resources are visible through the regular endpoints", () => + Effect.gen(function* () { + const fetched = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; - it("the created resources are visible through the regular endpoints", async () => { - const fetched = await run( - Effect.gen(function* () { - const client = yield* buildClient; - - const created = yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Article, { - attributes: { - title: "Fetch me later", - body: "", - createdAt: at("2024-06-02T00:00:00.000Z"), - }, - relationships: { - author: { data: Person.ref(sampleAuthor.id) }, - }, - }), - ), - }); - - const idData = created["atomic:results"][0].data; - assert.exists(idData); - const id = idData.id; - return yield* client.articles.get({ params: { id: Article.Id.make(id) }, query: {} }); - }), - ); + const created = yield* client.operations.operations({ + payload: Atomic.request( + Atomic.add(Article, { + attributes: { + title: "Fetch me later", + body: "", + createdAt: at("2024-06-02T00:00:00.000Z"), + }, + relationships: { + author: { data: Person.ref(sampleAuthor.id) }, + }, + }), + ), + }); - expect(fetched.data?.attributes.title).toBe("Fetch me later"); - }); + const idData = created["atomic:results"][0].data; + + assert.exists(idData); + + const id = idData.id; + return yield* client.articles.get({ params: { id: Article.Id.make(id) }, query: {} }); + }), + ); + + expect(fetched.data?.attributes.title).toBe("Fetch me later"); + }), + ); }); describe("atomic operations: updating and removing", () => { - it("updates and removes resources in one request", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - - // create a comment to remove (so the sample data stays intact) - const created = yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Comment, { - attributes: { body: "Doomed" }, - relationships: { author: { data: Person.ref(sampleAuthor.id) } }, - }), - ), - }); - const doomedIdData = created["atomic:results"][0].data; - assert.exists(doomedIdData); - const doomedId = doomedIdData.id; - - return yield* client.operations.operations({ - payload: Atomic.request( - Atomic.update(Article, { - id: sampleArticle.id, - attributes: { title: "Atomically retitled" }, - }), - Atomic.remove(Comment, doomedId), - ), - }); - }), - ); + it.effect("updates and removes resources in one request", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + + // create a comment to remove (so the sample data stays intact) + const created = yield* client.operations.operations({ + payload: Atomic.request( + Atomic.add(Comment, { + attributes: { body: "Doomed" }, + relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + }), + ), + }); + const doomedIdData = created["atomic:results"][0].data; + assert.exists(doomedIdData); + const doomedId = doomedIdData.id; - const results = document["atomic:results"]; - expect(results).toHaveLength(2); - // updates return the updated resource; removals return no data - expect(results[0]?.data?.attributes).toMatchObject({ title: "Atomically retitled" }); - expect(results[1]?.data).toBeUndefined(); - }); + return yield* client.operations.operations({ + payload: Atomic.request( + Atomic.update(Article, { + id: sampleArticle.id, + attributes: { title: "Atomically retitled" }, + }), + Atomic.remove(Comment, doomedId), + ), + }); + }), + ); + + const results = document["atomic:results"]; + expect(results).toHaveLength(2); + // updates return the updated resource; removals return no data + expect(results[0]?.data?.attributes).toMatchObject({ title: "Atomically retitled" }); + expect(results[1]?.data).toBeUndefined(); + }), + ); - it("removes a resource created earlier in the same request, by lid", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Comment, { - lid: "ephemeral", - attributes: { body: "Now you see me" }, - relationships: { author: { data: Person.ref(sampleAuthor.id) } }, - }), - Atomic.remove(Comment, { lid: "ephemeral" }), - ), - }); - }), - ); + it.effect("removes a resource created earlier in the same request, by lid", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.operations.operations({ + payload: Atomic.request( + Atomic.add(Comment, { + lid: "ephemeral", + attributes: { body: "Now you see me" }, + relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + }), + Atomic.remove(Comment, { lid: "ephemeral" }), + ), + }); + }), + ); - expect(document["atomic:results"]).toHaveLength(2); - expect(document["atomic:results"][1]?.data).toBeUndefined(); - }); + expect(document["atomic:results"]).toHaveLength(2); + expect(document["atomic:results"][1]?.data).toBeUndefined(); + }), + ); }); describe("atomic operations: relationship operations", () => { - it("replaces a required (`one`) to-one relationship", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - - // create a second person to point the comment's author at - const comment = sampleComments[0]; - return yield* client.operations.operations({ - payload: Atomic.request( - // `one` relationships are replaced with another identifier — never null - Atomic.updateRelationship(Comment, comment.id, "author", Person.ref(sampleAuthor.id)), - ), - }); - }), - ); + it.effect("replaces a required (`one`) to-one relationship", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + + // create a second person to point the comment's author at + const comment = sampleComments[0]; + return yield* client.operations.operations({ + payload: Atomic.request( + // `one` relationships are replaced with another identifier — never null + Atomic.updateRelationship(Comment, comment.id, "author", Person.ref(sampleAuthor.id)), + ), + }); + }), + ); - // relationship operations return no data - expect(document["atomic:results"]).toEqual([{}]); - }); + // relationship operations return no data + expect(document["atomic:results"]).toEqual([{}]); + }), + ); - it("replaces an article's tags (`many`, inline linkage)", async () => { - const { after, document } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const document = yield* client.operations.operations({ - payload: Atomic.request(Atomic.updateRelationship(Article, sampleArticle.id, "tags", [])), - }); - const after = yield* client.articles.get({ - params: { id: sampleArticle.id }, - query: {}, - }); - // restore the original tag for other tests - yield* client.operations.operations({ - payload: Atomic.request( - Atomic.updateRelationship(Article, sampleArticle.id, "tags", [Tag.ref(sampleTag.id)]), - ), - }); - return { after, document }; - }), - ); + it.effect("replaces an article's tags (`many`, inline linkage)", () => + Effect.gen(function* () { + const { after, document } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const document = yield* client.operations.operations({ + payload: Atomic.request( + Atomic.updateRelationship(Article, sampleArticle.id, "tags", []), + ), + }); + const after = yield* client.articles.get({ + params: { id: sampleArticle.id }, + query: {}, + }); + // restore the original tag for other tests + yield* client.operations.operations({ + payload: Atomic.request( + Atomic.updateRelationship(Article, sampleArticle.id, "tags", [Tag.ref(sampleTag.id)]), + ), + }); + return { after, document }; + }), + ); + + expect(document["atomic:results"]).toEqual([{}]); + expect(after.data?.relationships?.tags?.data).toEqual([]); + }), + ); - expect(document["atomic:results"]).toEqual([{}]); - expect(after.data?.relationships?.tags?.data).toEqual([]); - }); + it.effect("adds to and removes from a `paginated` relationship", () => + Effect.gen(function* () { + const { added, removed } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; - it("adds to and removes from a `paginated` relationship", async () => { - const { added, removed } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - - // create a standalone comment, then link it to the article's comments - const created = yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Comment, { - lid: "linked", - attributes: { body: "Link me" }, - relationships: { author: { data: Person.ref(sampleAuthor.id) } }, - }), - Atomic.addToRelationship(Article, sampleArticle.id, "comments", [ - Comment.lidRef("linked"), - ]), - ), - }); - - const commentIdData = created["atomic:results"][0].data; - assert.exists(commentIdData); - const commentId = commentIdData.id; - const afterAdd = yield* client.articles.commentsRelationship({ - params: { id: sampleArticle.id }, - query: {}, - }); - - // now unlink it again - yield* client.operations.operations({ - payload: Atomic.request( - Atomic.removeFromRelationship(Article, sampleArticle.id, "comments", [ - Comment.ref(commentId), - ]), - ), - }); - const afterRemove = yield* client.articles.commentsRelationship({ - params: { id: sampleArticle.id }, - query: {}, - }); - - return { - added: afterAdd.data.map((ref) => ref.id), - removed: afterRemove.data.map((ref) => ref.id), - }; - }), - ); + // create a standalone comment, then link it to the article's comments + const created = yield* client.operations.operations({ + payload: Atomic.request( + Atomic.add(Comment, { + lid: "linked", + attributes: { body: "Link me" }, + relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + }), + Atomic.addToRelationship(Article, sampleArticle.id, "comments", [ + Comment.lidRef("linked"), + ]), + ), + }); - expect(added.length).toBe(removed.length + 1); - }); -}); + const commentIdData = created["atomic:results"][0].data; -describe("atomic operations: all-or-nothing", () => { - it("a failing operation rolls back every earlier operation", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.operations.operations({ - payload: Atomic.request( - // this one would succeed... - Atomic.add(Article, { - attributes: { title: "Never persisted", body: "", createdAt: now() }, - relationships: { author: { data: Person.ref(sampleAuthor.id) } }, - }), - // ...but this one fails (unknown article), so nothing is applied - Atomic.update(Article, { - id: Article.Id.make("does-not-exist"), - attributes: { title: "Nope" }, - }), - ), - }); - }), - ); + assert.exists(commentIdData); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - expect(error).toBeInstanceOf(OperationFailed); - // the error identifies the operation that failed - expect((error as OperationFailed).operation).toBe(1); - - // the first operation's article was not committed - const list = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.list({ query: {} }); - }), - ); - expect(list.data.map((article) => article.attributes.title)).not.toContain("Never persisted"); - }); - - it("referencing an unknown lid fails the whole request", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Article, { - attributes: { title: "Refers to nothing", body: "", createdAt: now() }, - relationships: { - author: { data: Person.lidRef("never-declared") }, - }, - }), - ), - }); - }), - ); + const commentId = commentIdData.id; + const afterAdd = yield* client.articles.commentsRelationship({ + params: { id: sampleArticle.id }, + query: {}, + }); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - expect(error).toBeInstanceOf(OperationFailed); - expect((error as OperationFailed).reason).toMatch(/never-declared/); - expect((error as OperationFailed).operation).toBe(0); - }); + // now unlink it again + yield* client.operations.operations({ + payload: Atomic.request( + Atomic.removeFromRelationship(Article, sampleArticle.id, "comments", [ + Comment.ref(commentId), + ]), + ), + }); + const afterRemove = yield* client.articles.commentsRelationship({ + params: { id: sampleArticle.id }, + query: {}, + }); + + return { + added: afterAdd.data.map((ref) => ref.id), + removed: afterRemove.data.map((ref) => ref.id), + }; + }), + ); + + expect(added.length).toBe(removed.length + 1); + }), + ); }); -describe("atomic operations: linkage to an absent resource", () => { - it("an author op naming an unknown person 404s and rolls back the whole request", async () => { - const { exit, articles, author } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const exit = yield* Effect.exit( - client.operations.operations({ +describe("atomic operations: all-or-nothing", () => { + it.effect("a failing operation rolls back every earlier operation", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.operations.operations({ payload: Atomic.request( // this one would succeed... Atomic.add(Article, { - attributes: { - title: "Orphaned by a 404", - body: "", - createdAt: sampleArticle.attributes.createdAt, - }, + attributes: { title: "Never persisted", body: "", createdAt: now() }, relationships: { author: { data: Person.ref(sampleAuthor.id) } }, }), - // ...but this one names a person the store does not hold - Atomic.updateRelationship( - Article, - sampleArticle.id, - "author", - Person.ref("does-not-exist"), - ), + // ...but this one fails (unknown article), so nothing is applied + Atomic.update(Article, { + id: Article.Id.make("does-not-exist"), + attributes: { title: "Nope" }, + }), ), - }), - ); - const list = yield* client.articles.list({ query: {} }); - const after = yield* client.articles.get({ params: { id: sampleArticle.id }, query: {} }); - return { - exit, - articles: list.data.map((article) => article.attributes.title), - author: after.data?.relationships?.author?.data.id, - }; - }), - ); + }); + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + expect(error).toBeInstanceOf(OperationFailed); + // the error identifies the operation that failed + expect((error as OperationFailed).operation).toBe(1); + + // the first operation's article was not committed + const list = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.list({ query: {} }); + }), + ); + expect(list.data.map((article) => article.attributes.title)).not.toContain("Never persisted"); + }), + ); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof PersonNotFound); - expect(error.id).toBe("does-not-exist"); - // the pointer locates the linkage inside the failing operation - expect(error.pointer).toBe("/atomic:operations/1/data"); - // all-or-nothing: neither operation was committed - expect(articles).not.toContain("Orphaned by a 404"); - expect(author).toBe(sampleAuthor.id); - }); + it.effect("referencing an unknown lid fails the whole request", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.operations.operations({ + payload: Atomic.request( + Atomic.add(Article, { + attributes: { title: "Refers to nothing", body: "", createdAt: now() }, + relationships: { + author: { data: Person.lidRef("never-declared") }, + }, + }), + ), + }); + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + expect(error).toBeInstanceOf(OperationFailed); + expect((error as OperationFailed).reason).toMatch(/never-declared/); + expect((error as OperationFailed).operation).toBe(0); + }), + ); +}); - it("a resource op linking an unknown author 404s, pointing at its relationship", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Comment, { - attributes: { body: "Who wrote this?" }, - relationships: { author: { data: Person.ref("does-not-exist") } }, +describe("atomic operations: linkage to an absent resource", () => { + it.effect("an author op naming an unknown person 404s and rolls back the whole request", () => + Effect.gen(function* () { + const { exit, articles, author } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const exit = yield* Effect.exit( + client.operations.operations({ + payload: Atomic.request( + // this one would succeed... + Atomic.add(Article, { + attributes: { + title: "Orphaned by a 404", + body: "", + createdAt: sampleArticle.attributes.createdAt, + }, + relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + }), + // ...but this one names a person the store does not hold + Atomic.updateRelationship( + Article, + sampleArticle.id, + "author", + Person.ref("does-not-exist"), + ), + ), }), - ), - }); - }), - ); - - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof PersonNotFound); - expect(error.pointer).toBe("/atomic:operations/0/data/relationships/author/data"); - }); + ); + const list = yield* client.articles.list({ query: {} }); + const after = yield* client.articles.get({ params: { id: sampleArticle.id }, query: {} }); + return { + exit, + articles: list.data.map((article) => article.attributes.title), + author: after.data?.relationships?.author?.data.id, + }; + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof PersonNotFound); + expect(error.id).toBe("does-not-exist"); + // the pointer locates the linkage inside the failing operation + expect(error.pointer).toBe("/atomic:operations/1/data"); + // all-or-nothing: neither operation was committed + expect(articles).not.toContain("Orphaned by a 404"); + expect(author).toBe(sampleAuthor.id); + }), + ); - it("a tags op naming an unknown tag 404s at that identifier and rolls back", async () => { - const { exit, tags } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const exit = yield* Effect.exit( - client.operations.operations({ + it.effect("a resource op linking an unknown author 404s, pointing at its relationship", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.operations.operations({ payload: Atomic.request( - // this one would succeed (clearing the tags)... - Atomic.updateRelationship(Article, sampleArticle.id, "tags", []), - // ...but this one names a tag the store does not hold - Atomic.addToRelationship(Article, sampleArticle.id, "tags", [ - Tag.ref(sampleTag.id), - Tag.ref("does-not-exist"), - ]), + Atomic.add(Comment, { + attributes: { body: "Who wrote this?" }, + relationships: { author: { data: Person.ref("does-not-exist") } }, + }), ), - }), - ); - const after = yield* client.articles.get({ params: { id: sampleArticle.id }, query: {} }); - return { exit, tags: after.data?.relationships?.tags?.data }; - }), - ); - - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof TagNotFound); - expect(error.id).toBe("does-not-exist"); - expect(error.pointer).toBe("/atomic:operations/1/data/1"); - // all-or-nothing: the clearing operation was not committed either - expect(tags).toEqual([Tag.ref(sampleTag.id)]); - }); + }); + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof PersonNotFound); + expect(error.pointer).toBe("/atomic:operations/0/data/relationships/author/data"); + }), + ); - it("an article add linking an unknown tag 404s at its relationship", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Article, { - attributes: { - title: "Tagged with nothing", - body: "", - createdAt: sampleArticle.attributes.createdAt, - }, - relationships: { - author: { data: Person.ref(sampleAuthor.id) }, - tags: { data: [Tag.ref("does-not-exist")] }, - }, + it.effect("a tags op naming an unknown tag 404s at that identifier and rolls back", () => + Effect.gen(function* () { + const { exit, tags } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const exit = yield* Effect.exit( + client.operations.operations({ + payload: Atomic.request( + // this one would succeed (clearing the tags)... + Atomic.updateRelationship(Article, sampleArticle.id, "tags", []), + // ...but this one names a tag the store does not hold + Atomic.addToRelationship(Article, sampleArticle.id, "tags", [ + Tag.ref(sampleTag.id), + Tag.ref("does-not-exist"), + ]), + ), }), - ), - }); - }), - ); - - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof TagNotFound); - expect(error.pointer).toBe("/atomic:operations/0/data/relationships/tags/data/0"); - }); + ); + const after = yield* client.articles.get({ params: { id: sampleArticle.id }, query: {} }); + return { exit, tags: after.data?.relationships?.tags?.data }; + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof TagNotFound); + expect(error.id).toBe("does-not-exist"); + expect(error.pointer).toBe("/atomic:operations/1/data/1"); + // all-or-nothing: the clearing operation was not committed either + expect(tags).toEqual([Tag.ref(sampleTag.id)]); + }), + ); - it("a comments op naming an unknown comment 404s and links none of its batch", async () => { - const { exit, linked } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const before = yield* client.articles.commentsRelationship({ - params: { id: sampleArticle.id }, - query: {}, - }); - const exit = yield* Effect.exit( - client.operations.operations({ + it.effect("an article add linking an unknown tag 404s at its relationship", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.operations.operations({ payload: Atomic.request( - // a comment created earlier in the same request is linkable... - Atomic.add(Comment, { - lid: "fresh", - attributes: { body: "Created in this request" }, - relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + Atomic.add(Article, { + attributes: { + title: "Tagged with nothing", + body: "", + createdAt: sampleArticle.attributes.createdAt, + }, + relationships: { + author: { data: Person.ref(sampleAuthor.id) }, + tags: { data: [Tag.ref("does-not-exist")] }, + }, }), - // ...but the unknown one fails the whole request - Atomic.addToRelationship(Article, sampleArticle.id, "comments", [ - Comment.lidRef("fresh"), - Comment.ref("does-not-exist"), - ]), ), - }), - ); - const after = yield* client.articles.commentsRelationship({ - params: { id: sampleArticle.id }, - query: {}, - }); - return { - exit, - linked: { - before: before.data.map((ref) => ref.id), - after: after.data.map((ref) => ref.id), - }, - }; - }), - ); - - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof CommentNotFound); - expect(error.id).toBe("does-not-exist"); - expect(error.pointer).toBe("/atomic:operations/1/data/1"); - expect(linked.after).toEqual(linked.before); - }); + }); + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof TagNotFound); + expect(error.pointer).toBe("/atomic:operations/0/data/relationships/tags/data/0"); + }), + ); - it("a remove naming an unknown tag or comment succeeds, removing the rest", async () => { - // #477: a resource that does not exist is already missing from the - // relationship, so a `remove` naming one is applied, not refused with a - // 404. The article is the request's own, so the shared sample is untouched. - const comment = sampleComments[0]; - assert(comment !== undefined); - const { tags, comments } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const created = yield* client.operations.operations({ - payload: Atomic.request( - Atomic.add(Article, { - lid: "a1", - attributes: { - title: "Removing what is not there", - body: "", - createdAt: sampleArticle.attributes.createdAt, - }, - relationships: { - author: { data: Person.ref(sampleAuthor.id) }, - tags: { data: [Tag.ref(sampleTag.id)] }, - }, + it.effect("a comments op naming an unknown comment 404s and links none of its batch", () => + Effect.gen(function* () { + const { exit, linked } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const before = yield* client.articles.commentsRelationship({ + params: { id: sampleArticle.id }, + query: {}, + }); + const exit = yield* Effect.exit( + client.operations.operations({ + payload: Atomic.request( + // a comment created earlier in the same request is linkable... + Atomic.add(Comment, { + lid: "fresh", + attributes: { body: "Created in this request" }, + relationships: { author: { data: Person.ref(sampleAuthor.id) } }, + }), + // ...but the unknown one fails the whole request + Atomic.addToRelationship(Article, sampleArticle.id, "comments", [ + Comment.lidRef("fresh"), + Comment.ref("does-not-exist"), + ]), + ), }), - Atomic.addToRelationship(Article, { lid: "a1" }, "comments", [Comment.ref(comment.id)]), - ), - }); - const added = created["atomic:results"][0]?.data; - assert(added !== undefined && added !== null); - const id = Article.Id.make(added.id); - yield* client.operations.operations({ - payload: Atomic.request( - Atomic.removeFromRelationship(Article, id, "tags", [ - Tag.ref(sampleTag.id), - Tag.ref("does-not-exist"), - ]), - Atomic.removeFromRelationship(Article, id, "comments", [ - Comment.ref("does-not-exist"), - Comment.ref(comment.id), - ]), - ), - }); - const article = yield* client.articles.get({ params: { id }, query: {} }); - const linked = yield* client.articles.commentsRelationship({ params: { id }, query: {} }); - return { - tags: article.data?.relationships?.tags?.data, - comments: linked.data.map((ref) => ref.id), - }; - }), - ); + ); + const after = yield* client.articles.commentsRelationship({ + params: { id: sampleArticle.id }, + query: {}, + }); + return { + exit, + linked: { + before: before.data.map((ref) => ref.id), + after: after.data.map((ref) => ref.id), + }, + }; + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof CommentNotFound); + expect(error.id).toBe("does-not-exist"); + expect(error.pointer).toBe("/atomic:operations/1/data/1"); + expect(linked.after).toEqual(linked.before); + }), + ); - expect(tags).toEqual([]); - expect(comments).toEqual([]); - }); + it.effect("a remove naming an unknown tag or comment succeeds, removing the rest", () => + Effect.gen(function* () { + // #477: a resource that does not exist is already missing from the + // relationship, so a `remove` naming one is applied, not refused with a + // 404. The article is the request's own, so the shared sample is untouched. + const comment = sampleComments[0]; + assert(comment !== undefined); + const { tags, comments } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const created = yield* client.operations.operations({ + payload: Atomic.request( + Atomic.add(Article, { + lid: "a1", + attributes: { + title: "Removing what is not there", + body: "", + createdAt: sampleArticle.attributes.createdAt, + }, + relationships: { + author: { data: Person.ref(sampleAuthor.id) }, + tags: { data: [Tag.ref(sampleTag.id)] }, + }, + }), + Atomic.addToRelationship(Article, { lid: "a1" }, "comments", [ + Comment.ref(comment.id), + ]), + ), + }); + const added = created["atomic:results"][0]?.data; + assert(added !== undefined && added !== null); + const id = Article.Id.make(added.id); + yield* client.operations.operations({ + payload: Atomic.request( + Atomic.removeFromRelationship(Article, id, "tags", [ + Tag.ref(sampleTag.id), + Tag.ref("does-not-exist"), + ]), + Atomic.removeFromRelationship(Article, id, "comments", [ + Comment.ref("does-not-exist"), + Comment.ref(comment.id), + ]), + ), + }); + const article = yield* client.articles.get({ params: { id }, query: {} }); + const linked = yield* client.articles.commentsRelationship({ params: { id }, query: {} }); + return { + tags: article.data?.relationships?.tags?.data, + comments: linked.data.map((ref) => ref.id), + }; + }), + ); + + expect(tags).toEqual([]); + expect(comments).toEqual([]); + }), + ); it("the 404's error document carries the pointer as source.pointer", () => { const encoded = Schema.encodeSync(PersonNotFound.wire)( diff --git a/examples/blog/test/blog.test.ts b/examples/blog/test/blog.test.ts index b11451b..9854331 100644 --- a/examples/blog/test/blog.test.ts +++ b/examples/blog/test/blog.test.ts @@ -3,8 +3,9 @@ * encoding → routing → middleware → handler → response decoding) through the * in-memory `HttpApiTest` client. */ +import { it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { assert, describe, expect, expectTypeOf, it } from "vite-plus/test"; +import { assert, describe, expect, expectTypeOf } from "vite-plus/test"; import * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; @@ -36,18 +37,14 @@ const buildClient = HttpApiTest.groups(Api, ["articles", "search"]); const jsonText = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); -const run = (effect: Effect.Effect): Promise => - Effect.runPromise( - effect.pipe( - Effect.scoped, - Effect.provide( - Layer.provideMerge(Layer.mergeAll(ArticlesLive, SearchLive), Middleware.layer), - ), - ) as Effect.Effect, - ); +const run = (effect: Effect.Effect): Effect.Effect => + effect.pipe( + Effect.scoped, + Effect.provide(Layer.provideMerge(Layer.mergeAll(ArticlesLive, SearchLive), Middleware.layer)), + ) as Effect.Effect; -const runExit = (effect: Effect.Effect): Promise> => - Effect.runPromiseExit( +const runExit = (effect: Effect.Effect): Effect.Effect> => + Effect.exit( effect.pipe( Effect.scoped, Effect.provide( @@ -62,186 +59,209 @@ const findFailure = (cause: Cause.Cause): E | undefined => { }; describe("blog example: fetching", () => { - it("fetches a single article document with a self link", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ - params: { id: Article.Id.make("1") }, - query: {}, - }); - }), - ); - - expect(document.data).toMatchObject({ - type: "articles", - id: "1", - attributes: { title: "JSON:API paints my bikeshed!" }, - }); - expect(document.links?.self).toBe("/articles/1"); - // dates decode through the wire format - expect(document.data?.attributes.createdAt).toBeInstanceOf(Date); - // no `?include=`, no compound document: the member is absent, not `[]` - expect(document).not.toHaveProperty("included"); - }); - - it("serves compound documents for ?include=author,tags", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ - params: { id: Article.Id.make("1") }, - query: { include: ["author", "tags"] }, - }); - }), - ); - - const types = Arr.sort(document.included?.map((resource) => resource.type) ?? [], Order.String); - expect(types).toEqual(["people", "tags"]); - }); - - it("projects ?fields[TYPE]= on primary data and `included`, and advertises JSON:API 1.1", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ - params: { id: Article.Id.make("1") }, - query: { include: ["author"], fields: { articles: ["title"], people: ["lastName"] } }, - }); - }), - ); + it.effect("fetches a single article document with a self link", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ + params: { id: Article.Id.make("1") }, + query: {}, + }); + }), + ); + + expect(document.data).toMatchObject({ + type: "articles", + id: "1", + attributes: { title: "JSON:API paints my bikeshed!" }, + }); + expect(document.links?.self).toBe("/articles/1"); + // dates decode through the wire format + expect(document.data?.attributes.createdAt).toBeInstanceOf(Date); + // no `?include=`, no compound document: the member is absent, not `[]` + expect(document).not.toHaveProperty("included"); + }), + ); - // `onResource: Handlers.project(query.fields)` applies each fieldset to - // every resource of that type, wherever it sits in the document. - expect(document.data.attributes).toEqual({ title: sampleArticle.attributes.title }); - expect(document.included?.map((resource) => resource.attributes)).toEqual([ - { lastName: sampleAuthor.attributes.lastName }, - ]); - // A relationship is a field too (#494): `author` was not requested, so it - // is dropped, and the included author it linked is exempt from full - // linkage (§Compound Documents). - expect(document.data.relationships).toBeUndefined(); - expect(document.jsonapi).toEqual({ version: "1.1" }); - }); + it.effect("serves compound documents for ?include=author,tags", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ + params: { id: Article.Id.make("1") }, + query: { include: ["author", "tags"] }, + }); + }), + ); + + const types = Arr.sort( + document.included?.map((resource) => resource.type) ?? [], + Order.String, + ); + expect(types).toEqual(["people", "tags"]); + }), + ); - it("keeps the relationships a fieldset names", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ - params: { id: Article.Id.make("1") }, - query: { include: ["author"], fields: { articles: ["title", "author"] } }, - }); - }), - ); - expect(document.data.attributes).toEqual({ title: sampleArticle.attributes.title }); - expect(Object.keys(document.data.relationships ?? {})).toEqual(["author"]); - expect(document.data.relationships?.author?.data).toEqual(Person.ref(sampleAuthor.id)); - }); + it.effect( + "projects ?fields[TYPE]= on primary data and `included`, and advertises JSON:API 1.1", + () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ + params: { id: Article.Id.make("1") }, + query: { include: ["author"], fields: { articles: ["title"], people: ["lastName"] } }, + }); + }), + ); - it("paginated relationships appear as links, never as inline data or includes", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ - params: { id: Article.Id.make("1") }, - query: {}, - }); + // `onResource: Handlers.project(query.fields)` applies each fieldset to + // every resource of that type, wherever it sits in the document. + expect(document.data.attributes).toEqual({ title: sampleArticle.attributes.title }); + expect(document.included?.map((resource) => resource.attributes)).toEqual([ + { lastName: sampleAuthor.attributes.lastName }, + ]); + // A relationship is a field too (#494): `author` was not requested, so it + // is dropped, and the included author it linked is exempt from full + // linkage (§Compound Documents). + expect(document.data.relationships).toBeUndefined(); + expect(document.jsonapi).toEqual({ version: "1.1" }); }), - ); - - // The comments relationship carries only links pointing at its endpoints. - const comments = document.data?.relationships?.comments; - expect(comments).toEqual({ - links: { - self: "/articles/1/relationships/comments", - related: "/articles/1/comments", - }, - }); - // ... and `comments` is not a legal include path. - type IncludePaths = Resource.IncludePath; - expectTypeOf().toEqualTypeOf<"author" | "tags">(); - }); + ); - it("narrows `included` to the requested include paths on the client", async () => { - const include = ["author"] as const; - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles - .get({ + it.effect("keeps the relationships a fieldset names", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ params: { id: Article.Id.make("1") }, - query: { include }, - }) - .pipe(Client.narrowIncluded(Article, include)); - }), - ); + query: { include: ["author"], fields: { articles: ["title", "author"] } }, + }); + }), + ); + expect(document.data.attributes).toEqual({ title: sampleArticle.attributes.title }); + expect(Object.keys(document.data.relationships ?? {})).toEqual(["author"]); + expect(document.data.relationships?.author?.data).toEqual(Person.ref(sampleAuthor.id)); + }), + ); - // Runtime: the server only included the requested author - expect(document.included?.map((resource) => resource.type)).toEqual(["people"]); - // Types: `included` is narrowed to Person — its attributes are accessible - // without discriminating on `type` - const author = document.included?.[0]; - expect(author?.attributes.firstName).toBe("Dan"); - assert(author !== undefined); - expectTypeOf(author.attributes.firstName).toEqualTypeOf(); - expectTypeOf(author.type).toEqualTypeOf<"people">(); - }); + it.effect("paginated relationships appear as links, never as inline data or includes", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ + params: { id: Article.Id.make("1") }, + query: {}, + }); + }), + ); + + // The comments relationship carries only links pointing at its endpoints. + const comments = document.data?.relationships?.comments; + expect(comments).toEqual({ + links: { + self: "/articles/1/relationships/comments", + related: "/articles/1/comments", + }, + }); + // ... and `comments` is not a legal include path. + type IncludePaths = Resource.IncludePath; + expectTypeOf().toEqualTypeOf<"author" | "tags">(); + }), + ); - it("404s with a typed error for unknown articles", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ - params: { id: Article.Id.make("nope") }, - query: {}, - }); - }), - ); + it.effect("narrows `included` to the requested include paths on the client", () => + Effect.gen(function* () { + const include = ["author"] as const; + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles + .get({ + params: { id: Article.Id.make("1") }, + query: { include }, + }) + .pipe(Client.narrowIncluded(Article, include)); + }), + ); + + // Runtime: the server only included the requested author + expect(document.included?.map((resource) => resource.type)).toEqual(["people"]); + // Types: `included` is narrowed to Person — its attributes are accessible + // without discriminating on `type` + const author = document.included?.[0]; + expect(author?.attributes.firstName).toBe("Dan"); + assert(author !== undefined); + expectTypeOf(author.attributes.firstName).toEqualTypeOf(); + expectTypeOf(author.type).toEqualTypeOf<"people">(); + }), + ); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - expect(error).toBeInstanceOf(ArticleNotFound); - expect((error as ArticleNotFound).id).toBe("nope"); - }); + it.effect("404s with a typed error for unknown articles", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ + params: { id: Article.Id.make("nope") }, + query: {}, + }); + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + expect(error).toBeInstanceOf(ArticleNotFound); + expect((error as ArticleNotFound).id).toBe("nope"); + }), + ); }); describe("blog example: listing", () => { - it("lists articles with sorting, pagination and typed meta", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.list({ - query: { - sort: [{ field: "createdAt", direction: "desc" }], - page: { offset: 0, limit: 10 }, - }, - }); - }), - ); - - expect(document.data.length).toBeGreaterThan(0); - expect(document.meta?.total).toBeGreaterThan(0); - expect(document.links?.first).toBe("/articles?sort=-createdAt&page[offset]=0&page[limit]=10"); - }); - - it("filters by author", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.list({ - query: { filter: { author: "does-not-exist" } }, - }); - }), - ); + it.effect("lists articles with sorting, pagination and typed meta", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.list({ + query: { + sort: [{ field: "createdAt", direction: "desc" }], + page: { offset: 0, limit: 10 }, + }, + }); + }), + ); + + expect(document.data.length).toBeGreaterThan(0); + expect(document.meta?.total).toBeGreaterThan(0); + expect(document.links?.first).toBe("/articles?sort=-createdAt&page[offset]=0&page[limit]=10"); + }), + ); - expect(document.data).toEqual([]); - }); + it.effect("filters by author", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.list({ + query: { filter: { author: "does-not-exist" } }, + }); + }), + ); + + expect(document.data).toEqual([]); + }), + ); }); describe("blog example: writing", () => { - it("creates an article from a JSON:API payload (201) and then deletes it (204)", async () => { - await run( + it.effect("creates an article from a JSON:API payload (201) and then deletes it (204)", () => + run( Effect.gen(function* () { const client = yield* buildClient; @@ -275,345 +295,383 @@ describe("blog example: writing", () => { // and delete it again yield* client.articles.delete({ params: { id: created.data.id } }); }), - ); - }); + ), + ); - it("409s when the title is already taken", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.create({ - payload: { - data: { - type: "articles", - attributes: { - title: sampleArticle.attributes.title, - body: "duplicate", - createdAt: now(), - }, - relationships: { - author: { data: Person.ref(sampleAuthor.id) }, + it.effect("409s when the title is already taken", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.create({ + payload: { + data: { + type: "articles", + attributes: { + title: sampleArticle.attributes.title, + body: "duplicate", + createdAt: now(), + }, + relationships: { + author: { data: Person.ref(sampleAuthor.id) }, + }, }, }, - }, - }); - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(TitleTaken); - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(TitleTaken); + }), + ); - it("updates an article with partial attributes", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.update({ - params: { id: Article.Id.make("1") }, - payload: { - data: { - type: "articles", - id: Article.Id.make("1"), - attributes: { body: "Updated body" }, + it.effect("updates an article with partial attributes", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.update({ + params: { id: Article.Id.make("1") }, + payload: { + data: { + type: "articles", + id: Article.Id.make("1"), + attributes: { body: "Updated body" }, + }, }, - }, - }); - }), - ); - - expect(document.data?.attributes.body).toBe("Updated body"); - expect(document.data?.attributes.title).toBe(sampleArticle.attributes.title); - // a write response advertises JSON:API 1.1 too, not only the reads - expect(document.jsonapi?.version).toBe("1.1"); - }); + }); + }), + ); + + expect(document.data?.attributes.body).toBe("Updated body"); + expect(document.data?.attributes.title).toBe(sampleArticle.attributes.title); + // a write response advertises JSON:API 1.1 too, not only the reads + expect(document.jsonapi?.version).toBe("1.1"); + }), + ); }); describe("blog example: related resource endpoints", () => { - it("GET /articles/:id/author serves the author as a full resource document", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.author({ - params: { id: Article.Id.make("1") }, - query: {}, - }); - }), - ); - - expect(document.data).toMatchObject({ - type: "people", - id: sampleAuthor.id, - attributes: { firstName: "Dan", lastName: "Gebhardt" }, - }); - expect(document.links?.self).toBe("/articles/1/author"); - }); - - it("GET /articles/:id/comments serves the paginated comment collection", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.comments({ - params: { id: Article.Id.make("1") }, - query: { page: { offset: 0, limit: 1 } }, - }); - }), - ); - - // Full comment resources, paginated - expect(document.data).toHaveLength(1); - expect(document.data[0]?.attributes.body).toBe("First!"); - expect(document.meta?.total).toBe(2); - expect(document.links?.next).toBe("/articles/1/comments?page[offset]=1&page[limit]=1"); - }); - - it("GET /articles/:id/comments supports compound documents (?include=author)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.comments({ - params: { id: Article.Id.make("1") }, - query: { include: ["author"] }, - }); - }), - ); + it.effect("GET /articles/:id/author serves the author as a full resource document", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.author({ + params: { id: Article.Id.make("1") }, + query: {}, + }); + }), + ); + + expect(document.data).toMatchObject({ + type: "people", + id: sampleAuthor.id, + attributes: { firstName: "Dan", lastName: "Gebhardt" }, + }); + expect(document.links?.self).toBe("/articles/1/author"); + }), + ); - expect(document.data).toHaveLength(2); - // Both comments share the same author — deduplicated to one include. - expect(document.included?.map((resource) => resource.type)).toEqual(["people"]); - }); + it.effect("GET /articles/:id/comments serves the paginated comment collection", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.comments({ + params: { id: Article.Id.make("1") }, + query: { page: { offset: 0, limit: 1 } }, + }); + }), + ); + + // Full comment resources, paginated + expect(document.data).toHaveLength(1); + expect(document.data[0]?.attributes.body).toBe("First!"); + expect(document.meta?.total).toBe(2); + expect(document.links?.next).toBe("/articles/1/comments?page[offset]=1&page[limit]=1"); + }), + ); - it("404s for related endpoints of unknown articles", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.comments({ - params: { id: Article.Id.make("nope") }, - query: {}, - }); - }), - ); + it.effect("GET /articles/:id/comments supports compound documents (?include=author)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.comments({ + params: { id: Article.Id.make("1") }, + query: { include: ["author"] }, + }); + }), + ); + + expect(document.data).toHaveLength(2); + // Both comments share the same author — deduplicated to one include. + expect(document.included?.map((resource) => resource.type)).toEqual(["people"]); + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(ArticleNotFound); - }); + it.effect("404s for related endpoints of unknown articles", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.comments({ + params: { id: Article.Id.make("nope") }, + query: {}, + }); + }), + ); + + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(ArticleNotFound); + }), + ); }); describe("blog example: relationship endpoints", () => { - it("GET /articles/:id/relationships/comments serves paginated linkage", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.commentsRelationship({ - params: { id: Article.Id.make("1") }, - query: {}, - }); - }), - ); - - // Identifiers only — no attributes - expect(document.data).toEqual( - sampleComments.map((comment) => ({ type: "comments", id: comment.id })), - ); - expect(document.links?.self).toBe("/articles/1/relationships/comments"); - expect(document.links?.related).toBe("/articles/1/comments"); - expect(document.meta?.total).toBe(2); - }); + it.effect("GET /articles/:id/relationships/comments serves paginated linkage", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.commentsRelationship({ + params: { id: Article.Id.make("1") }, + query: {}, + }); + }), + ); + + // Identifiers only — no attributes + expect(document.data).toEqual( + sampleComments.map((comment) => ({ type: "comments", id: comment.id })), + ); + expect(document.links?.self).toBe("/articles/1/relationships/comments"); + expect(document.links?.related).toBe("/articles/1/comments"); + expect(document.meta?.total).toBe(2); + }), + ); - it("GET /articles/:id/relationships/comments?include=comments.author serves the page's comments and their authors", async () => { - // The spec's own example (§Inclusion of Related Resources), on the - // paginated `comments` (#483). - const [bare, firstPage, secondPage] = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const params = { id: Article.Id.make("1") }; - return [ - yield* client.articles.commentsRelationship({ params, query: {} }), - yield* client.articles.commentsRelationship({ - params, - query: { include: ["comments.author"], page: { limit: 1 } }, - }), - yield* client.articles.commentsRelationship({ - params, - query: { include: ["comments"], page: { offset: 1, limit: 1 } }, + it.effect( + "GET /articles/:id/relationships/comments?include=comments.author serves the page's comments and their authors", + () => + Effect.gen(function* () { + // The spec's own example (§Inclusion of Related Resources), on the + // paginated `comments` (#483). + const [bare, firstPage, secondPage] = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const params = { id: Article.Id.make("1") }; + return [ + yield* client.articles.commentsRelationship({ params, query: {} }), + yield* client.articles.commentsRelationship({ + params, + query: { include: ["comments.author"], page: { limit: 1 } }, + }), + yield* client.articles.commentsRelationship({ + params, + query: { include: ["comments"], page: { offset: 1, limit: 1 } }, + }), + ] as const; }), - ] as const; - }), - ); - - // Without `?include=`, linkage only: no `included` member. - expect(bare).not.toHaveProperty("included"); - // With it, the comments on the page — not the whole relationship — and, - // for `comments.author`, their author. - const [first, second] = sampleComments; - assert(first !== undefined && second !== undefined); - expect(firstPage.data).toEqual([Comment.ref(first.id)]); - expect(firstPage.included).toEqual([first, sampleAuthor]); - expect(secondPage.data).toEqual([Comment.ref(second.id)]); - expect(secondPage.included).toEqual([second]); - expect(firstPage.meta?.total).toBe(2); - }); + ); - it("GET /articles/:id/relationships/tags?include=tags serves a compound relationship document", async () => { - const [bare, compound] = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const params = { id: Article.Id.make("1") }; - return [ - yield* client.articles.tagsRelationship({ params, query: {} }), - yield* client.articles.tagsRelationship({ params, query: { include: ["tags"] } }), - ] as const; + // Without `?include=`, linkage only: no `included` member. + expect(bare).not.toHaveProperty("included"); + // With it, the comments on the page — not the whole relationship — and, + // for `comments.author`, their author. + const [first, second] = sampleComments; + assert(first !== undefined && second !== undefined); + expect(firstPage.data).toEqual([Comment.ref(first.id)]); + expect(firstPage.included).toEqual([first, sampleAuthor]); + expect(secondPage.data).toEqual([Comment.ref(second.id)]); + expect(secondPage.included).toEqual([second]); + expect(firstPage.meta?.total).toBe(2); }), - ); + ); - // Without `?include=`, linkage only: no `included` member. - expect(bare.data).toEqual([{ type: "tags", id: sampleTag.id }]); - expect(bare).not.toHaveProperty("included"); - // With it, the identifiers stay the primary data and the tags they name are - // `included` — the same `(type, id)` in both is no duplicate. - expect(compound.data).toEqual([{ type: "tags", id: sampleTag.id }]); - // The endpoint declares `fields` (#485), so an `included` tag's - // attributes decode as optional. - expectTypeOf[number]["attributes"]>().toEqualTypeOf<{ - readonly name?: string; - readonly slug?: string; - }>(); - expect(compound.included).toEqual([sampleTag]); - expect(compound.links?.self).toBe("/articles/1/relationships/tags"); - }); + it.effect( + "GET /articles/:id/relationships/tags?include=tags serves a compound relationship document", + () => + Effect.gen(function* () { + const [bare, compound] = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const params = { id: Article.Id.make("1") }; + return [ + yield* client.articles.tagsRelationship({ params, query: {} }), + yield* client.articles.tagsRelationship({ params, query: { include: ["tags"] } }), + ] as const; + }), + ); - it("GET /articles/:id/relationships/tags?include=tags&fields[tags]=name narrows the included tags", async () => { - const sparse = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.tagsRelationship({ - params: { id: Article.Id.make("1") }, - query: { include: ["tags"], fields: { tags: ["name"] } }, - }); + // Without `?include=`, linkage only: no `included` member. + expect(bare.data).toEqual([{ type: "tags", id: sampleTag.id }]); + expect(bare).not.toHaveProperty("included"); + // With it, the identifiers stay the primary data and the tags they name are + // `included` — the same `(type, id)` in both is no duplicate. + expect(compound.data).toEqual([{ type: "tags", id: sampleTag.id }]); + // The endpoint declares `fields` (#485), so an `included` tag's + // attributes decode as optional. + expectTypeOf[number]["attributes"]>().toEqualTypeOf<{ + readonly name?: string; + readonly slug?: string; + }>(); + expect(compound.included).toEqual([sampleTag]); + expect(compound.links?.self).toBe("/articles/1/relationships/tags"); }), - ); + ); - // #485: the fieldset narrows the `included` tags; the identifiers, which - // have no fields, are untouched. A client decodes the attributes as - // optional, since a fieldset may leave any of them out. - expect(sparse.data).toEqual([{ type: "tags", id: sampleTag.id }]); - expect(sparse.included).toEqual([ - { ...sampleTag, attributes: { name: sampleTag.attributes.name } }, - ]); - expectTypeOf[number]["attributes"]["slug"]>().toEqualTypeOf< - string | undefined - >(); - }); + it.effect( + "GET /articles/:id/relationships/tags?include=tags&fields[tags]=name narrows the included tags", + () => + Effect.gen(function* () { + const sparse = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.tagsRelationship({ + params: { id: Article.Id.make("1") }, + query: { include: ["tags"], fields: { tags: ["name"] } }, + }); + }), + ); - it("PATCH /articles/:id/relationships/author replaces the author", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const replaced = yield* client.articles.updateAuthorRelationship({ - params: { id: Article.Id.make("1") }, - payload: { data: Person.ref(sampleAuthor.id) }, - }); - // The article reflects the change - const article = yield* client.articles.get({ - params: { id: Article.Id.make("1") }, - query: {}, - }); - expect(article.data?.relationships?.author?.data.id).toBe(sampleAuthor.id); - return replaced; + // #485: the fieldset narrows the `included` tags; the identifiers, which + // have no fields, are untouched. A client decodes the attributes as + // optional, since a fieldset may leave any of them out. + expect(sparse.data).toEqual([{ type: "tags", id: sampleTag.id }]); + expect(sparse.included).toEqual([ + { ...sampleTag, attributes: { name: sampleTag.attributes.name } }, + ]); + expectTypeOf< + NonNullable[number]["attributes"]["slug"] + >().toEqualTypeOf(); }), - ); - - expect(document.data).toEqual({ type: "people", id: sampleAuthor.id }); - }); - - it("POST /articles/:id/relationships/comments attaches comments; DELETE detaches them", async () => { - await run( - Effect.gen(function* () { - const client = yield* buildClient; - const articleId = Article.Id.make("1"); + ); - // Detach one comment - yield* client.articles.removeCommentsRelationship({ - params: { id: articleId }, - payload: { data: [Comment.ref(sampleComments[0].id)] }, - }); + it.effect("PATCH /articles/:id/relationships/author replaces the author", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const replaced = yield* client.articles.updateAuthorRelationship({ + params: { id: Article.Id.make("1") }, + payload: { data: Person.ref(sampleAuthor.id) }, + }); + // The article reflects the change + const article = yield* client.articles.get({ + params: { id: Article.Id.make("1") }, + query: {}, + }); + expect(article.data?.relationships?.author?.data.id).toBe(sampleAuthor.id); + return replaced; + }), + ); + + expect(document.data).toEqual({ type: "people", id: sampleAuthor.id }); + }), + ); - const afterRemove = yield* client.articles.commentsRelationship({ - params: { id: articleId }, - query: {}, - }); - expect(afterRemove.data.map((identifier) => identifier.id)).toEqual([sampleComments[1].id]); + it.effect( + "POST /articles/:id/relationships/comments attaches comments; DELETE detaches them", + () => + run( + Effect.gen(function* () { + const client = yield* buildClient; + const articleId = Article.Id.make("1"); + + // Detach one comment + yield* client.articles.removeCommentsRelationship({ + params: { id: articleId }, + payload: { data: [Comment.ref(sampleComments[0].id)] }, + }); + + const afterRemove = yield* client.articles.commentsRelationship({ + params: { id: articleId }, + query: {}, + }); + expect(afterRemove.data.map((identifier) => identifier.id)).toEqual([ + sampleComments[1].id, + ]); + + // Re-attach it + const afterAdd = yield* client.articles.addCommentsRelationship({ + params: { id: articleId }, + payload: { data: [Comment.ref(sampleComments[0].id)] }, + }); + expect( + Arr.sort( + afterAdd.data.map((identifier) => identifier.id), + Order.String, + ), + ).toEqual( + Arr.sort( + sampleComments.map((comment) => comment.id), + Order.String, + ), + ); + }), + ), + ); - // Re-attach it - const afterAdd = yield* client.articles.addCommentsRelationship({ - params: { id: articleId }, - payload: { data: [Comment.ref(sampleComments[0].id)] }, - }); - expect( - Arr.sort( - afterAdd.data.map((identifier) => identifier.id), - Order.String, - ), - ).toEqual( - Arr.sort( - sampleComments.map((comment) => comment.id), - Order.String, - ), + it.effect( + "404s when PATCHing the author to a person that does not exist, leaving it unchanged", + () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.updateAuthorRelationship({ + params: { id: Article.Id.make("1") }, + payload: { data: Person.ref("nobody") }, + }); + }), ); - }), - ); - }); - - it("404s when PATCHing the author to a person that does not exist, leaving it unchanged", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.updateAuthorRelationship({ - params: { id: Article.Id.make("1") }, - payload: { data: Person.ref("nobody") }, - }); - }), - ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(PersonNotFound); - const article = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.get({ params: { id: Article.Id.make("1") }, query: {} }); - }), - ); - expect(article.data?.relationships?.author?.data.id).toBe(sampleAuthor.id); - }); - - it("404s when POSTing a comment that does not exist, linking none of the batch", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.addCommentsRelationship({ - params: { id: Article.Id.make("1") }, - payload: { - data: [ - ...sampleComments.map((comment) => Comment.ref(comment.id)), - Comment.ref("nothing"), - ], - }, - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(PersonNotFound); + const article = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.get({ params: { id: Article.Id.make("1") }, query: {} }); + }), + ); + expect(article.data?.relationships?.author?.data.id).toBe(sampleAuthor.id); }), - ); + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(CommentNotFound); - const linkage = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.articles.commentsRelationship({ - params: { id: Article.Id.make("1") }, - query: {}, - }); - }), - ); - expect(linkage.data.map((identifier) => identifier.id)).not.toContain("nothing"); - }); + it.effect("404s when POSTing a comment that does not exist, linking none of the batch", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.addCommentsRelationship({ + params: { id: Article.Id.make("1") }, + payload: { + data: [ + ...sampleComments.map((comment) => Comment.ref(comment.id)), + Comment.ref("nothing"), + ], + }, + }); + }), + ); + + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(CommentNotFound); + const linkage = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.articles.commentsRelationship({ + params: { id: Article.Id.make("1") }, + query: {}, + }); + }), + ); + expect(linkage.data.map((identifier) => identifier.id)).not.toContain("nothing"); + }), + ); it("documents relationship endpoints in OpenAPI", () => { const spec = OpenApi.fromApi(Api); @@ -636,140 +694,155 @@ describe("blog example: relationship endpoints", () => { }); describe("blog example: heterogeneous search", () => { - it("returns a mixed collection of articles and people, discriminated by type", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - // "an" matches both "...paints my bikeshed!" (article body "...Ever.") — no. - // Use a term hitting both stores: "d" → "bikeshed"/"Dan"/"Gebhardt" - return yield* client.search.search({ - query: { filter: { q: "d" } }, - }); - }), - ); - - const types = Arr.sort([...new Set(document.data.map((result) => result.type))], Order.String); - expect(types).toEqual(["articles", "people"]); - - // the union is discriminated by the `type` tag; the endpoint declares - // `fields`, so a client reads each attribute as optional (#322) - Arr.forEach(document.data, (result) => { - if (result.type === "articles") { - expectTypeOf(result.attributes.title).toEqualTypeOf(); - } else { - expectTypeOf(result.attributes.firstName).toEqualTypeOf(); - } - // each member still carries its own type's attribute at runtime - expect( - P.isString( - result.type === "articles" ? result.attributes.title : result.attributes.firstName, - ), - ).toBe(true); - }); - }); - - it("filters across both resource types", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "bikeshed" } }, - }); - }), - ); - - // only the article matches "bikeshed" - expect(document.data.map((result) => result.type)).toEqual(["articles"]); - expect(document.meta?.total).toBe(1); - }); - - it("keeps the request's `include`, `fields` and `filter` on `next` (#447)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { - include: ["author"], - fields: { articles: ["title"] }, - filter: { q: "e" }, - page: { offset: 0, limit: 1 }, - }, - }); - }), - ); - - const next = document.links?.next; - assert(P.isString(next)); - expect(next).toBe( - "/search?include=author&fields[articles]=title&filter[q]=e&page[offset]=1&page[limit]=1", - ); - // `next` is the same query on the next page, decoded through the schema - // the endpoint decodes. - const search = Rec.fromEntries(new URL(next, "https://example.test").searchParams); - expect(Schema.decodeUnknownSync(SearchQuery)(search)).toEqual({ - include: ["author"], - fields: { articles: ["title"] }, - filter: { q: "e" }, - page: { offset: 1, limit: 1 }, - }); - }); - - it("paginates heterogeneous results with links", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "" }, page: { offset: 0, limit: 1 } }, - }); - }), - ); + it.effect("returns a mixed collection of articles and people, discriminated by type", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + // "an" matches both "...paints my bikeshed!" (article body "...Ever.") — no. + // Use a term hitting both stores: "d" → "bikeshed"/"Dan"/"Gebhardt" + return yield* client.search.search({ + query: { filter: { q: "d" } }, + }); + }), + ); + + const types = Arr.sort( + [...new Set(document.data.map((result) => result.type))], + Order.String, + ); + expect(types).toEqual(["articles", "people"]); + + // the union is discriminated by the `type` tag; the endpoint declares + // `fields`, so a client reads each attribute as optional (#322) + Arr.forEach(document.data, (result) => { + if (result.type === "articles") { + expectTypeOf(result.attributes.title).toEqualTypeOf(); + } else { + expectTypeOf(result.attributes.firstName).toEqualTypeOf(); + } + // each member still carries its own type's attribute at runtime + expect( + P.isString( + result.type === "articles" ? result.attributes.title : result.attributes.firstName, + ), + ).toBe(true); + }); + }), + ); - expect(document.data).toHaveLength(1); - expect(document.meta?.total).toBeGreaterThan(1); - expect(document.links?.next).toBe("/search?filter[q]=&page[offset]=1&page[limit]=1"); - }); + it.effect("filters across both resource types", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "bikeshed" } }, + }); + }), + ); + + // only the article matches "bikeshed" + expect(document.data.map((result) => result.type)).toEqual(["articles"]); + expect(document.meta?.total).toBe(1); + }), + ); - it("supports include across the searched resources' graphs", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "bikeshed" }, include: ["author"] }, - }); - }), - ); + it.effect("keeps the request's `include`, `fields` and `filter` on `next` (#447)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { + include: ["author"], + fields: { articles: ["title"] }, + filter: { q: "e" }, + page: { offset: 0, limit: 1 }, + }, + }); + }), + ); + + const next = document.links?.next; + assert(P.isString(next)); + expect(next).toBe( + "/search?include=author&fields[articles]=title&filter[q]=e&page[offset]=1&page[limit]=1", + ); + // `next` is the same query on the next page, decoded through the schema + // the endpoint decodes. + const search = Rec.fromEntries(new URL(next, "https://example.test").searchParams); + expect(yield* Schema.decodeUnknownEffect(SearchQuery)(search)).toEqual({ + include: ["author"], + fields: { articles: ["title"] }, + filter: { q: "e" }, + page: { offset: 1, limit: 1 }, + }); + }), + ); - // the matched article's author is included - expect(document.included?.map((resource) => resource.type)).toEqual(["people"]); - }); + it.effect("paginates heterogeneous results with links", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "" }, page: { offset: 0, limit: 1 } }, + }); + }), + ); + + expect(document.data).toHaveLength(1); + expect(document.meta?.total).toBeGreaterThan(1); + expect(document.links?.next).toBe("/search?filter[q]=&page[offset]=1&page[limit]=1"); + }), + ); - it("keeps an empty `included` when every included author is already a hit (#232)", async () => { - // "d" hits the article and its author, Dan: the author is primary data, so - // the dedupe leaves nothing to include — but the request carried - // `include`, and §Fetching Includes requires the key, even empty. - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "d" }, include: ["author"] }, - }); - }), - ); + it.effect("supports include across the searched resources' graphs", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "bikeshed" }, include: ["author"] }, + }); + }), + ); + + // the matched article's author is included + expect(document.included?.map((resource) => resource.type)).toEqual(["people"]); + }), + ); - // the article and its author are both hits - expect(document.data.map((result) => `${result.type}:${result.id}`)).toEqual( - expect.arrayContaining(["articles:1", `people:${sampleAuthor.id}`]), - ); - expect(document.included).toEqual([]); - // …and without `include` the member is absent - const plain = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ query: { filter: { q: "d" } } }); - }), - ); - expect(plain).not.toHaveProperty("included"); - }); + it.effect("keeps an empty `included` when every included author is already a hit (#232)", () => + Effect.gen(function* () { + // "d" hits the article and its author, Dan: the author is primary data, so + // the dedupe leaves nothing to include — but the request carried + // `include`, and §Fetching Includes requires the key, even empty. + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "d" }, include: ["author"] }, + }); + }), + ); + + // the article and its author are both hits + expect(document.data.map((result) => `${result.type}:${result.id}`)).toEqual( + expect.arrayContaining(["articles:1", `people:${sampleAuthor.id}`]), + ); + expect(document.included).toEqual([]); + // …and without `include` the member is absent + const plain = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ query: { filter: { q: "d" } } }); + }), + ); + expect(plain).not.toHaveProperty("included"); + }), + ); it("documents the search endpoint in OpenAPI", () => { const spec = OpenApi.fromApi(Api); diff --git a/examples/blog/test/client.test.ts b/examples/blog/test/client.test.ts index 157c81d..4ca69d0 100644 --- a/examples/blog/test/client.test.ts +++ b/examples/blog/test/client.test.ts @@ -8,7 +8,8 @@ * façade synthesises without a server at all, all reduced to one message by one * accessor. */ -import { assert, describe, expect, it } from "vite-plus/test"; +import { it } from "@effect/vitest"; +import { assert, describe, expect } from "vite-plus/test"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -29,10 +30,8 @@ import { Article } from "../resources.js"; const jsonText = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); -const run = (effect: Effect.Effect): Promise => - Effect.runPromise( - effect.pipe(Effect.scoped, Effect.provide(ServerHttpClient)) as Effect.Effect, - ); +const run = (effect: Effect.Effect): Effect.Effect => + effect.pipe(Effect.scoped, Effect.provide(ServerHttpClient)) as Effect.Effect; /** A load balancer in front of the server, answering with its own opaque body. */ const gateway = (body: string, status: number, contentType: string): HttpClient.HttpClient => @@ -46,93 +45,97 @@ const gateway = (body: string, status: number, contentType: string): HttpClient. ); describe("blog client: negotiation", () => { - it("round-trips a document against the blog server", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* blogClient; - return yield* client.articles.get({ params: { id: Article.Id.make("1") }, query: {} }); - }), - ); - - expect(document.data).toMatchObject({ - type: "articles", - attributes: { title: "JSON:API paints my bikeshed!" }, - }); - }); - - it("advertises the extension the server supports, on both headers", async () => { - const sent: Array> = []; - const recorder = HttpClient.make((request) => { - sent.push({ ...request.headers }); - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(null, { status: 204 })), + it.effect("round-trips a document against the blog server", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* blogClient; + return yield* client.articles.get({ params: { id: Article.Id.make("1") }, query: {} }); + }), ); - }); - await Effect.runPromise( - Effect.gen(function* () { + expect(document.data).toMatchObject({ + type: "articles", + attributes: { title: "JSON:API paints my bikeshed!" }, + }); + }), + ); + + it.effect("advertises the extension the server supports, on both headers", () => + Effect.gen(function* () { + const sent: Array> = []; + const recorder = HttpClient.make((request) => { + sent.push({ ...request.headers }); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 204 })), + ); + }); + + yield* Effect.gen(function* () { const client = yield* Client.make(Api, { ...negotiation, baseUrl: "http://blog.example.com", }); yield* client.articles.delete({ params: { id: Article.Id.make("1") } }); - }).pipe(Effect.provideService(HttpClient.HttpClient, recorder)) as Effect.Effect, - ); - - const expected = `${MEDIA_TYPE};ext="https://jsonapi.org/ext/atomic"`; - // A bodyless DELETE carries the label too — the detail independent - // implementations get inconsistently right. - expect(sent[0]?.["accept"]).toBe(expected); - expect(sent[0]?.["content-type"]).toBe(expected); - }); - - it("a plain HttpApiClient sends neither header", async () => { - const sent: Array> = []; - const recorder = HttpClient.make((request) => { - sent.push({ ...request.headers }); - return Effect.succeed( - HttpClientResponse.fromWeb(request, new Response(null, { status: 204 })), - ); - }); + }).pipe(Effect.provideService(HttpClient.HttpClient, recorder)) as Effect.Effect; + + const expected = `${MEDIA_TYPE};ext="https://jsonapi.org/ext/atomic"`; + // A bodyless DELETE carries the label too — the detail independent + // implementations get inconsistently right. + expect(sent[0]?.["accept"]).toBe(expected); + expect(sent[0]?.["content-type"]).toBe(expected); + }), + ); - await Effect.runPromise( - Effect.gen(function* () { + it.effect("a plain HttpApiClient sends neither header", () => + Effect.gen(function* () { + const sent: Array> = []; + const recorder = HttpClient.make((request) => { + sent.push({ ...request.headers }); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 204 })), + ); + }); + + yield* Effect.gen(function* () { const client = yield* HttpApiClient.make(Api, { baseUrl: "http://blog.example.com" }); yield* client.articles.delete({ params: { id: Article.Id.make("1") } }); - }).pipe(Effect.provideService(HttpClient.HttpClient, recorder)) as Effect.Effect, - ); + }).pipe(Effect.provideService(HttpClient.HttpClient, recorder)) as Effect.Effect; - expect(sent[0]?.["accept"]).toBeUndefined(); - expect(sent[0]?.["content-type"]).toBeUndefined(); - }); + expect(sent[0]?.["accept"]).toBeUndefined(); + expect(sent[0]?.["content-type"]).toBeUndefined(); + }), + ); }); describe("blog client: error documents", () => { - it("a declared error arrives as a typed error, and renders the same document", async () => { - const failure = await Effect.runPromise( - Effect.gen(function* () { + it.effect("a declared error arrives as a typed error, and renders the same document", () => + Effect.gen(function* () { + const failure = yield* Effect.gen(function* () { const client = yield* blogClient; return yield* client.articles.get({ params: { id: Article.Id.make("999") }, query: {} }); }).pipe( Effect.scoped, Effect.provide(ServerHttpClient), Effect.flip, - ) as Effect.Effect, - ); - - expect(failure).toBeInstanceOf(ArticleNotFound); - // The typed error and a decoded wire document meet at the same accessor. - expect(Client.errorMessage(ApiError.toDocument(failure as ArticleNotFound))).toBe( - "Article 999 not found", - ); - }); - - it("an undeclared error document from in front of the server is decoded", async () => { - // A 503 the load balancer renders as a JSON:API error document: the api - // never declared it, so it surfaces as an HttpClientError. - const document = ApiError.toDocument(new ApiError.Conflict({ detail: "Upstream is draining" })); - const cause = await Effect.runPromise( - Effect.gen(function* () { + ) as Effect.Effect; + + expect(failure).toBeInstanceOf(ArticleNotFound); + // The typed error and a decoded wire document meet at the same accessor. + expect(Client.errorMessage(ApiError.toDocument(failure as ArticleNotFound))).toBe( + "Article 999 not found", + ); + }), + ); + + it.effect("an undeclared error document from in front of the server is decoded", () => + Effect.gen(function* () { + // A 503 the load balancer renders as a JSON:API error document: the api + // never declared it, so it surfaces as an HttpClientError. + const document = ApiError.toDocument( + new ApiError.Conflict({ detail: "Upstream is draining" }), + ); + const cause = yield* Effect.gen(function* () { const client = yield* Client.make(Api, { ...negotiation, baseUrl: "http://blog.example.com", @@ -141,15 +144,15 @@ describe("blog client: error documents", () => { }).pipe( Effect.provideService(HttpClient.HttpClient, gateway(jsonText(document), 503, MEDIA_TYPE)), Effect.flip, - ) as Effect.Effect, - ); + ) as Effect.Effect; - expect(await Effect.runPromise(describeFailure(cause))).toBe("Upstream is draining"); - }); + expect(yield* describeFailure(cause)).toBe("Upstream is draining"); + }), + ); - it("a proxy's HTML degrades to the fallback message rather than throwing", async () => { - const cause = await Effect.runPromise( - Effect.gen(function* () { + it.effect("a proxy's HTML degrades to the fallback message rather than throwing", () => + Effect.gen(function* () { + const cause = yield* Effect.gen(function* () { const client = yield* Client.make(Api, { ...negotiation, baseUrl: "http://blog.example.com", @@ -161,20 +164,20 @@ describe("blog client: error documents", () => { gateway("

502 Bad Gateway

", 502, "text/html"), ), Effect.flip, - ) as Effect.Effect, - ); + ) as Effect.Effect; - expect(await Effect.runPromise(describeFailure(cause))).toBe("The blog could not be reached"); - }); + expect(yield* describeFailure(cause)).toBe("The blog could not be reached"); + }), + ); - it("the offline façade's own error decodes through the same seam", async () => { - const document = servedOffline(); - assert(Option.isSome(document)); - expect(Client.errorMessage(document.value)).toBe("This article is not available offline"); + it.effect("the offline façade's own error decodes through the same seam", () => + Effect.gen(function* () { + const document = servedOffline(); + assert(Option.isSome(document)); + expect(Client.errorMessage(document.value)).toBe("This article is not available offline"); - // Indistinguishable from the same document arriving over the network. - const cause = await Effect.runPromise( - Effect.gen(function* () { + // Indistinguishable from the same document arriving over the network. + const cause = yield* Effect.gen(function* () { const client = yield* Client.make(Api, { ...negotiation, baseUrl: "http://blog.example.com", @@ -186,9 +189,9 @@ describe("blog client: error documents", () => { gateway(jsonText(ApiError.toDocument(new Offline())), 503, MEDIA_TYPE), ), Effect.flip, - ) as Effect.Effect, - ); + ) as Effect.Effect; - expect(await Effect.runPromise(Client.errorDocument(cause))).toStrictEqual(document); - }); + expect(yield* Client.errorDocument(cause)).toStrictEqual(document); + }), + ); }); diff --git a/examples/blog/test/conformance.test.ts b/examples/blog/test/conformance.test.ts index 0fc3daa..79dca2c 100644 --- a/examples/blog/test/conformance.test.ts +++ b/examples/blog/test/conformance.test.ts @@ -8,9 +8,12 @@ * here), and a disappearing one means a fixed bug whose entry should come * off this list. */ -import { describe, expect, it } from "vite-plus/test"; +import { layer } from "@effect/vitest"; +import { expect } from "vite-plus/test"; import * as Arr from "effect/Array"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Order from "effect/Order"; import * as P from "effect/Predicate"; import { Conformance } from "@thomasfosterau/effect-jsonapi"; @@ -74,207 +77,243 @@ const died = (run: Conformance.Report): ReadonlyArray => P.isTagged(outcome, "Errored") ? [`${outcome.rule.id}: ${outcome.message}`] : [], ); -const report = await Effect.runPromise( +/** The one run every test below reads, built once for the suite. */ +class Run extends Context.Service()("example/Run") {} + +const RunLive = Layer.effect( + Run, Conformance.verify(Api, { ids: IDS, mutating: true, writes: WRITES }).pipe( Effect.provide(BlogLive), Effect.scoped, ) as Effect.Effect, ); -describe("blog: JSON:API conformance", () => { - it("decided every rule it ran: none died", () => { - // The message carries the whole report, so a dead rule explains itself - // alongside its neighbours; the diff names each dead rule and its defect. - expect( - died(report), - `a rule died — a defect, not a finding\n${Conformance.format(report)}`, - ).toEqual([]); - }); +layer(RunLive)("blog: JSON:API conformance", (it) => { + it.effect("decided every rule it ran: none died", () => + Effect.gen(function* () { + const report = yield* Run; + // The message carries the whole report, so a dead rule explains itself + // alongside its neighbours; the diff names each dead rule and its defect. + expect( + died(report), + `a rule died — a defect, not a finding\n${Conformance.format(report)}`, + ).toEqual([]); + }), + ); - it("sampled only resources the example holds: every sample read answered 200", () => { - // An `ids` entry the example does not hold fails no rule: its `/:type/:id` - // read answers 404, and every rule that resolves it sees less of the api - // (#301). `report.samples` records each such read with its status (#319). - // Keyed by type, so a sample that did not resolve shows up under its type. - expect( - Object.fromEntries((report.samples ?? []).map((sample) => [sample.type, sample.status])), - Conformance.format(report), - ).toEqual({ articles: 200 }); - }); + it.effect("sampled only resources the example holds: every sample read answered 200", () => + Effect.gen(function* () { + const report = yield* Run; + // An `ids` entry the example does not hold fails no rule: its `/:type/:id` + // read answers 404, and every rule that resolves it sees less of the api + // (#301). `report.samples` records each such read with its status (#319). + // Keyed by type, so a sample that did not resolve shows up under its type. + expect( + Object.fromEntries((report.samples ?? []).map((sample) => [sample.type, sample.status])), + Conformance.format(report), + ).toEqual({ articles: 200 }); + }), + ); - it("breaks exactly the rules that are already filed", () => { - const failing = Arr.sort( - report.outcomes - .filter((outcome) => P.isTagged(outcome, "Failed")) - .map((outcome) => outcome.rule.id), - Order.String, - ); - const known = Arr.sort( - KNOWN_FAILURES.map(([id]) => id), - Order.String, - ); + it.effect("breaks exactly the rules that are already filed", () => + Effect.gen(function* () { + const report = yield* Run; + const failing = Arr.sort( + report.outcomes + .filter((outcome) => P.isTagged(outcome, "Failed")) + .map((outcome) => outcome.rule.id), + Order.String, + ); + const known = Arr.sort( + KNOWN_FAILURES.map(([id]) => id), + Order.String, + ); - // The whole report is the assertion message, so a new failure explains itself. - expect(failing, Conformance.format(report)).toEqual(known); - }); + // The whole report is the assertion message, so a new failure explains itself. + expect(failing, Conformance.format(report)).toEqual(known); + }), + ); - it("every failure names a rule, cites its section and shows the request", () => { - Arr.forEach(report.outcomes, (outcome) => { - if (!P.isTagged(outcome, "Failed")) return; - expect(outcome.rule.requirement.length).toBeGreaterThan(20); - expect(outcome.rule.reference).toMatch(/^https:\/\//); - Arr.forEach(outcome.findings, (finding) => { - expect(finding.detail).not.toBe(""); - expect(finding.expected).not.toBe(""); - expect(finding.observed).not.toBe(""); + it.effect("every failure names a rule, cites its section and shows the request", () => + Effect.gen(function* () { + const report = yield* Run; + Arr.forEach(report.outcomes, (outcome) => { + if (!P.isTagged(outcome, "Failed")) return; + expect(outcome.rule.requirement.length).toBeGreaterThan(20); + expect(outcome.rule.reference).toMatch(/^https:\/\//); + Arr.forEach(outcome.findings, (finding) => { + expect(finding.detail).not.toBe(""); + expect(finding.expected).not.toBe(""); + expect(finding.observed).not.toBe(""); + }); }); - }); - }); + }), + ); - it("actually probed the api rather than skipping its way to a verdict", () => { - const summary = Conformance.summarise(report); - expect(summary.probes).toBeGreaterThan(50); - expect(summary.passed).toBeGreaterThan(15); - }); + it.effect("actually probed the api rather than skipping its way to a verdict", () => + Effect.gen(function* () { + const report = yield* Run; + const summary = Conformance.summarise(report); + expect(summary.probes).toBeGreaterThan(50); + expect(summary.passed).toBeGreaterThan(15); + }), + ); - it("honours an empty sparse fieldset as no fields, on primary data and `included` alike", () => { - // #488: `?fields[TYPE]=` asks for no fields, not every field, and - // `Handlers.project` answers it with no attributes. - const ids = [ - "spec/query/sparse-fieldsets-primary", - "spec/query/sparse-fieldsets-included", - "spec/query/sparse-fieldsets-empty", - ]; - expect( - ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), - ).toEqual(ids.map((id) => `${id}: Passed`)); - }); + it.effect( + "honours an empty sparse fieldset as no fields, on primary data and `included` alike", + () => + Effect.gen(function* () { + const report = yield* Run; + // #488: `?fields[TYPE]=` asks for no fields, not every field, and + // `Handlers.project` answers it with no attributes. + const ids = [ + "spec/query/sparse-fieldsets-primary", + "spec/query/sparse-fieldsets-included", + "spec/query/sparse-fieldsets-empty", + ]; + expect( + ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), + ).toEqual(ids.map((id) => `${id}: Passed`)); + }), + ); - it("follows every relationship's and document's `self` link to a verdict", () => { - // #309: the relationship `self` link `Handlers.paginatedRelationship` - // writes for an article's comments is served by a declared - // `Endpoint.getRelationship`, so both MUSTs pass rather than skip. That - // relationship is links-only, so the relationship SHOULD has no linkage to - // compare and skips. - const ids = [ - "spec/links/relationship-self-dereferences", - "spec/links/relationship-self-matches-linkage", - "spec/links/top-level-self-dereferences", - "spec/links/top-level-self-matches-document", - ]; - const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); - expect(ids.map((id) => `${id}: ${outcomeOf(id)?._tag}`)).toEqual([ - "spec/links/relationship-self-dereferences: Passed", - "spec/links/relationship-self-matches-linkage: Skipped", - "spec/links/top-level-self-dereferences: Passed", - "spec/links/top-level-self-matches-document: Passed", - ]); - // Skipped for want of linkage, not for want of a link to follow. - expect(outcomeOf("spec/links/relationship-self-matches-linkage")).toMatchObject({ - reason: expect.stringContaining("carries both a `self` link and resource linkage"), - }); - }); + it.effect("follows every relationship's and document's `self` link to a verdict", () => + Effect.gen(function* () { + const report = yield* Run; + // #309: the relationship `self` link `Handlers.paginatedRelationship` + // writes for an article's comments is served by a declared + // `Endpoint.getRelationship`, so both MUSTs pass rather than skip. That + // relationship is links-only, so the relationship SHOULD has no linkage to + // compare and skips. + const ids = [ + "spec/links/relationship-self-dereferences", + "spec/links/relationship-self-matches-linkage", + "spec/links/top-level-self-dereferences", + "spec/links/top-level-self-matches-document", + ]; + const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); + expect(ids.map((id) => `${id}: ${outcomeOf(id)?._tag}`)).toEqual([ + "spec/links/relationship-self-dereferences: Passed", + "spec/links/relationship-self-matches-linkage: Skipped", + "spec/links/top-level-self-dereferences: Passed", + "spec/links/top-level-self-matches-document: Passed", + ]); + // Skipped for want of linkage, not for want of a link to follow. + expect(outcomeOf("spec/links/relationship-self-matches-linkage")).toMatchObject({ + reason: expect.stringContaining("carries both a `self` link and resource linkage"), + }); + }), + ); - it("judges the compound relationship document by the compound-document rules", () => { - // #439: `GET /articles/:id/relationships/tags` declares `include`, so the - // kit's compound probe asks it for `?include=tags`. Its primary data is - // the tag identifiers and its `included` the tags they name: full linkage - // starts from those identifiers, and a tag in both is no duplicate. - // #483: `GET /articles/:id/relationships/comments`, paginated, declares - // `include` too, so it is asked for `?include=comments` and answers the - // comments on its page. - // #485: it declares `fields` too, so the `included` variant of the - // sparse-fieldset rule asks it for `?include=tags&fields[tags]=name`. - const ids = [ - "spec/document/full-linkage", - "spec/document/no-duplicate-resources", - "spec/document/included-on-include", - "spec/query/sparse-fieldsets-included", - ]; - expect( - ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), - ).toEqual(ids.map((id) => `${id}: Passed`)); - }); + it.effect("judges the compound relationship document by the compound-document rules", () => + Effect.gen(function* () { + const report = yield* Run; + // #439: `GET /articles/:id/relationships/tags` declares `include`, so the + // kit's compound probe asks it for `?include=tags`. Its primary data is + // the tag identifiers and its `included` the tags they name: full linkage + // starts from those identifiers, and a tag in both is no duplicate. + // #483: `GET /articles/:id/relationships/comments`, paginated, declares + // `include` too, so it is asked for `?include=comments` and answers the + // comments on its page. + // #485: it declares `fields` too, so the `included` variant of the + // sparse-fieldset rule asks it for `?include=tags&fields[tags]=name`. + const ids = [ + "spec/document/full-linkage", + "spec/document/no-duplicate-resources", + "spec/document/included-on-include", + "spec/query/sparse-fieldsets-included", + ]; + expect( + ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), + ).toEqual(ids.map((id) => `${id}: Passed`)); + }), + ); - it("ran the write rules against targets it created, and left nothing behind", () => { - const writeRules = [ - "spec/status/create-response-document", - // #236: the 201 carries `Location`, copied from the created resource's - // own `links.self`, so the two match. - "spec/status/create-location", - "spec/status/create-location-matches-self", - "spec/status/update-response", - "spec/status/delete-response", - // #237: what each create and update answered reads back through the - // resource's own GET. - "spec/status/create-read-back", - "spec/status/update-read-back", - "spec/atomic/response-ext-parameter", - // #164: processing, judged by what the blog stored afterwards. The - // blog's operations endpoint takes articles and comments, and the one - // fixture here, `articles`, links only to a person, which no fixture - // creates, so `lid-resolution` runs its update probe rather than its - // linkage one: an `add` under a `lid`, then an `update` naming it by - // that `lid`, read back by the id the blog gave it. `all-or-nothing` - // lists `/articles` around a request whose last operation names an - // absent `lid`; `results-order` sends an `add` then a `remove` by `lid`. - "spec/atomic/all-or-nothing", - "spec/atomic/lid-resolution", - "spec/atomic/results-order", - // #471: an `add` under the fixture's client id, which the blog does not - // support, answered 403 naming `/atomic:operations/0/data/id` (#464). - "spec/atomic/add-client-id-unsupported", - // #429: a created article's `comments` linked to the `ids` comment and - // unlinked again, each read back through - // `GET /articles/:id/relationships/comments`. The `author` PATCH has no - // relationship GET to read back through, so `update-replaces` skips. - "spec/relationships/add-appends", - "spec/relationships/remove-deletes", - // #451: what each of those writes, and the `author` PATCH, answered — - // the PATCH's 200 linkage judged by what it replaced the linkage with. - "spec/relationships/write-response", - // #461: the `author` PATCH and `comments` POST answer 404 for a resource - // that does not exist. - "spec/relationships/absent-related-404", - // #477: a `comments` DELETE, and an atomic `remove` from a created - // article's `comments`, naming a comment that does not exist succeed — - // it is already missing from the relationship. - "spec/relationships/remove-absent-succeeds", - "spec/atomic/remove-absent-succeeds", - ]; - expect( - writeRules.map((id) => report.outcomes.find((outcome) => outcome.rule.id === id)?._tag), - ).toEqual(writeRules.map(() => "Passed")); - const writes = report.writes ?? []; - expect(writes.length).toBeGreaterThan(0); - expect(writes.map((write) => write.disposal)).toEqual( - writes.map(() => expect.stringMatching(/^(deleted|cleaned-up)$/)), - ); - }); + it.effect("ran the write rules against targets it created, and left nothing behind", () => + Effect.gen(function* () { + const report = yield* Run; + const writeRules = [ + "spec/status/create-response-document", + // #236: the 201 carries `Location`, copied from the created resource's + // own `links.self`, so the two match. + "spec/status/create-location", + "spec/status/create-location-matches-self", + "spec/status/update-response", + "spec/status/delete-response", + // #237: what each create and update answered reads back through the + // resource's own GET. + "spec/status/create-read-back", + "spec/status/update-read-back", + "spec/atomic/response-ext-parameter", + // #164: processing, judged by what the blog stored afterwards. The + // blog's operations endpoint takes articles and comments, and the one + // fixture here, `articles`, links only to a person, which no fixture + // creates, so `lid-resolution` runs its update probe rather than its + // linkage one: an `add` under a `lid`, then an `update` naming it by + // that `lid`, read back by the id the blog gave it. `all-or-nothing` + // lists `/articles` around a request whose last operation names an + // absent `lid`; `results-order` sends an `add` then a `remove` by `lid`. + "spec/atomic/all-or-nothing", + "spec/atomic/lid-resolution", + "spec/atomic/results-order", + // #471: an `add` under the fixture's client id, which the blog does not + // support, answered 403 naming `/atomic:operations/0/data/id` (#464). + "spec/atomic/add-client-id-unsupported", + // #429: a created article's `comments` linked to the `ids` comment and + // unlinked again, each read back through + // `GET /articles/:id/relationships/comments`. The `author` PATCH has no + // relationship GET to read back through, so `update-replaces` skips. + "spec/relationships/add-appends", + "spec/relationships/remove-deletes", + // #451: what each of those writes, and the `author` PATCH, answered — + // the PATCH's 200 linkage judged by what it replaced the linkage with. + "spec/relationships/write-response", + // #461: the `author` PATCH and `comments` POST answer 404 for a resource + // that does not exist. + "spec/relationships/absent-related-404", + // #477: a `comments` DELETE, and an atomic `remove` from a created + // article's `comments`, naming a comment that does not exist succeed — + // it is already missing from the relationship. + "spec/relationships/remove-absent-succeeds", + "spec/atomic/remove-absent-succeeds", + ]; + expect( + writeRules.map((id) => report.outcomes.find((outcome) => outcome.rule.id === id)?._tag), + ).toEqual(writeRules.map(() => "Passed")); + const writes = report.writes ?? []; + expect(writes.length).toBeGreaterThan(0); + expect(writes.map((write) => write.disposal)).toEqual( + writes.map(() => expect.stringMatching(/^(deleted|cleaned-up)$/)), + ); + }), + ); - it("renders a report that states what it did not check", () => { - const text = Conformance.format(report); - expect(text).toContain("NOT COVERED BY THIS KIT"); - expect(text).toContain("SUMMARY"); - // Skipped rules are named individually, not rolled into the pass count. - expect(text).toContain("not checked:"); - }); + it.effect("renders a report that states what it did not check", () => + Effect.gen(function* () { + const report = yield* Run; + const text = Conformance.format(report); + expect(text).toContain("NOT COVERED BY THIS KIT"); + expect(text).toContain("SUMMARY"); + // Skipped rules are named individually, not rolled into the pass count. + expect(text).toContain("not checked:"); + }), + ); - it("runs the spec tier without the profile tier", async () => { - const specOnly = await Effect.runPromise( - Conformance.verify(Api, { ids: { articles: "1" }, tiers: ["spec"] }).pipe( - Effect.provide(BlogLive), - Effect.scoped, - ) as Effect.Effect, - ); - expect(specOnly.outcomes.every((outcome) => outcome.rule.tier === "spec")).toBe(true); - expect( - died(specOnly), - `a rule died — a defect, not a finding\n${Conformance.format(specOnly)}`, - ).toEqual([]); - const failing = specOnly.outcomes - .filter((outcome) => P.isTagged(outcome, "Failed")) - .map((outcome) => outcome.rule.id); - expect(failing).not.toContain("profile/document/jsonapi-member"); - }); + it.effect("runs the spec tier without the profile tier", () => + Effect.gen(function* () { + const specOnly = yield* Conformance.verify(Api, { + ids: { articles: "1" }, + tiers: ["spec"], + }).pipe(Effect.provide(BlogLive), Effect.scoped) as Effect.Effect; + expect(specOnly.outcomes.every((outcome) => outcome.rule.tier === "spec")).toBe(true); + expect( + died(specOnly), + `a rule died — a defect, not a finding\n${Conformance.format(specOnly)}`, + ).toEqual([]); + const failing = specOnly.outcomes + .filter((outcome) => P.isTagged(outcome, "Failed")) + .map((outcome) => outcome.rule.id); + expect(failing).not.toContain("profile/document/jsonapi-member"); + }), + ); }); diff --git a/examples/github/package.json b/examples/github/package.json index fa9ce46..c28462c 100644 --- a/examples/github/package.json +++ b/examples/github/package.json @@ -9,6 +9,7 @@ "effect": "catalog:" }, "devDependencies": { + "@effect/vitest": "catalog:", "@types/node": "catalog:", "vite-plus": "catalog:" } diff --git a/examples/github/test/conformance.test.ts b/examples/github/test/conformance.test.ts index 7b3db05..e4b30dd 100644 --- a/examples/github/test/conformance.test.ts +++ b/examples/github/test/conformance.test.ts @@ -8,9 +8,12 @@ * here), and a disappearing one means a fixed bug whose entry should come * off this list. */ -import { describe, expect, it } from "vite-plus/test"; +import { layer } from "@effect/vitest"; +import { expect } from "vite-plus/test"; import * as Arr from "effect/Array"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Order from "effect/Order"; import * as P from "effect/Predicate"; import { Conformance } from "@thomasfosterau/effect-jsonapi"; @@ -94,197 +97,235 @@ const died = (run: Conformance.Report): ReadonlyArray => P.isTagged(outcome, "Errored") ? [`${outcome.rule.id}: ${outcome.message}`] : [], ); -const report = await Effect.runPromise( +/** The one run every test below reads, built once for the suite. */ +class Run extends Context.Service()("example/Run") {} + +const RunLive = Layer.effect( + Run, Conformance.verify(Api, { ids: IDS, mutating: true, writes: WRITES }).pipe( Effect.provide(GitHubLive), Effect.scoped, ) as Effect.Effect, ); -describe("github: JSON:API conformance", () => { - it("decided every rule it ran: none died", () => { - // The message carries the whole report, so a dead rule explains itself - // alongside its neighbours; the diff names each dead rule and its defect. - expect( - died(report), - `a rule died — a defect, not a finding\n${Conformance.format(report)}`, - ).toEqual([]); - }); +layer(RunLive)("github: JSON:API conformance", (it) => { + it.effect("decided every rule it ran: none died", () => + Effect.gen(function* () { + const report = yield* Run; + // The message carries the whole report, so a dead rule explains itself + // alongside its neighbours; the diff names each dead rule and its defect. + expect( + died(report), + `a rule died — a defect, not a finding\n${Conformance.format(report)}`, + ).toEqual([]); + }), + ); - it("sampled only resources the example holds: every sample read answered 200", () => { - // An `ids` entry the example does not hold fails no rule: its `/:type/:id` - // read answers 404, and every rule that resolves it sees less of the api - // (#301). `report.samples` records each such read with its status (#319). - // Keyed by type, so a sample that did not resolve shows up under its type. - // `labels` and `issueComments` have no `GET /:type/:id` endpoint, so their - // samples key relationship and related reads only, and record no read. - expect( - Object.fromEntries((report.samples ?? []).map((sample) => [sample.type, sample.status])), - Conformance.format(report), - ).toEqual({ users: 200, repositories: 200, issues: 200, pulls: 200 }); - }); + it.effect("sampled only resources the example holds: every sample read answered 200", () => + Effect.gen(function* () { + const report = yield* Run; + // An `ids` entry the example does not hold fails no rule: its `/:type/:id` + // read answers 404, and every rule that resolves it sees less of the api + // (#301). `report.samples` records each such read with its status (#319). + // Keyed by type, so a sample that did not resolve shows up under its type. + // `labels` and `issueComments` have no `GET /:type/:id` endpoint, so their + // samples key relationship and related reads only, and record no read. + expect( + Object.fromEntries((report.samples ?? []).map((sample) => [sample.type, sample.status])), + Conformance.format(report), + ).toEqual({ users: 200, repositories: 200, issues: 200, pulls: 200 }); + }), + ); - it("breaks exactly the rules that are already filed", () => { - const failing = Arr.sort( - report.outcomes - .filter((outcome) => P.isTagged(outcome, "Failed")) - .map((outcome) => outcome.rule.id), - Order.String, - ); - const known = Arr.sort( - KNOWN_FAILURES.map(([id]) => id), - Order.String, - ); + it.effect("breaks exactly the rules that are already filed", () => + Effect.gen(function* () { + const report = yield* Run; + const failing = Arr.sort( + report.outcomes + .filter((outcome) => P.isTagged(outcome, "Failed")) + .map((outcome) => outcome.rule.id), + Order.String, + ); + const known = Arr.sort( + KNOWN_FAILURES.map(([id]) => id), + Order.String, + ); - // The whole report is the assertion message, so a new failure explains itself. - expect(failing, Conformance.format(report)).toEqual(known); - }); + // The whole report is the assertion message, so a new failure explains itself. + expect(failing, Conformance.format(report)).toEqual(known); + }), + ); - it("every failure names a rule, cites its section and shows the request", () => { - Arr.forEach(report.outcomes, (outcome) => { - if (!P.isTagged(outcome, "Failed")) return; - expect(outcome.rule.requirement.length).toBeGreaterThan(20); - expect(outcome.rule.reference).toMatch(/^https:\/\//); - Arr.forEach(outcome.findings, (finding) => { - expect(finding.detail).not.toBe(""); - expect(finding.expected).not.toBe(""); - expect(finding.observed).not.toBe(""); + it.effect("every failure names a rule, cites its section and shows the request", () => + Effect.gen(function* () { + const report = yield* Run; + Arr.forEach(report.outcomes, (outcome) => { + if (!P.isTagged(outcome, "Failed")) return; + expect(outcome.rule.requirement.length).toBeGreaterThan(20); + expect(outcome.rule.reference).toMatch(/^https:\/\//); + Arr.forEach(outcome.findings, (finding) => { + expect(finding.detail).not.toBe(""); + expect(finding.expected).not.toBe(""); + expect(finding.observed).not.toBe(""); + }); }); - }); - }); + }), + ); - it("actually probed the api rather than skipping its way to a verdict", () => { - const summary = Conformance.summarise(report); - expect(summary.probes).toBeGreaterThan(50); - expect(summary.passed).toBeGreaterThan(15); - }); + it.effect("actually probed the api rather than skipping its way to a verdict", () => + Effect.gen(function* () { + const report = yield* Run; + const summary = Conformance.summarise(report); + expect(summary.probes).toBeGreaterThan(50); + expect(summary.passed).toBeGreaterThan(15); + }), + ); - it("honours an empty sparse fieldset as no fields, on primary data and `included` alike", () => { - // #488: `?fields[TYPE]=` asks for no fields, not every field, and - // `Handlers.project` answers it with no attributes. - const ids = [ - "spec/query/sparse-fieldsets-primary", - "spec/query/sparse-fieldsets-included", - "spec/query/sparse-fieldsets-empty", - ]; - expect( - ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), - ).toEqual(ids.map((id) => `${id}: Passed`)); - }); + it.effect( + "honours an empty sparse fieldset as no fields, on primary data and `included` alike", + () => + Effect.gen(function* () { + const report = yield* Run; + // #488: `?fields[TYPE]=` asks for no fields, not every field, and + // `Handlers.project` answers it with no attributes. + const ids = [ + "spec/query/sparse-fieldsets-primary", + "spec/query/sparse-fieldsets-included", + "spec/query/sparse-fieldsets-empty", + ]; + expect( + ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), + ).toEqual(ids.map((id) => `${id}: Passed`)); + }), + ); - it("follows every relationship's and document's `self` link to a verdict", () => { - // #309: the relationship `self` link `Handlers.paginatedRelationship` - // writes for an issue's comments (`/issues/:id/relationships/comments`) - // is served by a declared `Endpoint.getRelationship`, so both MUSTs pass - // rather than skip. That relationship is links-only, so the relationship - // SHOULD has no linkage to compare and skips. - const ids = [ - "spec/links/relationship-self-dereferences", - "spec/links/relationship-self-matches-linkage", - "spec/links/top-level-self-dereferences", - "spec/links/top-level-self-matches-document", - ]; - const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); - expect(ids.map((id) => `${id}: ${outcomeOf(id)?._tag}`)).toEqual([ - "spec/links/relationship-self-dereferences: Passed", - "spec/links/relationship-self-matches-linkage: Skipped", - "spec/links/top-level-self-dereferences: Passed", - "spec/links/top-level-self-matches-document: Passed", - ]); - // Skipped for want of linkage, not for want of a link to follow. - expect(outcomeOf("spec/links/relationship-self-matches-linkage")).toMatchObject({ - reason: expect.stringContaining("carries both a `self` link and resource linkage"), - }); - }); + it.effect("follows every relationship's and document's `self` link to a verdict", () => + Effect.gen(function* () { + const report = yield* Run; + // #309: the relationship `self` link `Handlers.paginatedRelationship` + // writes for an issue's comments (`/issues/:id/relationships/comments`) + // is served by a declared `Endpoint.getRelationship`, so both MUSTs pass + // rather than skip. That relationship is links-only, so the relationship + // SHOULD has no linkage to compare and skips. + const ids = [ + "spec/links/relationship-self-dereferences", + "spec/links/relationship-self-matches-linkage", + "spec/links/top-level-self-dereferences", + "spec/links/top-level-self-matches-document", + ]; + const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); + expect(ids.map((id) => `${id}: ${outcomeOf(id)?._tag}`)).toEqual([ + "spec/links/relationship-self-dereferences: Passed", + "spec/links/relationship-self-matches-linkage: Skipped", + "spec/links/top-level-self-dereferences: Passed", + "spec/links/top-level-self-matches-document: Passed", + ]); + // Skipped for want of linkage, not for want of a link to follow. + expect(outcomeOf("spec/links/relationship-self-matches-linkage")).toMatchObject({ + reason: expect.stringContaining("carries both a `self` link and resource linkage"), + }); + }), + ); - it("judges GET /issues, which speaks the filter grammar, by the profile's own semantics", () => { - // #433: `GET /issues` declares `filter: true` and advertises the profile, - // so the filter-profile rules run here rather than only against the kit's - // canned servers. The evaluation rule decides the empty groups, the - // ordering operators on `number` (never NULL) and `assignee`, a to-one - // relationship empty on two of the three issues; the §6.5 corollaries on - // `assignee` and `include=…` beside a filter (#458) — and says why the - // rest went undecided: no attribute is ever NULL, and the endpoint - // declares no `fields[issues]` (deliberately, #322) to send beside a - // filter. Spelling equivalence runs on `title`, the first string - // attribute, `number` leading it (#458). - const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); - expect(outcomeOf("profile/filter/advertises-profile-uri")?._tag).toBe("Passed"); - expect(outcomeOf("profile/filter/rejections")?._tag).toBe("Passed"); - expect(outcomeOf("profile/filter/spelling-equivalence")?._tag).toBe("Passed"); - expect(outcomeOf("profile/filter/evaluation")).toMatchObject({ - _tag: "Passed", - probes: 20, - note: expect.stringMatching( - /^not decided: F-CMP-1, .* on \/issues: no attribute .*; F-EVAL-6 on \/issues: it declares no `fields\[issues\]`/, - ), - }); - }); + it.effect( + "judges GET /issues, which speaks the filter grammar, by the profile's own semantics", + () => + Effect.gen(function* () { + const report = yield* Run; + // #433: `GET /issues` declares `filter: true` and advertises the profile, + // so the filter-profile rules run here rather than only against the kit's + // canned servers. The evaluation rule decides the empty groups, the + // ordering operators on `number` (never NULL) and `assignee`, a to-one + // relationship empty on two of the three issues; the §6.5 corollaries on + // `assignee` and `include=…` beside a filter (#458) — and says why the + // rest went undecided: no attribute is ever NULL, and the endpoint + // declares no `fields[issues]` (deliberately, #322) to send beside a + // filter. Spelling equivalence runs on `title`, the first string + // attribute, `number` leading it (#458). + const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); + expect(outcomeOf("profile/filter/advertises-profile-uri")?._tag).toBe("Passed"); + expect(outcomeOf("profile/filter/rejections")?._tag).toBe("Passed"); + expect(outcomeOf("profile/filter/spelling-equivalence")?._tag).toBe("Passed"); + expect(outcomeOf("profile/filter/evaluation")).toMatchObject({ + _tag: "Passed", + probes: 20, + note: expect.stringMatching( + /^not decided: F-CMP-1, .* on \/issues: no attribute .*; F-EVAL-6 on \/issues: it declares no `fields\[issues\]`/, + ), + }); + }), + ); - it("ran the write rules against targets it created, and left nothing behind", () => { - const writeRules = [ - "spec/status/create-response-document", - // #236: the 201 carries `Location`, copied from the created resource's - // own `links.self`, so the two match. - "spec/status/create-location", - "spec/status/create-location-matches-self", - "spec/status/update-response", - "spec/status/delete-response", - // #237: what each create and update answered reads back through the - // resource's own GET. - "spec/status/create-read-back", - "spec/status/update-read-back", - // #429: a created issue's `labels` replaced with, added to and removed - // from by the `ids` label, each read back through - // `GET /issues/:id/relationships/labels`. The `assignee` PATCH has no - // relationship GET to read back through, so is not decided. - "spec/relationships/update-replaces", - "spec/relationships/add-appends", - "spec/relationships/remove-deletes", - // #451: what each of those writes, and the `assignee` PATCH, answered. - // `update-to-one-null` is not decided: `assignee` has no relationship - // GET to read the cleared linkage back through. - "spec/relationships/write-response", - // #461: the `assignee` and `labels` writes answer 404 for a resource - // that does not exist. - "spec/relationships/absent-related-404", - // #477: a `labels` DELETE naming a label that does not exist succeeds — - // it is already missing from the relationship. - "spec/relationships/remove-absent-succeeds", - ]; - expect( - writeRules.map((id) => report.outcomes.find((outcome) => outcome.rule.id === id)?._tag), - ).toEqual(writeRules.map(() => "Passed")); - const writes = report.writes ?? []; - expect(writes.length).toBeGreaterThan(0); - expect(writes.map((write) => write.disposal)).toEqual( - writes.map(() => expect.stringMatching(/^(deleted|cleaned-up)$/)), - ); - }); + it.effect("ran the write rules against targets it created, and left nothing behind", () => + Effect.gen(function* () { + const report = yield* Run; + const writeRules = [ + "spec/status/create-response-document", + // #236: the 201 carries `Location`, copied from the created resource's + // own `links.self`, so the two match. + "spec/status/create-location", + "spec/status/create-location-matches-self", + "spec/status/update-response", + "spec/status/delete-response", + // #237: what each create and update answered reads back through the + // resource's own GET. + "spec/status/create-read-back", + "spec/status/update-read-back", + // #429: a created issue's `labels` replaced with, added to and removed + // from by the `ids` label, each read back through + // `GET /issues/:id/relationships/labels`. The `assignee` PATCH has no + // relationship GET to read back through, so is not decided. + "spec/relationships/update-replaces", + "spec/relationships/add-appends", + "spec/relationships/remove-deletes", + // #451: what each of those writes, and the `assignee` PATCH, answered. + // `update-to-one-null` is not decided: `assignee` has no relationship + // GET to read the cleared linkage back through. + "spec/relationships/write-response", + // #461: the `assignee` and `labels` writes answer 404 for a resource + // that does not exist. + "spec/relationships/absent-related-404", + // #477: a `labels` DELETE naming a label that does not exist succeeds — + // it is already missing from the relationship. + "spec/relationships/remove-absent-succeeds", + ]; + expect( + writeRules.map((id) => report.outcomes.find((outcome) => outcome.rule.id === id)?._tag), + ).toEqual(writeRules.map(() => "Passed")); + const writes = report.writes ?? []; + expect(writes.length).toBeGreaterThan(0); + expect(writes.map((write) => write.disposal)).toEqual( + writes.map(() => expect.stringMatching(/^(deleted|cleaned-up)$/)), + ); + }), + ); - it("renders a report that states what it did not check", () => { - const text = Conformance.format(report); - expect(text).toContain("NOT COVERED BY THIS KIT"); - expect(text).toContain("SUMMARY"); - // Skipped rules are named individually, not rolled into the pass count. - expect(text).toContain("not checked:"); - }); + it.effect("renders a report that states what it did not check", () => + Effect.gen(function* () { + const report = yield* Run; + const text = Conformance.format(report); + expect(text).toContain("NOT COVERED BY THIS KIT"); + expect(text).toContain("SUMMARY"); + // Skipped rules are named individually, not rolled into the pass count. + expect(text).toContain("not checked:"); + }), + ); - it("runs the spec tier without the profile tier", async () => { - const specOnly = await Effect.runPromise( - Conformance.verify(Api, { ids: IDS, tiers: ["spec"] }).pipe( + it.effect("runs the spec tier without the profile tier", () => + Effect.gen(function* () { + const specOnly = yield* Conformance.verify(Api, { ids: IDS, tiers: ["spec"] }).pipe( Effect.provide(GitHubLive), Effect.scoped, - ) as Effect.Effect, - ); - expect(specOnly.outcomes.every((outcome) => outcome.rule.tier === "spec")).toBe(true); - expect( - died(specOnly), - `a rule died — a defect, not a finding\n${Conformance.format(specOnly)}`, - ).toEqual([]); - const failing = specOnly.outcomes - .filter((outcome) => P.isTagged(outcome, "Failed")) - .map((outcome) => outcome.rule.id); - expect(failing).not.toContain("profile/document/jsonapi-member"); - }); + ) as Effect.Effect; + expect(specOnly.outcomes.every((outcome) => outcome.rule.tier === "spec")).toBe(true); + expect( + died(specOnly), + `a rule died — a defect, not a finding\n${Conformance.format(specOnly)}`, + ).toEqual([]); + const failing = specOnly.outcomes + .filter((outcome) => P.isTagged(outcome, "Failed")) + .map((outcome) => outcome.rule.id); + expect(failing).not.toContain("profile/document/jsonapi-member"); + }), + ); }); diff --git a/examples/github/test/github.test.ts b/examples/github/test/github.test.ts index 8f7c1e0..46659f8 100644 --- a/examples/github/test/github.test.ts +++ b/examples/github/test/github.test.ts @@ -3,8 +3,9 @@ * (request encoding → routing → middleware → handler → response decoding) * through the in-memory `HttpApiTest` client. */ +import { it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { assert, describe, expect, expectTypeOf, it } from "vite-plus/test"; +import { assert, describe, expect, expectTypeOf } from "vite-plus/test"; import * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; @@ -48,13 +49,11 @@ const buildClient = HttpApiTest.groups(Api, ["users", "repositories", "issues", const jsonText = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); -const run = (effect: Effect.Effect): Promise
=> - Effect.runPromise(effect.pipe(Effect.scoped, Effect.provide(GitHubLive)) as Effect.Effect); +const run = (effect: Effect.Effect): Effect.Effect => + effect.pipe(Effect.scoped, Effect.provide(GitHubLive)) as Effect.Effect; -const runExit = (effect: Effect.Effect): Promise> => - Effect.runPromiseExit( - effect.pipe(Effect.scoped, Effect.provide(GitHubLive)) as Effect.Effect, - ); +const runExit = (effect: Effect.Effect): Effect.Effect> => + Effect.exit(effect.pipe(Effect.scoped, Effect.provide(GitHubLive)) as Effect.Effect); const findFailure = (cause: Cause.Cause): E | undefined => { const result = Cause.findError(cause); @@ -62,284 +61,322 @@ const findFailure = (cause: Cause.Cause): E | undefined => { }; describe("github example: fetching", () => { - it("fetches a repository document with a self link", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.get({ - params: { id: Repository.Id.make("1") }, - query: {}, - }); - }), - ); + it.effect("fetches a repository document with a self link", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.get({ + params: { id: Repository.Id.make("1") }, + query: {}, + }); + }), + ); - expect(document.data).toMatchObject({ - type: "repositories", - id: "1", - attributes: { name: "Hello-World", stargazerCount: 2127 }, - }); - expect(document.links?.self).toBe("/repositories/1"); - // dates decode through the wire format - expect(document.data?.attributes.createdAt).toBeInstanceOf(Date); - }); + expect(document.data).toMatchObject({ + type: "repositories", + id: "1", + attributes: { name: "Hello-World", stargazerCount: 2127 }, + }); + expect(document.links?.self).toBe("/repositories/1"); + // dates decode through the wire format + expect(document.data?.attributes.createdAt).toBeInstanceOf(Date); + }), + ); - it("serves compound documents for ?include=owner", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.get({ - params: { id: Repository.Id.make("1") }, - query: { include: ["owner"] }, - }); - }), - ); + it.effect("serves compound documents for ?include=owner", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.get({ + params: { id: Repository.Id.make("1") }, + query: { include: ["owner"] }, + }); + }), + ); - expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); - }); + expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); + }), + ); - it("omits `included` when the request carries no `include` (#232)", async () => { - const { list, one } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const one = yield* client.repositories.get({ - params: { id: Repository.Id.make("1") }, - query: {}, - }); - const list = yield* client.repositories.list({ query: {} }); - return { list, one }; - }), - ); - expect(one).not.toHaveProperty("included"); - expect(list).not.toHaveProperty("included"); - }); + it.effect("omits `included` when the request carries no `include` (#232)", () => + Effect.gen(function* () { + const { list, one } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const one = yield* client.repositories.get({ + params: { id: Repository.Id.make("1") }, + query: {}, + }); + const list = yield* client.repositories.list({ query: {} }); + return { list, one }; + }), + ); + expect(one).not.toHaveProperty("included"); + expect(list).not.toHaveProperty("included"); + }), + ); - it("answers `?include=` with no paths with an empty `included` (#232)", async () => { - // `include: []` goes on the wire as a bare `?include=`, which decodes to - // `[]`: the request carried `include`, so the compound document keeps its - // key (§Fetching Includes), empty because no path names anything to load. - const { list, one } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const one = yield* client.repositories.get({ - params: { id: Repository.Id.make("1") }, - query: { include: [] }, - }); - const list = yield* client.repositories.list({ query: { include: [] } }); - return { list, one }; - }), - ); - expect(one.included).toEqual([]); - expect(list.included).toEqual([]); - }); + it.effect("answers `?include=` with no paths with an empty `included` (#232)", () => + Effect.gen(function* () { + // `include: []` goes on the wire as a bare `?include=`, which decodes to + // `[]`: the request carried `include`, so the compound document keeps its + // key (§Fetching Includes), empty because no path names anything to load. + const { list, one } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const one = yield* client.repositories.get({ + params: { id: Repository.Id.make("1") }, + query: { include: [] }, + }); + const list = yield* client.repositories.list({ query: { include: [] } }); + return { list, one }; + }), + ); + expect(one.included).toEqual([]); + expect(list.included).toEqual([]); + }), + ); - it("resolves 2-hop include paths: issue → repository → owner", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.get({ - params: { id: Issue.Id.make("1") }, - query: { include: ["repository.owner", "author", "labels"] }, - }); - }), - ); + it.effect("resolves 2-hop include paths: issue → repository → owner", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.get({ + params: { id: Issue.Id.make("1") }, + query: { include: ["repository.owner", "author", "labels"] }, + }); + }), + ); - const types = Arr.sort(document.included?.map((resource) => resource.type) ?? [], Order.String); - // repository (intermediate), its owner + the issue's author (deduplicated users), the labels - expect(types).toEqual(["labels", "repositories", "users", "users"]); - }); + const types = Arr.sort( + document.included?.map((resource) => resource.type) ?? [], + Order.String, + ); + // repository (intermediate), its owner + the issue's author (deduplicated users), the labels + expect(types).toEqual(["labels", "repositories", "users", "users"]); + }), + ); - it("narrows `included` to the requested include paths on the client", async () => { - const include = ["owner"] as const; - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories - .get({ - params: { id: Repository.Id.make("1") }, - query: { include }, - }) - .pipe(Client.narrowIncluded(Repository, include)); - }), - ); + it.effect("narrows `included` to the requested include paths on the client", () => + Effect.gen(function* () { + const include = ["owner"] as const; + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories + .get({ + params: { id: Repository.Id.make("1") }, + query: { include }, + }) + .pipe(Client.narrowIncluded(Repository, include)); + }), + ); - // Runtime: the server only included the requested owner - expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); - // Types: `included` is narrowed to User — its attributes are accessible - // without discriminating on `type` - const owner = document.included?.[0]; - expect(owner?.attributes.login).toBe("octocat"); - assert(owner !== undefined); - expectTypeOf(owner.attributes.login).toEqualTypeOf(); - expectTypeOf(owner.type).toEqualTypeOf<"users">(); - }); + // Runtime: the server only included the requested owner + expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); + // Types: `included` is narrowed to User — its attributes are accessible + // without discriminating on `type` + const owner = document.included?.[0]; + expect(owner?.attributes.login).toBe("octocat"); + assert(owner !== undefined); + expectTypeOf(owner.attributes.login).toEqualTypeOf(); + expectTypeOf(owner.type).toEqualTypeOf<"users">(); + }), + ); - it("fetches a pull request with its reviewers included", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.pulls.get({ - params: { id: PullRequest.Id.make("1") }, - query: { include: ["author", "reviewers"] }, - }); - }), - ); + it.effect("fetches a pull request with its reviewers included", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.pulls.get({ + params: { id: PullRequest.Id.make("1") }, + query: { include: ["author", "reviewers"] }, + }); + }), + ); - expect(document.data?.attributes.headRef).toBe("octocat:patch-1"); - // author + 2 reviewers - expect(document.included?.filter((resource) => resource.type === "users")).toHaveLength(3); - }); + expect(document.data?.attributes.headRef).toBe("octocat:patch-1"); + // author + 2 reviewers + expect(document.included?.filter((resource) => resource.type === "users")).toHaveLength(3); + }), + ); - it("404s with a typed error for unknown repositories", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.get({ - params: { id: Repository.Id.make("nope") }, - query: {}, - }); - }), - ); + it.effect("404s with a typed error for unknown repositories", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.get({ + params: { id: Repository.Id.make("nope") }, + query: {}, + }); + }), + ); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - expect(error).toBeInstanceOf(RepositoryNotFound); - expect((error as RepositoryNotFound).id).toBe("nope"); - }); + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + expect(error).toBeInstanceOf(RepositoryNotFound); + expect((error as RepositoryNotFound).id).toBe("nope"); + }), + ); }); describe("github example: listing", () => { - it("lists repositories sorted by stars with page-number pagination", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.list({ - query: { - sort: [{ field: "stargazerCount", direction: "desc" }], - page: { number: 1, size: 2 }, - }, - }); - }), - ); - - // most-starred first - expect(document.data[0]?.attributes.name).toBe(spoonKnife.attributes.name); - expect(document.data).toHaveLength(2); - expect(document.meta?.total).toBe(3); - expect(document.links?.next).toBe( - "/repositories?sort=-stargazerCount&page[number]=2&page[size]=2", - ); - }); - - it("filters repositories by language", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.list({ - query: { filter: { language: "TypeScript" } }, - }); - }), - ); + it.effect("lists repositories sorted by stars with page-number pagination", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.list({ + query: { + sort: [{ field: "stargazerCount", direction: "desc" }], + page: { number: 1, size: 2 }, + }, + }); + }), + ); - expect(document.data.map((repository) => repository.attributes.name)).toEqual([ - "secret-project", - ]); - }); + // most-starred first + expect(document.data[0]?.attributes.name).toBe(spoonKnife.attributes.name); + expect(document.data).toHaveLength(2); + expect(document.meta?.total).toBe(3); + expect(document.links?.next).toBe( + "/repositories?sort=-stargazerCount&page[number]=2&page[size]=2", + ); + }), + ); - it("filters repositories by owner and visibility", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.list({ - query: { filter: { owner: octocat.id, visibility: "public" } }, - }); - }), - ); + it.effect("filters repositories by language", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.list({ + query: { filter: { language: "TypeScript" } }, + }); + }), + ); - const names = Arr.sort( - document.data.map((repository) => repository.attributes.name), - Order.String, - ); - expect(names).toEqual(["Hello-World", "Spoon-Knife"]); - }); + expect(document.data.map((repository) => repository.attributes.name)).toEqual([ + "secret-project", + ]); + }), + ); - it("filters issues by state and repository", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.list({ - query: { - filter: Filter.and(Filter.eq("state", "open"), Filter.eq("repository", helloWorld.id)), - }, - }); - }), - ); + it.effect("filters repositories by owner and visibility", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.list({ + query: { filter: { owner: octocat.id, visibility: "public" } }, + }); + }), + ); - expect(document.data.map((issue) => issue.attributes.title)).toEqual([ - bugIssue.attributes.title, - ]); - // the closed attribute set decodes to its literal type - Arr.forEach(document.data, (issue) => { - expectTypeOf(issue.attributes.state).toEqualTypeOf<"open" | "closed">(); - expect(issue.attributes.state).toBe("open"); - }); - }); + const names = Arr.sort( + document.data.map((repository) => repository.attributes.name), + Order.String, + ); + expect(names).toEqual(["Hello-World", "Spoon-Knife"]); + }), + ); - it("evaluates an issue filter three-valued: an unassigned issue matches neither eq nor ne", async () => { - const ids = (filter: Query.FilterAst) => - run( + it.effect("filters issues by state and repository", () => + Effect.gen(function* () { + const document = yield* run( Effect.gen(function* () { const client = yield* buildClient; - const document = yield* client.issues.list({ query: { filter } }); - return document.data.map((issue) => issue.id); + return yield* client.issues.list({ + query: { + filter: Filter.and( + Filter.eq("state", "open"), + Filter.eq("repository", helloWorld.id), + ), + }, + }); }), ); - // bugIssue is octocat's; featureIssue and lockedIssue are unassigned. - expect(await ids(Filter.eq("assignee", octocat.id))).toEqual([bugIssue.id]); - expect(await ids(Filter.ne("assignee", octocat.id))).toEqual([]); - expect(await ids(Filter.isNull("assignee"))).toEqual([featureIssue.id, lockedIssue.id]); - // F-CONS-1: excluded middle does not hold where the field is NULL. - const eq = Filter.eq("assignee", octocat.id); - expect(await ids(Filter.or(eq, Filter.not(eq)))).toEqual([bugIssue.id]); - // F-ORD-1: numbers numerically, dates as ISO-8601 text. - expect(await ids(Filter.gt("number", 1000))).toEqual([bugIssue.id, featureIssue.id]); - expect(await ids(Filter.lt("createdAt", lockedIssue.attributes.createdAt))).toEqual([ - bugIssue.id, - featureIssue.id, - ]); - // F-AND-2: the empty groups. - expect(await ids(Filter.and())).toHaveLength(3); - expect(await ids(Filter.or())).toEqual([]); - }); - it("lists users sorted by login", async () => { - const document = await run( + expect(document.data.map((issue) => issue.attributes.title)).toEqual([ + bugIssue.attributes.title, + ]); + // the closed attribute set decodes to its literal type + Arr.forEach(document.data, (issue) => { + expectTypeOf(issue.attributes.state).toEqualTypeOf<"open" | "closed">(); + expect(issue.attributes.state).toBe("open"); + }); + }), + ); + + it.effect( + "evaluates an issue filter three-valued: an unassigned issue matches neither eq nor ne", + () => Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.users.list({ - query: { sort: [{ field: "login", direction: "asc" }] }, - }); + const ids = (filter: Query.FilterAst) => + run( + Effect.gen(function* () { + const client = yield* buildClient; + const document = yield* client.issues.list({ query: { filter } }); + return document.data.map((issue) => issue.id); + }), + ); + // bugIssue is octocat's; featureIssue and lockedIssue are unassigned. + expect(yield* ids(Filter.eq("assignee", octocat.id))).toEqual([bugIssue.id]); + expect(yield* ids(Filter.ne("assignee", octocat.id))).toEqual([]); + expect(yield* ids(Filter.isNull("assignee"))).toEqual([featureIssue.id, lockedIssue.id]); + // F-CONS-1: excluded middle does not hold where the field is NULL. + const eq = Filter.eq("assignee", octocat.id); + expect(yield* ids(Filter.or(eq, Filter.not(eq)))).toEqual([bugIssue.id]); + // F-ORD-1: numbers numerically, dates as ISO-8601 text. + expect(yield* ids(Filter.gt("number", 1000))).toEqual([bugIssue.id, featureIssue.id]); + expect(yield* ids(Filter.lt("createdAt", lockedIssue.attributes.createdAt))).toEqual([ + bugIssue.id, + featureIssue.id, + ]); + // F-AND-2: the empty groups. + expect(yield* ids(Filter.and())).toHaveLength(3); + expect(yield* ids(Filter.or())).toEqual([]); }), - ); + ); - expect(document.data.map((user) => user.attributes.login)).toEqual([ - "defunkt", - "hubot", - "octocat", - ]); - }); + it.effect("lists users sorted by login", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.users.list({ + query: { sort: [{ field: "login", direction: "asc" }] }, + }); + }), + ); - it("filters pull requests by state", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.pulls.list({ - query: { filter: { state: "merged" } }, - }); - }), - ); + expect(document.data.map((user) => user.attributes.login)).toEqual([ + "defunkt", + "hubot", + "octocat", + ]); + }), + ); - expect(document.data).toEqual([]); - }); + it.effect("filters pull requests by state", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.pulls.list({ + query: { filter: { state: "merged" } }, + }); + }), + ); + + expect(document.data).toEqual([]); + }), + ); }); describe("github example: pagination links carry the request's query (#447)", () => { @@ -347,77 +384,83 @@ describe("github example: pagination links carry the request's query (#447)", () const searchOf = (link: string): Record => Rec.fromEntries(new URL(link, "https://example.test").searchParams); - it("`next` on GET /issues keeps `sort`, `filter` and `include`, and continues the order", async () => { - const [first, second] = await run( + it.effect( + "`next` on GET /issues keeps `sort`, `filter` and `include`, and continues the order", + () => Effect.gen(function* () { - const client = yield* buildClient; - const first = yield* client.issues.list({ - query: { - include: ["author"], - filter: Filter.eq("state", "open"), - sort: [{ field: "number", direction: "desc" }], - page: { number: 1, size: 1 }, - }, - }); - const next = first.links?.next; - assert(P.isString(next)); - const query = yield* Schema.decodeUnknownEffect(IssuesQuery)(searchOf(next)); - const second = yield* client.issues.list({ query }); - return [first, second] as const; - }), - ); - - expect(first.links?.next).toBe( - "/issues?include=author&filter[state]=open&sort=-number&page[number]=2&page[size]=1", - ); - expect(first.links?.last).toMatch( - /^\/issues\?include=author&filter\[state\]=open&sort=-number&/, - ); - // Following `next` serves the second page of the same query, not the - // default order: still open issues, still descending by number. - const [top] = first.data; - const [next] = second.data; - assert.isDefined(top); - assert.isDefined(next); - expect(next.attributes.state).toBe("open"); - expect(next.attributes.number).toBeLessThan(top.attributes.number); - expect(second.links?.prev).toBe( - "/issues?include=author&filter[state]=open&sort=-number&page[number]=1&page[size]=1", - ); - }); + const [first, second] = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const first = yield* client.issues.list({ + query: { + include: ["author"], + filter: Filter.eq("state", "open"), + sort: [{ field: "number", direction: "desc" }], + page: { number: 1, size: 1 }, + }, + }); + const next = first.links?.next; + assert(P.isString(next)); + const query = yield* Schema.decodeUnknownEffect(IssuesQuery)(searchOf(next)); + const second = yield* client.issues.list({ query }); + return [first, second] as const; + }), + ); - it("`next` on GET /search keeps `fields`, `filter` and `include`", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { - include: ["owner"], - fields: { repositories: ["name"] }, - filter: { q: "o" }, - page: { offset: 0, limit: 1 }, - }, - }); + expect(first.links?.next).toBe( + "/issues?include=author&filter[state]=open&sort=-number&page[number]=2&page[size]=1", + ); + expect(first.links?.last).toMatch( + /^\/issues\?include=author&filter\[state\]=open&sort=-number&/, + ); + // Following `next` serves the second page of the same query, not the + // default order: still open issues, still descending by number. + const [top] = first.data; + const [next] = second.data; + assert.isDefined(top); + assert.isDefined(next); + expect(next.attributes.state).toBe("open"); + expect(next.attributes.number).toBeLessThan(top.attributes.number); + expect(second.links?.prev).toBe( + "/issues?include=author&filter[state]=open&sort=-number&page[number]=1&page[size]=1", + ); }), - ); + ); - expect(document.links?.next).toBe( - "/search?include=owner&fields[repositories]=name&filter[q]=o&page[offset]=1&page[limit]=1", - ); - const next = document.links?.next; - assert(P.isString(next)); - expect(Schema.decodeUnknownSync(SearchQuery)(searchOf(next))).toEqual({ - include: ["owner"], - fields: { repositories: ["name"] }, - filter: { q: "o" }, - page: { offset: 1, limit: 1 }, - }); - }); + it.effect("`next` on GET /search keeps `fields`, `filter` and `include`", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { + include: ["owner"], + fields: { repositories: ["name"] }, + filter: { q: "o" }, + page: { offset: 0, limit: 1 }, + }, + }); + }), + ); + + expect(document.links?.next).toBe( + "/search?include=owner&fields[repositories]=name&filter[q]=o&page[offset]=1&page[limit]=1", + ); + const next = document.links?.next; + assert(P.isString(next)); + expect(yield* Schema.decodeUnknownEffect(SearchQuery)(searchOf(next))).toEqual({ + include: ["owner"], + fields: { repositories: ["name"] }, + filter: { q: "o" }, + page: { offset: 1, limit: 1 }, + }); + }), + ); }); describe("github example: writing", () => { - it("creates a repository from a JSON:API payload (201) and then deletes it (204)", async () => { - await run( + it.effect("creates a repository from a JSON:API payload (201) and then deletes it (204)", () => + run( Effect.gen(function* () { const client = yield* buildClient; @@ -448,414 +491,450 @@ describe("github example: writing", () => { // and delete it again yield* client.repositories.delete({ params: { id: created.data.id } }); }), - ); - }); + ), + ); - it("422s when the repository name is already taken by the same owner", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.create({ - payload: { - data: { - type: "repositories", - attributes: { - name: helloWorld.attributes.name, - private: false, - stargazerCount: 0, - createdAt: now(), - }, - relationships: { - owner: { data: User.ref(octocat.id) }, + it.effect("422s when the repository name is already taken by the same owner", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.create({ + payload: { + data: { + type: "repositories", + attributes: { + name: helloWorld.attributes.name, + private: false, + stargazerCount: 0, + createdAt: now(), + }, + relationships: { + owner: { data: User.ref(octocat.id) }, + }, }, }, - }, - }); - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(RepositoryNameTaken); - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(RepositoryNameTaken); + }), + ); - it("opens an issue against a repository (201)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.create({ - payload: { - data: { - type: "issues", - attributes: { - number: 1350, - title: "Docs are out of date", - body: "The README still references the old API.", - state: "open", - locked: false, - createdAt: at("2024-06-01T00:00:00.000Z"), + it.effect("opens an issue against a repository (201)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.create({ + payload: { + data: { + type: "issues", + attributes: { + number: 1350, + title: "Docs are out of date", + body: "The README still references the old API.", + state: "open", + locked: false, + createdAt: at("2024-06-01T00:00:00.000Z"), + }, + relationships: { + repository: { data: Repository.ref(helloWorld.id) }, + author: { data: User.ref(octocat.id) }, + assignee: { data: null }, + labels: { data: [] }, + }, }, - relationships: { - repository: { data: Repository.ref(helloWorld.id) }, - author: { data: User.ref(octocat.id) }, - assignee: { data: null }, - labels: { data: [] }, + }, + }); + }), + ); + + expect(document.data?.attributes.title).toBe("Docs are out of date"); + expect(document.data?.relationships?.repository.data?.id).toBe(helloWorld.id); + }), + ); + + it.effect("404s when opening an issue against a missing repository", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.create({ + payload: { + data: { + type: "issues", + attributes: { + number: 1, + title: "Lost issue", + body: "", + state: "open", + locked: false, + createdAt: now(), + }, + relationships: { + repository: { data: Repository.ref("does-not-exist") }, + // `author` is required (`one`) — null wouldn't even decode. + author: { data: User.ref(octocat.id) }, + assignee: { data: null }, + labels: { data: [] }, + }, }, }, - }, - }); - }), - ); + }); + }), + ); - expect(document.data?.attributes.title).toBe("Docs are out of date"); - expect(document.data?.relationships?.repository.data?.id).toBe(helloWorld.id); - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(RepositoryNotFound); + }), + ); - it("404s when opening an issue against a missing repository", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.create({ - payload: { - data: { - type: "issues", - attributes: { - number: 1, - title: "Lost issue", - body: "", - state: "open", - locked: false, - createdAt: now(), + it.effect("404s when opening an issue with linkage to a missing label, creating nothing", () => + Effect.gen(function* () { + const { before, exit, after } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const list = client.issues.list({ query: {} }); + const before = (yield* list).meta?.total; + const exit = yield* Effect.exit( + client.issues.create({ + payload: { + data: { + type: "issues", + attributes: { + number: 1351, + title: "Mislabelled", + body: "", + state: "open", + locked: false, + createdAt: bugIssue.attributes.createdAt, + }, + relationships: { + repository: { data: Repository.ref(helloWorld.id) }, + author: { data: User.ref(octocat.id) }, + assignee: { data: null }, + labels: { data: [Label.ref(bugLabel.id), Label.ref("does-not-exist")] }, + }, + }, }, - relationships: { - repository: { data: Repository.ref("does-not-exist") }, - // `author` is required (`one`) — null wouldn't even decode. - author: { data: User.ref(octocat.id) }, - assignee: { data: null }, - labels: { data: [] }, + }), + ); + const after = (yield* list).meta?.total; + return { before, exit, after }; + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof LabelNotFound); + expect(error.id).toBe("does-not-exist"); + expect(after).toBe(before); + }), + ); + + it.effect("404s when updating an issue's labels to a missing label, leaving it unchanged", () => + Effect.gen(function* () { + const { exit, labels, title } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const exit = yield* Effect.exit( + client.issues.update({ + params: { id: bugIssue.id }, + payload: { + data: { + type: "issues", + id: bugIssue.id, + attributes: { title: "Renamed" }, + relationships: { labels: { data: [Label.ref("does-not-exist")] } }, + }, }, - }, - }, - }); - }), - ); + }), + ); + const after = yield* client.issues.get({ params: { id: bugIssue.id }, query: {} }); + return { + exit, + labels: after.data?.relationships?.labels?.data, + title: after.data?.attributes.title, + }; + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(RepositoryNotFound); - }); + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + assert(error instanceof LabelNotFound); + expect(error.id).toBe("does-not-exist"); + // the whole update is refused, attributes included + expect(labels).toEqual(bugIssue.relationships?.labels.data); + expect(title).toBe(bugIssue.attributes.title); + }), + ); - it("404s when opening an issue with linkage to a missing label, creating nothing", async () => { - const { before, exit, after } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const list = client.issues.list({ query: {} }); - const before = (yield* list).meta?.total; - const exit = yield* Effect.exit( - client.issues.create({ + it.effect("closes an issue with a partial update", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.update({ + params: { id: Issue.Id.make("1") }, payload: { data: { type: "issues", - attributes: { - number: 1351, - title: "Mislabelled", - body: "", - state: "open", - locked: false, - createdAt: bugIssue.attributes.createdAt, - }, - relationships: { - repository: { data: Repository.ref(helloWorld.id) }, - author: { data: User.ref(octocat.id) }, - assignee: { data: null }, - labels: { data: [Label.ref(bugLabel.id), Label.ref("does-not-exist")] }, - }, + id: Issue.Id.make("1"), + attributes: { state: "closed" }, }, }, - }), - ); - const after = (yield* list).meta?.total; - return { before, exit, after }; - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof LabelNotFound); - expect(error.id).toBe("does-not-exist"); - expect(after).toBe(before); - }); + expect(document.data?.attributes.state).toBe("closed"); + // other attributes are untouched + expect(document.data?.attributes.title).toBe(bugIssue.attributes.title); + // a write response advertises JSON:API 1.1 too, not only the reads + expect(document.jsonapi?.version).toBe("1.1"); + }), + ); - it("404s when updating an issue's labels to a missing label, leaving it unchanged", async () => { - const { exit, labels, title } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const exit = yield* Effect.exit( - client.issues.update({ - params: { id: bugIssue.id }, + it.effect("403s with a typed error when updating a locked issue", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.update({ + params: { id: lockedIssue.id }, payload: { data: { type: "issues", - id: bugIssue.id, - attributes: { title: "Renamed" }, - relationships: { labels: { data: [Label.ref("does-not-exist")] } }, + id: lockedIssue.id, + attributes: { state: "closed" }, }, }, - }), - ); - const after = yield* client.issues.get({ params: { id: bugIssue.id }, query: {} }); - return { - exit, - labels: after.data?.relationships?.labels?.data, - title: after.data?.attributes.title, - }; - }), - ); - - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - assert(error instanceof LabelNotFound); - expect(error.id).toBe("does-not-exist"); - // the whole update is refused, attributes included - expect(labels).toEqual(bugIssue.relationships?.labels.data); - expect(title).toBe(bugIssue.attributes.title); - }); - - it("closes an issue with a partial update", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.update({ - params: { id: Issue.Id.make("1") }, - payload: { - data: { - type: "issues", - id: Issue.Id.make("1"), - attributes: { state: "closed" }, - }, - }, - }); - }), - ); - - expect(document.data?.attributes.state).toBe("closed"); - // other attributes are untouched - expect(document.data?.attributes.title).toBe(bugIssue.attributes.title); - // a write response advertises JSON:API 1.1 too, not only the reads - expect(document.jsonapi?.version).toBe("1.1"); - }); - - it("403s with a typed error when updating a locked issue", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.update({ - params: { id: lockedIssue.id }, - payload: { - data: { - type: "issues", - id: lockedIssue.id, - attributes: { state: "closed" }, - }, - }, - }); - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - expect(error).toBeInstanceOf(IssueLocked); - expect((error as IssueLocked).id).toBe(lockedIssue.id); - }); + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + expect(error).toBeInstanceOf(IssueLocked); + expect((error as IssueLocked).id).toBe(lockedIssue.id); + }), + ); }); describe("github example: related resource endpoints", () => { - it("GET /repositories/:id/owner serves the owning user", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.repositories.owner({ - params: { id: Repository.Id.make("1") }, - query: {}, - }); - }), - ); + it.effect("GET /repositories/:id/owner serves the owning user", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.repositories.owner({ + params: { id: Repository.Id.make("1") }, + query: {}, + }); + }), + ); - expect(document.data).toMatchObject({ - type: "users", - id: octocat.id, - attributes: { login: "octocat" }, - }); - expect(document.links?.self).toBe("/repositories/1/owner"); - }); + expect(document.data).toMatchObject({ + type: "users", + id: octocat.id, + attributes: { login: "octocat" }, + }); + expect(document.links?.self).toBe("/repositories/1/owner"); + }), + ); - it("GET /issues/:id/comments serves the paginated comment feed", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.comments({ - params: { id: bugIssue.id }, - query: { page: { number: 1, size: 2 } }, - }); - }), - ); + it.effect("GET /issues/:id/comments serves the paginated comment feed", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.comments({ + params: { id: bugIssue.id }, + query: { page: { number: 1, size: 2 } }, + }); + }), + ); - // Full comment resources, paginated GitHub-style - expect(document.data).toHaveLength(2); - expect(document.data[0]?.attributes.body).toBe(bugComments[0].attributes.body); - expect(document.meta?.total).toBe(3); - expect(document.links?.next).toBe("/issues/1/comments?page[number]=2&page[size]=2"); - }); + // Full comment resources, paginated GitHub-style + expect(document.data).toHaveLength(2); + expect(document.data[0]?.attributes.body).toBe(bugComments[0].attributes.body); + expect(document.meta?.total).toBe(3); + expect(document.links?.next).toBe("/issues/1/comments?page[number]=2&page[size]=2"); + }), + ); - it("GET /issues/:id/comments supports compound documents (?include=author)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.comments({ - params: { id: bugIssue.id }, - query: { include: ["author"] }, - }); - }), - ); + it.effect("GET /issues/:id/comments supports compound documents (?include=author)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.comments({ + params: { id: bugIssue.id }, + query: { include: ["author"] }, + }); + }), + ); - // Three comments by two distinct users → two deduplicated includes - expect(document.data).toHaveLength(3); - const authors = Arr.sort(document.included?.map((resource) => resource.id) ?? [], Order.String); - expect(authors).toEqual(Arr.sort([octocat.id, defunkt.id], Order.String)); - }); + // Three comments by two distinct users → two deduplicated includes + expect(document.data).toHaveLength(3); + const authors = Arr.sort( + document.included?.map((resource) => resource.id) ?? [], + Order.String, + ); + expect(authors).toEqual(Arr.sort([octocat.id, defunkt.id], Order.String)); + }), + ); - it("issues with no comments serve an empty related collection", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.comments({ - params: { id: lockedIssue.id }, - query: {}, - }); - }), - ); + it.effect("issues with no comments serve an empty related collection", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.comments({ + params: { id: lockedIssue.id }, + query: {}, + }); + }), + ); - expect(document.data).toEqual([]); - expect(document.meta?.total).toBe(0); - }); + expect(document.data).toEqual([]); + expect(document.meta?.total).toBe(0); + }), + ); }); describe("github example: issue triage via relationship endpoints", () => { - it("GET /issues/:id/relationships/labels serves label linkage", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.labelsRelationship({ - params: { id: bugIssue.id }, - query: {}, - }); - }), - ); - - expect(document.data).toEqual([{ type: "labels", id: bugLabel.id }]); - expect(document.links?.self).toBe("/issues/1/relationships/labels"); - expect(document.links?.related).toBe("/issues/1/labels"); - }); - - it("PATCH /issues/:id/relationships/assignee assigns a user", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const linkage = yield* client.issues.updateAssigneeRelationship({ - params: { id: bugIssue.id }, - payload: { data: User.ref(hubot.id) }, - }); - // The issue reflects the assignment - const issue = yield* client.issues.get({ params: { id: bugIssue.id }, query: {} }); - expect(issue.data?.relationships?.assignee?.data?.id).toBe(hubot.id); - return linkage; - }), - ); - - expect(document.data).toEqual({ type: "users", id: hubot.id }); - }); - - it("PATCH /issues/:id/relationships/assignee with null unassigns", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.updateAssigneeRelationship({ - params: { id: bugIssue.id }, - payload: { data: null }, - }); - }), - ); - - expect(document.data).toBeNull(); - }); - - it("404s when assigning an unknown user", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.updateAssigneeRelationship({ - params: { id: bugIssue.id }, - payload: { data: User.ref("ghost") }, - }); - }), - ); - - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(UserNotFound); - }); - - it.each(["updateLabelsRelationship", "addLabelsRelationship"] as const)( - "404s when %s names a label that does not exist, leaving the labels unchanged", - async (endpoint) => { - const before = await run( + it.effect("GET /issues/:id/relationships/labels serves label linkage", () => + Effect.gen(function* () { + const document = yield* run( Effect.gen(function* () { const client = yield* buildClient; return yield* client.issues.labelsRelationship({ - params: { id: featureIssue.id }, + params: { id: bugIssue.id }, query: {}, }); }), ); - const exit = await runExit( + + expect(document.data).toEqual([{ type: "labels", id: bugLabel.id }]); + expect(document.links?.self).toBe("/issues/1/relationships/labels"); + expect(document.links?.related).toBe("/issues/1/labels"); + }), + ); + + it.effect("PATCH /issues/:id/relationships/assignee assigns a user", () => + Effect.gen(function* () { + const document = yield* run( Effect.gen(function* () { const client = yield* buildClient; - return yield* client.issues[endpoint]({ - params: { id: featureIssue.id }, - payload: { data: [Label.ref(bugLabel.id), Label.ref("no-such-label")] }, + const linkage = yield* client.issues.updateAssigneeRelationship({ + params: { id: bugIssue.id }, + payload: { data: User.ref(hubot.id) }, }); + // The issue reflects the assignment + const issue = yield* client.issues.get({ params: { id: bugIssue.id }, query: {} }); + expect(issue.data?.relationships?.assignee?.data?.id).toBe(hubot.id); + return linkage; }), ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(LabelNotFound); - const after = await run( + expect(document.data).toEqual({ type: "users", id: hubot.id }); + }), + ); + + it.effect("PATCH /issues/:id/relationships/assignee with null unassigns", () => + Effect.gen(function* () { + const document = yield* run( Effect.gen(function* () { const client = yield* buildClient; - return yield* client.issues.labelsRelationship({ - params: { id: featureIssue.id }, - query: {}, + return yield* client.issues.updateAssigneeRelationship({ + params: { id: bugIssue.id }, + payload: { data: null }, + }); + }), + ); + + expect(document.data).toBeNull(); + }), + ); + + it.effect("404s when assigning an unknown user", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.updateAssigneeRelationship({ + params: { id: bugIssue.id }, + payload: { data: User.ref("ghost") }, }); }), ); - expect(after.data).toEqual(before.data); - }, + + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(UserNotFound); + }), ); - it("403s when triaging a locked issue", async () => { - const exit = await runExit( + it.effect.each(["updateLabelsRelationship", "addLabelsRelationship"] as const)( + "404s when %s names a label that does not exist, leaving the labels unchanged", + (endpoint) => Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.issues.addLabelsRelationship({ - params: { id: lockedIssue.id }, - payload: { data: [Label.ref(bugLabel.id)] }, - }); + const before = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.labelsRelationship({ + params: { id: featureIssue.id }, + query: {}, + }); + }), + ); + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues[endpoint]({ + params: { id: featureIssue.id }, + payload: { data: [Label.ref(bugLabel.id), Label.ref("no-such-label")] }, + }); + }), + ); + + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(LabelNotFound); + const after = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.labelsRelationship({ + params: { id: featureIssue.id }, + query: {}, + }); + }), + ); + expect(after.data).toEqual(before.data); }), - ); + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(IssueLocked); - }); + it.effect("403s when triaging a locked issue", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.issues.addLabelsRelationship({ + params: { id: lockedIssue.id }, + payload: { data: [Label.ref(bugLabel.id)] }, + }); + }), + ); - it("POST adds labels, DELETE removes them, PATCH replaces them", async () => { - await run( + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(IssueLocked); + }), + ); + + it.effect("POST adds labels, DELETE removes them, PATCH replaces them", () => + run( Effect.gen(function* () { const client = yield* buildClient; const issueId = bugIssue.id; @@ -897,8 +976,8 @@ describe("github example: issue triage via relationship endpoints", () => { }); expect(replaced.data).toEqual([{ type: "labels", id: bugLabel.id }]); }), - ); - }); + ), + ); it("documents relationship endpoints in OpenAPI", () => { const spec = OpenApi.fromApi(Api); @@ -921,76 +1000,89 @@ describe("github example: issue triage via relationship endpoints", () => { }); describe("github example: heterogeneous search", () => { - it("returns a mixed collection of repositories, issues and users, discriminated by type", async () => { - const document = await run( + it.effect( + "returns a mixed collection of repositories, issues and users, discriminated by type", + () => Effect.gen(function* () { - const client = yield* buildClient; - // "o" hits all three stores: "Hello-World", "Found a bug", "octocat" - return yield* client.search.search({ - query: { filter: { q: "o" } }, - }); - }), - ); - - const types = Arr.sort([...new Set(document.data.map((result) => result.type))], Order.String); - expect(types).toEqual(["issues", "repositories", "users"]); - - // the union is discriminated by the `type` tag; the endpoint declares - // `fields`, so a client reads each attribute as optional (#322) - Arr.forEach(document.data, (result) => { - if (result.type === "repositories") { - expectTypeOf(result.attributes.stargazerCount).toEqualTypeOf(); - } else if (result.type === "issues") { - expectTypeOf(result.attributes.state).toEqualTypeOf<"open" | "closed" | undefined>(); - } else { - expectTypeOf(result.attributes.login).toEqualTypeOf(); - } - }); - }); + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + // "o" hits all three stores: "Hello-World", "Found a bug", "octocat" + return yield* client.search.search({ + query: { filter: { q: "o" } }, + }); + }), + ); - it("filters across all resource types", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "spoon" } }, + const types = Arr.sort( + [...new Set(document.data.map((result) => result.type))], + Order.String, + ); + expect(types).toEqual(["issues", "repositories", "users"]); + + // the union is discriminated by the `type` tag; the endpoint declares + // `fields`, so a client reads each attribute as optional (#322) + Arr.forEach(document.data, (result) => { + if (result.type === "repositories") { + expectTypeOf(result.attributes.stargazerCount).toEqualTypeOf(); + } else if (result.type === "issues") { + expectTypeOf(result.attributes.state).toEqualTypeOf<"open" | "closed" | undefined>(); + } else { + expectTypeOf(result.attributes.login).toEqualTypeOf(); + } }); }), - ); + ); - // only the Spoon-Knife repository matches - expect(document.data.map((result) => result.type)).toEqual(["repositories"]); - expect(document.meta?.total).toBe(1); - }); + it.effect("filters across all resource types", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "spoon" } }, + }); + }), + ); - it("paginates heterogeneous results with links", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "" }, page: { offset: 0, limit: 2 } }, - }); - }), - ); + // only the Spoon-Knife repository matches + expect(document.data.map((result) => result.type)).toEqual(["repositories"]); + expect(document.meta?.total).toBe(1); + }), + ); - expect(document.data).toHaveLength(2); - expect(document.meta?.total).toBeGreaterThan(2); - expect(document.links?.next).toBe("/search?filter[q]=&page[offset]=2&page[limit]=2"); - }); + it.effect("paginates heterogeneous results with links", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "" }, page: { offset: 0, limit: 2 } }, + }); + }), + ); - it("supports include across the searched resources' graphs", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "spoon" }, include: ["owner"] }, - }); - }), - ); + expect(document.data).toHaveLength(2); + expect(document.meta?.total).toBeGreaterThan(2); + expect(document.links?.next).toBe("/search?filter[q]=&page[offset]=2&page[limit]=2"); + }), + ); - // the matched repository's owner is included - expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); - }); + it.effect("supports include across the searched resources' graphs", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "spoon" }, include: ["owner"] }, + }); + }), + ); + + // the matched repository's owner is included + expect(document.included?.map((resource) => resource.type)).toEqual(["users"]); + }), + ); }); describe("github example: spec compliance on the wire", () => { diff --git a/examples/northwind/package.json b/examples/northwind/package.json index b1cc2e9..d70838d 100644 --- a/examples/northwind/package.json +++ b/examples/northwind/package.json @@ -9,6 +9,7 @@ "effect": "catalog:" }, "devDependencies": { + "@effect/vitest": "catalog:", "@types/node": "catalog:", "vite-plus": "catalog:" } diff --git a/examples/northwind/test/conformance.test.ts b/examples/northwind/test/conformance.test.ts index 0b8052b..583d6f1 100644 --- a/examples/northwind/test/conformance.test.ts +++ b/examples/northwind/test/conformance.test.ts @@ -8,9 +8,12 @@ * here), and a disappearing one means a fixed bug whose entry should come * off this list. */ -import { describe, expect, it } from "vite-plus/test"; +import { layer } from "@effect/vitest"; +import { expect } from "vite-plus/test"; import * as Arr from "effect/Array"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Order from "effect/Order"; import * as P from "effect/Predicate"; import { HttpApiTest } from "effect/http-api"; @@ -160,7 +163,14 @@ const resolveSamples = Effect.fn("resolveSamples")(function* () { // The samples are resolved first, against the store as seeded, then the suite // runs against the same layer. -const { report, resolved } = await Effect.runPromise( +/** The one run every test below reads, built once for the suite. */ +class Run extends Context.Service< + Run, + { readonly report: Conformance.Report; readonly resolved: Record } +>()("example/Run") {} + +const RunLive = Layer.effect( + Run, Effect.all( { resolved: resolveSamples(), @@ -173,171 +183,203 @@ const { report, resolved } = await Effect.runPromise( }>, ); -describe("northwind: JSON:API conformance", () => { - it("decided every rule it ran: none died", () => { - // The message carries the whole report, so a dead rule explains itself - // alongside its neighbours; the diff names each dead rule and its defect. - expect( - died(report), - `a rule died — a defect, not a finding\n${Conformance.format(report)}`, - ).toEqual([]); - }); +layer(RunLive)("northwind: JSON:API conformance", (it) => { + it.effect("decided every rule it ran: none died", () => + Effect.gen(function* () { + const { report } = yield* Run; + // The message carries the whole report, so a dead rule explains itself + // alongside its neighbours; the diff names each dead rule and its defect. + expect( + died(report), + `a rule died — a defect, not a finding\n${Conformance.format(report)}`, + ).toEqual([]); + }), + ); - it("samples an id the example holds for every resource type", () => { - // An `ids` entry the example does not hold fails no rule: the read endpoints - // answer 404, and the rules that resolve `/:type/:id` see less of the api - // (#301). This is the direct guard: each sample fetched through its own - // `get` endpoint, independent of how the kit words anything in its report. - // Keyed by type, so the returned `data.id`s are compared with `IDS` entry by - // entry and a sample that does not resolve shows up under its type. - expect(resolved).toEqual(IDS); - }); + it.effect("samples an id the example holds for every resource type", () => + Effect.gen(function* () { + const { resolved } = yield* Run; + // An `ids` entry the example does not hold fails no rule: the read endpoints + // answer 404, and the rules that resolve `/:type/:id` see less of the api + // (#301). This is the direct guard: each sample fetched through its own + // `get` endpoint, independent of how the kit words anything in its report. + // Keyed by type, so the returned `data.id`s are compared with `IDS` entry by + // entry and a sample that does not resolve shows up under its type. + expect(resolved).toEqual(IDS); + }), + ); - it("sampled only resources the example holds: every sample read answered 200", () => { - // A second line of defence behind the direct guard above, over what the kit - // itself read: `report.samples` records every `/:type/:id` read the `ids` - // resolve, with its status, as data rather than in a note's wording (#319). - // Keyed by type, so a sample that did not resolve shows up under its type, - // and a type the kit resolved no read for is missing. - expect( - Object.fromEntries((report.samples ?? []).map((sample) => [sample.type, sample.status])), - Conformance.format(report), - ).toEqual(Object.fromEntries(Object.keys(IDS).map((type) => [type, 200]))); - }); + it.effect("sampled only resources the example holds: every sample read answered 200", () => + Effect.gen(function* () { + const { report } = yield* Run; + // A second line of defence behind the direct guard above, over what the kit + // itself read: `report.samples` records every `/:type/:id` read the `ids` + // resolve, with its status, as data rather than in a note's wording (#319). + // Keyed by type, so a sample that did not resolve shows up under its type, + // and a type the kit resolved no read for is missing. + expect( + Object.fromEntries((report.samples ?? []).map((sample) => [sample.type, sample.status])), + Conformance.format(report), + ).toEqual(Object.fromEntries(Object.keys(IDS).map((type) => [type, 200]))); + }), + ); - it("breaks exactly the rules that are already filed", () => { - const failing = Arr.sort( - report.outcomes - .filter((outcome) => P.isTagged(outcome, "Failed")) - .map((outcome) => outcome.rule.id), - Order.String, - ); - const known = Arr.sort( - KNOWN_FAILURES.map(([id]) => id), - Order.String, - ); + it.effect("breaks exactly the rules that are already filed", () => + Effect.gen(function* () { + const { report } = yield* Run; + const failing = Arr.sort( + report.outcomes + .filter((outcome) => P.isTagged(outcome, "Failed")) + .map((outcome) => outcome.rule.id), + Order.String, + ); + const known = Arr.sort( + KNOWN_FAILURES.map(([id]) => id), + Order.String, + ); - // The whole report is the assertion message, so a new failure explains itself. - expect(failing, Conformance.format(report)).toEqual(known); - }); + // The whole report is the assertion message, so a new failure explains itself. + expect(failing, Conformance.format(report)).toEqual(known); + }), + ); - it("every failure names a rule, cites its section and shows the request", () => { - Arr.forEach(report.outcomes, (outcome) => { - if (!P.isTagged(outcome, "Failed")) return; - expect(outcome.rule.requirement.length).toBeGreaterThan(20); - expect(outcome.rule.reference).toMatch(/^https:\/\//); - Arr.forEach(outcome.findings, (finding) => { - expect(finding.detail).not.toBe(""); - expect(finding.expected).not.toBe(""); - expect(finding.observed).not.toBe(""); + it.effect("every failure names a rule, cites its section and shows the request", () => + Effect.gen(function* () { + const { report } = yield* Run; + Arr.forEach(report.outcomes, (outcome) => { + if (!P.isTagged(outcome, "Failed")) return; + expect(outcome.rule.requirement.length).toBeGreaterThan(20); + expect(outcome.rule.reference).toMatch(/^https:\/\//); + Arr.forEach(outcome.findings, (finding) => { + expect(finding.detail).not.toBe(""); + expect(finding.expected).not.toBe(""); + expect(finding.observed).not.toBe(""); + }); }); - }); - }); + }), + ); - it("actually probed the api rather than skipping its way to a verdict", () => { - const summary = Conformance.summarise(report); - expect(summary.probes).toBeGreaterThan(50); - expect(summary.passed).toBeGreaterThan(15); - }); + it.effect("actually probed the api rather than skipping its way to a verdict", () => + Effect.gen(function* () { + const { report } = yield* Run; + const summary = Conformance.summarise(report); + expect(summary.probes).toBeGreaterThan(50); + expect(summary.passed).toBeGreaterThan(15); + }), + ); - it("honours an empty sparse fieldset as no fields, on primary data and `included` alike", () => { - // #488: `?fields[TYPE]=` asks for no fields, not every field, and - // `Handlers.project` answers it with no attributes. - const ids = [ - "spec/query/sparse-fieldsets-primary", - "spec/query/sparse-fieldsets-included", - "spec/query/sparse-fieldsets-empty", - ]; - expect( - ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), - ).toEqual(ids.map((id) => `${id}: Passed`)); - }); + it.effect( + "honours an empty sparse fieldset as no fields, on primary data and `included` alike", + () => + Effect.gen(function* () { + const { report } = yield* Run; + // #488: `?fields[TYPE]=` asks for no fields, not every field, and + // `Handlers.project` answers it with no attributes. + const ids = [ + "spec/query/sparse-fieldsets-primary", + "spec/query/sparse-fieldsets-included", + "spec/query/sparse-fieldsets-empty", + ]; + expect( + ids.map((id) => `${id}: ${report.outcomes.find((o) => o.rule.id === id)?._tag}`), + ).toEqual(ids.map((id) => `${id}: Passed`)); + }), + ); - it("follows every relationship's and document's `self` link to a verdict", () => { - // #309: the relationship `self` link `Handlers.paginatedRelationship` - // writes for an order's line items - // (`/orders/:id/relationships/lineItems`) is served by a declared - // `Endpoint.getRelationship`, so both MUSTs pass rather than skip. That - // relationship is links-only, so the relationship SHOULD has no linkage to - // compare and skips. - const ids = [ - "spec/links/relationship-self-dereferences", - "spec/links/relationship-self-matches-linkage", - "spec/links/top-level-self-dereferences", - "spec/links/top-level-self-matches-document", - ]; - const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); - expect(ids.map((id) => `${id}: ${outcomeOf(id)?._tag}`)).toEqual([ - "spec/links/relationship-self-dereferences: Passed", - "spec/links/relationship-self-matches-linkage: Skipped", - "spec/links/top-level-self-dereferences: Passed", - "spec/links/top-level-self-matches-document: Passed", - ]); - // Skipped for want of linkage, not for want of a link to follow. - expect(outcomeOf("spec/links/relationship-self-matches-linkage")).toMatchObject({ - reason: expect.stringContaining("carries both a `self` link and resource linkage"), - }); - }); + it.effect("follows every relationship's and document's `self` link to a verdict", () => + Effect.gen(function* () { + const { report } = yield* Run; + // #309: the relationship `self` link `Handlers.paginatedRelationship` + // writes for an order's line items + // (`/orders/:id/relationships/lineItems`) is served by a declared + // `Endpoint.getRelationship`, so both MUSTs pass rather than skip. That + // relationship is links-only, so the relationship SHOULD has no linkage to + // compare and skips. + const ids = [ + "spec/links/relationship-self-dereferences", + "spec/links/relationship-self-matches-linkage", + "spec/links/top-level-self-dereferences", + "spec/links/top-level-self-matches-document", + ]; + const outcomeOf = (id: string) => report.outcomes.find((outcome) => outcome.rule.id === id); + expect(ids.map((id) => `${id}: ${outcomeOf(id)?._tag}`)).toEqual([ + "spec/links/relationship-self-dereferences: Passed", + "spec/links/relationship-self-matches-linkage: Skipped", + "spec/links/top-level-self-dereferences: Passed", + "spec/links/top-level-self-matches-document: Passed", + ]); + // Skipped for want of linkage, not for want of a link to follow. + expect(outcomeOf("spec/links/relationship-self-matches-linkage")).toMatchObject({ + reason: expect.stringContaining("carries both a `self` link and resource linkage"), + }); + }), + ); - it("ran the write rules against targets it created, and left nothing behind", () => { - const writeRules = [ - "spec/status/create-response-document", - // #236: the 201 carries `Location`, copied from the created resource's - // own `links.self`, so the two match. - "spec/status/create-location", - "spec/status/create-location-matches-self", - "spec/status/update-response", - "spec/status/delete-response", - // #237: what each create and update answered reads back through the - // resource's own GET. - "spec/status/create-read-back", - "spec/status/update-read-back", - // #429: a created order's `shipper` replaced with the `ids` shipper and - // read back through `GET /orders/:id/relationships/shipper`. A product's - // `category` / `supplier` PATCH has no relationship GET to read back - // through, so is not decided. - "spec/relationships/update-replaces", - // #451: the same `shipper` cleared with `{ "data": null }` and read back - // empty (a product's `category` / `supplier` are required, so their - // payloads admit no `null`); what each order and product relationship - // PATCH answered; and the 404 for linking a shipper that does not exist. - "spec/relationships/update-to-one-null", - "spec/relationships/write-response", - "spec/relationships/absent-related-404", - ]; - expect( - writeRules.map((id) => report.outcomes.find((outcome) => outcome.rule.id === id)?._tag), - ).toEqual(writeRules.map(() => "Passed")); - const writes = report.writes ?? []; - expect(writes.length).toBeGreaterThan(0); - expect(writes.map((write) => write.disposal)).toEqual( - writes.map(() => expect.stringMatching(/^(deleted|cleaned-up)$/)), - ); - }); + it.effect("ran the write rules against targets it created, and left nothing behind", () => + Effect.gen(function* () { + const { report } = yield* Run; + const writeRules = [ + "spec/status/create-response-document", + // #236: the 201 carries `Location`, copied from the created resource's + // own `links.self`, so the two match. + "spec/status/create-location", + "spec/status/create-location-matches-self", + "spec/status/update-response", + "spec/status/delete-response", + // #237: what each create and update answered reads back through the + // resource's own GET. + "spec/status/create-read-back", + "spec/status/update-read-back", + // #429: a created order's `shipper` replaced with the `ids` shipper and + // read back through `GET /orders/:id/relationships/shipper`. A product's + // `category` / `supplier` PATCH has no relationship GET to read back + // through, so is not decided. + "spec/relationships/update-replaces", + // #451: the same `shipper` cleared with `{ "data": null }` and read back + // empty (a product's `category` / `supplier` are required, so their + // payloads admit no `null`); what each order and product relationship + // PATCH answered; and the 404 for linking a shipper that does not exist. + "spec/relationships/update-to-one-null", + "spec/relationships/write-response", + "spec/relationships/absent-related-404", + ]; + expect( + writeRules.map((id) => report.outcomes.find((outcome) => outcome.rule.id === id)?._tag), + ).toEqual(writeRules.map(() => "Passed")); + const writes = report.writes ?? []; + expect(writes.length).toBeGreaterThan(0); + expect(writes.map((write) => write.disposal)).toEqual( + writes.map(() => expect.stringMatching(/^(deleted|cleaned-up)$/)), + ); + }), + ); - it("renders a report that states what it did not check", () => { - const text = Conformance.format(report); - expect(text).toContain("NOT COVERED BY THIS KIT"); - expect(text).toContain("SUMMARY"); - // Skipped rules are named individually, not rolled into the pass count. - expect(text).toContain("not checked:"); - }); + it.effect("renders a report that states what it did not check", () => + Effect.gen(function* () { + const { report } = yield* Run; + const text = Conformance.format(report); + expect(text).toContain("NOT COVERED BY THIS KIT"); + expect(text).toContain("SUMMARY"); + // Skipped rules are named individually, not rolled into the pass count. + expect(text).toContain("not checked:"); + }), + ); - it("runs the spec tier without the profile tier", async () => { - const specOnly = await Effect.runPromise( - Conformance.verify(Api, { ids: IDS, tiers: ["spec"] }).pipe( + it.effect("runs the spec tier without the profile tier", () => + Effect.gen(function* () { + const specOnly = yield* Conformance.verify(Api, { ids: IDS, tiers: ["spec"] }).pipe( Effect.provide(NorthwindLive), Effect.scoped, - ) as Effect.Effect, - ); - expect(specOnly.outcomes.every((outcome) => outcome.rule.tier === "spec")).toBe(true); - expect( - died(specOnly), - `a rule died — a defect, not a finding\n${Conformance.format(specOnly)}`, - ).toEqual([]); - const failing = specOnly.outcomes - .filter((outcome) => P.isTagged(outcome, "Failed")) - .map((outcome) => outcome.rule.id); - expect(failing).not.toContain("profile/document/jsonapi-member"); - }); + ) as Effect.Effect; + expect(specOnly.outcomes.every((outcome) => outcome.rule.tier === "spec")).toBe(true); + expect( + died(specOnly), + `a rule died — a defect, not a finding\n${Conformance.format(specOnly)}`, + ).toEqual([]); + const failing = specOnly.outcomes + .filter((outcome) => P.isTagged(outcome, "Failed")) + .map((outcome) => outcome.rule.id); + expect(failing).not.toContain("profile/document/jsonapi-member"); + }), + ); }); diff --git a/examples/northwind/test/northwind.test.ts b/examples/northwind/test/northwind.test.ts index 20e2160..c907d3f 100644 --- a/examples/northwind/test/northwind.test.ts +++ b/examples/northwind/test/northwind.test.ts @@ -3,8 +3,9 @@ * (request encoding → routing → middleware → handler → response decoding) * through the in-memory `HttpApiTest` client. */ +import { it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { assert, describe, expect, expectTypeOf, it } from "vite-plus/test"; +import { assert, describe, expect, expectTypeOf } from "vite-plus/test"; import * as Arr from "effect/Array"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; @@ -73,15 +74,11 @@ const buildClient = HttpApiTest.groups(Api, [ const jsonText = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); -const run = (effect: Effect.Effect): Promise => - Effect.runPromise( - effect.pipe(Effect.scoped, Effect.provide(NorthwindLive)) as Effect.Effect, - ); +const run = (effect: Effect.Effect): Effect.Effect => + effect.pipe(Effect.scoped, Effect.provide(NorthwindLive)) as Effect.Effect; -const runExit = (effect: Effect.Effect): Promise> => - Effect.runPromiseExit( - effect.pipe(Effect.scoped, Effect.provide(NorthwindLive)) as Effect.Effect, - ); +const runExit = (effect: Effect.Effect): Effect.Effect> => + Effect.exit(effect.pipe(Effect.scoped, Effect.provide(NorthwindLive)) as Effect.Effect); const findFailure = (cause: Cause.Cause): E | undefined => { const result = Cause.findError(cause); @@ -89,283 +86,320 @@ const findFailure = (cause: Cause.Cause): E | undefined => { }; describe("northwind example: fetching", () => { - it("fetches a product document with a self link", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.get({ params: { id: Product.Id.make("1") }, query: {} }); - }), - ); - - expect(document.data).toMatchObject({ - type: "products", - id: "1", - attributes: { name: "Chai", unitPrice: 18 }, - }); - expect(document.links?.self).toBe("/products/1"); - }); - - it("serves compound documents for ?include=category,supplier", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.get({ - params: { id: Product.Id.make("1") }, - query: { include: ["category", "supplier"] }, - }); - }), - ); - - expect(Arr.sort(document.included?.map((resource) => resource.type) ?? [], Ord.String)).toEqual( - ["categories", "suppliers"], - ); - }); - - it("omits `included` when the request carries no `include` (#232)", async () => { - const { list, one } = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const one = yield* client.products.get({ params: { id: Product.Id.make("1") }, query: {} }); - const list = yield* client.products.list({ query: {} }); - return { list, one }; - }), - ); - expect(one).not.toHaveProperty("included"); - expect(list).not.toHaveProperty("included"); - }); - - it("narrows `included` to the requested include paths on the client", async () => { - const include = ["category"] as const; - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products - .get({ params: { id: Product.Id.make("1") }, query: { include } }) - .pipe(Client.narrowIncluded(Product, include)); - }), - ); + it.effect("fetches a product document with a self link", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.get({ params: { id: Product.Id.make("1") }, query: {} }); + }), + ); + + expect(document.data).toMatchObject({ + type: "products", + id: "1", + attributes: { name: "Chai", unitPrice: 18 }, + }); + expect(document.links?.self).toBe("/products/1"); + }), + ); - // Runtime: only the requested category was included - expect(document.included?.map((resource) => resource.type)).toEqual(["categories"]); - // Types: `included` is narrowed to Category — its attributes are accessible - // without discriminating on `type` - const category = document.included?.[0]; - expect(category?.attributes.name).toBe("Beverages"); - assert(category !== undefined); - expectTypeOf(category.attributes.name).toEqualTypeOf(); - expectTypeOf(category.type).toEqualTypeOf<"categories">(); - }); + it.effect("serves compound documents for ?include=category,supplier", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.get({ + params: { id: Product.Id.make("1") }, + query: { include: ["category", "supplier"] }, + }); + }), + ); + + expect( + Arr.sort(document.included?.map((resource) => resource.type) ?? [], Ord.String), + ).toEqual(["categories", "suppliers"]); + }), + ); - it("fetches an employee with its territories included", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.employees.get({ - params: { id: nancy.id }, - query: { include: ["territories"] }, - }); - }), - ); + it.effect("omits `included` when the request carries no `include` (#232)", () => + Effect.gen(function* () { + const { list, one } = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const one = yield* client.products.get({ + params: { id: Product.Id.make("1") }, + query: {}, + }); + const list = yield* client.products.list({ query: {} }); + return { list, one }; + }), + ); + expect(one).not.toHaveProperty("included"); + expect(list).not.toHaveProperty("included"); + }), + ); - expect(document.data?.attributes.lastName).toBe("Davolio"); - // dates decode through the wire format - expect(document.data?.attributes.hireDate).toBeInstanceOf(Date); - expect(document.included?.map((resource) => resource.type)).toEqual([ - "territories", - "territories", - ]); - }); + it.effect("narrows `included` to the requested include paths on the client", () => + Effect.gen(function* () { + const include = ["category"] as const; + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products + .get({ params: { id: Product.Id.make("1") }, query: { include } }) + .pipe(Client.narrowIncluded(Product, include)); + }), + ); + + // Runtime: only the requested category was included + expect(document.included?.map((resource) => resource.type)).toEqual(["categories"]); + // Types: `included` is narrowed to Category — its attributes are accessible + // without discriminating on `type` + const category = document.included?.[0]; + expect(category?.attributes.name).toBe("Beverages"); + assert(category !== undefined); + expectTypeOf(category.attributes.name).toEqualTypeOf(); + expectTypeOf(category.type).toEqualTypeOf<"categories">(); + }), + ); - it("resolves the depth-2 path employee.territories on an order (#338)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.get({ - params: { id: order10248.id }, - query: { include: ["employee.territories"] }, - }); - }), - ); + it.effect("fetches an employee with its territories included", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.employees.get({ + params: { id: nancy.id }, + query: { include: ["territories"] }, + }); + }), + ); + + expect(document.data?.attributes.lastName).toBe("Davolio"); + // dates decode through the wire format + expect(document.data?.attributes.hireDate).toBeInstanceOf(Date); + expect(document.included?.map((resource) => resource.type)).toEqual([ + "territories", + "territories", + ]); + }), + ); - // The salesperson (the path's first hop) and both of Nancy's territories - // (its last) — not the employee alone. - expect(document.included?.map((resource) => `${resource.type}:${resource.id}`)).toEqual([ - `employees:${nancy.id}`, - `territories:${westboro.id}`, - `territories:${boston.id}`, - ]); - }); + it.effect("resolves the depth-2 path employee.territories on an order (#338)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.get({ + params: { id: order10248.id }, + query: { include: ["employee.territories"] }, + }); + }), + ); + + // The salesperson (the path's first hop) and both of Nancy's territories + // (its last) — not the employee alone. + expect(document.included?.map((resource) => `${resource.type}:${resource.id}`)).toEqual([ + `employees:${nancy.id}`, + `territories:${westboro.id}`, + `territories:${boston.id}`, + ]); + }), + ); - it("resolves depth-2 paths across a page of orders, contributing each resource once (#338)", async () => { - const document = await run( + it.effect( + "resolves depth-2 paths across a page of orders, contributing each resource once (#338)", + () => Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.list({ - query: { - include: ["customer", "employee.territories"], - sort: [{ field: "orderDate", direction: "asc" }], - }, - }); - }), - ); - - // Three orders, three salespeople; only Nancy (10248) and Andrew (10250) - // have territories. - const keys = document.included?.map((resource) => `${resource.type}:${resource.id}`) ?? []; - expect( - Arr.sort( - keys.filter((key) => key.startsWith("territories:")), - Ord.String, - ), - ).toEqual( - Arr.sort( - [`territories:${westboro.id}`, `territories:${boston.id}`, "territories:90405"], - Ord.String, - ), - ); - expect(keys.filter((key) => key.startsWith("employees:"))).toHaveLength(3); - expect(new Set(keys).size).toBe(keys.length); - }); + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.list({ + query: { + include: ["customer", "employee.territories"], + sort: [{ field: "orderDate", direction: "asc" }], + }, + }); + }), + ); - it("404s with a typed error for unknown products", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.get({ params: { id: Product.Id.make("nope") }, query: {} }); + // Three orders, three salespeople; only Nancy (10248) and Andrew (10250) + // have territories. + const keys = document.included?.map((resource) => `${resource.type}:${resource.id}`) ?? []; + expect( + Arr.sort( + keys.filter((key) => key.startsWith("territories:")), + Ord.String, + ), + ).toEqual( + Arr.sort( + [`territories:${westboro.id}`, `territories:${boston.id}`, "territories:90405"], + Ord.String, + ), + ); + expect(keys.filter((key) => key.startsWith("employees:"))).toHaveLength(3); + expect(new Set(keys).size).toBe(keys.length); }), - ); + ); - assert(Exit.isFailure(exit)); - const error = findFailure(exit.cause); - expect(error).toBeInstanceOf(ProductNotFound); - expect((error as ProductNotFound).id).toBe("nope"); - }); + it.effect("404s with a typed error for unknown products", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.get({ params: { id: Product.Id.make("nope") }, query: {} }); + }), + ); + + assert(Exit.isFailure(exit)); + const error = findFailure(exit.cause); + expect(error).toBeInstanceOf(ProductNotFound); + expect((error as ProductNotFound).id).toBe("nope"); + }), + ); }); describe("northwind example: listing & filtering", () => { - it("lists products sorted by price with offset pagination", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.list({ - query: { - sort: [{ field: "unitPrice", direction: "desc" }], - page: { offset: 0, limit: 2 }, - }, - }); - }), - ); - - // most expensive first: Chef Anton's Gumbo Mix (21.35), Chang (19) - expect(document.data.map((product) => product.attributes.name)).toEqual([ - gumbo.attributes.name, - "Chang", - ]); - expect(document.meta?.total).toBe(5); - expect(document.links?.next).toBe("/products?sort=-unitPrice&page[offset]=2&page[limit]=2"); - }); - - it("serves a category's products via filter[category]", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.list({ - query: { - filter: { category: beverages.id }, - sort: [{ field: "name", direction: "asc" }], - }, - }); - }), - ); - - expect(document.data.map((product) => product.attributes.name)).toEqual(["Chai", "Chang"]); - }); - - it("filters products by a numeric price range (decoded from the query string)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.list({ query: { filter: { minPrice: 10, maxPrice: 19 } } }); - }), - ); - - const prices = Arr.sort( - document.data.map((product) => product.attributes.unitPrice), - Ord.Number, - ); - expect(prices).toEqual([10, 18, 19]); - }); - - it("filters products by discontinued flag", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.list({ query: { filter: { discontinued: "true" } } }); - }), - ); - - expect(document.data.map((product) => product.id)).toEqual([gumbo.id]); - }); + it.effect("lists products sorted by price with offset pagination", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.list({ + query: { + sort: [{ field: "unitPrice", direction: "desc" }], + page: { offset: 0, limit: 2 }, + }, + }); + }), + ); + + // most expensive first: Chef Anton's Gumbo Mix (21.35), Chang (19) + expect(document.data.map((product) => product.attributes.name)).toEqual([ + gumbo.attributes.name, + "Chang", + ]); + expect(document.meta?.total).toBe(5); + expect(document.links?.next).toBe("/products?sort=-unitPrice&page[offset]=2&page[limit]=2"); + }), + ); - it("filters suppliers by country", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.suppliers.list({ query: { filter: { country: "Japan" } } }); - }), - ); + it.effect("serves a category's products via filter[category]", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.list({ + query: { + filter: { category: beverages.id }, + sort: [{ field: "name", direction: "asc" }], + }, + }); + }), + ); - expect(document.data.map((supplier) => supplier.attributes.companyName)).toEqual([ - "Tokyo Traders", - ]); - }); + expect(document.data.map((product) => product.attributes.name)).toEqual(["Chai", "Chang"]); + }), + ); - it("lists an employee's direct reports via filter[manager]", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.employees.list({ - query: { - filter: { manager: andrew.id }, - sort: [{ field: "lastName", direction: "asc" }], - }, - }); - }), - ); + it.effect("filters products by a numeric price range (decoded from the query string)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.list({ query: { filter: { minPrice: 10, maxPrice: 19 } } }); + }), + ); + + const prices = Arr.sort( + document.data.map((product) => product.attributes.unitPrice), + Ord.Number, + ); + expect(prices).toEqual([10, 18, 19]); + }), + ); - // Andrew Fuller's reports, by surname - expect(document.data.map((employee) => employee.attributes.lastName)).toEqual([ - "Davolio", - "Leverling", - "Peacock", - ]); - }); + it.effect("filters products by discontinued flag", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.list({ query: { filter: { discontinued: "true" } } }); + }), + ); + + expect(document.data.map((product) => product.id)).toEqual([gumbo.id]); + }), + ); - it("serves a customer's orders via filter[customer]", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.list({ query: { filter: { customer: alfreds.id } } }); - }), - ); + it.effect("filters suppliers by country", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.suppliers.list({ query: { filter: { country: "Japan" } } }); + }), + ); + + expect(document.data.map((supplier) => supplier.attributes.companyName)).toEqual([ + "Tokyo Traders", + ]); + }), + ); - expect(document.data.map((order) => order.id)).toEqual([order10248.id]); - }); + it.effect("lists an employee's direct reports via filter[manager]", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.employees.list({ + query: { + filter: { manager: andrew.id }, + sort: [{ field: "lastName", direction: "asc" }], + }, + }); + }), + ); + + // Andrew Fuller's reports, by surname + expect(document.data.map((employee) => employee.attributes.lastName)).toEqual([ + "Davolio", + "Leverling", + "Peacock", + ]); + }), + ); - it("filters orders by shipped status", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.list({ query: { filter: { shipped: "false" } } }); - }), - ); + it.effect("serves a customer's orders via filter[customer]", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.list({ query: { filter: { customer: alfreds.id } } }); + }), + ); + + expect(document.data.map((order) => order.id)).toEqual([order10248.id]); + }), + ); - // only order 10249 has no shipped date - expect(document.data.map((order) => order.id)).toContain(order10249.id); - Arr.forEach(document.data, (order) => { - expect(order.attributes.shippedDate).toBeUndefined(); - }); - }); + it.effect("filters orders by shipped status", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.list({ query: { filter: { shipped: "false" } } }); + }), + ); + + // only order 10249 has no shipped date + expect(document.data.map((order) => order.id)).toContain(order10249.id); + Arr.forEach(document.data, (order) => { + expect(order.attributes.shippedDate).toBeUndefined(); + }); + }), + ); }); describe("northwind example: pagination links carry the request's query (#447)", () => { @@ -373,78 +407,84 @@ describe("northwind example: pagination links carry the request's query (#447)", const searchOf = (link: string): Record => Rec.fromEntries(new URL(link, "https://example.test").searchParams); - it("`next` on GET /products keeps `sort`, `filter` and `include`, and continues the order", async () => { - const [first, second] = await run( - Effect.gen(function* () { - const client = yield* buildClient; - const first = yield* client.products.list({ - query: { - include: ["category"], - filter: { maxPrice: 20 }, - sort: [{ field: "unitPrice", direction: "desc" }], - page: { offset: 0, limit: 1 }, - }, - }); - const next = first.links?.next; - assert(P.isString(next)); - const query = yield* Schema.decodeUnknownEffect(ProductsQuery)(searchOf(next)); - const second = yield* client.products.list({ query }); - return [first, second] as const; - }), - ); - - expect(first.links?.next).toBe( - "/products?include=category&filter[maxPrice]=20&sort=-unitPrice&page[offset]=1&page[limit]=1", - ); - expect(first.links?.last).toMatch( - /^\/products\?include=category&filter\[maxPrice\]=20&sort=-unitPrice&/, - ); - // Following `next` serves the second page of the same query, not the - // default order: still at most 20, still descending by price. - const [top] = first.data; - const [next] = second.data; - assert.isDefined(top); - assert.isDefined(next); - expect(next.attributes.unitPrice).toBeLessThanOrEqual(20); - expect(next.attributes.unitPrice).toBeLessThanOrEqual(top.attributes.unitPrice); - expect(next.id).not.toBe(top.id); - expect(second.links?.prev).toBe( - "/products?include=category&filter[maxPrice]=20&sort=-unitPrice&page[offset]=0&page[limit]=1", - ); - }); - - it("`next` on GET /search keeps `fields`, `filter` and `include`", async () => { - const document = await run( + it.effect( + "`next` on GET /products keeps `sort`, `filter` and `include`, and continues the order", + () => Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { - include: ["category"], - fields: { products: ["name"] }, - filter: { q: "a" }, - page: { offset: 0, limit: 1 }, - }, - }); + const [first, second] = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const first = yield* client.products.list({ + query: { + include: ["category"], + filter: { maxPrice: 20 }, + sort: [{ field: "unitPrice", direction: "desc" }], + page: { offset: 0, limit: 1 }, + }, + }); + const next = first.links?.next; + assert(P.isString(next)); + const query = yield* Schema.decodeUnknownEffect(ProductsQuery)(searchOf(next)); + const second = yield* client.products.list({ query }); + return [first, second] as const; + }), + ); + + expect(first.links?.next).toBe( + "/products?include=category&filter[maxPrice]=20&sort=-unitPrice&page[offset]=1&page[limit]=1", + ); + expect(first.links?.last).toMatch( + /^\/products\?include=category&filter\[maxPrice\]=20&sort=-unitPrice&/, + ); + // Following `next` serves the second page of the same query, not the + // default order: still at most 20, still descending by price. + const [top] = first.data; + const [next] = second.data; + assert.isDefined(top); + assert.isDefined(next); + expect(next.attributes.unitPrice).toBeLessThanOrEqual(20); + expect(next.attributes.unitPrice).toBeLessThanOrEqual(top.attributes.unitPrice); + expect(next.id).not.toBe(top.id); + expect(second.links?.prev).toBe( + "/products?include=category&filter[maxPrice]=20&sort=-unitPrice&page[offset]=0&page[limit]=1", + ); }), - ); + ); - expect(document.links?.next).toBe( - "/search?include=category&fields[products]=name&filter[q]=a&page[offset]=1&page[limit]=1", - ); - const next = document.links?.next; - assert(P.isString(next)); - expect(Schema.decodeUnknownSync(SearchQuery)(searchOf(next))).toEqual({ - include: ["category"], - fields: { products: ["name"] }, - filter: { q: "a" }, - page: { offset: 1, limit: 1 }, - }); - }); + it.effect("`next` on GET /search keeps `fields`, `filter` and `include`", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { + include: ["category"], + fields: { products: ["name"] }, + filter: { q: "a" }, + page: { offset: 0, limit: 1 }, + }, + }); + }), + ); + + expect(document.links?.next).toBe( + "/search?include=category&fields[products]=name&filter[q]=a&page[offset]=1&page[limit]=1", + ); + const next = document.links?.next; + assert(P.isString(next)); + expect(yield* Schema.decodeUnknownEffect(SearchQuery)(searchOf(next))).toEqual({ + include: ["category"], + fields: { products: ["name"] }, + filter: { q: "a" }, + page: { offset: 1, limit: 1 }, + }); + }), + ); }); describe("northwind example: writing", () => { - it("adds a product to the catalog (201) and then removes it (204)", async () => { - await run( + it.effect("adds a product to the catalog (201) and then removes it (204)", () => + run( Effect.gen(function* () { const client = yield* buildClient; @@ -472,254 +512,279 @@ describe("northwind example: writing", () => { yield* client.products.delete({ params: { id: created.data.id } }); }), - ); - }); + ), + ); - it("409s when the product name is already taken", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.create({ - payload: { - data: { - type: "products", - attributes: { - name: chai.attributes.name, - unitPrice: 1, - unitsInStock: 1, - discontinued: false, - }, - relationships: { - category: { data: Category.ref(beverages.id) }, - supplier: { data: Supplier.ref(exotic.id) }, + it.effect("409s when the product name is already taken", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.create({ + payload: { + data: { + type: "products", + attributes: { + name: chai.attributes.name, + unitPrice: 1, + unitsInStock: 1, + discontinued: false, + }, + relationships: { + category: { data: Category.ref(beverages.id) }, + supplier: { data: Supplier.ref(exotic.id) }, + }, }, }, - }, - }); - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(ProductNameTaken); - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(ProductNameTaken); + }), + ); - it("404s when creating a product in a missing category", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.create({ - payload: { - data: { - type: "products", - attributes: { - name: "Phantom Tea", - unitPrice: 1, - unitsInStock: 1, - discontinued: false, - }, - relationships: { - category: { data: Category.ref("does-not-exist") }, - supplier: { data: Supplier.ref(exotic.id) }, + it.effect("404s when creating a product in a missing category", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.create({ + payload: { + data: { + type: "products", + attributes: { + name: "Phantom Tea", + unitPrice: 1, + unitsInStock: 1, + discontinued: false, + }, + relationships: { + category: { data: Category.ref("does-not-exist") }, + supplier: { data: Supplier.ref(exotic.id) }, + }, }, }, - }, - }); - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(CategoryNotFound); - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(CategoryNotFound); + }), + ); - it("marks a product discontinued with a partial update", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.update({ - params: { id: Product.Id.make("2") }, - payload: { - data: { - type: "products", - id: Product.Id.make("2"), - attributes: { discontinued: true }, + it.effect("marks a product discontinued with a partial update", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.update({ + params: { id: Product.Id.make("2") }, + payload: { + data: { + type: "products", + id: Product.Id.make("2"), + attributes: { discontinued: true }, + }, }, - }, - }); - }), - ); - - expect(document.data?.attributes.discontinued).toBe(true); - // other attributes are untouched - expect(document.data?.attributes.name).toBe("Chang"); - // a write response advertises JSON:API 1.1 too, not only the reads - expect(document.jsonapi?.version).toBe("1.1"); - }); + }); + }), + ); + + expect(document.data?.attributes.discontinued).toBe(true); + // other attributes are untouched + expect(document.data?.attributes.name).toBe("Chang"); + // a write response advertises JSON:API 1.1 too, not only the reads + expect(document.jsonapi?.version).toBe("1.1"); + }), + ); - it("opens an order against a customer and employee (201)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.create({ - payload: { - data: { - type: "orders", - attributes: { - orderDate: at("1996-07-09T00:00:00.000Z"), - requiredDate: at("1996-08-06T00:00:00.000Z"), - freight: 12.34, - shipCity: "Berlin", - shipCountry: "Germany", - }, - relationships: { - customer: { data: Customer.ref(alfreds.id) }, - employee: { data: Employee.ref(nancy.id) }, - // an order is opened unshipped - shipper: { data: null }, + it.effect("opens an order against a customer and employee (201)", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.create({ + payload: { + data: { + type: "orders", + attributes: { + orderDate: at("1996-07-09T00:00:00.000Z"), + requiredDate: at("1996-08-06T00:00:00.000Z"), + freight: 12.34, + shipCity: "Berlin", + shipCountry: "Germany", + }, + relationships: { + customer: { data: Customer.ref(alfreds.id) }, + employee: { data: Employee.ref(nancy.id) }, + // an order is opened unshipped + shipper: { data: null }, + }, }, }, - }, - }); - }), - ); - - expect(document.data?.attributes.shipCountry).toBe("Germany"); - expect(document.data?.relationships?.customer.data?.id).toBe(alfreds.id); - // the paginated line-item feed exists as a link, with no inline data - expect(document.data?.relationships?.lineItems.links?.related).toBe( - `/orders/${document.data?.id}/lineItems`, - ); - }); + }); + }), + ); + + expect(document.data?.attributes.shipCountry).toBe("Germany"); + expect(document.data?.relationships?.customer.data?.id).toBe(alfreds.id); + // the paginated line-item feed exists as a link, with no inline data + expect(document.data?.relationships?.lineItems.links?.related).toBe( + `/orders/${document.data?.id}/lineItems`, + ); + }), + ); - it("404s when opening an order for a missing customer", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.create({ - payload: { - data: { - type: "orders", - attributes: { - orderDate: now(), - requiredDate: now(), - freight: 0, - shipCountry: "Germany", - }, - relationships: { - customer: { data: Customer.ref("ghost") }, - employee: { data: Employee.ref(nancy.id) }, + it.effect("404s when opening an order for a missing customer", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.create({ + payload: { + data: { + type: "orders", + attributes: { + orderDate: now(), + requiredDate: now(), + freight: 0, + shipCountry: "Germany", + }, + relationships: { + customer: { data: Customer.ref("ghost") }, + employee: { data: Employee.ref(nancy.id) }, + }, }, }, - }, - }); - }), - ); + }); + }), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(CustomerNotFound); - }); + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(CustomerNotFound); + }), + ); - it("records an order's shipped date with a partial update", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.update({ - params: { id: order10249.id }, - payload: { - data: { - type: "orders", - id: order10249.id, - attributes: { shippedDate: at("1996-07-10T00:00:00.000Z") }, + it.effect("records an order's shipped date with a partial update", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.update({ + params: { id: order10249.id }, + payload: { + data: { + type: "orders", + id: order10249.id, + attributes: { shippedDate: at("1996-07-10T00:00:00.000Z") }, + }, }, - }, - }); - }), - ); + }); + }), + ); - expect(document.data?.attributes.shippedDate).toBeInstanceOf(Date); - }); + expect(document.data?.attributes.shippedDate).toBeInstanceOf(Date); + }), + ); }); describe("northwind example: related & relationship endpoints", () => { - it("GET /products/:id/supplier serves the supplying company", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.products.supplier({ params: { id: Product.Id.make("1") }, query: {} }); - }), - ); - - expect(document.data).toMatchObject({ - type: "suppliers", - id: exotic.id, - attributes: { companyName: "Exotic Liquids" }, - }); - expect(document.links?.self).toBe("/products/1/supplier"); - }); - - it("GET /orders/:id/lineItems serves the paginated line-item feed with its products", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.lineItems({ - params: { id: order10248.id }, - query: { include: ["product"] }, - }); - }), - ); - - expect(document.data).toHaveLength(2); - expect(document.meta?.total).toBe(2); - // each line item's product is brought into the compound document - expect(document.included?.map((resource) => resource.type)).toEqual(["products", "products"]); - }); - - it("resolves the depth-2 path product.category,product.supplier on the line-item feed (#338)", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.orders.lineItems({ - params: { id: order10248.id }, - query: { include: ["product.category", "product.supplier"] }, - }); - }), - ); + it.effect("GET /products/:id/supplier serves the supplying company", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.products.supplier({ + params: { id: Product.Id.make("1") }, + query: {}, + }); + }), + ); + + expect(document.data).toMatchObject({ + type: "suppliers", + id: exotic.id, + attributes: { companyName: "Exotic Liquids" }, + }); + expect(document.links?.self).toBe("/products/1/supplier"); + }), + ); - // Each path's intermediate product is included alongside its last hop, in - // walk order: the products first, then their categories, then their - // suppliers. - expect(document.included?.map((resource) => `${resource.type}:${resource.id}`)).toEqual([ - `products:${chai.id}`, - `products:${konbu.id}`, - `categories:${beverages.id}`, - `categories:${seafood.id}`, - `suppliers:${exotic.id}`, - `suppliers:${tokyo.id}`, - ]); - }); + it.effect("GET /orders/:id/lineItems serves the paginated line-item feed with its products", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.lineItems({ + params: { id: order10248.id }, + query: { include: ["product"] }, + }); + }), + ); + + expect(document.data).toHaveLength(2); + expect(document.meta?.total).toBe(2); + // each line item's product is brought into the compound document + expect(document.included?.map((resource) => resource.type)).toEqual(["products", "products"]); + }), + ); - it("reassigns a product's category through the relationship endpoint", async () => { - const document = await run( + it.effect( + "resolves the depth-2 path product.category,product.supplier on the line-item feed (#338)", + () => Effect.gen(function* () { - const client = yield* buildClient; - const linkage = yield* client.products.updateCategoryRelationship({ - params: { id: Product.Id.make("4") }, - payload: { data: Category.ref(seafood.id) }, - }); - // the product reflects the reassignment - const product = yield* client.products.get({ - params: { id: Product.Id.make("4") }, - query: {}, - }); - expect(product.data?.relationships?.category?.data?.id).toBe(seafood.id); - return linkage; + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.orders.lineItems({ + params: { id: order10248.id }, + query: { include: ["product.category", "product.supplier"] }, + }); + }), + ); + + // Each path's intermediate product is included alongside its last hop, in + // walk order: the products first, then their categories, then their + // suppliers. + expect(document.included?.map((resource) => `${resource.type}:${resource.id}`)).toEqual([ + `products:${chai.id}`, + `products:${konbu.id}`, + `categories:${beverages.id}`, + `categories:${seafood.id}`, + `suppliers:${exotic.id}`, + `suppliers:${tokyo.id}`, + ]); }), - ); + ); - expect(document.data).toEqual({ type: "categories", id: seafood.id }); - }); + it.effect("reassigns a product's category through the relationship endpoint", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + const linkage = yield* client.products.updateCategoryRelationship({ + params: { id: Product.Id.make("4") }, + payload: { data: Category.ref(seafood.id) }, + }); + // the product reflects the reassignment + const product = yield* client.products.get({ + params: { id: Product.Id.make("4") }, + query: {}, + }); + expect(product.data?.relationships?.category?.data?.id).toBe(seafood.id); + return linkage; + }), + ); + + expect(document.data).toEqual({ type: "categories", id: seafood.id }); + }), + ); - it("assigns and clears an order's shipper (optional to-one)", async () => { - await run( + it.effect("assigns and clears an order's shipper (optional to-one)", () => + run( Effect.gen(function* () { const client = yield* buildClient; @@ -744,11 +809,11 @@ describe("northwind example: related & relationship endpoints", () => { }); expect(cleared.data).toBeNull(); }), - ); - }); + ), + ); - it("POST assigns territories, DELETE unassigns them, PATCH replaces them", async () => { - await run( + it.effect("POST assigns territories, DELETE unassigns them, PATCH replaces them", () => + run( Effect.gen(function* () { const client = yield* buildClient; const employeeId = margaret.id; // starts with no territories @@ -790,80 +855,93 @@ describe("northwind example: related & relationship endpoints", () => { }); expect(replaced.data).toEqual([{ type: "territories", id: westboro.id }]); }), - ); - }); - - it("404s when assigning a missing territory", async () => { - const exit = await runExit( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.employees.addTerritoriesRelationship({ - params: { id: janet.id }, - payload: { data: [Territory.ref("99999")] }, - }); - }), - ); + ), + ); - assert(Exit.isFailure(exit)); - expect(findFailure(exit.cause)).toBeInstanceOf(Error); - }); + it.effect("404s when assigning a missing territory", () => + Effect.gen(function* () { + const exit = yield* runExit( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.employees.addTerritoriesRelationship({ + params: { id: janet.id }, + payload: { data: [Territory.ref("99999")] }, + }); + }), + ); + + assert(Exit.isFailure(exit)); + expect(findFailure(exit.cause)).toBeInstanceOf(Error); + }), + ); }); describe("northwind example: heterogeneous search", () => { - it("returns a mixed collection of products, customers and suppliers, discriminated by type", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - // "a" hits all three stores - return yield* client.search.search({ query: { filter: { q: "a" } } }); - }), - ); - - const types = Arr.sort([...new Set(document.data.map((result) => result.type))], Ord.String); - expect(types).toEqual(["customers", "products", "suppliers"]); - - // The endpoint declares `fields`, so a client reads each attribute as - // optional (#322). - Arr.forEach(document.data, (result) => { - if (result.type === "products") { - expectTypeOf(result.attributes.unitPrice).toEqualTypeOf(); - } else if (result.type === "customers") { - expectTypeOf(result.attributes.companyName).toEqualTypeOf(); - } else { - expectTypeOf(result.attributes.country).toEqualTypeOf(); - } - }); - }); - - it("supports include across the searched resources' graphs", async () => { - const document = await run( + it.effect( + "returns a mixed collection of products, customers and suppliers, discriminated by type", + () => Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "chai" }, include: ["category"] }, + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + // "a" hits all three stores + return yield* client.search.search({ query: { filter: { q: "a" } } }); + }), + ); + + const types = Arr.sort( + [...new Set(document.data.map((result) => result.type))], + Ord.String, + ); + expect(types).toEqual(["customers", "products", "suppliers"]); + + // The endpoint declares `fields`, so a client reads each attribute as + // optional (#322). + Arr.forEach(document.data, (result) => { + if (result.type === "products") { + expectTypeOf(result.attributes.unitPrice).toEqualTypeOf(); + } else if (result.type === "customers") { + expectTypeOf(result.attributes.companyName).toEqualTypeOf(); + } else { + expectTypeOf(result.attributes.country).toEqualTypeOf(); + } }); }), - ); - - // the matched product's category is included - expect(document.data.map((result) => result.type)).toEqual(["products"]); - expect(document.included?.map((resource) => resource.type)).toEqual(["categories"]); - }); + ); - it("paginates heterogeneous results with links", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.search.search({ - query: { filter: { q: "" }, page: { offset: 0, limit: 2 } }, - }); - }), - ); + it.effect("supports include across the searched resources' graphs", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "chai" }, include: ["category"] }, + }); + }), + ); + + // the matched product's category is included + expect(document.data.map((result) => result.type)).toEqual(["products"]); + expect(document.included?.map((resource) => resource.type)).toEqual(["categories"]); + }), + ); - expect(document.data).toHaveLength(2); - expect(document.meta?.total).toBeGreaterThan(2); - expect(document.links?.next).toBe("/search?filter[q]=&page[offset]=2&page[limit]=2"); - }); + it.effect("paginates heterogeneous results with links", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.search.search({ + query: { filter: { q: "" }, page: { offset: 0, limit: 2 } }, + }); + }), + ); + + expect(document.data).toHaveLength(2); + expect(document.meta?.total).toBeGreaterThan(2); + expect(document.links?.next).toBe("/search?filter[q]=&page[offset]=2&page[limit]=2"); + }), + ); }); describe("northwind example: spec compliance on the wire", () => { @@ -938,14 +1016,16 @@ describe("northwind example: spec compliance on the wire", () => { expect(product.relationships?.category.data.id).toBe(beverages.id); }); - it("speedy express is reachable as a shipper", async () => { - const document = await run( - Effect.gen(function* () { - const client = yield* buildClient; - return yield* client.shippers.get({ params: { id: speedy.id }, query: {} }); - }), - ); - - expect(document.data?.attributes.companyName).toBe("Speedy Express"); - }); + it.effect("speedy express is reachable as a shipper", () => + Effect.gen(function* () { + const document = yield* run( + Effect.gen(function* () { + const client = yield* buildClient; + return yield* client.shippers.get({ params: { id: speedy.id }, query: {} }); + }), + ); + + expect(document.data?.attributes.companyName).toBe("Speedy Express"); + }), + ); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e8bed1..73ed43d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -127,6 +127,9 @@ importers: specifier: 4.1.4 version: 4.1.4 devDependencies: + '@effect/vitest': + specifier: 'catalog:' + version: 4.1.4(effect@4.1.4)(vitest@5.0.5) '@types/node': specifier: 'catalog:' version: 26.6.1 @@ -143,6 +146,9 @@ importers: specifier: 4.1.4 version: 4.1.4 devDependencies: + '@effect/vitest': + specifier: 'catalog:' + version: 4.1.4(effect@4.1.4)(vitest@5.0.5) '@types/node': specifier: 'catalog:' version: 26.6.1 @@ -159,6 +165,9 @@ importers: specifier: 4.1.4 version: 4.1.4 devDependencies: + '@effect/vitest': + specifier: 'catalog:' + version: 4.1.4(effect@4.1.4)(vitest@5.0.5) '@types/node': specifier: 'catalog:' version: 26.6.1 diff --git a/vite.config.ts b/vite.config.ts index 0bbddd7..93ef01b 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -145,7 +145,6 @@ export default defineConfig({ "effect/avoid-native-object-helpers": "warn", "effect/avoid-any": "warn", "effect/prefer-effect-is": "warn", - "effect/effect-run-in-body": "warn", "effect/prefer-option-over-null": "warn", // ---- Type-aware rules (tsgolint): staged rollout (#535) ------------ // `typeAware` turned these on. Each sits at `warn` with its count on