Преглед изворни кода

feat: Re-implement startup messaging for plugins

The old way relied on the use of the `createProxyHandler` helper, which is now mostly not needed.
Michael Bromley пре 4 година
родитељ
комит
0984c6d399

+ 9 - 1
packages/admin-ui-plugin/src/plugin.ts

@@ -6,7 +6,14 @@ import {
     AdminUiConfig,
     Type,
 } from '@vendure/common/lib/shared-types';
-import { ConfigService, createProxyHandler, Logger, PluginCommonModule, VendurePlugin } from '@vendure/core';
+import {
+    ConfigService,
+    createProxyHandler,
+    Logger,
+    PluginCommonModule,
+    registerPluginStartupMessage,
+    VendurePlugin,
+} from '@vendure/core';
 import express from 'express';
 import fs from 'fs-extra';
 import path from 'path';
@@ -166,6 +173,7 @@ export class AdminUiPlugin implements NestModule {
                 await overwriteConfig();
             }
         }
+        registerPluginStartupMessage('Admin UI', route);
     }
 
     private async createStaticServer(app?: AdminUiAppConfig) {

+ 2 - 0
packages/asset-server-plugin/src/plugin.ts

@@ -4,6 +4,7 @@ import {
     AssetStorageStrategy,
     Logger,
     PluginCommonModule,
+    registerPluginStartupMessage,
     RuntimeVendureConfig,
     VendurePlugin,
 } from '@vendure/core';
@@ -178,6 +179,7 @@ export class AssetServerPlugin implements NestModule, OnApplicationBootstrap {
     configure(consumer: MiddlewareConsumer) {
         Logger.info('Creating asset server middleware', loggerCtx);
         consumer.apply(this.createAssetServer()).forRoutes(AssetServerPlugin.options.route);
+        registerPluginStartupMessage('Asset server', AssetServerPlugin.options.route);
     }
 
     /**

+ 11 - 8
packages/core/src/bootstrap.ts

@@ -16,7 +16,7 @@ import { registerCustomEntityFields } from './entity/register-custom-entity-fiel
 import { setEntityIdStrategy } from './entity/set-entity-id-strategy';
 import { validateCustomFieldsConfig } from './entity/validate-custom-fields-config';
 import { getConfigurationFunction, getEntitiesFromPlugins } from './plugin/plugin-metadata';
-import { getProxyMiddlewareCliGreetings } from './plugin/plugin-utils';
+import { getPluginStartupMessages } from './plugin/plugin-utils';
 
 export type VendureBootstrapFunction = (config: VendureConfig) => Promise<INestApplication>;
 
@@ -70,7 +70,7 @@ export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INe
 
 /**
  * @description
- * Bootstraps the Vendure . Read more about the [Vendure Worker]({{< relref "vendure-worker" >}})
+ * Bootstraps the Vendure worker. Read more about the [Vendure Worker]({{< relref "vendure-worker" >}})
  *
  * @example
  * ```TypeScript
@@ -202,11 +202,14 @@ function logWelcomeMessage(config: RuntimeVendureConfig) {
     } catch (e) {
         version = ' unknown';
     }
-    const { port, shopApiPath, adminApiPath } = config.apiOptions;
-    const apiCliGreetings: Array<[string, string]> = [];
-    apiCliGreetings.push(['Shop API', `http://localhost:${port}/${shopApiPath}`]);
-    apiCliGreetings.push(['Admin API', `http://localhost:${port}/${adminApiPath}`]);
-    apiCliGreetings.push(...getProxyMiddlewareCliGreetings(config));
+    const { port, shopApiPath, adminApiPath, hostname } = config.apiOptions;
+    const apiCliGreetings: Array<readonly [string, string]> = [];
+    const pathToUrl = (path: string) => `http://${hostname || 'localhost'}:${port}/${path}`;
+    apiCliGreetings.push(['Shop API', pathToUrl(shopApiPath)]);
+    apiCliGreetings.push(['Admin API', pathToUrl(adminApiPath)]);
+    apiCliGreetings.push(
+        ...getPluginStartupMessages().map(({ label, path }) => [label, pathToUrl(path)] as const),
+    );
     const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
     const title = `Vendure server (v${version}) now running on port ${port}`;
     const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
@@ -218,7 +221,7 @@ function logWelcomeMessage(config: RuntimeVendureConfig) {
     Logger.info(`=`.repeat(maxLineLength));
 }
 
-function arrangeCliGreetingsInColumns(lines: Array<[string, string]>): string[] {
+function arrangeCliGreetingsInColumns(lines: Array<readonly [string, string]>): string[] {
     const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
     return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
 }

+ 1 - 1
packages/core/src/plugin/index.ts

@@ -2,4 +2,4 @@ export * from './default-search-plugin/default-search-plugin';
 export * from './default-job-queue-plugin/default-job-queue-plugin';
 export * from './vendure-plugin';
 export * from './plugin-common.module';
-export { createProxyHandler, ProxyOptions } from './plugin-utils';
+export * from './plugin-utils';

+ 10 - 19
packages/core/src/plugin/plugin-utils.ts

@@ -63,9 +63,6 @@ export function createProxyHandler(options: ProxyOptions): RequestHandler {
             };
         },
     });
-    // Attach the options to the middleware function to allow
-    // the info to be logged after bootstrap.
-    (middleware as any).proxyMiddleware = options;
     return middleware;
 }
 
@@ -107,22 +104,16 @@ export interface ProxyOptions {
     basePath?: string;
 }
 
+const pluginStartupMessages: Array<{ label: string; path: string }> = [];
+
 /**
- * Generate CLI greeting lines for any proxy middleware that was set up with the createProxyHandler function.
+ * Use this function to add a line to the bootstrap log output listing a service added
+ * by this plugin.
  */
-export function getProxyMiddlewareCliGreetings(config: RuntimeVendureConfig): Array<[string, string]> {
-    const output: Array<[string, string]> = [];
-    for (const middleware of config.apiOptions.middleware || []) {
-        if ((middleware.handler as any).proxyMiddleware) {
-            const { port, hostname, label, route, basePath } = (middleware.handler as any)
-                .proxyMiddleware as ProxyOptions;
-            output.push([
-                label,
-                `http://${config.apiOptions.hostname || 'localhost'}:${
-                    config.apiOptions.port
-                }/${route}/ -> http://${hostname || 'localhost'}:${port}${basePath ? `/${basePath}` : ''}`,
-            ]);
-        }
-    }
-    return output;
+export function registerPluginStartupMessage(serviceName: string, path: string) {
+    pluginStartupMessages.push({ label: serviceName, path });
+}
+
+export function getPluginStartupMessages(): ReadonlyArray<{ label: string; path: string }> {
+    return pluginStartupMessages;
 }

+ 2 - 0
packages/email-plugin/src/plugin.ts

@@ -7,6 +7,7 @@ import {
     JobQueueService,
     Logger,
     PluginCommonModule,
+    registerPluginStartupMessage,
     Type,
     VendurePlugin,
 } from '@vendure/core';
@@ -213,6 +214,7 @@ export class EmailPlugin implements OnApplicationBootstrap, NestModule {
             this.devMailbox = new DevMailbox();
             consumer.apply(this.devMailbox.serve(options)).forRoutes(options.route);
             this.devMailbox.handleMockEvent((handler, event) => this.handleEvent(handler, event));
+            registerPluginStartupMessage('Dev mailbox', options.route);
         }
     }