import { FastifyReply, FastifyRequest, RouteHandlerMethod } from "fastify";
import "fastify-cookie";
import "fastify-formbody";
import "fastify-multipart";
export type MiddlewareRequest
= FastifyRequest & { middlewareParams: P };
export type HandlerMethod = (request: MiddlewareRequest, reply: FastifyReply, next?: any) => void;
export type MiddlewareMethod = (request: MiddlewareRequest, reply: FastifyReply, next: () => void) => void;
export type HandlerMethodWithMiddleware = (request: MiddlewareRequest>, reply: FastifyReply) => void;
export type IteratorNext = () => void;
export type MiddlewareParams = T extends MiddlewareMethod[] ? X : never;
/**
* A route handler that supports middleware methods
*/
export function handleMiddleware[]>(middleware: T, handler?: HandlerMethodWithMiddleware) {
let result = > (async (request, reply, next) => {
var iterator = middleware[Symbol.iterator]();
var nextMiddleware = async () => {
let result = iterator.next();
if (result.done) {
if (handler) {
(handler)(request, reply);
} else if (next !== undefined) {
next();
}
return;
}
result.value(request, reply, nextMiddleware);
};
nextMiddleware();
});
return result;
}