Created
January 25, 2021 04:04
-
-
Save azu/34c45967c915f3e636ea7045ec2685d1 to your computer and use it in GitHub Desktop.
express router lazy loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
/** | |
* lazy load express router | |
* @param resolver | |
* @example | |
* ```js | |
* import { lazyLoad } from "./lazyLoad" | |
* router.use( | |
* '/path_to_router', | |
* lazyLoad(() => import('./path_to_router')), | |
* ); | |
* ``` | |
*/ | |
export function lazyLoad(resolver: () => Promise<{ default: express.Router } | express.Router>) { | |
const lazyRouter = express.Router(); | |
let alreadyLoaded = false; | |
lazyRouter.use((req, res, next) => { | |
if (alreadyLoaded) { | |
return next(); | |
} else { | |
// initial startup | |
resolver() | |
.then(router => { | |
alreadyLoaded = true; | |
if ('default' in router) { | |
lazyRouter.use(router.default); | |
} else { | |
lazyRouter.use(router); | |
} | |
next(); | |
}) | |
.catch(error => { | |
next(error); | |
}); | |
} | |
}); | |
return lazyRouter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment