Skip to content

Instantly share code, notes, and snippets.

@ericmorand
Last active February 26, 2021 17:04
Show Gist options
  • Save ericmorand/80dc260072f68f24fff4184e3d1c2f52 to your computer and use it in GitHub Desktop.
Save ericmorand/80dc260072f68f24fff4184e3d1c2f52 to your computer and use it in GitHub Desktop.
NestJS Plugin
type Anonymize<T> = Omit<T, "provide">;
export type AnonymousProvider<T = any> =
Anonymize<ClassProvider<T>> |
Anonymize<ValueProvider<T>> |
Anonymize<FactoryProvider<T>> |
Anonymize<ExistingProvider<T>>;
export type Plugin<T extends Record<string, AnonymousProvider>> = Pick<ModuleMetadata, "imports" | "providers"> & T;
@ericmorand
Copy link
Author

Which allow us to write this:

export interface FooProviderInterface {
}

export type MyPlugin = Plugin<{
    fooProvider: AnonymousProvider<FooProviderInterface>
}>;

export const boostrap = (plugin: MyPlugin) => {
    const {imports, providers, fooProvider} = plugin;

    return NestFactory.createMicroservice<MicroserviceOptions>(
        {
            module: AppModule,
            imports: imports,
            providers: (providers || []).concat([
                Object.assign({
                    provide: 'FooProvider'
                }, fooProvider)
            ])
        },
        {
            transport: Transport.TCP,
            options: {
                port
            }
        },
    ).then((app) => {
        return app.listenAsync().then(() => {
            return app;
        });
    });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment