fastify / fastify/fastify-swagger

Recursive type definition using Typebox in schema leads to broken swagger file

Open
#865 0 comments 2 reactions 0 assignees View on GitHub
bug
Dominant language
JavaScript
Stars
1.1k
Forks
219
Avg merge
4h 24m
Merged PRs (30d)
2

Description

### Prerequisites

- [x] I have written a descriptive issue title
- [x] I have searched existing issues to ensure the bug has not already been reported

### Fastify version

5.1.0

### Plugin version

9.4.2

### Node.js version

22.12.0

### Operating system

macOS

### Operating system version (i.e. 20.04, 11.3, 10)

15.2

### Description

When using Recursive definition inside schema.body, swagger file generated as a result will be broken. It will generate `$ref: "#/components/schemas/def-0"`, but the "def-0" definition itself won't be generated.

The endpoint body is defined as follows:
```
import {Type, type Static} from '@sinclair/typebox';
const TreeNode = Type.Recursive(
(Node) =>
Type.Object({
name: Type.String(),
children: Type.Optional(Type.Array(Node)),
}),
{$id: 'Node'},
);

const BodySchema = Type.Object({
name: Type.String(),
age: Type.Number({minimum: 0}),
treeNodes: Type.Array(TreeNode),
});
type BodyType = Static;

// ...

server.register(
async (server: FastifyInstance) => {
return [
server.route({
method: 'POST',
url: 'submit',
handler: async (request, reply) => {
const body = request.body as BodyType;
reply.send({message: `Received: ${body.name}, ${body.age}`});
},
schema: {
operationId: 'testSubmit',
summary: 'Test',
description: 'Submit user data',
body: BodySchema,
response: {
200: Type.Object({
message: Type.String(),
}),
},
},
}),
]
},
{prefix: '/'},
);
```

The definition of the "/submit" endpoint in this example will generated as such:
```
/submit:
post:
operationId: testSubmit
summary: Test
description: Submit user data
requestBody:
content:
application/json:
schema:
type: object
properties:
name:
type: string
age:
minimum: 0
type: number
treeNodes:
type: array
items:
type: object
properties:
name:
type: string
children:
type: array
items:
$ref: "#/components/schemas/def-0"
required:
- name
title: Node
```
The problem is that the "def-0" schema definition will not be created in the resulting file.

### Link to code that reproduces the bug

https://gist.github.com/CruelCrow/2b5ee3ec6fbaecc474906cdaa45ba83e

### Expected Behavior

Recursive definition of an object should be created in the resulting swagger file.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.