DynamicRegistry.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { pathToFileURL } from 'url';
  2. import * as path from 'path';
  3. import * as fs from 'fs';
  4. import { InvalidMiddlewareException, InvalidRouteException } from '../exceptions';
  5. import { Route, HttpHandler, Middleware } from '../http';
  6. import Registry from './Registry';
  7. class DynamicRegistry extends Registry {
  8. private readonly routesDir?: string;
  9. private readonly middlewaresDir?: string;
  10. public constructor(routesDir?: string, middlewaresDir?: string) {
  11. super();
  12. this.routesDir = routesDir;
  13. this.middlewaresDir = middlewaresDir;
  14. }
  15. protected async registerRoutes(): Promise<Registry> {
  16. if(this.routesDir == null)
  17. return this;
  18. const routesDir: string = this.routesDir;
  19. const files = fs.readdirSync(routesDir, { recursive: true, encoding: 'utf8' });
  20. for(const file of files) {
  21. if(/\.js$/.test(file)) {
  22. const fileUrl = pathToFileURL(path.join(routesDir, file)).toString();
  23. const RouteClass = await import(fileUrl).then(mod => mod.default?.default ?? mod.default ?? mod);
  24. if(RouteClass.prototype instanceof Route) {
  25. this.registerHttpHandler(<HttpHandler>new RouteClass(this.getServer()));
  26. } else throw new InvalidRouteException(fileUrl);
  27. }
  28. }
  29. return this;
  30. }
  31. protected async registerMiddlewares(): Promise<Registry> {
  32. if(this.middlewaresDir == null)
  33. return this;
  34. const middlewaresDir: string = this.middlewaresDir;
  35. const files = fs.readdirSync(middlewaresDir, { recursive: true, encoding: 'utf8' });
  36. for(const file of files) {
  37. if(/\.js$/.test(file)) {
  38. const fileUrl = pathToFileURL(path.join(middlewaresDir, file)).toString();
  39. const MiddlewareClass = await import(fileUrl).then(mod => mod.default?.default ?? mod.default ?? mod);
  40. if(MiddlewareClass.prototype instanceof Middleware) {
  41. this.registerHttpHandler(<HttpHandler>new MiddlewareClass(this.getServer()));
  42. } else throw new InvalidMiddlewareException(fileUrl);
  43. }
  44. }
  45. return this;
  46. }
  47. }
  48. export default DynamicRegistry;