Created
January 21, 2023 14:13
-
-
Save kaboc/c391c062a7371757da28f04c72cf8b5e to your computer and use it in GitHub Desktop.
Example of using PocketBase (v0.11.3) as a framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "log" | |
| "net/http" | |
| "github.com/labstack/echo/v5" | |
| "github.com/pocketbase/dbx" | |
| "github.com/pocketbase/pocketbase" | |
| "github.com/pocketbase/pocketbase/apis" | |
| "github.com/pocketbase/pocketbase/core" | |
| "github.com/pocketbase/pocketbase/models" | |
| ) | |
| func main() { | |
| app := pocketbase.New() | |
| app.OnBeforeServe().Add(func(e *core.ServeEvent) error { | |
| e.Router.POST( | |
| "/tasks", | |
| func(c echo.Context) error { | |
| task := c.QueryParams().Get("task") | |
| if task == "" { | |
| return apis.NewBadRequestError("Task to be added must be given.", nil) | |
| } | |
| collection, err := app.Dao().FindCollectionByNameOrId("tasks") | |
| if err != nil { | |
| return err | |
| } | |
| authRecord := c.Get(apis.ContextAuthRecordKey).(*models.Record) | |
| record := models.NewRecord(collection) | |
| record.Set("task", task) | |
| record.Set("user", authRecord.Id) | |
| if err := app.Dao().SaveRecord(record); err != nil { | |
| return err | |
| } | |
| return nil | |
| }, | |
| apis.ActivityLogger(app), | |
| apis.RequireAdminOrRecordAuth(), | |
| ) | |
| return nil | |
| }) | |
| app.OnBeforeServe().Add(func(e *core.ServeEvent) error { | |
| e.Router.GET( | |
| "/tasks", | |
| func(c echo.Context) error { | |
| authRecord := c.Get(apis.ContextAuthRecordKey).(*models.Record) | |
| expr := dbx.HashExp{"user": authRecord.Id} | |
| records, err := app.Dao().FindRecordsByExpr("tasks", expr) | |
| if err != nil { | |
| return err | |
| } | |
| return c.JSON(http.StatusOK, records) | |
| }, | |
| apis.ActivityLogger(app), | |
| apis.RequireAdminOrRecordAuth(), | |
| ) | |
| return nil | |
| }) | |
| app.OnBeforeServe().Add(func(e *core.ServeEvent) error { | |
| e.Router.DELETE( | |
| "/tasks/:id", | |
| func(c echo.Context) error { | |
| authRecord := c.Get(apis.ContextAuthRecordKey).(*models.Record) | |
| record, err := app.Dao().FindRecordById("tasks", c.PathParam("id")) | |
| if err != nil || record.GetString("user") != authRecord.Id { | |
| return apis.NewNotFoundError("No task not found with the ID.", err) | |
| } | |
| if err := app.Dao().DeleteRecord(record); err != nil { | |
| return err | |
| } | |
| return nil | |
| }, | |
| apis.ActivityLogger(app), | |
| apis.RequireAdminOrRecordAuth(), | |
| ) | |
| return nil | |
| }) | |
| if err := app.Start(); err != nil { | |
| log.Fatal(err) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment