feat: item-attachments CRUD (#22)

* change /content/ -> /homebox/

* add cache to code generators

* update env variables to set data storage

* update env variables

* set env variables in prod container

* implement attachment post route (WIP)

* get attachment endpoint

* attachment download

* implement string utilities lib

* implement generic drop zone

* use explicit truncate

* remove clean dir

* drop strings composable for lib

* update item types and add attachments

* add attachment API

* implement service context

* consolidate API code

* implement editing attachments

* implement upload limit configuration

* improve error handling

* add docs for max upload size

* fix test cases
This commit is contained in:
Hayden 2022-09-24 11:33:38 -08:00 committed by GitHub
parent 852d312ba7
commit 31b34241e0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
165 changed files with 2509 additions and 664 deletions

View file

@ -3,12 +3,12 @@ package main
import (
"time"
"github.com/hay-kot/content/backend/ent"
"github.com/hay-kot/content/backend/internal/config"
"github.com/hay-kot/content/backend/internal/repo"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/pkgs/mailer"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/config"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/pkgs/mailer"
"github.com/hay-kot/homebox/backend/pkgs/server"
)
type app struct {

View file

@ -224,6 +224,222 @@ const docTemplate = `{
}
}
},
"/v1/items/{id}/attachments": {
"post": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Items"
],
"summary": "imports items into the database",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "file",
"description": "File attachment",
"name": "file",
"in": "formData",
"required": true
},
{
"type": "string",
"description": "Type of file",
"name": "type",
"in": "formData",
"required": true
},
{
"type": "string",
"description": "name of the file including extension",
"name": "name",
"in": "formData",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/types.ItemOut"
}
},
"422": {
"description": "Unprocessable Entity",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/server.ValidationError"
}
}
}
}
}
},
"/v1/items/{id}/attachments/download": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/octet-stream"
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment token",
"name": "token",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": ""
}
}
}
},
"/v1/items/{id}/attachments/{attachment_id}": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/octet-stream"
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment ID",
"name": "attachment_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/types.ItemAttachmentToken"
}
}
}
},
"put": {
"security": [
{
"Bearer": []
}
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment ID",
"name": "attachment_id",
"in": "path",
"required": true
},
{
"description": "Attachment Update",
"name": "payload",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/types.ItemAttachmentUpdate"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/types.ItemOut"
}
}
}
},
"delete": {
"security": [
{
"Bearer": []
}
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment ID",
"name": "attachment_id",
"in": "path",
"required": true
}
],
"responses": {
"204": {
"description": ""
}
}
}
},
"/v1/labels": {
"get": {
"security": [
@ -818,6 +1034,17 @@ const docTemplate = `{
}
}
},
"server.ValidationError": {
"type": "object",
"properties": {
"field": {
"type": "string"
},
"reason": {
"type": "string"
}
}
},
"types.ApiSummary": {
"type": "object",
"properties": {
@ -881,11 +1108,33 @@ const docTemplate = `{
"id": {
"type": "string"
},
"type": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
}
},
"types.ItemAttachmentToken": {
"type": "object",
"properties": {
"token": {
"type": "string"
}
}
},
"types.ItemAttachmentUpdate": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"type": {
"type": "string"
}
}
},
"types.ItemCreate": {
"type": "object",
"properties": {
@ -1185,9 +1434,6 @@ const docTemplate = `{
"description": {
"type": "string"
},
"groupId": {
"type": "string"
},
"id": {
"type": "string"
},
@ -1214,9 +1460,6 @@ const docTemplate = `{
"description": {
"type": "string"
},
"groupId": {
"type": "string"
},
"id": {
"type": "string"
},

View file

@ -216,6 +216,222 @@
}
}
},
"/v1/items/{id}/attachments": {
"post": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"Items"
],
"summary": "imports items into the database",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "file",
"description": "File attachment",
"name": "file",
"in": "formData",
"required": true
},
{
"type": "string",
"description": "Type of file",
"name": "type",
"in": "formData",
"required": true
},
{
"type": "string",
"description": "name of the file including extension",
"name": "name",
"in": "formData",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/types.ItemOut"
}
},
"422": {
"description": "Unprocessable Entity",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/server.ValidationError"
}
}
}
}
}
},
"/v1/items/{id}/attachments/download": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/octet-stream"
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment token",
"name": "token",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"description": ""
}
}
}
},
"/v1/items/{id}/attachments/{attachment_id}": {
"get": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/octet-stream"
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment ID",
"name": "attachment_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/types.ItemAttachmentToken"
}
}
}
},
"put": {
"security": [
{
"Bearer": []
}
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment ID",
"name": "attachment_id",
"in": "path",
"required": true
},
{
"description": "Attachment Update",
"name": "payload",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/types.ItemAttachmentUpdate"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/types.ItemOut"
}
}
}
},
"delete": {
"security": [
{
"Bearer": []
}
],
"tags": [
"Items"
],
"summary": "retrieves an attachment for an item",
"parameters": [
{
"type": "string",
"description": "Item ID",
"name": "id",
"in": "path",
"required": true
},
{
"type": "string",
"description": "Attachment ID",
"name": "attachment_id",
"in": "path",
"required": true
}
],
"responses": {
"204": {
"description": ""
}
}
}
},
"/v1/labels": {
"get": {
"security": [
@ -810,6 +1026,17 @@
}
}
},
"server.ValidationError": {
"type": "object",
"properties": {
"field": {
"type": "string"
},
"reason": {
"type": "string"
}
}
},
"types.ApiSummary": {
"type": "object",
"properties": {
@ -873,11 +1100,33 @@
"id": {
"type": "string"
},
"type": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
}
},
"types.ItemAttachmentToken": {
"type": "object",
"properties": {
"token": {
"type": "string"
}
}
},
"types.ItemAttachmentUpdate": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"type": {
"type": "string"
}
}
},
"types.ItemCreate": {
"type": "object",
"properties": {
@ -1177,9 +1426,6 @@
"description": {
"type": "string"
},
"groupId": {
"type": "string"
},
"id": {
"type": "string"
},
@ -1206,9 +1452,6 @@
"description": {
"type": "string"
},
"groupId": {
"type": "string"
},
"id": {
"type": "string"
},

View file

@ -14,6 +14,13 @@ definitions:
items:
type: any
type: object
server.ValidationError:
properties:
field:
type: string
reason:
type: string
type: object
types.ApiSummary:
properties:
build:
@ -55,9 +62,23 @@ definitions:
$ref: '#/definitions/types.DocumentOut'
id:
type: string
type:
type: string
updatedAt:
type: string
type: object
types.ItemAttachmentToken:
properties:
token:
type: string
type: object
types.ItemAttachmentUpdate:
properties:
title:
type: string
type:
type: string
type: object
types.ItemCreate:
properties:
description:
@ -264,8 +285,6 @@ definitions:
type: string
description:
type: string
groupId:
type: string
id:
type: string
items:
@ -283,8 +302,6 @@ definitions:
type: string
description:
type: string
groupId:
type: string
id:
type: string
name:
@ -503,6 +520,143 @@ paths:
summary: updates a item
tags:
- Items
/v1/items/{id}/attachments:
post:
parameters:
- description: Item ID
in: path
name: id
required: true
type: string
- description: File attachment
in: formData
name: file
required: true
type: file
- description: Type of file
in: formData
name: type
required: true
type: string
- description: name of the file including extension
in: formData
name: name
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/types.ItemOut'
"422":
description: Unprocessable Entity
schema:
items:
$ref: '#/definitions/server.ValidationError'
type: array
security:
- Bearer: []
summary: imports items into the database
tags:
- Items
/v1/items/{id}/attachments/{attachment_id}:
delete:
parameters:
- description: Item ID
in: path
name: id
required: true
type: string
- description: Attachment ID
in: path
name: attachment_id
required: true
type: string
responses:
"204":
description: ""
security:
- Bearer: []
summary: retrieves an attachment for an item
tags:
- Items
get:
parameters:
- description: Item ID
in: path
name: id
required: true
type: string
- description: Attachment ID
in: path
name: attachment_id
required: true
type: string
produces:
- application/octet-stream
responses:
"200":
description: OK
schema:
$ref: '#/definitions/types.ItemAttachmentToken'
security:
- Bearer: []
summary: retrieves an attachment for an item
tags:
- Items
put:
parameters:
- description: Item ID
in: path
name: id
required: true
type: string
- description: Attachment ID
in: path
name: attachment_id
required: true
type: string
- description: Attachment Update
in: body
name: payload
required: true
schema:
$ref: '#/definitions/types.ItemAttachmentUpdate'
responses:
"200":
description: OK
schema:
$ref: '#/definitions/types.ItemOut'
security:
- Bearer: []
summary: retrieves an attachment for an item
tags:
- Items
/v1/items/{id}/attachments/download:
get:
parameters:
- description: Item ID
in: path
name: id
required: true
type: string
- description: Attachment token
in: query
name: token
required: true
type: string
produces:
- application/octet-stream
responses:
"200":
description: ""
security:
- Bearer: []
summary: retrieves an attachment for an item
tags:
- Items
/v1/items/import:
post:
parameters:

View file

@ -4,7 +4,7 @@ import (
"os"
"strings"
"github.com/hay-kot/content/backend/internal/config"
"github.com/hay-kot/homebox/backend/internal/config"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

View file

@ -5,12 +5,12 @@ import (
"os"
"time"
"github.com/hay-kot/content/backend/app/api/docs"
"github.com/hay-kot/content/backend/ent"
"github.com/hay-kot/content/backend/internal/config"
"github.com/hay-kot/content/backend/internal/repo"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/app/api/docs"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/config"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/pkgs/server"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog/log"
)
@ -37,10 +37,6 @@ func main() {
path = os.Args[1]
}
if path == "" {
log.Warn().Msg("No configuration detected, using defaults")
}
cfg, err := config.NewConfig(path)
if err != nil {
panic(err)
@ -55,17 +51,22 @@ func main() {
func run(cfg *config.Config) error {
app := new(cfg)
app.setupLogger()
// =========================================================================
// Initialize Database & Repos
c, err := ent.Open(cfg.Database.GetDriver(), cfg.Database.GetUrl())
err := os.MkdirAll(cfg.Storage.Data, 0755)
if err != nil {
log.Fatal().Err(err).Msg("failed to create data directory")
}
c, err := ent.Open("sqlite3", cfg.Storage.SqliteUrl)
if err != nil {
log.Fatal().
Err(err).
Str("driver", cfg.Database.GetDriver()).
Str("url", cfg.Database.GetUrl()).
Str("driver", "sqlite").
Str("url", cfg.Storage.SqliteUrl).
Msg("failed opening connection to sqlite")
}
defer func(c *ent.Client) {
@ -74,12 +75,14 @@ func run(cfg *config.Config) error {
if err := c.Schema.Create(context.Background()); err != nil {
log.Fatal().
Err(err).
Str("driver", "sqlite").
Str("url", cfg.Storage.SqliteUrl).
Msg("failed creating schema resources")
}
app.db = c
app.repos = repo.EntAllRepos(c)
app.services = services.NewServices(app.repos)
app.services = services.NewServices(app.repos, cfg.Storage.Data)
// =========================================================================
// Start Server

View file

@ -8,9 +8,9 @@ import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/hay-kot/content/backend/internal/config"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/internal/config"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)

View file

@ -11,10 +11,10 @@ import (
"path/filepath"
"github.com/go-chi/chi/v5"
_ "github.com/hay-kot/content/backend/app/api/docs"
v1 "github.com/hay-kot/content/backend/app/api/v1"
"github.com/hay-kot/content/backend/internal/repo"
"github.com/hay-kot/content/backend/internal/types"
_ "github.com/hay-kot/homebox/backend/app/api/docs"
v1 "github.com/hay-kot/homebox/backend/app/api/v1"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/rs/zerolog/log"
httpSwagger "github.com/swaggo/http-swagger" // http-swagger middleware
)
@ -43,7 +43,7 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
// API Version 1
v1Base := v1.BaseUrlFunc(prefix)
v1Ctrl := v1.NewControllerV1(a.services)
v1Ctrl := v1.NewControllerV1(a.services, v1.WithMaxUploadSize(a.conf.Web.MaxUploadSize))
{
r.Get(v1Base("/status"), v1Ctrl.HandleBase(func() bool { return true }, types.Build{
Version: Version,
@ -54,6 +54,10 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
r.Post(v1Base("/users/register"), v1Ctrl.HandleUserRegistration())
r.Post(v1Base("/users/login"), v1Ctrl.HandleAuthLogin())
// Attachment download URl needs a `token` query param to be passed in the request.
// and also needs to be outside of the `auth` middleware.
r.Get(v1Base("/items/{id}/attachments/download"), v1Ctrl.HandleItemAttachmentDownload())
r.Group(func(r chi.Router) {
r.Use(a.mwAuthToken)
r.Get(v1Base("/users/self"), v1Ctrl.HandleUserSelf())
@ -81,6 +85,11 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
r.Get(v1Base("/items/{id}"), v1Ctrl.HandleItemGet())
r.Put(v1Base("/items/{id}"), v1Ctrl.HandleItemUpdate())
r.Delete(v1Base("/items/{id}"), v1Ctrl.HandleItemDelete())
r.Post(v1Base("/items/{id}/attachments"), v1Ctrl.HandleItemAttachmentCreate())
r.Get(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentToken())
r.Put(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentUpdate())
r.Delete(v1Base("/items/{id}/attachments/{attachment_id}"), v1Ctrl.HandleItemAttachmentDelete())
})
}

View file

@ -3,13 +3,20 @@ package v1
import (
"net/http"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
)
func WithMaxUploadSize(maxUploadSize int64) func(*V1Controller) {
return func(ctrl *V1Controller) {
ctrl.maxUploadSize = maxUploadSize
}
}
type V1Controller struct {
svc *services.AllServices
svc *services.AllServices
maxUploadSize int64
}
func BaseUrlFunc(prefix string) func(s string) string {
@ -21,7 +28,7 @@ func BaseUrlFunc(prefix string) func(s string) string {
return prefixFunc
}
func NewControllerV1(svc *services.AllServices) *V1Controller {
func NewControllerV1(svc *services.AllServices, options ...func(*V1Controller)) *V1Controller {
ctrl := &V1Controller{
svc: svc,
}

View file

@ -5,7 +5,7 @@ import (
"net/http/httptest"
"testing"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)

View file

@ -4,10 +4,10 @@ import (
"context"
"testing"
"github.com/hay-kot/content/backend/ent"
"github.com/hay-kot/content/backend/internal/mocks"
"github.com/hay-kot/content/backend/internal/mocks/factories"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/mocks"
"github.com/hay-kot/homebox/backend/internal/mocks/factories"
"github.com/hay-kot/homebox/backend/internal/types"
)
var mockHandler = &V1Controller{}

View file

@ -5,9 +5,9 @@ import (
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)

View file

@ -4,9 +4,9 @@ import (
"errors"
"net/http"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)

View file

@ -4,9 +4,9 @@ import (
"encoding/csv"
"net/http"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)
@ -64,7 +64,7 @@ func (ctrl *V1Controller) HandleItemsCreate() http.HandlerFunc {
// @Summary deletes a item
// @Tags Items
// @Produce json
// @Param id path string true "Item ID"
// @Param id path string true "Item ID"
// @Success 204
// @Router /v1/items/{id} [DELETE]
// @Security Bearer
@ -114,7 +114,7 @@ func (ctrl *V1Controller) HandleItemGet() http.HandlerFunc {
// @Summary updates a item
// @Tags Items
// @Produce json
// @Param id path string true "Item ID"
// @Param id path string true "Item ID"
// @Param payload body types.ItemUpdate true "Item Data"
// @Success 200 {object} types.ItemOut
// @Router /v1/items/{id} [PUT]

View file

@ -0,0 +1,237 @@
package v1
import (
"errors"
"fmt"
"net/http"
"path/filepath"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent/attachment"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)
// HandleItemsImport godocs
// @Summary imports items into the database
// @Tags Items
// @Produce json
// @Param id path string true "Item ID"
// @Param file formData file true "File attachment"
// @Param type formData string true "Type of file"
// @Param name formData string true "name of the file including extension"
// @Success 200 {object} types.ItemOut
// @Failure 422 {object} []server.ValidationError
// @Router /v1/items/{id}/attachments [POST]
// @Security Bearer
func (ctrl *V1Controller) HandleItemAttachmentCreate() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
if err != nil {
log.Err(err).Msg("failed to parse multipart form")
server.RespondError(w, http.StatusBadRequest, errors.New("failed to parse multipart form"))
return
}
errs := make(server.ValidationErrors, 0)
file, _, err := r.FormFile("file")
if err != nil {
switch {
case errors.Is(err, http.ErrMissingFile):
log.Debug().Msg("file for attachment is missing")
errs = errs.Append("file", "file is required")
default:
log.Err(err).Msg("failed to get file from form")
server.RespondServerError(w)
return
}
}
attachmentName := r.FormValue("name")
if attachmentName == "" {
log.Debug().Msg("failed to get name from form")
errs = errs.Append("name", "name is required")
}
if errs.HasErrors() {
server.Respond(w, http.StatusUnprocessableEntity, errs)
return
}
attachmentType := r.FormValue("type")
if attachmentType == "" {
attachmentType = attachment.TypeAttachment.String()
}
id, _, err := ctrl.partialParseIdAndUser(w, r)
if err != nil {
return
}
ctx := services.NewContext(r.Context())
item, err := ctrl.svc.Items.AttachmentAdd(
ctx,
id,
attachmentName,
attachment.Type(attachmentType),
file,
)
if err != nil {
log.Err(err).Msg("failed to add attachment")
server.RespondServerError(w)
return
}
server.Respond(w, http.StatusCreated, item)
}
}
// HandleItemAttachmentGet godocs
// @Summary retrieves an attachment for an item
// @Tags Items
// @Produce application/octet-stream
// @Param id path string true "Item ID"
// @Param token query string true "Attachment token"
// @Success 200
// @Router /v1/items/{id}/attachments/download [GET]
// @Security Bearer
func (ctrl *V1Controller) HandleItemAttachmentDownload() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := server.GetParam(r, "token", "")
path, err := ctrl.svc.Items.AttachmentPath(r.Context(), token)
if err != nil {
log.Err(err).Msg("failed to get attachment")
server.RespondServerError(w)
return
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(path)))
w.Header().Set("Content-Type", "application/octet-stream")
http.ServeFile(w, r, path)
}
}
// HandleItemAttachmentToken godocs
// @Summary retrieves an attachment for an item
// @Tags Items
// @Produce application/octet-stream
// @Param id path string true "Item ID"
// @Param attachment_id path string true "Attachment ID"
// @Success 200 {object} types.ItemAttachmentToken
// @Router /v1/items/{id}/attachments/{attachment_id} [GET]
// @Security Bearer
func (ctrl *V1Controller) HandleItemAttachmentToken() http.HandlerFunc {
return ctrl.handleItemAttachmentsHandler
}
// HandleItemAttachmentDelete godocs
// @Summary retrieves an attachment for an item
// @Tags Items
// @Param id path string true "Item ID"
// @Param attachment_id path string true "Attachment ID"
// @Success 204
// @Router /v1/items/{id}/attachments/{attachment_id} [DELETE]
// @Security Bearer
func (ctrl *V1Controller) HandleItemAttachmentDelete() http.HandlerFunc {
return ctrl.handleItemAttachmentsHandler
}
// HandleItemAttachmentUpdate godocs
// @Summary retrieves an attachment for an item
// @Tags Items
// @Param id path string true "Item ID"
// @Param attachment_id path string true "Attachment ID"
// @Param payload body types.ItemAttachmentUpdate true "Attachment Update"
// @Success 200 {object} types.ItemOut
// @Router /v1/items/{id}/attachments/{attachment_id} [PUT]
// @Security Bearer
func (ctrl *V1Controller) HandleItemAttachmentUpdate() http.HandlerFunc {
return ctrl.handleItemAttachmentsHandler
}
func (ctrl *V1Controller) handleItemAttachmentsHandler(w http.ResponseWriter, r *http.Request) {
uid, user, err := ctrl.partialParseIdAndUser(w, r)
if err != nil {
return
}
attachmentId, err := uuid.Parse(chi.URLParam(r, "attachment_id"))
if err != nil {
log.Err(err).Msg("failed to parse attachment_id param")
server.RespondError(w, http.StatusBadRequest, err)
return
}
ctx := services.NewContext(r.Context())
switch r.Method {
// Token Handler
case http.MethodGet:
token, err := ctrl.svc.Items.AttachmentToken(ctx, uid, attachmentId)
if err != nil {
switch err {
case services.ErrNotFound:
log.Err(err).
Str("id", attachmentId.String()).
Msg("failed to find attachment with id")
server.RespondError(w, http.StatusNotFound, err)
case services.ErrFileNotFound:
log.Err(err).
Str("id", attachmentId.String()).
Msg("failed to find file path for attachment with id")
log.Warn().Msg("attachment with no file path removed from database")
server.RespondError(w, http.StatusNotFound, err)
default:
log.Err(err).Msg("failed to get attachment")
server.RespondServerError(w)
return
}
}
server.Respond(w, http.StatusOK, types.ItemAttachmentToken{Token: token})
// Delete Attachment Handler
case http.MethodDelete:
err = ctrl.svc.Items.AttachmentDelete(r.Context(), user.GroupID, uid, attachmentId)
if err != nil {
log.Err(err).Msg("failed to delete attachment")
server.RespondServerError(w)
return
}
server.Respond(w, http.StatusNoContent, nil)
// Update Attachment Handler
case http.MethodPut:
var attachment types.ItemAttachmentUpdate
err = server.Decode(r, &attachment)
if err != nil {
log.Err(err).Msg("failed to decode attachment")
server.RespondError(w, http.StatusBadRequest, err)
return
}
attachment.ID = attachmentId
val, err := ctrl.svc.Items.AttachmentUpdate(ctx, uid, &attachment)
if err != nil {
log.Err(err).Msg("failed to delete attachment")
server.RespondServerError(w)
return
}
server.Respond(w, http.StatusOK, val)
}
}

View file

@ -3,10 +3,10 @@ package v1
import (
"net/http"
"github.com/hay-kot/content/backend/ent"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)

View file

@ -3,10 +3,10 @@ package v1
import (
"net/http"
"github.com/hay-kot/content/backend/ent"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)

View file

@ -4,9 +4,9 @@ import (
"net/http"
"github.com/google/uuid"
"github.com/hay-kot/content/backend/internal/services"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/server"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)