@busy-hour/blaze
Version:
<h1 align='center'>🔥 Blaze</h1> <div align='center'> An event driven framework for 🔥 Hono.js </div>
105 lines (104 loc) • 3.12 kB
JavaScript
// src/router/BlazeRouter.ts
import { Hono } from "hono";
import { BlazeConfig } from "../internal/config/instance.js";
import { Logger } from "../internal/logger/index.js";
import { isEmpty, isNil } from "../utils/common.js";
import { ExternalModule } from "../utils/constant/config/index.js";
import {
assignOpenAPIRegistry,
createOpenApiRouter,
fixOpenApiPath
} from "../utils/helper/router.js";
var BlazeRouter = class _BlazeRouter extends Hono {
openAPIRegistry;
zodApi;
constructor(options = {}) {
super({ strict: false, router: options.router });
this.zodApi = BlazeConfig.modules[ExternalModule.ZodApi];
if (!this.zodApi) {
this.openAPIRegistry = null;
return;
}
this.openAPIRegistry = new this.zodApi.OpenAPIRegistry();
}
openapi(route) {
const newRoute = createOpenApiRouter(route);
const mws = route.serviceMiddlewares.reduce(
(acc, curr) => {
if (!acc[curr[0]])
acc[curr[0]] = /* @__PURE__ */ new Set();
acc[curr[0]].add(curr[1]);
return acc;
},
{}
);
Object.entries(mws).forEach(
([method, value]) => this.on(method, route.path, ...value)
);
const handlers = [route.handler];
if (!isNil(route.middlewares) && !isEmpty(route.middlewares)) {
handlers.unshift(...route.middlewares);
}
if (!isNil(route.afterMiddlewares) && !isEmpty(route.afterMiddlewares)) {
handlers.push(...route.afterMiddlewares);
}
this.on(route.method, route.path, ...handlers);
if (!this.openAPIRegistry)
return;
this.openAPIRegistry.registerPath(newRoute);
}
getOpenAPIDocument(config) {
if (!this.zodApi || !this.openAPIRegistry) {
throw Logger.throw(`${ExternalModule.ZodApi} is not installed`);
}
const generator = new this.zodApi.OpenApiGeneratorV3(
this.openAPIRegistry.definitions
);
const document = generator.generateDocument(config);
return document;
}
getOpenAPI31Document(config) {
if (!this.zodApi || !this.openAPIRegistry) {
throw Logger.throw(`${ExternalModule.ZodApi} is not installed`);
}
const generator = new this.zodApi.OpenApiGeneratorV31(
this.openAPIRegistry.definitions
);
const document = generator.generateDocument(config);
return document;
}
doc(path, config) {
this.get(path, (ctx) => {
try {
const document = this.getOpenAPIDocument(config);
return ctx.json(document);
} catch (e) {
return ctx.json(e, 500);
}
});
}
doc31(path, config) {
this.get(path, (ctx) => {
try {
const document = this.getOpenAPI31Document(config);
return ctx.json(document);
} catch (e) {
return ctx.json(e, 500);
}
});
}
route(path, app) {
super.route(path, app);
if (!(app instanceof _BlazeRouter) || !app.openAPIRegistry) {
return this;
}
const docPath = fixOpenApiPath(path);
app.openAPIRegistry.definitions.forEach((def) => {
assignOpenAPIRegistry(this, docPath, def);
});
return this;
}
};
export {
BlazeRouter
};