Spaces:
Running
Running
Download cmd/exec.go from miss-clean-spa/api: direct link, hf CLI and curl.
- Browser
- Download file 7.52 kB
-
https://huggingface.co/spaces/miss-clean-spa/api/resolve/main/cmd/exec.go
- Command line
-
hf download hf://spaces/miss-clean-spa/api/cmd/exec.go
-
curl -L -o exec.go https://huggingface.co/spaces/miss-clean-spa/api/resolve/main/cmd/exec.go
7.52 kB
| package cmd | |
| import ( | |
| "api/internal/chatbot" | |
| "api/internal/dashboard" | |
| "api/migrations" | |
| "os" | |
| "strings" | |
| "github.com/pocketbase/dbx" | |
| "github.com/pocketbase/pocketbase" | |
| "github.com/pocketbase/pocketbase/apis" | |
| "github.com/pocketbase/pocketbase/core" | |
| "github.com/pocketbase/pocketbase/tools/hook" | |
| "github.com/redis/go-redis/v9" | |
| ) | |
| var app *pocketbase.PocketBase | |
| func Start() error { | |
| app = pocketbase.New() | |
| if _, err := Execute(app); err != nil { | |
| return err | |
| } | |
| return nil | |
| } | |
| func Execute(app *pocketbase.PocketBase) (*pocketbase.PocketBase, error) { | |
| app.RootCmd.Root() | |
| // Use a flag to ensure migration runs only once | |
| var migrationRun bool | |
| // Run migration on serve when DB is definitely ready | |
| app.OnServe().BindFunc(func(se *core.ServeEvent) error { | |
| if !migrationRun { | |
| if err := migrations.FixVerifiedFieldRequired(se.App); err != nil { | |
| se.App.Logger().Error("Migration failed", "error", err) | |
| } | |
| migrationRun = true | |
| } | |
| return se.Next() | |
| }) | |
| app.OnServe().BindFunc(func(se *core.ServeEvent) error { | |
| // attach global middleware | |
| se.Router.BindFunc(func(e *core.RequestEvent) error { | |
| println(0) | |
| return e.Next() | |
| }).Bind(apis.SkipSuccessActivityLog()) | |
| sub := se.Router.Group("/sub") | |
| // attach group middleware | |
| sub.BindFunc(func(e *core.RequestEvent) error { | |
| println(1) | |
| return e.Next() | |
| }) | |
| // attach group middleware with an id and custom priority | |
| sub.Bind(&hook.Handler[*core.RequestEvent]{ | |
| Id: "something", | |
| Func: func(e *core.RequestEvent) error { | |
| println(2) | |
| return e.Next() | |
| }, | |
| Priority: -1, | |
| }) | |
| // attach middleware to a single route | |
| // | |
| // "GET /sub/hello" should print the sequence: 2,0,1,3,4 | |
| sub.GET("/hello", func(e *core.RequestEvent) error { | |
| println(4) | |
| return e.String(200, "Hello!") | |
| }).BindFunc(func(e *core.RequestEvent) error { | |
| println(3) | |
| return e.Next() | |
| }).Unbind("something") | |
| se.Router.POST("/cust/auth/phone-login", func(e *core.RequestEvent) error { | |
| println("=> start this") | |
| data := struct { | |
| Phone string `json:"phone" form:"phone"` | |
| Password string `json:"password" form:"password"` | |
| }{} | |
| if err := e.BindBody(&data); err != nil { | |
| return e.BadRequestError("Failed to read request data", err) | |
| } | |
| println("=> pass") | |
| record, err := e.App.FindFirstRecordByData("customers", "phone_number", data.Phone) | |
| if err != nil || !record.ValidatePassword(data.Password) { | |
| return e.BadRequestError("Invalid credentials", err) | |
| } | |
| return apis.RecordAuthResponse(e, record, "phone", map[string]any{"token_duration": 315360000}) | |
| }) | |
| se.Router.PUT("/order-status", func(e *core.RequestEvent) error { | |
| data := struct { | |
| OrderID string `json:"orderId"` | |
| Status OrderStatus `json:"status"` | |
| }{} | |
| if err := e.BindBody(&data); err != nil { | |
| return e.BadRequestError("Failed to read request data", err) | |
| } | |
| _, err := app.DB(). | |
| Update( | |
| "orders", | |
| dbx.Params{"status": data.Status}, | |
| dbx.NewExp("LOWER([[id]])={:id}", dbx.Params{"id": strings.ToLower(data.OrderID)}), | |
| ). | |
| Execute() | |
| if err != nil { | |
| return apis.NewInternalServerError("Failed to retrieve order data", err) // More specific error message | |
| } | |
| return e.JSON(200, map[string]string{"status": "success"}) | |
| }) | |
| se.Router.POST("/auth/phone-login", func(e *core.RequestEvent) error { | |
| data := struct { | |
| Phone string `json:"phone" form:"phone"` | |
| Password string `json:"password" form:"password"` | |
| }{} | |
| if err := e.BindBody(&data); err != nil { | |
| return e.BadRequestError("Failed to read request data", err) | |
| } | |
| record, err := e.App.FindFirstRecordByData("users", "phone_number", data.Phone) | |
| if err != nil || !record.ValidatePassword(data.Password) { | |
| return e.BadRequestError("Invalid credentials", err) | |
| } | |
| return apis.RecordAuthResponse(e, record, "phone", map[string]any{"token_duration": 315360000}) | |
| }) | |
| customer := se.Router.Group("/cust").Bind(apis.RequireAuth("customers")) | |
| customer.POST("/checkout", Checkout) | |
| customer.GET("/order-list", ListOrdersByCustID) | |
| bo := se.Router.Group("").Bind(apis.RequireAuth("users")) | |
| bo.GET("/order-list", ListOrders) | |
| dashboard := dashboard.NewDashboardService(app) | |
| bo.GET("/dashboard/status-count", dashboard.StatusCount) | |
| bo.GET("/dashboard/sell-revenue", dashboard.SellRevenue) | |
| // Initialize Redis client for chatbot | |
| redisAddr := os.Getenv("REDIS_ADDR") | |
| if redisAddr == "" { | |
| redisAddr = "localhost:6379" | |
| } | |
| redisPassword := os.Getenv("REDIS_PASSWORD") | |
| redisClient := redis.NewClient(&redis.Options{ | |
| Addr: redisAddr, | |
| Password: redisPassword, | |
| DB: 0, | |
| }) | |
| // Initialize chatbot service | |
| chatbotService := chatbot.NewChatbotService(app, redisClient) | |
| // Chatbot endpoints | |
| chatbotGroup := se.Router.Group("/chatbot") | |
| chatbotGroup.POST("/message", func(e *core.RequestEvent) error { | |
| data := struct { | |
| Message string `json:"message"` | |
| }{} | |
| if err := e.BindBody(&data); err != nil { | |
| return e.BadRequestError("Failed to read request data", err) | |
| } | |
| user := e.Auth | |
| response, err := chatbotService.ProcessMessage(e.Request.Context(), user.Id, data.Message) | |
| if err != nil { | |
| return e.InternalServerError("Failed to process message", err) | |
| } | |
| return e.JSON(200, response) | |
| }) | |
| // WebSocket endpoint for real-time chat | |
| se.Router.GET("/chatbot/ws", func(e *core.RequestEvent) error { | |
| // Set user in request context for WebSocket handler | |
| ctx := e.Request.Context() | |
| // ctx = context.WithValue(ctx, "user", e.Auth) | |
| e.Request = e.Request.WithContext(ctx) | |
| return chatbotService.HandleWebSocket(e.Response, e.Request) | |
| }) | |
| return se.Next() | |
| }) | |
| app.OnRecordCreateRequest("customers").BindFunc(func(e *core.RecordRequestEvent) error { | |
| // Always set verified to false for new customers | |
| e.Record.Set("verified", false) | |
| return e.Next() | |
| }) | |
| app.OnRecordCreateRequest("users").BindFunc(func(e *core.RecordRequestEvent) error { | |
| e.Record.Set("verified", false) | |
| return e.Next() | |
| }) | |
| app.OnSettingsReload().BindFunc(func(e *core.SettingsReloadEvent) error { | |
| println("on setting reload") | |
| if err := e.Next(); err != nil { | |
| return err | |
| } | |
| e.App.Settings() | |
| return nil | |
| }) | |
| app.OnTerminate().BindFunc(func(e *core.TerminateEvent) error { | |
| println("app is terminated") | |
| return e.Next() | |
| }) | |
| app.OnMailerSend().BindFunc(func(e *core.MailerEvent) error { | |
| return e.Next() | |
| }) | |
| app.OnMailerRecordVerificationSend().BindFunc(func(e *core.MailerRecordEvent) error { | |
| e.Message.Subject = "hook verify email" | |
| return e.Next() | |
| }) | |
| app.OnMailerRecordOTPSend().BindFunc(func(e *core.MailerRecordEvent) error { | |
| e.Message.Subject = "OnMailerRecordOTPSend" | |
| return e.Next() | |
| }) | |
| // use for sse | |
| app.OnRealtimeConnectRequest().BindFunc(func(e *core.RealtimeConnectRequestEvent) error { | |
| println("sse connecting") | |
| e.App.Logger().Info("SSE connection established", "client", e.Client, "timeout", e.IdleTimeout) | |
| return e.Next() | |
| }) | |
| app.OnRealtimeMessageSend().BindFunc(func(e *core.RealtimeMessageEvent) error { | |
| println("send sse message") | |
| e.App.Logger().Info("SSE message sent", "client", e.Client, "message", e.Message) | |
| return e.Next() | |
| }) | |
| app.OnCollectionsListRequest().BindFunc(func(e *core.CollectionsListRequestEvent) error { | |
| e.App.Logger().Info("Collections list requested") | |
| return e.Next() | |
| }) | |
| if err := app.Start(); err != nil { | |
| app.Logger().Error("Failed to start application", "error", err) | |
| return nil, err | |
| } | |
| return app, nil | |
| } | |