Skip to content

Commit 9116189

Browse files
authored
Expose buffered response encoding and declared header schemas (#10537)
1 parent ee5550a commit 9116189

3 files changed

Lines changed: 109 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Expose `HttpApiSchema.getResponseEncodingSchema` and `getEncodeToWithHeadersParts` for inspecting buffered response encodings and declared body/header schemas.

‎packages/effect/src/http-api/HttpApiSchema.ts‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ declare module "../Schema.ts" {
5454
*/
5555
export interface WithHeadersAnnotation {
5656
readonly body: Schema.Top
57-
readonly headers: Schema.Top
57+
readonly headers: Schema.Struct<Schema.Struct.Fields>
5858
/**
5959
* Codecs from the body and headers types to their response representation.
6060
* `HttpApiEndpoint` replaces them with the response encoding codecs.
@@ -1458,6 +1458,44 @@ const resolveHttpApiEncoding = SchemaAST.resolveAt<Encoding>("~httpApiEncoding")
14581458
*/
14591459
export const getWithHeadersAnnotation = SchemaAST.resolveAt<WithHeadersAnnotation>("~httpApiWithHeaders")
14601460

1461+
/**
1462+
* Returns the declared body and headers schemas of an `encodeToWithHeaders`
1463+
* response, or `undefined` for any other schema.
1464+
*
1465+
* **When to use**
1466+
*
1467+
* Use to inspect response schemas for code generation before a response exists,
1468+
* including schemas obtained through `HttpApi.reflect`.
1469+
*
1470+
* **Details**
1471+
*
1472+
* Both schemas keep their declared identity through endpoint construction and
1473+
* reflection, with or without `disableCodecs`. The headers schema is a
1474+
* `Schema.Struct`, so its fields can be inspected directly.
1475+
*
1476+
* **Gotchas**
1477+
*
1478+
* These are declared schemas, not the response codecs installed by an endpoint.
1479+
* Plain schemas, `WithHeaders` wrappers, and ordinary transformations from an
1480+
* identical `{ body, headers }` struct return `undefined`. So do schemas derived
1481+
* from the result with operations such as `.check`, `Schema.Union`, or
1482+
* `Schema.decodeTo` with a target that lacks this metadata, while `.annotate`,
1483+
* `Schema.brand`, and `Schema.decode` keep the parts.
1484+
*
1485+
* @see encodeToWithHeaders
1486+
* @see getResponseEncodingSchema
1487+
* @stability unstable
1488+
* @category getters
1489+
* @since 4.1.4
1490+
*/
1491+
export function getEncodeToWithHeadersParts(schema: Schema.Constraint): {
1492+
readonly body: Schema.Top
1493+
readonly headers: Schema.Struct<Schema.Struct.Fields>
1494+
} | undefined {
1495+
const annotation = getWithHeadersAnnotation(schema.ast)
1496+
return annotation === undefined ? undefined : { body: annotation.body, headers: annotation.headers }
1497+
}
1498+
14611499
function findHttpApiStatusAnnotation(
14621500
ast: SchemaAST.AST | SchemaAST.FilterGroup<any>
14631501
): Schema.Annotations.Annotations | undefined {
@@ -1533,7 +1571,35 @@ export function getStatusSuccessSchema(schema: Schema.Constraint): number {
15331571
}
15341572

15351573
/**
1536-
* @internal
1574+
* Returns the buffered response encoding resolved from a schema's annotations,
1575+
* defaulting to `{ _tag: "Json", contentType: "application/json" }`.
1576+
*
1577+
* **When to use**
1578+
*
1579+
* Use to read response media types from declared schemas or schemas obtained
1580+
* through `HttpApi.reflect` without encoding a response value.
1581+
*
1582+
* **Details**
1583+
*
1584+
* For `WithHeaders`, the wrapper's encoding takes precedence over the inner
1585+
* schema's encoding. For `encodeToWithHeaders`, the body schema's encoding is
1586+
* used. Re-annotating the result changes what this function returns, not what
1587+
* the server sends.
1588+
*
1589+
* **Gotchas**
1590+
*
1591+
* - No-content schemas also receive the JSON default. Check `isNoContent` on
1592+
* the body AST first: `schema.schema.ast` for `WithHeaders`, `parts.body.ast`
1593+
* from `getEncodeToWithHeadersParts`, or `schema.ast` otherwise.
1594+
* - Streaming and upgrade schemas are outside this buffered-response contract;
1595+
* their JSON fallback does not describe their wire representation.
1596+
* - Multipart encoding throws because multipart responses are not supported.
1597+
*
1598+
* @see getEncodeToWithHeadersParts
1599+
* @see isNoContent
1600+
* @stability unstable
1601+
* @category getters
1602+
* @since 4.1.4
15371603
*/
15381604
export function getResponseEncodingSchema(schema: Schema.Constraint): ResponseEncoding {
15391605
if (isWithHeaders(schema) && resolveHttpApiEncoding(schema.ast) === undefined) {

‎packages/effect/test/httpapi/HttpApiSchema.test.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { assert, describe, it } from "@effect/vitest"
2-
import { Schema } from "effect"
3-
import { HttpApiSchema } from "effect/http-api"
2+
import { Schema, SchemaTransformation } from "effect"
3+
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api"
44

55
const getStreamMetadata = (self: HttpApiSchema.StreamSchema) =>
66
self._tag === "StreamSse" ?
@@ -332,6 +332,40 @@ describe("HttpApiSchema", () => {
332332
encoding: { _tag: "Json", contentType: "application/json" }
333333
})
334334
})
335+
336+
it("distinguishes reflected declared parts from an ordinary pair transformation", () => {
337+
const Body = Schema.Array(Schema.String)
338+
const headers = { "x-total": Schema.String }
339+
const Page = Schema.Struct({ rows: Body, total: Schema.String })
340+
const transformation = {
341+
decode: ({ body, headers }: { body: typeof Body.Type; headers: { "x-total": string } }) => ({
342+
rows: body,
343+
total: headers["x-total"]
344+
}),
345+
encode: (page: typeof Page.Type) => ({ body: page.rows, headers: { "x-total": page.total } })
346+
}
347+
const PageWithHeaders = Page.pipe(HttpApiSchema.encodeToWithHeaders({ body: Body, headers }, transformation))
348+
const PageFromPair = Schema.Struct({ body: Body, headers: Schema.Struct(headers) }).pipe(
349+
Schema.decodeTo(Page, SchemaTransformation.transform(transformation))
350+
)
351+
352+
const api = HttpApi.make("Api").add(
353+
HttpApiGroup.make("pages").add(
354+
HttpApiEndpoint.get("split", "/split", { success: PageWithHeaders }),
355+
HttpApiEndpoint.get("pair", "/pair", { success: PageFromPair })
356+
)
357+
)
358+
const reflected: Record<string, ReturnType<typeof HttpApiSchema.getEncodeToWithHeadersParts>> = {}
359+
HttpApi.reflect(api, {
360+
onGroup: () => {},
361+
onEndpoint: ({ endpoint, successes }) => {
362+
reflected[endpoint.identifier] = HttpApiSchema.getEncodeToWithHeadersParts(successes.get(200)![0])
363+
}
364+
})
365+
assert.strictEqual(reflected.split?.body, Body)
366+
assert.strictEqual(reflected.split?.headers.fields["x-total"], headers["x-total"])
367+
assert.isUndefined(reflected.pair)
368+
})
335369
})
336370

337371
it("does not identify buffered schemas as stream schemas", () => {

0 commit comments

Comments
 (0)