1.1.3 • Published 5 months ago
skeemex v1.1.3
Skeemex
Introduction
Skeemex is a simple and lightweight wrapper around express that infers routers configurations and types from an Open Api schema specification.
Usage
First of all, create a Server instance, that contains an express app and a registry that is a container of the OpenApi schema:
import {Server, Router} from 'skeemex';
const server = new Server();
const openApiRegistry = server.getOpenApiRegistry();
You can specify the DTO schemas using Zod:
import { z } from "zod";
const UserSchema = z.object({
id: z.string().openapi({ example: '12345' }),
name: z.string().openapi({ example: 'John Doe' }),
age: z.number().openapi({ example: 42 }),
});
const GetUserParamsSchema = z.object({
id: z.string()
});
Create a router and specify its schema:
import UserService from './user.service.ts';
const router = new Router(openApiRegistry);
router.use({
method: 'get',
path: '/users/{id}',
description: 'Get User by id',
summary: 'Get a single User',
request: {
params: GetUserParamsSchema
},
responses: {
200: {
description: 'A single Pet',
content: {
'application/json': {
schema: UserSchema
}
}
},
},
}, async (req, res) => {
const user = await new UserService().getById(req.params.id)
res.status(200).json(user)
})
Register all the express middlewares and the router that we have declared and start the server:
import cors from 'cors';
server.use(cors(), router);
server.listen(process.env.PORT || 80, () => {
console.log(`Server is listening on port ${port}`)
});
If you want to generate the Open Api specification:
import yaml from 'yaml';
import {writeFileSync} from 'fs';
const specification = server.generateOpenApiSpecV3({
info: { title: "My schema", version: "1.0.0" },
openapi: "3.0.0",
servers: [{ url: "http://myserver.com" }],
tags: [{ name: "skeemex" }],
});
writeFileSync('spec.yaml', yaml.stringify(specification));
Contributing
This project welcomes all kind of contributions: from ideas, enhancement, bug fixing and more.
Disclaimer
The project is under construction and for now we heavily depends on zod and @asteasolutions/zod-to-openapi.