Last active
July 23, 2021 16:00
-
-
Save marcj/53c59f0e258c8b508be697e32515b1df to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ts-node-script | |
import 'reflect-metadata'; | |
import { Application, onServerMainBootstrap } from '@deepkit/framework'; | |
import { injectable, InjectorContext } from '@deepkit/injector'; | |
import { t } from '@deepkit/type'; | |
import { AppModule, AppModuleConfig } from '@deepkit/app'; | |
import { ClassType } from '@deepkit/core'; | |
import { eventDispatcher } from '@deepkit/event'; | |
type Options = { exchange: string, routingKey: string, queue: string }; | |
const mappedClasses = new Map<ClassType, Options & { property: string }>(); | |
function rabbitSubscribe(options: Options) { | |
return (target: any, property: string) => { | |
mappedClasses.set(target.constructor, { ...options, property }); | |
}; | |
} | |
const rabbitConfig = new AppModuleConfig({ | |
exchanges: t.array({ name: t.string, type: t.string }).optional, | |
uri: t.string.description('The URI in format of amqp://rabbitmq:rabbitmq@localhost:5672') | |
}); | |
class ConnectionConfig extends rabbitConfig.slice(['uri']) { | |
} | |
@injectable() | |
class ConnectionManager { | |
constructor( | |
private config: ConnectionConfig, | |
private injector: InjectorContext, | |
) { | |
} | |
connect() { | |
//establish connection using this.config.uri | |
//register callbacks | |
for (const [classType, options] of mappedClasses) { | |
const service = this.injector.get(classType); | |
// service[options.property] is the function callback | |
} | |
} | |
} | |
@injectable() | |
class BootstrapListener { | |
constructor(private connectionManager: ConnectionManager) { | |
} | |
@eventDispatcher.listen(onServerMainBootstrap) | |
onBoostrap() { | |
this.connectionManager.connect(); | |
} | |
} | |
const rabbitModule = new AppModule({ | |
config: rabbitConfig, | |
listeners: [BootstrapListener], | |
providers: [ConnectionManager], | |
}, 'rabbit').forRoot(); | |
//------- here is the user code of the module | |
@injectable() | |
export class MessagingService { | |
@rabbitSubscribe({ | |
exchange: 'exchange1', | |
routingKey: 'subscribe-route', | |
queue: 'subscribe-queue', | |
}) | |
public async pubSubHandler(msg: {}) { | |
console.log(`Received message: ${JSON.stringify(msg)}`); | |
} | |
} | |
Application.create({ | |
providers: [MessagingService], | |
imports: [ | |
rabbitModule.configure({ | |
uri: 'amqp://rabbitmq:rabbitmq@localhost:5672' | |
}) | |
] | |
}).run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment