From f66eb477ba6dc2cb8ef5412d6048f28721a8f4f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Nison?= Date: Mon, 11 Dec 2017 10:10:54 -0800 Subject: [PATCH] Adds an indirection layer to enhance the Metro middleware Reviewed By: BYK Differential Revision: D6436722 fbshipit-source-id: d864960e2eb7c8c2a96e9869c0b340cc6257808e --- packages/metro/src/Config.js | 10 ++++++++++ packages/metro/src/index.js | 14 ++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/metro/src/Config.js b/packages/metro/src/Config.js index f2c97a85..fb96e0e4 100644 --- a/packages/metro/src/Config.js +++ b/packages/metro/src/Config.js @@ -25,10 +25,19 @@ import type {PostProcessModules} from './DeltaBundler'; import type {PostProcessModules as PostProcessModulesForBuck} from './ModuleGraph/types.flow.js'; import type {TransformVariants} from './ModuleGraph/types.flow'; import type {HasteImpl} from './node-haste/Module'; +import type {IncomingMessage, ServerResponse} from 'http'; + +type Middleware = (IncomingMessage, ServerResponse, ?(?Error) => void) => void; export type ConfigT = { assetRegistryPath: string, + /** + * Called with the Metro middleware in parameter; can be used to wrap this + * middleware inside another one + */ + enhanceMiddleware: Middleware => Middleware, + extraNodeModules: {[id: string]: string}, /** * Specify any additional asset file extensions to be used by the packager. @@ -148,6 +157,7 @@ export type ConfigT = { const DEFAULT = ({ assetRegistryPath: 'missing-asset-registry-path', + enhanceMiddleware: middleware => middleware, extraNodeModules: {}, assetTransforms: false, getAssetExts: () => [], diff --git a/packages/metro/src/index.js b/packages/metro/src/index.js index fd7c103c..02150175 100644 --- a/packages/metro/src/index.js +++ b/packages/metro/src/index.js @@ -69,7 +69,7 @@ async function runMetro({ maxWorkers = 1, projectRoots = [], watch = false, -}: PrivateMetroOptions) { +}: PrivateMetroOptions): Promise { const normalizedConfig = config ? Config.normalize(config) : Config.DEFAULT; const assetExts = defaults.assetExts.concat( @@ -136,6 +136,7 @@ type CreateConnectMiddlewareOptions = {| exports.createConnectMiddleware = async function( options: CreateConnectMiddlewareOptions, ) { + // $FlowFixMe I don't know why Flow thinks there's an error here... runMetro IS async const metroServer = await runMetro({ config: options.config, maxWorkers: options.maxWorkers, @@ -144,10 +145,15 @@ exports.createConnectMiddleware = async function( watch: true, }); + const normalizedConfig = options.config + ? Config.normalize(options.config) + : Config.DEFAULT; + return { - middleware(req: IncomingMessage, res: ServerResponse) { - return metroServer.processRequest(req, res); - }, + middleware: normalizedConfig.enhanceMiddleware( + (req: IncomingMessage, res: ServerResponse, next: ?(?Error) => void) => + metroServer.processRequest(req, res, next), + ), end() { metroServer.end(); },