farmstar-survey-backend/internal/router/registration.go

75 lines
2.0 KiB
Go
Raw Normal View History

2024-02-05 14:05:28 +01:00
package router
import (
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/daos"
2024-02-05 14:05:28 +01:00
"github.com/pocketbase/pocketbase/forms"
"github.com/pocketbase/pocketbase/models"
)
func (r *RouterContainer) bootstrapRegistrationRoute() {
r.PB.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.POST("/registration", func(c echo.Context) error {
requestData := struct {
Name string `json:"name"`
Phone string `json:"phone"`
Gender string `json:"gender"`
AgeGroup string `json:"age_group"`
ParticipantType string `json:"participant_type"`
}{}
if err := c.Bind(&requestData); err != nil {
return apis.NewBadRequestError("Failed to read request data", err)
2024-02-05 14:05:28 +01:00
}
if err := r.PB.Dao().RunInTransaction(func(txDao *daos.Dao) error {
address, err := r.ussd.GetAddress(c.Request().Context(), requestData.Phone)
if err != nil {
return err
}
2024-02-05 14:05:28 +01:00
if address == "" {
return apis.NewNotFoundError("Phone # not registered on Sarafu Network", nil)
}
2024-02-05 14:05:28 +01:00
usersCollection, err := r.PB.Dao().FindCollectionByNameOrId("users")
if err != nil {
return err
}
2024-02-05 14:05:28 +01:00
userRecord := models.NewRecord(usersCollection)
userForm := forms.NewRecordUpsert(r.PB, userRecord)
userForm.SetDao(txDao)
userForm.LoadData(map[string]any{
"name": requestData.Name,
"phone": requestData.Phone,
"gender": requestData.Gender,
"age_group": requestData.AgeGroup,
"participant_type": requestData.ParticipantType,
"blockchain_address": address,
"activated": true,
})
if err := userForm.Submit(); err != nil {
return apis.NewBadRequestError("Failed to submit user details", err)
}
return nil
}); err != nil {
c.JSON(400, map[string]any{"ok": "false", "error": err.Error()})
2024-02-05 14:05:28 +01:00
return nil
2024-02-05 14:05:28 +01:00
}
c.JSON(200, map[string]any{"ok": "true"})
return nil
})
return nil
})
}