Skip to main content
Became Hot Network Question
Added data to better understand the code.
Source Link

The code checks if theI'm using fiber and mongodb. Field "field" is needed to obtain certain data to unload the load on the database. If field "field" is empty, you needthen needs to use one model, otherwiseoutput all the otherdata from the database to make work easier to frontend. I don't like this crutch. Is there a much better solution?

func GetUserById(c *fiber.Ctx) error {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    var userId = c.Params("userId")
    defer cancel()

    objId, _ := primitive.ObjectIDFromHex(userId)

    // Creates options for search.
    opts, err := search.GetOneOptions(c, models.UserModel{})
    if err != nil {
        return responses.Response(c, http.StatusBadRequest, err.Error())
    }

    if c.Query("field") != "" {
        var user models.UserModelOmitempty

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    } else {
        var user models.UserModel

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    } 

}

Result in postman: without field

with field

The code checks if the "field" field is empty, you need to use one model, otherwise the other. Is there a much better solution?

if c.Query("field") != "" {
        var user models.UserModelOmitempty

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    } else {
        var user models.UserModel

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    }

I'm using fiber and mongodb. Field "field" is needed to obtain certain data to unload the load on the database. If field "field" is empty, then needs to output all the data from the database to make work easier to frontend. I don't like this crutch. Is there a much better solution?

func GetUserById(c *fiber.Ctx) error {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    var userId = c.Params("userId")
    defer cancel()

    objId, _ := primitive.ObjectIDFromHex(userId)

    // Creates options for search.
    opts, err := search.GetOneOptions(c, models.UserModel{})
    if err != nil {
        return responses.Response(c, http.StatusBadRequest, err.Error())
    }

    if c.Query("field") != "" {
        var user models.UserModelOmitempty

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    } else {
        var user models.UserModel

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    } 

}

Result in postman: without field

with field

added 2 characters in body
Source Link

The code checks if the "field" field is empty, you need to use one model, otherwise the other. Is there a much better optionsolution?

The code checks if the "field" field is empty, you need to use one model, otherwise the other. Is there a much better option?

The code checks if the "field" field is empty, you need to use one model, otherwise the other. Is there a much better solution?

Source Link

Change interface depending on if statement

The code checks if the "field" field is empty, you need to use one model, otherwise the other. Is there a much better option?

if c.Query("field") != "" {
        var user models.UserModelOmitempty

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    } else {
        var user models.UserModel

        err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
        if err != nil {
            return responses.Response(c, http.StatusBadRequest, "user not found")
        }

        return responses.ResponseWithData(c, http.StatusOK, "success", user)
    }

models.UserModel

type UserModel struct {
    Id               primitive.ObjectID `json:"id" bson:"_id" query:"string"`
    Name             string             `json:"name" bson:"name" validate:"required" query:"string"`
    Email            string             `json:"email" bson:"email" validate:"required" query:"string"`
    Password         string             `json:"-" bson:"password" validate:"required"`
    CreatedAt        int64              `json:"createdAt" bson:"createdAt" query:"int"`
    Rights           string             `json:"rights" bson:"rights" query:"string"`
    PhotoUrl         string             `json:"photoUrl" bson:"photoUrl"`
    Sex              string             `json:"sex" bson:"sex" query:"string"`
    BirthDate        int64              `json:"birthDate" bson:"birthDate" query:"int"`
    Country          string             `json:"country" bson:"country" query:"string"`
    EmailSubscribe   bool               `json:"emailSubscribe" bson:"emailSubscribe" query:"bool"`
    AccountConfirmed bool               `json:"accountConfirmed" bson:"accountConfirmed" query:"bool"`
}

models.UserModelOmitempty

type UserModelOmitempty struct {
    Id               primitive.ObjectID `json:"id" bson:"_id" query:"string"`
    Name             string             `json:"name,omitempty" bson:"name" validate:"required" query:"string"`
    Email            string             `json:"email,omitempty" bson:"email" validate:"required" query:"string"`
    Password         string             `json:"-" bson:"password" validate:"required"`
    CreatedAt        int64              `json:"createdAt,omitempty" bson:"createdAt" query:"int"`
    Rights           string             `json:"rights,omitempty" bson:"rights" query:"string"`
    PhotoUrl         string             `json:"photoUrl,omitempty" bson:"photoUrl"`
    Sex              string             `json:"sex,omitempty" bson:"sex" query:"string"`
    BirthDate        int64              `json:"birthDate,omitempty" bson:"birthDate" query:"int"`
    Country          string             `json:"country,omitempty" bson:"country" query:"string"`
    EmailSubscribe   bool               `json:"emailSubscribe,omitempty" bson:"emailSubscribe" query:"bool"`
    AccountConfirmed bool               `json:"accountConfirmed,omitempty" bson:"accountConfirmed" query:"bool"`
}