NibuTake / ReactRest

0 stars 0 forks source link

Zod based api definition #1

Open NibuTake opened 4 months ago

NibuTake commented 4 months ago
// src/schemas.ts
import { z } from 'zod';

export const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(1),
  email: z.string().email(),
});

export type User = z.infer<typeof UserSchema>;
// src/openapi.ts
import { OpenAPIObject, openApiBuilder, defineSchema } from 'zod-to-openapi';
import { UserSchema } from './schemas';

const userSchema = defineSchema(UserSchema, {
  title: 'User',
  description: 'A user in the system',
});

const openApiDoc: OpenAPIObject = openApiBuilder({
  title: 'My API',
  version: '1.0.0',
})
  .addSchema(userSchema)
  .addPath('/users', {
    get: {
      description: 'Retrieve a list of users',
      responses: {
        '200': {
          description: 'A list of users',
          content: {
            'application/json': {
              schema: {
                type: 'array',
                items: userSchema.ref(),
              },
            },
          },
        },
      },
    },
  })
  .addPath('/users/{id}', {
    get: {
      description: 'Retrieve a user by ID',
      parameters: [
        {
          name: 'id',
          in: 'path',
          required: true,
          schema: {
            type: 'string',
            format: 'uuid',
          },
        },
      ],
      responses: {
        '200': {
          description: 'A single user',
          content: {
            'application/json': {
              schema: userSchema.ref(),
            },
          },
        },
      },
    },
  })
  .build();

console.log(JSON.stringify(openApiDoc, null, 2));