import 'reflect-metadata' ; import tachijs , { ConfigSetter , controller , httpGet , httpPost , reqParams , reqBody , inject , BaseController } from '../../' ; import { IsString } from 'class-validator' ; import bodyParser from 'body-parser' ; enum ServiceTypes { EmailService = 'EmailService' , NotificationService = 'NotificationService' } abstract class MailerService { abstract sendEmail ( content ) ; } class MockEmailService extends MailerService { async sendEmail ( content ) { console . log ( `Not sending email.... content: ${ content }` ) ; } } class EmailService extends MailerService { async sendEmail ( content ) { console . log ( `Sending email.... content: ${ content }` ) ; } } class NotificationService { constructor ( @ inject ( ServiceTypes . EmailService ) private mailer ) { } async notifyMessage ( content ) { this . mailer . sendEmail ( content ) ; } } class NotifyRequestBody { @ IsString ( ) message : string ; } @ controller ( '/' ) class HomeController extends BaseController { constructor ( @ inject ( ServiceTypes . NotificationService ) private notifier ) { super ( ) ; } @ httpGet ( '/' ) home ( ) { return `<form action='/notify' method='post'><input type='text' name='message'><button>Notify</button></form>` ; } @ httpGet ( '/posts/:id' ) async showId ( @ reqParams ( 'id' ) id ) { return { id } ; } @ httpPost ( '/notify' ) async notify ( @ reqBody ( NotifyRequestBody ) body ) { await this . notifier . notifyMessage ( body . message ) ; return this . redirect ( '/' ) ; } } interface Container { [ ServiceTypes . EmailService ] : typeof MailerService ; [ ServiceTypes . NotificationService ] : typeof NotificationService ; } const envIsDev = process . env . NODE_ENV === 'development' ; const container = envIsDev ? { [ ServiceTypes . EmailService ] : MockEmailService , [ ServiceTypes . NotificationService ] : NotificationService } : { [ ServiceTypes . EmailService ] : EmailService , [ ServiceTypes . NotificationService ] : NotificationService } ; const before = app => { app . use ( bodyParser . urlencoded ( { extended : true } ) ) ; } ; const server = tachijs ( { before , controllers : [ HomeController ] , container } ) ; server . listen ( 8000 ) ;