admin-ui-plugin.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import express from 'express';
  2. import fs from 'fs-extra';
  3. import path from 'path';
  4. import { VendureConfig } from '../../config/vendure-config';
  5. import { InjectorFn, VendurePlugin } from '../../config/vendure-plugin/vendure-plugin';
  6. import { createProxyHandler } from '../plugin-utils';
  7. export interface AdminUiOptions {
  8. hostname?: string;
  9. port: number;
  10. }
  11. /**
  12. * This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path
  13. * of the main Vendure server.
  14. */
  15. export class AdminUiPlugin implements VendurePlugin {
  16. constructor(private options: AdminUiOptions) {}
  17. configure(config: Required<VendureConfig>): Required<VendureConfig> {
  18. const route = 'admin';
  19. config.middleware.push({
  20. handler: createProxyHandler({ ...this.options, route }, !config.silent),
  21. route,
  22. });
  23. return config;
  24. }
  25. onBootstrap(inject: InjectorFn): void | Promise<void> {
  26. const adminUiPath = this.getAdminUiPath();
  27. const assetServer = express();
  28. assetServer.use(express.static(adminUiPath));
  29. assetServer.use((req, res) => {
  30. res.sendFile(path.join(adminUiPath, 'index.html'));
  31. });
  32. assetServer.listen(this.options.port);
  33. }
  34. private getAdminUiPath(): string {
  35. // attempt to read the index.html file from the Vendure dist bundle (as when installed
  36. // in an end-user project)
  37. const prodPath = path.join(__dirname, '../../../../admin-ui');
  38. if (fs.existsSync(path.join(prodPath, 'index.html'))) {
  39. return prodPath;
  40. }
  41. // attempt to read from the built admin-ui in the /server/dist/ folder when developing
  42. const devPath = path.join(__dirname, '../../../dist/admin-ui');
  43. if (fs.existsSync(path.join(devPath, 'index.html'))) {
  44. return devPath;
  45. }
  46. throw new Error(`AdminUiPlugin: admin-ui app not found`);
  47. }
  48. }