mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-01 03:05:36 +08:00
improve httpapi union and client encoding handling (#484)
This commit is contained in:
@@ -250,14 +250,14 @@ export const reflect = <Id extends string, Groups extends HttpApiGroup.Any>(
|
||||
} as any)
|
||||
) continue
|
||||
|
||||
const errors = extractMembers(endpoint.errorSchema.ast, HttpApiSchema.getStatusError)
|
||||
const errors = extractMembers(endpoint.errorSchema, HttpApiSchema.getStatusError)
|
||||
options.onEndpoint({
|
||||
group,
|
||||
endpoint,
|
||||
middleware: endpoint.middlewares as any,
|
||||
mergedAnnotations: ServiceMap.merge(groupAnnotations, endpoint.annotations),
|
||||
payloads: endpoint.payloadSchema ? extractPayloads(endpoint.payloadSchema.ast) : emptyMap,
|
||||
successes: extractMembers(endpoint.successSchema.ast, HttpApiSchema.getStatusSuccess),
|
||||
successes: extractMembers(endpoint.successSchema, HttpApiSchema.getStatusSuccess),
|
||||
errors
|
||||
})
|
||||
}
|
||||
@@ -269,7 +269,7 @@ export const reflect = <Id extends string, Groups extends HttpApiGroup.Any>(
|
||||
const emptyMap = new Map<never, never>()
|
||||
|
||||
const extractMembers = (
|
||||
ast: AST.AST,
|
||||
schema: Schema.Top,
|
||||
getStatus: (ast: AST.AST) => number
|
||||
): ReadonlyMap<number, {
|
||||
readonly ast: AST.AST | undefined
|
||||
@@ -279,33 +279,21 @@ const extractMembers = (
|
||||
readonly ast: AST.AST | undefined
|
||||
readonly description: string | undefined
|
||||
}>()
|
||||
function process(type: AST.AST) {
|
||||
if (AST.isNeverKeyword(type)) {
|
||||
return
|
||||
}
|
||||
const annotations = HttpApiSchema.getHttpApiAnnotations(ast.annotations)
|
||||
// Avoid changing the reference unless necessary
|
||||
// Otherwise, deduplication of the ASTs below will not be possible
|
||||
if (!Record.isEmptyRecord(annotations)) {
|
||||
type = AST.annotate(type, {
|
||||
...annotations,
|
||||
...type.annotations
|
||||
})
|
||||
}
|
||||
const status = getStatus(type)
|
||||
const isEmpty = type.annotations?.httpApiIsEmpty
|
||||
function process(type: Schema.Top) {
|
||||
const status = getStatus(type.ast)
|
||||
const isEmpty = type.ast.annotations?.httpApiIsEmpty
|
||||
const current = members.get(status)
|
||||
members.set(
|
||||
status,
|
||||
{
|
||||
description: current?.description ?? getDescriptionOrIdentifier(type),
|
||||
ast: UndefinedOr.map(current?.ast, (ast) => HttpApiSchema.UnionUnifyAST(ast, type)) ??
|
||||
(!isEmpty && HttpApiSchema.isVoid(type) ? undefined : type)
|
||||
description: current?.description ?? getDescriptionOrIdentifier(type.ast),
|
||||
ast: UndefinedOr.map(current?.ast, (ast) => HttpApiSchema.UnionUnifyAST(ast, type.ast)) ??
|
||||
(!isEmpty && HttpApiSchema.isVoid(type.ast) ? undefined : type.ast)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
HttpApiSchema.extractUnionTypes(ast).forEach(process)
|
||||
HttpApiSchema.forEachMember(schema, process)
|
||||
return members
|
||||
}
|
||||
|
||||
|
||||
@@ -605,10 +605,10 @@ const makeSecurityMiddleware = (
|
||||
const responseSchema = Schema.declare(Response.isHttpServerResponse)
|
||||
|
||||
const makeSuccessSchema = (
|
||||
schema: Schema.Schema<any>
|
||||
schema: Schema.Top
|
||||
): Schema.Codec<unknown, HttpServerResponse> => {
|
||||
const schemas = new Set<Schema.Schema<any>>()
|
||||
HttpApiSchema.deunionize(schemas, schema)
|
||||
HttpApiSchema.forEachMember(schema, (_) => schemas.add(_))
|
||||
return Schema.Union(Array.from(schemas, toResponseSuccess)) as any
|
||||
}
|
||||
|
||||
@@ -618,10 +618,10 @@ const makeErrorSchema = (
|
||||
const schemas = new Set<Schema.Schema<any>>([HttpApiSchemaError])
|
||||
for (const group of Object.values(api.groups)) {
|
||||
for (const endpoint of Object.values(group.endpoints)) {
|
||||
HttpApiSchema.deunionize(schemas, endpoint.errorSchema)
|
||||
HttpApiSchema.forEachMember(endpoint.errorSchema, (_) => schemas.add(_))
|
||||
for (const middleware of endpoint.middlewares) {
|
||||
const key = middleware as any as HttpApiMiddleware.AnyKey
|
||||
HttpApiSchema.deunionize(schemas, key.error)
|
||||
HttpApiSchema.forEachMember(key.error, (_) => schemas.add(_))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,10 +521,10 @@ const responseAsVoid = (_response: HttpClientResponse.HttpClientResponse) => Eff
|
||||
|
||||
const HttpBodyFromSelf = Schema.declare(HttpBody.isHttpBody)
|
||||
|
||||
const payloadSchemaBody = (schema: Schema.Top): Schema.decodeTo<typeof HttpBodyFromSelf, Schema.Any> => {
|
||||
const members = schema.ast._tag === "UnionType" ? schema.ast.types : [schema.ast]
|
||||
return Schema.Union(members.map(bodyFromPayload)) as any
|
||||
}
|
||||
const payloadSchemaBody = (schema: Schema.Top): Schema.decodeTo<typeof HttpBodyFromSelf, Schema.Any> =>
|
||||
schema.ast._tag === "UnionType"
|
||||
? Schema.Union(schema.ast.types.map(bodyFromPayload)) as any
|
||||
: bodyFromPayload(schema.ast) as any
|
||||
|
||||
const bodyFromPayloadCache = new WeakMap<AST.AST, Schema.Top>()
|
||||
|
||||
@@ -543,11 +543,12 @@ const bodyFromPayload = (ast: AST.AST) => {
|
||||
encode(toI: any) {
|
||||
switch (encoding.kind) {
|
||||
case "Json": {
|
||||
return HttpBody.json(toI).pipe(
|
||||
Effect.mapError((error) =>
|
||||
new Issue.InvalidValue(Option.some(toI), { message: `Could not encode as JSON: ${error}` })
|
||||
)
|
||||
)
|
||||
try {
|
||||
const body = JSON.stringify(toI)
|
||||
return Effect.succeed(HttpBody.text(body, encoding.contentType))
|
||||
} catch {
|
||||
return Effect.fail(new Issue.InvalidValue(Option.some(toI), { message: "Could not encode as JSON" }))
|
||||
}
|
||||
}
|
||||
case "Text": {
|
||||
if (typeof toI !== "string") {
|
||||
@@ -555,7 +556,7 @@ const bodyFromPayload = (ast: AST.AST) => {
|
||||
new Issue.InvalidValue(Option.some(toI), { message: "Expected a string" })
|
||||
)
|
||||
}
|
||||
return Effect.succeed(HttpBody.text(toI))
|
||||
return Effect.succeed(HttpBody.text(toI, encoding.contentType))
|
||||
}
|
||||
case "UrlParams": {
|
||||
return Effect.succeed(HttpBody.urlParams(UrlParams.fromInput(toI as any)))
|
||||
@@ -566,7 +567,7 @@ const bodyFromPayload = (ast: AST.AST) => {
|
||||
new Issue.InvalidValue(Option.some(toI), { message: "Expected a Uint8Array" })
|
||||
)
|
||||
}
|
||||
return Effect.succeed(HttpBody.uint8Array(toI))
|
||||
return Effect.succeed(HttpBody.uint8Array(toI, encoding.contentType))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
* @since 4.0.0
|
||||
*/
|
||||
import type { YieldableError } from "../../Cause.ts"
|
||||
import * as Iterable from "../../collections/Iterable.ts"
|
||||
import type { Brand } from "../../data/Brand.ts"
|
||||
import { constant, constVoid, dual, type LazyArg } from "../../Function.ts"
|
||||
import type * as FileSystem from "../../platform/FileSystem.ts"
|
||||
@@ -75,9 +76,27 @@ export const getHttpApiAnnotations = (self: Annotations.Annotations | undefined)
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
* @category reflection
|
||||
*/
|
||||
export const extractUnionTypes = (ast: AST.AST): ReadonlyArray<AST.AST> => {
|
||||
export const UnionUnifyAST = (self: AST.AST, that: AST.AST): AST.AST => {
|
||||
const asts = new Set<AST.AST>([...extractUnionTypes(self), ...extractUnionTypes(that)])
|
||||
if (asts.size === 1) {
|
||||
return Iterable.headUnsafe(asts)
|
||||
}
|
||||
return new AST.UnionType(
|
||||
Array.from(asts),
|
||||
"anyOf",
|
||||
{
|
||||
...(AST.isUnionType(self) ? self.annotations : {}),
|
||||
...(AST.isUnionType(that) ? that.annotations : {})
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const extractUnionTypes = (ast: AST.AST): ReadonlyArray<AST.AST> => {
|
||||
const out: Array<AST.AST> = []
|
||||
process(ast)
|
||||
return out
|
||||
|
||||
function process(ast: AST.AST): void {
|
||||
if (AST.isUnionType(ast)) {
|
||||
for (const type of ast.types) {
|
||||
@@ -87,27 +106,15 @@ export const extractUnionTypes = (ast: AST.AST): ReadonlyArray<AST.AST> => {
|
||||
out.push(ast)
|
||||
}
|
||||
}
|
||||
const out: Array<AST.AST> = []
|
||||
process(ast)
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const UnionUnifyAST = (self: AST.AST, that: AST.AST): AST.AST =>
|
||||
new AST.UnionType(
|
||||
Array.from(new Set<AST.AST>([...extractUnionTypes(self), ...extractUnionTypes(that)])),
|
||||
"anyOf"
|
||||
)
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const UnionUnify = <
|
||||
A extends Schema.Top,
|
||||
B extends Schema.Top
|
||||
>(self: A, that: B): Schema.Union<[A, B]> => Schema.make(UnionUnifyAST(self.ast, that.ast)) as any
|
||||
>(self: A, that: B): Schema.Top => Schema.make(UnionUnifyAST(self.ast, that.ast))
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
@@ -452,39 +459,47 @@ export const Uint8Array = (options?: {
|
||||
readonly contentType?: string
|
||||
}): Schema.Uint8Array => withEncoding(Schema.Uint8Array, { kind: "Uint8Array", ...options })
|
||||
|
||||
const astCache = new WeakMap<AST.AST, Schema.Top>()
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
*/
|
||||
export const deunionize = (
|
||||
schemas: Set<Schema.Top>,
|
||||
schema: Schema.Top
|
||||
export const forEachMember = (
|
||||
schema: Schema.Top,
|
||||
f: (member: Schema.Top) => void
|
||||
): void => {
|
||||
if (astCache.has(schema.ast)) {
|
||||
schemas.add(astCache.get(schema.ast)!)
|
||||
f(astCache.get(schema.ast)!)
|
||||
return
|
||||
}
|
||||
const ast = schema.ast
|
||||
if (ast._tag === "UnionType") {
|
||||
let unionCache = unionCaches.get(ast)
|
||||
if (!unionCache) {
|
||||
unionCache = new WeakMap<AST.AST, Schema.Top>()
|
||||
unionCaches.set(ast, unionCache)
|
||||
}
|
||||
for (const astType of ast.types) {
|
||||
if (astCache.has(astType)) {
|
||||
schemas.add(astCache.get(astType)!)
|
||||
if (unionCache.has(astType)) {
|
||||
f(unionCache.get(astType)!)
|
||||
continue
|
||||
} else if (astType._tag === "NeverKeyword") {
|
||||
continue
|
||||
}
|
||||
const memberSchema = Schema.make(astType).annotate({
|
||||
...ast.annotations,
|
||||
...getHttpApiAnnotations(ast.annotations),
|
||||
...astType.annotations
|
||||
})
|
||||
astCache.set(astType, memberSchema)
|
||||
schemas.add(memberSchema)
|
||||
unionCache.set(astType, memberSchema)
|
||||
f(memberSchema)
|
||||
}
|
||||
} else {
|
||||
} else if (ast._tag !== "NeverKeyword") {
|
||||
astCache.set(ast, schema)
|
||||
schemas.add(schema)
|
||||
f(schema)
|
||||
}
|
||||
}
|
||||
|
||||
const astCache = new WeakMap<AST.AST, Schema.Top>()
|
||||
const unionCaches = new WeakMap<AST.AST, WeakMap<AST.AST, Schema.Top>>()
|
||||
|
||||
/**
|
||||
* @since 4.0.0
|
||||
* @category empty errors
|
||||
|
||||
Reference in New Issue
Block a user