From d90e8c3090cbc78e2bc7b51c974df66ffefacdfa Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Sat, 20 Apr 2024 09:18:46 +0200 Subject: [PATCH] Schema: JSONSchema should support make(Class) (#2579) --- .changeset/hot-items-complain.md | 33 +++++++++++++++++++++++++ packages/schema/src/JSONSchema.ts | 4 +++ packages/schema/test/JSONSchema.test.ts | 22 ++++++++++++++++- 3 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 .changeset/hot-items-complain.md diff --git a/.changeset/hot-items-complain.md b/.changeset/hot-items-complain.md new file mode 100644 index 0000000000..dbfa9c5ca5 --- /dev/null +++ b/.changeset/hot-items-complain.md @@ -0,0 +1,33 @@ +--- +"@effect/schema": patch +--- + +Schema: JSONSchema should support make(Class) + +Before + +```ts +import { JSONSchema, Schema } from "@effect/schema" + +class A extends Schema.Class("A")({ + a: Schema.String +}) {} + +console.log(JSONSchema.make(A)) // throws MissingAnnotation: cannot build a JSON Schema for a declaration without a JSON Schema annotation +``` + +Now + +```ts +console.log(JSONSchema.make(A)) +/* +Output: +{ + '$schema': 'http://json-schema.org/draft-07/schema#', + type: 'object', + required: [ 'a' ], + properties: { a: { type: 'string', description: 'a string', title: 'string' } }, + additionalProperties: false +} +*/ +``` diff --git a/packages/schema/src/JSONSchema.ts b/packages/schema/src/JSONSchema.ts index 71edd03bd2..5ae2080022 100644 --- a/packages/schema/src/JSONSchema.ts +++ b/packages/schema/src/JSONSchema.ts @@ -278,6 +278,10 @@ export const DEFINITION_PREFIX = "#/$defs/" const get$ref = (id: string): string => `${DEFINITION_PREFIX}${id}` const go = (ast: AST.AST, $defs: Record, handleIdentifier: boolean = true): JsonSchema7 => { + const surrogate = AST.getSurrogateAnnotation(ast) + if (Option.isSome(surrogate)) { + return go(surrogate.value, $defs, handleIdentifier) + } const hook = AST.getJSONSchemaAnnotation(ast) if (Option.isSome(hook)) { const handler = hook.value as JsonSchema7 diff --git a/packages/schema/test/JSONSchema.test.ts b/packages/schema/test/JSONSchema.test.ts index 6a47c3dc74..dbff66ab23 100644 --- a/packages/schema/test/JSONSchema.test.ts +++ b/packages/schema/test/JSONSchema.test.ts @@ -1523,7 +1523,27 @@ describe("JSONSchema", () => { }) describe("Class", () => { - it("should support S.encodedSchema(Class)", () => { + it("should support make(Class)", () => { + class A extends S.Class("A")({ a: S.String }) {} + const jsonSchema = JSONSchema.make(A) + expect(jsonSchema).toEqual({ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": [ + "a" + ], + "properties": { + "a": { + "type": "string", + "description": "a string", + "title": "string" + } + }, + "additionalProperties": false + }) + }) + + it("should support make(S.encodedSchema(Class))", () => { class A extends S.Class("A")({ a: S.String }) {} const jsonSchema = JSONSchema.make(S.encodedSchema(A)) expect(jsonSchema).toEqual({