Skip to content

Commit

Permalink
Schema: JSONSchema should support make(Class) (#2579)
Browse files Browse the repository at this point in the history
  • Loading branch information
gcanti committed Apr 20, 2024
1 parent c2df604 commit d90e8c3
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
33 changes: 33 additions & 0 deletions .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")({
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
}
*/
```
4 changes: 4 additions & 0 deletions packages/schema/src/JSONSchema.ts
Expand Up @@ -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<string, JsonSchema7>, 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
Expand Down
22 changes: 21 additions & 1 deletion packages/schema/test/JSONSchema.test.ts
Expand Up @@ -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")({ 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")({ a: S.String }) {}
const jsonSchema = JSONSchema.make(S.encodedSchema(A))
expect(jsonSchema).toEqual({
Expand Down

0 comments on commit d90e8c3

Please sign in to comment.