I have created a post Api in go giber to to create a prompt. From the frontend I am passing the payload creator which has a string type but in my prompt_model i have it as prmitive.ObjectId type.
when I am running the function c.BodyParser(&prompt) it throws the error bad request Unprocessable Entity.
Here is the Prompt model:
type Prompts struct{
Id primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
Creator primitive.ObjectID `json:"creator,omitempty" bson:"creator,omitempty"`
CreatorUser User `json:"creatorUser,omitempty" bson:"-"`
Prompt string `json:"prompt,omitempty" validate:"required"`
Tag string `json:"tag,omitempty" validate:"required"`
}
here is the code for create-prompt controller:
func CreatePrompt(c *fiber.Ctx) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var prompt models.Prompts
// Extract session ID from the URL parameter
// sessionID := c.FormValue("creator")
// sessionObjectID, _ := primitive.ObjectIDFromHex(sessionID)
// fmt.Printf("ss %v \n ",sessionID)
// Validate the request body
fmt.Println("dd", c.BodyParser(&prompt))
if err := c.BodyParser(&prompt); err != nil {
return c.Status(http.StatusBadRequest).JSON(responses.UserResponse{
Status: http.StatusBadRequest,
Message: "error",
Data: &fiber.Map{"data": err.Error()},
})
}
// Assuming the session ID is stored in the Creator field
newPrompt := models.Prompts{
Id: primitive.NewObjectID(),
Creator: prompt.Creator,
Prompt: prompt.Prompt,
Tag: prompt.Tag,
}
result, err := promptCollection.InsertOne(ctx, newPrompt)
if err != nil {
return c.Status(http.StatusInternalServerError).JSON(responses.UserResponse{
Status: http.StatusInternalServerError,
Message: "error",
Data: &fiber.Map{"data": err.Error()},
})
}
return c.Status(http.StatusCreated).JSON(responses.UserResponse{
Status: http.StatusCreated,
Message: "success",
Data: &fiber.Map{"data": result},
})
}
here is the api call from frontend:
const response = await fetch("http://localhost:8000/create-prompt", {
method: "POST",
body: JSON.stringify({
creator: session?.user.id,
prompt: post.prompt,
tag: post.tag,
}),
here is the log for the payload data:
{
"creator":"64ea57ad19b714af26ef3756",
"prompt":"ads",
"tag":"as"
}
I tried to convert the creator from string type to objectId type before using the bodyParser method but it was in vein
what I am doing wrong exactly?