Created
March 27, 2024 13:27
-
-
Save austinhallett/617112547582168e5bf13630299ad565 to your computer and use it in GitHub Desktop.
Idea for a wrapper around Express.js to automatically document API endpoints using Zod. Similar to FastAPI's auto documentation functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const { z } = require('zod'); | |
const { generateOpenAPISpec } = require('./openapi-generator'); | |
const app = express(); | |
// Wrapper middleware function | |
function validateSchema(schema) { | |
return function (req, res, next) { | |
try { | |
schema.parse(req.body); // Validate request body | |
schema.parse(req.query); // Validate query parameters | |
// You can extend this to validate other parts of the request | |
next(); | |
} catch (error) { | |
res.status(400).json({ error: error.message }); | |
} | |
}; | |
} | |
// Define schemas for routes | |
const getUserSchema = z.object({ | |
userId: z.string().uuid(), | |
}); | |
// Example route with schema validation | |
app.get('/api/user/:userId', validateSchema(getUserSchema), (req, res) => { | |
// Route logic | |
}); | |
// Generate OpenAPI spec for each route | |
const openAPISpec = generateOpenAPISpec(app); | |
// Serve the OpenAPI spec | |
app.get('/openapi.json', (req, res) => { | |
res.json(openAPISpec); | |
}); | |
app.listen(3000, () => { | |
console.log('Server is running on port 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment