dashboard.plugin.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { MiddlewareConsumer, NestModule } from '@nestjs/common';
  2. import { Type } from '@vendure/common/lib/shared-types';
  3. import {
  4. Logger,
  5. PluginCommonModule,
  6. ProcessContext,
  7. registerPluginStartupMessage,
  8. SettingsStoreScopes,
  9. VendurePlugin,
  10. } from '@vendure/core';
  11. import express from 'express';
  12. import { rateLimit } from 'express-rate-limit';
  13. import fs from 'fs-extra';
  14. import path from 'path';
  15. import { adminApiExtensions } from './api/api-extensions.js';
  16. import { MetricsResolver } from './api/metrics.resolver.js';
  17. import { DASHBOARD_PLUGIN_OPTIONS, DEFAULT_APP_PATH, loggerCtx } from './constants.js';
  18. import { EntityDataMapperService } from './entity-data-mapper/entity-data-mapper.service';
  19. import { MetricsService } from './service/metrics.service.js';
  20. import { DashboardPluginOptions } from './types';
  21. /**
  22. * @description
  23. * This plugin serves the static files of the Vendure Dashboard and provides the
  24. * GraphQL extensions needed for the order metrics on the dashboard index page.
  25. *
  26. * ## Installation
  27. *
  28. * `npm install \@vendure/dashboard`
  29. *
  30. * ## Usage
  31. *
  32. * First you need to set up compilation of the Dashboard, using the Vite configuration
  33. * described in the [Dashboard Getting Started Guide](/guides/extending-the-dashboard/getting-started/)
  34. *
  35. * Once set up, you run `npx vite build` to build the production version of the dashboard app.
  36. *
  37. * The built app files will be output to the location specified by `build.outDir` in your Vite
  38. * config file. This should then be passed to the `appDir` init option, as in the example below:
  39. *
  40. * @example
  41. * ```ts
  42. * import { DashboardPlugin } from '\@vendure/dashboard/plugin';
  43. *
  44. * const config: VendureConfig = {
  45. * // Add an instance of the plugin to the plugins array
  46. * plugins: [
  47. * DashboardPlugin.init({
  48. * route: 'dashboard',
  49. * appDir: './dist/dashboard',
  50. * }),
  51. * ],
  52. * };
  53. * ```
  54. *
  55. * ## Metrics
  56. *
  57. * This plugin defines a `metricSummary` query which is used by the Dashboard UI to
  58. * display the order metrics on the dashboard.
  59. *
  60. * If you are building a stand-alone version of the Dashboard UI app, and therefore
  61. * don't need this plugin to serve the Dashboard UI, you can still use the
  62. * `metricSummary` query by adding the `DashboardPlugin` to the `plugins` array,
  63. * but without calling the `init()` method:
  64. *
  65. * @example
  66. * ```ts
  67. * import { DashboardPlugin } from '\@vendure/dashboard-plugin';
  68. *
  69. * const config: VendureConfig = {
  70. * plugins: [
  71. * DashboardPlugin, // <-- no call to .init()
  72. * ],
  73. * // ...
  74. * };
  75. * ```
  76. *
  77. * @docsCategory core plugins/DashboardPlugin
  78. */
  79. @VendurePlugin({
  80. imports: [PluginCommonModule],
  81. adminApiExtensions: {
  82. schema: adminApiExtensions,
  83. resolvers: [MetricsResolver],
  84. },
  85. providers: [
  86. { provide: DASHBOARD_PLUGIN_OPTIONS, useFactory: () => DashboardPlugin.options },
  87. MetricsService,
  88. EntityDataMapperService,
  89. ],
  90. configuration: config => {
  91. config.settingsStoreFields['vendure.dashboard'] = [
  92. {
  93. name: 'userSettings',
  94. scope: SettingsStoreScopes.user,
  95. },
  96. ];
  97. return config;
  98. },
  99. compatibility: '^3.0.0',
  100. })
  101. export class DashboardPlugin implements NestModule {
  102. private static options: DashboardPluginOptions | undefined;
  103. constructor(private readonly processContext: ProcessContext) {}
  104. /**
  105. * @description
  106. * Set the plugin options
  107. */
  108. static init(options: DashboardPluginOptions): Type<DashboardPlugin> {
  109. this.options = {
  110. ...options,
  111. };
  112. return DashboardPlugin;
  113. }
  114. configure(consumer: MiddlewareConsumer) {
  115. if (this.processContext.isWorker) {
  116. return;
  117. }
  118. if (!DashboardPlugin.options) {
  119. Logger.info(
  120. `DashboardPlugin's init() method was not called. The Dashboard UI will not be served.`,
  121. loggerCtx,
  122. );
  123. return;
  124. }
  125. const { route, appDir } = DashboardPlugin.options;
  126. const dashboardPath = appDir || this.getDashboardPath();
  127. Logger.info('Creating dashboard middleware', loggerCtx);
  128. consumer.apply(this.createStaticServer(dashboardPath)).forRoutes(route);
  129. registerPluginStartupMessage('Dashboard UI', route);
  130. }
  131. private createStaticServer(dashboardPath: string) {
  132. const limiter = rateLimit({
  133. windowMs: 60 * 1000,
  134. limit: process.env.NODE_ENV === 'production' ? 500 : 2000,
  135. standardHeaders: true,
  136. legacyHeaders: false,
  137. });
  138. const dashboardServer = express.Router();
  139. // This is a workaround for a type mismatch between express v5 (Vendure core)
  140. // and express v4 (several transitive dependencies). Can be removed once the
  141. // ecosystem has more significantly shifted to v5.
  142. dashboardServer.use(limiter as any);
  143. dashboardServer.use(express.static(dashboardPath));
  144. dashboardServer.use((req, res) => {
  145. res.sendFile('index.html', { root: dashboardPath });
  146. });
  147. return dashboardServer;
  148. }
  149. private getDashboardPath(): string {
  150. // First, try to find the dashboard dist directory in the @vendure/dashboard package
  151. try {
  152. const dashboardPackageJson = require.resolve('@vendure/dashboard/package.json');
  153. const dashboardPackageRoot = path.dirname(dashboardPackageJson);
  154. const dashboardDistPath = path.join(dashboardPackageRoot, 'dist');
  155. if (fs.existsSync(dashboardDistPath)) {
  156. Logger.info(`Found dashboard UI at ${dashboardDistPath}`, loggerCtx);
  157. return dashboardDistPath;
  158. }
  159. } catch (e) {
  160. // Dashboard package not found, continue to fallback
  161. }
  162. // Fallback to default path
  163. Logger.warn(
  164. `Could not find @vendure/dashboard dist directory. Falling back to default path: ${DEFAULT_APP_PATH}`,
  165. loggerCtx,
  166. );
  167. return DEFAULT_APP_PATH;
  168. }
  169. }