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

50 lines
1.2 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/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 {
data := apis.RequestInfo(c).Data
phone := data["phone"].(string)
address, err := r.ussd.GetAddress(c.Request().Context(), phone)
if err != nil {
return err
}
if address == "" {
return apis.NewNotFoundError("Phone # not registered on Sarafu Network", nil)
}
collection, err := r.PB.Dao().FindCollectionByNameOrId("users")
if err != nil {
return err
}
record := models.NewRecord(collection)
form := forms.NewRecordUpsert(r.PB, record)
if err := form.LoadRequest(c.Request(), ""); err != nil {
return apis.NewBadRequestError("Failed to register", err)
}
if err := form.Submit(); err != nil {
return apis.NewBadRequestError("Failed to register", err)
}
c.JSON(200, map[string]any{"ok": "true"})
return nil
})
return nil
})
}