|
| 1 | +package pg |
| 2 | + |
| 3 | +import ( |
| 4 | +"fmt" |
| 5 | +"reflect" |
| 6 | +"strings" |
| 7 | + |
| 8 | +"github.com/kataras/iris/v12" |
| 9 | +"github.com/kataras/iris/v12/x/errors" |
| 10 | + |
| 11 | +"github.com/kataras/pg" |
| 12 | +) |
| 13 | + |
| 14 | +// EntityController is a controller for a single entity. |
| 15 | +// It can be used to create a RESTful API for a single entity. |
| 16 | +// It is a wrapper around the pg.Repository. |
| 17 | +// It can be used as a base controller for a custom controller. |
| 18 | +// The T is the entity type (e.g. a custom type, Customer) and V is the ID type (e.g. string). |
| 19 | +// |
| 20 | +// The controller registers the following routes: |
| 21 | +// - POST / - creates a new entity. |
| 22 | +// - PUT / - updates an existing entity. |
| 23 | +// - GET /{id} - gets an entity by ID. |
| 24 | +// - DELETE /{id} - deletes an entity by ID. |
| 25 | +// The {id} parameter is the entity ID. It can be a string, int, uint, uuid, etc. |
| 26 | +type EntityController[T any, V comparable] struct { |
| 27 | +repository *pg.Repository[T] |
| 28 | + |
| 29 | +// GetID returns the entity ID for GET/{id} and DELETE/{id} paths from the request Context. |
| 30 | +GetID func(ctx iris.Context) V |
| 31 | + |
| 32 | +// ErrorHandler defaults to the PG's error handler. It can be customized for this controller. |
| 33 | +// Setting this to nil will panic the application on the first error. |
| 34 | +ErrorHandler func(ctx iris.Context, err error) bool |
| 35 | +} |
| 36 | + |
| 37 | +// NewEntityController returns a new EntityController[T, V]. |
| 38 | +// The T is the entity type (e.g. a custom type, Customer) and V is the ID type (e.g. string). |
| 39 | +// |
| 40 | +// Read the type's documentation for more information. |
| 41 | +func NewEntityController[T any, V comparable](middleware *PG) *EntityController[T, V] { |
| 42 | +repo := pg.NewRepository[T](middleware.GetDB()) |
| 43 | +errorHandler := middleware.opts.handleError |
| 44 | + |
| 45 | +return &EntityController[T, V]{ |
| 46 | +repository: repo, |
| 47 | +ErrorHandler: errorHandler, |
| 48 | +} |
| 49 | +} |
| 50 | + |
| 51 | +// Configure registers the controller's routes. |
| 52 | +// It is called automatically by the Iris API Builder when registered to the Iris Application. |
| 53 | +func (c *EntityController[T, V]) Configure(r iris.Party) { |
| 54 | +var v V |
| 55 | +typ := reflect.TypeOf(v) |
| 56 | +idParamName := fmt.Sprintf("%s_id", strings.ToLower(typ.Name())) |
| 57 | +idParam := fmt.Sprintf("/{%s}", idParamName) |
| 58 | +switch typ.Kind() { |
| 59 | +case reflect.String: |
| 60 | +idParam = fmt.Sprintf("/{%s:uuid}", idParamName) |
| 61 | +case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, |
| 62 | +reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 63 | +idParam = fmt.Sprintf("/{%s:int}", idParamName) |
| 64 | +} |
| 65 | + |
| 66 | +if c.GetID == nil { |
| 67 | +c.GetID = func(ctx iris.Context) V { |
| 68 | +return ctx.Params().GetEntry(idParamName).Value().(V) |
| 69 | +} |
| 70 | +} |
| 71 | + |
| 72 | +r.Post("/", c.create) |
| 73 | +r.Put("/", c.update) |
| 74 | +r.Get(idParam, c.get) |
| 75 | +r.Delete(idParam, c.delete) |
| 76 | +} |
| 77 | + |
| 78 | +// handleError handles the error. It returns true if the error was handled. |
| 79 | +func (c *EntityController[T, V]) handleError(ctx iris.Context, err error) bool { |
| 80 | +if err == nil { |
| 81 | +return false |
| 82 | +} |
| 83 | + |
| 84 | +return c.ErrorHandler(ctx, err) |
| 85 | +} |
| 86 | + |
| 87 | +// readPayload reads the request body and returns the entity. |
| 88 | +func (c *EntityController[T, V]) readPayload(ctx iris.Context) (T, bool) { |
| 89 | +var payload T |
| 90 | +err := ctx.ReadJSON(&payload) |
| 91 | +if err != nil { |
| 92 | +errors.InvalidArgument.Details(ctx, "unable to parse body", err.Error()) |
| 93 | +return payload, false |
| 94 | +} |
| 95 | + |
| 96 | +return payload, true |
| 97 | +} |
| 98 | + |
| 99 | +type idPayload[T comparable] struct { |
| 100 | +ID T `json:"id"` |
| 101 | +} |
| 102 | + |
| 103 | +// create creates a new entity. |
| 104 | +func (c *EntityController[T, V]) create(ctx iris.Context) { |
| 105 | +entry, ok := c.readPayload(ctx) |
| 106 | +if !ok { |
| 107 | +return |
| 108 | +} |
| 109 | + |
| 110 | +var id V |
| 111 | +err := c.repository.InsertSingle(ctx, entry, &id) |
| 112 | +if c.handleError(ctx, err) { |
| 113 | +return |
| 114 | +} |
| 115 | + |
| 116 | +ctx.StatusCode(iris.StatusCreated) |
| 117 | +ctx.JSON(idPayload[V]{ID: id}) |
| 118 | +} |
| 119 | + |
| 120 | +// get gets an entity by ID. |
| 121 | +func (c *EntityController[T, V]) get(ctx iris.Context) { |
| 122 | +id := c.GetID(ctx) |
| 123 | + |
| 124 | +entry, err := c.repository.SelectByID(ctx, id) |
| 125 | +if c.handleError(ctx, err) { |
| 126 | +return |
| 127 | +} |
| 128 | + |
| 129 | +ctx.JSON(entry) |
| 130 | +} |
| 131 | + |
| 132 | +// update updates an entity. |
| 133 | +func (c *EntityController[T, V]) update(ctx iris.Context) { |
| 134 | +entry, ok := c.readPayload(ctx) |
| 135 | +if !ok { |
| 136 | +return |
| 137 | +} |
| 138 | + |
| 139 | +// patch-like. |
| 140 | +onlyColumns := ctx.URLParamSlice("columns") |
| 141 | + |
| 142 | +var ( |
| 143 | +n int64 |
| 144 | +err error |
| 145 | +) |
| 146 | +if len(onlyColumns) > 0 { |
| 147 | +n, err = c.repository.UpdateOnlyColumns(ctx, onlyColumns, entry) |
| 148 | +} else { |
| 149 | +// put-like. |
| 150 | +n, err = c.repository.Update(ctx, entry) |
| 151 | +} |
| 152 | +if c.handleError(ctx, err) { |
| 153 | +return |
| 154 | +} |
| 155 | + |
| 156 | +if n == 0 { |
| 157 | +errors.NotFound.Message(ctx, "resource not found") |
| 158 | +return |
| 159 | +} |
| 160 | + |
| 161 | +ctx.StatusCode(iris.StatusNoContent) |
| 162 | +// ctx.StatusCode(iris.StatusOK) |
| 163 | +// ctx.JSON(iris.Map{"message": "resource updated successfully"}) |
| 164 | +} |
| 165 | + |
| 166 | +// delete deletes an entity by ID. |
| 167 | +func (c *EntityController[T, V]) delete(ctx iris.Context) { |
| 168 | +id := c.GetID(ctx) |
| 169 | + |
| 170 | +ok, err := c.repository.DeleteByID(ctx, id) |
| 171 | +if c.handleError(ctx, err) { |
| 172 | +return |
| 173 | +} |
| 174 | + |
| 175 | +if !ok { |
| 176 | +errors.NotFound.Details(ctx, "resource not found", err.Error()) |
| 177 | +return |
| 178 | +} |
| 179 | + |
| 180 | +ctx.StatusCode(iris.StatusNoContent) |
| 181 | +} |
0 commit comments