Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-openapi-from-api-cache-copy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

Return fresh OpenAPI specs from cached `OpenApi.fromApi` calls.
23 changes: 21 additions & 2 deletions packages/effect/src/unstable/httpapi/OpenApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,25 @@ export const annotations: (

const apiCache = new WeakMap<HttpApi.Constraint, OpenAPISpec>()

const cloneOpenAPISpec = <A>(value: A): A => {
if (Array.isArray(value)) {
return value.map(cloneOpenAPISpec) as A
}
if (value !== null && typeof value === "object") {
const out: Record<string, unknown> = {}
for (const key of Object.keys(value)) {
Object.defineProperty(out, key, {
value: cloneOpenAPISpec((value as Record<string, unknown>)[key]),
enumerable: true,
configurable: true,
writable: true
})
}
return out as A
}
return value
}

/**
* This function checks if a given tag exists within the provided context. If
* the tag is present, it retrieves the associated value and applies the given
Expand Down Expand Up @@ -253,7 +272,7 @@ export function fromApi<Id extends string, Groups extends HttpApiGroup.Constrain
): OpenAPISpec {
const cached = apiCache.get(api)
if (cached !== undefined) {
return cached
return cloneOpenAPISpec(cached)
}
let spec: OpenAPISpec = {
openapi: "3.1.0",
Expand Down Expand Up @@ -641,7 +660,7 @@ export function fromApi<Id extends string, Groups extends HttpApiGroup.Constrain

apiCache.set(api, spec)

return spec
return cloneOpenAPISpec(spec)
}

type ResponseBodies = Map<
Expand Down
20 changes: 20 additions & 0 deletions packages/effect/test/unstable/httpapi/OpenApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,26 @@ const makeSecurityApi = (
)

describe("OpenApi", () => {
it("returns fresh spec instances when using the cache", () => {
const Api = HttpApi.make("Api").add(
HttpApiGroup.make("test").add(
HttpApiEndpoint.get("get", "/resource")
)
)

const first = OpenApi.fromApi(Api)
first.info.title = "mutated"
first.paths["/resource"]!.get!.summary = "mutated"

const second = OpenApi.fromApi(Api)

assert.notStrictEqual(first, second)
assert.notStrictEqual(first.info, second.info)
assert.notStrictEqual(first.paths["/resource"]!.get, second.paths["/resource"]!.get)
assert.strictEqual(second.info.title, "Api")
assert.isUndefined(second.paths["/resource"]!.get!.summary)
})

it("preserves every declared payload content type for normalized equivalents", () => {
const profileA = "Application/Vnd.Effect+JSON; Profile=A"
const profileB = "application/vnd.effect+json; profile=b"
Expand Down