|
| 1 | +/** |
| 2 | + * Converts Connect/Express-style middleware to Koa middleware. |
| 3 | + * |
| 4 | + * This adapter bridges the gap between Vite's Connect-based middleware system |
| 5 | + * and Ladle's Koa-based server architecture. |
| 6 | + * |
| 7 | + * @param {Function} connectMiddleware - Connect/Express middleware function with signature (req, res, next) |
| 8 | + * @returns {Function} Koa middleware function with signature (ctx, next) |
| 9 | + * |
| 10 | + * @description |
| 11 | + * Vite uses Connect middleware internally (similar to Express), which expects |
| 12 | + * (req, res, next) function signatures. Koa uses a different pattern with a context |
| 13 | + * object (ctx) and async/await. This adapter wraps Connect middleware to work with Koa. |
| 14 | + * |
| 15 | + * **Supported Vite Versions:** |
| 16 | + * - Vite 7.x |
| 17 | + * - Vite 6.x |
| 18 | + * - Vite 5.x |
| 19 | + * - Vite 4.x |
| 20 | + * |
| 21 | + * **How it works:** |
| 22 | + * 1. Receives a Connect middleware that expects Node.js req/res objects |
| 23 | + * 2. Extracts req and res from the Koa context (ctx.req, ctx.res) |
| 24 | + * 3. Wraps the Connect middleware call in a Promise |
| 25 | + * 4. Handles errors from the Connect middleware by rejecting the Promise |
| 26 | + * 5. Continues the Koa middleware chain by calling next() |
| 27 | + * |
| 28 | + * @example |
| 29 | + * import { connectToKoa } from './connect-to-koa.js'; |
| 30 | + * import vite from 'vite'; |
| 31 | + * |
| 32 | + * const viteServer = await vite.createServer(); |
| 33 | + * app.use(connectToKoa(viteServer.middlewares)); |
| 34 | + */ |
| 35 | +export const connectToKoa = (connectMiddleware) => { |
| 36 | + return async (ctx, next) => { |
| 37 | + await new Promise((resolve, reject) => { |
| 38 | + connectMiddleware(ctx.req, ctx.res, (err) => { |
| 39 | + if (err) reject(err); |
| 40 | + else resolve(); |
| 41 | + }); |
| 42 | + }); |
| 43 | + await next(); |
| 44 | + }; |
| 45 | +}; |
0 commit comments