metaverse / truss

Truss helps you build go-kit microservices without having to worry about writing or maintaining boilerplate code.
Other
734 stars 143 forks source link

Adding MongoDB to handlers.go #260

Closed maeglindeveloper closed 5 years ago

maeglindeveloper commented 5 years ago

Hi everyone, I'm actually trying to instanciate a mongodb instance for my microservice (here UserService), that I would like to use for each of my method inside **handlers/handlers.go".

I would like to know if there is an efficient way to do it ?

I had the idea to insert a parameter to the NewService() constructor and then set an element of my structure userserviceService with the parameter, but it will mean that I will need to change the svc/server/run.go code, which I don't want to since it will be overwritten each time I'm regenerating the service.

handlers/handlers.go `func NewService() pb.UserServiceServer { return userserviceService{ /db:db/} }

type userserviceService struct { }` svc/server/run.go

func NewEndpoints() svc.Endpoints { // Business domain. var service pb.UserServiceServer { service = handlers.NewService() // Wrap Service with middlewares. See handlers/middlewares.go service = handlers.WrapService(service) } ... }

Thanks a lot!

maeglindeveloper commented 5 years ago

Any idea? @adamryman ? :s

zaquestion commented 5 years ago

@maeglindeveloper The short is do it through handlers.NewService.

At TUNE, we typically create a library to service the handlers and that library manages the DB connection. If you want to keep things tighter you can put the DB type on the userserviceService type that NewService returns.

It seems like you have some of this figured out, if configurations the issue I'll mention that NewService is the same place we'd load configuration from environment or file. It's the truss entry point for all intents and purposes

maeglindeveloper commented 5 years ago

@zaquestion : Thanks, so you would recommand something like getting a singleton, which contains all the helpers such as MongoDB connection, Kafka producer messages etc, inside the NewService function and set it as an argument of the userserviceService structure, right?

would be something like this ?

func NewService() pb.UserServiceServer {
    db := lib.getMongoHelper()
    return userserviceService{
        db: db 
    }
}

where lib is the external lib.

zaquestion commented 5 years ago

Correct.

It can be the bare sql.DB type if it pleases you as well. In our case we have a wrapper around the database/sql package which provides metrics and logging. It exposes its own DB type and we sometimes use that directly with the service struct. This limits the instances of the type, but obviates the need to a getter to the Singleton.

zaquestion commented 5 years ago

@maeglindeveloper I'm going to close this out, please reopen if you still have questions