lundi 17 août 2020

How to improve structure of Service and DAO Layer in Go using Receivers

I am having a bit of difficulty in designing my Go code.

I'll try to demonstrate things with a very simple example of adding a new user to the database.

My Handler is only doing one thing: Calling a service. The service is managing all the business logic and then calling the DAO to interact with the database. The DAO also has only responsibility: Storing in the database.

Also, just for context I am making GraphQL requests to interact with my ElasticSearch database, but the design shouldn't be affected by this too much.

I have read a lot of posts about using structs/interfaces to handle the service layer and DAO layer, but I am unable to implement the same in my usecase.

File: handlers/user.go

type Resolver struct {
    client *elastic.Client
    index  string
}

func (r *Resolver) CreateUser(ctx context.Context, userID string, name string, token *string) (*model.User, error) {
    u, err := CreateUserService(ctx, r.client, r.index, userID, name, token)
    
    if err != nil {
        fmt.Println("Could not add User to db")
        return nil, err
    }

    return u, nil
}

File: services/user.go

func CreateUserService(ctx context.Context, client *elastic.Client, index string, userID string, name string, token *string) (*model.User, error) {

    u := &model.User{
        UserID: userID,
        Name:   name,
        Token: token
    }

    s, err := utils.ParseToString(u)

    if err != nil {
        return nil, err
    }

    err := CreateUserDAO(ctx, client, index, s)

    if err != nil {
        return nil, err
    }

    return u, nil
}

File: dao/user.go

func CreateUserDAO(ctx context.Context, client *elastic.Client, index string, user string) error {
    _, err = client.Index().
        Index(index).
        BodyString(s).
        Do(ctx)
    
    if err != nil {
        return err
    }

    return nil
}

I don't have a background in Java/C# so I'm not well versed with OOP Principles but I did read a lot on MVC based on other answers. My code works for now, but is it bad code? What are the things I can smooth out?

I don't want to be passing parameters from one function to another. Is there a way to that with receivers on methods?

Aucun commentaire:

Enregistrer un commentaire