refactor: repositories (#28)

* cleanup unnecessary mocks

* refactor document storage location

* remove unused function

* move ownership to document types to repo package

* move types and mappers to repo package

* refactor sets to own package
This commit is contained in:
Hayden 2022-09-27 15:52:13 -08:00 committed by GitHub
parent 2e82398e5c
commit 343290a55a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
79 changed files with 3169 additions and 3160 deletions

View file

@ -1,6 +1,9 @@
package repo
import "github.com/google/uuid"
import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/pkgs/set"
)
// HasID is an interface to entities that have an ID uuid.UUID field and a GetID() method.
// This interface is fulfilled by all entities generated by entgo.io/ent via a custom template
@ -8,55 +11,11 @@ type HasID interface {
GetID() uuid.UUID
}
// IDSet is a utility set-like type for working with sets of uuid.UUIDs within a repository
// instance. Most useful for comparing lists of UUIDs for processing relationship
// IDs and remove/adding relationships as required.
//
// # See how ItemRepo uses it to manage the Labels-To-Items relationship
//
// NOTE: may be worth moving this to a more generic package/set implementation
// or use a 3rd party set library, but this is good enough for now
type IDSet struct {
mp map[uuid.UUID]struct{}
}
func NewIDSet(l int) *IDSet {
return &IDSet{
mp: make(map[uuid.UUID]struct{}, l),
}
}
func EntitiesToIDSet[T HasID](entities []T) *IDSet {
s := NewIDSet(len(entities))
func newIDSet[T HasID](entities []T) set.Set[uuid.UUID] {
uuids := make([]uuid.UUID, 0, len(entities))
for _, e := range entities {
s.Add(e.GetID())
uuids = append(uuids, e.GetID())
}
return s
}
func (t *IDSet) Slice() []uuid.UUID {
s := make([]uuid.UUID, 0, len(t.mp))
for k := range t.mp {
s = append(s, k)
}
return s
}
func (t *IDSet) Add(ids ...uuid.UUID) {
for _, id := range ids {
t.mp[id] = struct{}{}
}
}
func (t *IDSet) Has(id uuid.UUID) bool {
_, ok := t.mp[id]
return ok
}
func (t *IDSet) Len() int {
return len(t.mp)
}
func (t *IDSet) Remove(id uuid.UUID) {
delete(t.mp, id)
return set.New(uuids...)
}

View file

@ -18,7 +18,7 @@ var (
tClient *ent.Client
tRepos *AllRepos
tUser *ent.User
tUser UserOut
tGroup *ent.Group
)
@ -53,7 +53,7 @@ func TestMain(m *testing.M) {
}
tClient = client
tRepos = EntAllRepos(tClient)
tRepos = EntAllRepos(tClient, os.TempDir())
defer client.Close()
bootstrap()

View file

@ -0,0 +1,52 @@
package repo
// mapTErrFunc is a factory function that returns a mapper function that
// wraps the given mapper function but first will check for an error and
// return the error if present.
//
// Helpful for wrapping database calls that return both a value and an error
func mapTErrFunc[T any, Y any](fn func(T) Y) func(T, error) (Y, error) {
return func(t T, err error) (Y, error) {
if err != nil {
var zero Y
return zero, err
}
return fn(t), nil
}
}
// TODO: Future Usage
// func mapEachFunc[T any, Y any](fn func(T) Y) func([]T) []Y {
// return func(items []T) []Y {
// result := make([]Y, len(items))
// for i, item := range items {
// result[i] = fn(item)
// }
// return result
// }
// }
func mapTEachErrFunc[T any, Y any](fn func(T) Y) func([]T, error) ([]Y, error) {
return func(items []T, err error) ([]Y, error) {
if err != nil {
return nil, err
}
result := make([]Y, len(items))
for i, item := range items {
result[i] = fn(item)
}
return result, nil
}
}
func mapEach[T any, U any](items []T, fn func(T) U) []U {
result := make([]U, len(items))
for i, item := range items {
result[i] = fn(item)
}
return result
}

View file

@ -7,7 +7,6 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/types"
)
// DocumentTokensRepository is a repository for Document entity
@ -15,7 +14,35 @@ type DocumentTokensRepository struct {
db *ent.Client
}
func (r *DocumentTokensRepository) Create(ctx context.Context, data types.DocumentTokenCreate) (*ent.DocumentToken, error) {
type (
DocumentToken struct {
ID uuid.UUID `json:"-"`
TokenHash []byte `json:"tokenHash"`
ExpiresAt time.Time `json:"expiresAt"`
DocumentID uuid.UUID `json:"documentId"`
}
DocumentTokenCreate struct {
TokenHash []byte `json:"tokenHash"`
DocumentID uuid.UUID `json:"documentId"`
ExpiresAt time.Time `json:"expiresAt"`
}
)
var (
mapDocumentTokenErr = mapTErrFunc(mapDocumentToken)
)
func mapDocumentToken(e *ent.DocumentToken) DocumentToken {
return DocumentToken{
ID: e.ID,
TokenHash: e.Token,
ExpiresAt: e.ExpiresAt,
DocumentID: e.Edges.Document.ID,
}
}
func (r *DocumentTokensRepository) Create(ctx context.Context, data DocumentTokenCreate) (DocumentToken, error) {
result, err := r.db.DocumentToken.Create().
SetDocumentID(data.DocumentID).
SetToken(data.TokenHash).
@ -23,13 +50,13 @@ func (r *DocumentTokensRepository) Create(ctx context.Context, data types.Docume
Save(ctx)
if err != nil {
return nil, err
return DocumentToken{}, err
}
return r.db.DocumentToken.Query().
return mapDocumentTokenErr(r.db.DocumentToken.Query().
Where(documenttoken.ID(result.ID)).
WithDocument().
Only(ctx)
Only(ctx))
}
func (r *DocumentTokensRepository) PurgeExpiredTokens(ctx context.Context) (int, error) {

View file

@ -8,7 +8,6 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)
@ -19,7 +18,7 @@ func TestDocumentTokensRepository_Create(t *testing.T) {
type args struct {
ctx context.Context
data types.DocumentTokenCreate
data DocumentTokenCreate
}
tests := []struct {
name string
@ -31,7 +30,7 @@ func TestDocumentTokensRepository_Create(t *testing.T) {
name: "create document token",
args: args{
ctx: context.Background(),
data: types.DocumentTokenCreate{
data: DocumentTokenCreate{
DocumentID: doc.ID,
TokenHash: []byte("token"),
ExpiresAt: expires,
@ -39,7 +38,9 @@ func TestDocumentTokensRepository_Create(t *testing.T) {
},
want: &ent.DocumentToken{
Edges: ent.DocumentTokenEdges{
Document: doc,
Document: &ent.Document{
ID: doc.ID,
},
},
Token: []byte("token"),
ExpiresAt: expires,
@ -50,7 +51,7 @@ func TestDocumentTokensRepository_Create(t *testing.T) {
name: "create document token with empty token",
args: args{
ctx: context.Background(),
data: types.DocumentTokenCreate{
data: DocumentTokenCreate{
DocumentID: doc.ID,
TokenHash: []byte(""),
ExpiresAt: expires,
@ -63,7 +64,7 @@ func TestDocumentTokensRepository_Create(t *testing.T) {
name: "create document token with empty document id",
args: args{
ctx: context.Background(),
data: types.DocumentTokenCreate{
data: DocumentTokenCreate{
DocumentID: uuid.Nil,
TokenHash: []byte("token"),
ExpiresAt: expires,
@ -94,18 +95,18 @@ func TestDocumentTokensRepository_Create(t *testing.T) {
return
}
assert.Equal(t, tt.want.Token, got.Token)
assert.Equal(t, tt.want.Token, got.TokenHash)
assert.WithinDuration(t, tt.want.ExpiresAt, got.ExpiresAt, time.Duration(1)*time.Second)
assert.Equal(t, tt.want.Edges.Document.ID, got.Edges.Document.ID)
assert.Equal(t, tt.want.Edges.Document.ID, got.DocumentID)
})
}
}
func useDocTokens(t *testing.T, num int) []*ent.DocumentToken {
func useDocTokens(t *testing.T, num int) []DocumentToken {
entity := useDocs(t, 1)[0]
results := make([]*ent.DocumentToken, 0, num)
results := make([]DocumentToken, 0, num)
ids := make([]uuid.UUID, 0, num)
t.Cleanup(func() {
@ -115,7 +116,7 @@ func useDocTokens(t *testing.T, num int) []*ent.DocumentToken {
})
for i := 0; i < num; i++ {
e, err := tRepos.DocTokens.Create(context.Background(), types.DocumentTokenCreate{
e, err := tRepos.DocTokens.Create(context.Background(), DocumentTokenCreate{
DocumentID: entity.ID,
TokenHash: []byte(fk.Str(10)),
ExpiresAt: fk.Time(),

View file

@ -2,46 +2,117 @@ package repo
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/pathlib"
)
var (
ErrInvalidDocExtension = errors.New("invalid document extension")
)
// DocumentRepository is a repository for Document entity
type DocumentRepository struct {
db *ent.Client
db *ent.Client
dir string
}
func (r *DocumentRepository) Create(ctx context.Context, gid uuid.UUID, doc types.DocumentCreate) (*ent.Document, error) {
return r.db.Document.Create().
type (
DocumentCreate struct {
Title string `json:"title"`
Content io.Reader `json:"content"`
}
DocumentOut struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
Path string `json:"path"`
}
)
func mapDocumentOut(doc *ent.Document) DocumentOut {
return DocumentOut{
ID: doc.ID,
Title: doc.Title,
Path: doc.Path,
}
}
var (
mapDocumentOutErr = mapTErrFunc(mapDocumentOut)
mapDocumentOutEachErr = mapTEachErrFunc(mapDocumentOut)
)
func (r *DocumentRepository) path(gid uuid.UUID, ext string) string {
return pathlib.Safe(filepath.Join(r.dir, gid.String(), "documents", uuid.NewString()+ext))
}
func (r *DocumentRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]DocumentOut, error) {
return mapDocumentOutEachErr(r.db.Document.
Query().
Where(document.HasGroupWith(group.ID(gid))).
All(ctx),
)
}
func (r *DocumentRepository) Get(ctx context.Context, id uuid.UUID) (DocumentOut, error) {
return mapDocumentOutErr(r.db.Document.Get(ctx, id))
}
func (r *DocumentRepository) Create(ctx context.Context, gid uuid.UUID, doc DocumentCreate) (DocumentOut, error) {
ext := filepath.Ext(doc.Title)
if ext == "" {
return DocumentOut{}, ErrInvalidDocExtension
}
path := r.path(gid, ext)
parent := filepath.Dir(path)
err := os.MkdirAll(parent, 0755)
if err != nil {
return DocumentOut{}, err
}
f, err := os.Create(path)
if err != nil {
return DocumentOut{}, err
}
_, err = io.Copy(f, doc.Content)
if err != nil {
return DocumentOut{}, err
}
return mapDocumentOutErr(r.db.Document.Create().
SetGroupID(gid).
SetTitle(doc.Title).
SetPath(doc.Path).
Save(ctx)
SetPath(path).
Save(ctx),
)
}
func (r *DocumentRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]*ent.Document, error) {
return r.db.Document.Query().
Where(document.HasGroupWith(group.ID(gid))).
All(ctx)
}
func (r *DocumentRepository) Get(ctx context.Context, id uuid.UUID) (*ent.Document, error) {
return r.db.Document.Query().
Where(document.ID(id)).
Only(ctx)
}
func (r *DocumentRepository) Update(ctx context.Context, id uuid.UUID, doc types.DocumentUpdate) (*ent.Document, error) {
return r.db.Document.UpdateOneID(id).
SetTitle(doc.Title).
SetPath(doc.Path).
Save(ctx)
func (r *DocumentRepository) Rename(ctx context.Context, id uuid.UUID, title string) (DocumentOut, error) {
return mapDocumentOutErr(r.db.Document.UpdateOneID(id).
SetTitle(title).
Save(ctx))
}
func (r *DocumentRepository) Delete(ctx context.Context, id uuid.UUID) error {
doc, err := r.db.Document.Get(ctx, id)
if err != nil {
return err
}
err = os.Remove(doc.Path)
if err != nil {
return err
}
return r.db.Document.DeleteOneID(id).Exec(ctx)
}

View file

@ -1,110 +1,28 @@
package repo
import (
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)
func TestDocumentRepository_Create(t *testing.T) {
type args struct {
ctx context.Context
gid uuid.UUID
doc types.DocumentCreate
}
tests := []struct {
name string
args args
want *ent.Document
wantErr bool
}{
{
name: "create document",
args: args{
ctx: context.Background(),
gid: tGroup.ID,
doc: types.DocumentCreate{
Title: "test document",
Path: "/test/document",
},
},
want: &ent.Document{
Title: "test document",
Path: "/test/document",
},
wantErr: false,
},
{
name: "create document with empty title",
args: args{
ctx: context.Background(),
gid: tGroup.ID,
doc: types.DocumentCreate{
Title: "",
Path: "/test/document",
},
},
want: nil,
wantErr: true,
},
{
name: "create document with empty path",
args: args{
ctx: context.Background(),
gid: tGroup.ID,
doc: types.DocumentCreate{
Title: "test document",
Path: "",
},
},
want: nil,
wantErr: true,
},
}
ids := make([]uuid.UUID, 0, len(tests))
t.Cleanup(func() {
for _, id := range ids {
err := tRepos.Docs.Delete(context.Background(), id)
assert.NoError(t, err)
}
})
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tRepos.Docs.Create(tt.args.ctx, tt.args.gid, tt.args.doc)
if (err != nil) != tt.wantErr {
t.Errorf("DocumentRepository.Create() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.wantErr {
assert.Error(t, err)
assert.Nil(t, got)
return
}
assert.Equal(t, tt.want.Title, got.Title)
assert.Equal(t, tt.want.Path, got.Path)
ids = append(ids, got.ID)
})
}
}
func useDocs(t *testing.T, num int) []*ent.Document {
func useDocs(t *testing.T, num int) []DocumentOut {
t.Helper()
results := make([]*ent.Document, 0, num)
results := make([]DocumentOut, 0, num)
ids := make([]uuid.UUID, 0, num)
for i := 0; i < num; i++ {
doc, err := tRepos.Docs.Create(context.Background(), tGroup.ID, types.DocumentCreate{
Title: fk.Str(10),
Path: fk.Path(),
doc, err := tRepos.Docs.Create(context.Background(), tGroup.ID, DocumentCreate{
Title: fk.Str(10) + ".md",
Content: bytes.NewReader([]byte(fk.Str(10))),
})
assert.NoError(t, err)
@ -126,77 +44,68 @@ func useDocs(t *testing.T, num int) []*ent.Document {
return results
}
func TestDocumentRepository_GetAll(t *testing.T) {
entities := useDocs(t, 10)
for _, entity := range entities {
assert.NotNil(t, entity)
func TestDocumentRepository_CreateUpdateDelete(t *testing.T) {
temp := t.TempDir()
r := DocumentRepository{
db: tClient,
dir: temp,
}
all, err := tRepos.Docs.GetAll(context.Background(), tGroup.ID)
assert.NoError(t, err)
type args struct {
ctx context.Context
gid uuid.UUID
doc DocumentCreate
}
tests := []struct {
name string
content string
args args
title string
wantErr bool
}{
{
name: "basic create",
title: "test.md",
content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
args: args{
ctx: context.Background(),
gid: tGroup.ID,
doc: DocumentCreate{
Title: "test.md",
Content: bytes.NewReader([]byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create Document
got, err := r.Create(tt.args.ctx, tt.args.gid, tt.args.doc)
assert.NoError(t, err)
assert.Equal(t, tt.title, got.Title)
assert.Equal(t, fmt.Sprintf("%s/%s/documents", temp, tt.args.gid), filepath.Dir(got.Path))
assert.Len(t, all, 10)
for _, entity := range all {
assert.NotNil(t, entity)
for _, e := range entities {
if e.ID == entity.ID {
assert.Equal(t, e.Title, entity.Title)
assert.Equal(t, e.Path, entity.Path)
ensureRead := func() {
// Read Document
bts, err := os.ReadFile(got.Path)
assert.NoError(t, err)
assert.Equal(t, tt.content, string(bts))
}
}
}
}
func TestDocumentRepository_Get(t *testing.T) {
entities := useDocs(t, 10)
for _, entity := range entities {
got, err := tRepos.Docs.Get(context.Background(), entity.ID)
assert.NoError(t, err)
assert.Equal(t, entity.ID, got.ID)
assert.Equal(t, entity.Title, got.Title)
assert.Equal(t, entity.Path, got.Path)
}
}
func TestDocumentRepository_Update(t *testing.T) {
entities := useDocs(t, 10)
for _, entity := range entities {
got, err := tRepos.Docs.Get(context.Background(), entity.ID)
assert.NoError(t, err)
assert.Equal(t, entity.ID, got.ID)
assert.Equal(t, entity.Title, got.Title)
assert.Equal(t, entity.Path, got.Path)
}
for _, entity := range entities {
updateData := types.DocumentUpdate{
Title: fk.Str(10),
Path: fk.Path(),
}
updated, err := tRepos.Docs.Update(context.Background(), entity.ID, updateData)
assert.NoError(t, err)
assert.Equal(t, entity.ID, updated.ID)
assert.Equal(t, updateData.Title, updated.Title)
assert.Equal(t, updateData.Path, updated.Path)
}
}
func TestDocumentRepository_Delete(t *testing.T) {
entities := useDocs(t, 10)
for _, entity := range entities {
err := tRepos.Docs.Delete(context.Background(), entity.ID)
assert.NoError(t, err)
_, err = tRepos.Docs.Get(context.Background(), entity.ID)
assert.Error(t, err)
ensureRead()
// Update Document
got, err = r.Rename(tt.args.ctx, got.ID, "__"+tt.title+"__")
assert.NoError(t, err)
assert.Equal(t, "__"+tt.title+"__", got.Title)
ensureRead()
// Delete Document
err = r.Delete(tt.args.ctx, got.ID)
assert.NoError(t, err)
_, err = os.Stat(got.Path)
assert.Error(t, err)
})
}
}

View file

@ -2,6 +2,7 @@ package repo
import (
"context"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
@ -16,6 +17,36 @@ type AttachmentRepo struct {
db *ent.Client
}
type (
ItemAttachment struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Type string `json:"type"`
Document DocumentOut `json:"document"`
}
ItemAttachmentUpdate struct {
ID uuid.UUID `json:"-"`
Type string `json:"type"`
Title string `json:"title"`
}
)
func ToItemAttachment(attachment *ent.Attachment) ItemAttachment {
return ItemAttachment{
ID: attachment.ID,
CreatedAt: attachment.CreatedAt,
UpdatedAt: attachment.UpdatedAt,
Type: attachment.Type.String(),
Document: DocumentOut{
ID: attachment.Edges.Document.ID,
Title: attachment.Edges.Document.Title,
Path: attachment.Edges.Document.Path,
},
}
}
func (r *AttachmentRepo) Create(ctx context.Context, itemId, docId uuid.UUID, typ attachment.Type) (*ent.Attachment, error) {
return r.db.Attachment.Create().
SetType(typ).

View file

@ -2,21 +2,187 @@ package repo
import (
"context"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/ent/predicate"
)
type ItemsRepository struct {
db *ent.Client
}
func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (*ent.Item, error) {
return e.db.Item.Query().
Where(item.ID(id)).
type (
ItemCreate struct {
ImportRef string `json:"-"`
Name string `json:"name"`
Description string `json:"description"`
// Edges
LocationID uuid.UUID `json:"locationId"`
LabelIDs []uuid.UUID `json:"labelIds"`
}
ItemUpdate struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Quantity int `json:"quantity"`
Insured bool `json:"insured"`
// Edges
LocationID uuid.UUID `json:"locationId"`
LabelIDs []uuid.UUID `json:"labelIds"`
// Identifications
SerialNumber string `json:"serialNumber"`
ModelNumber string `json:"modelNumber"`
Manufacturer string `json:"manufacturer"`
// Warranty
LifetimeWarranty bool `json:"lifetimeWarranty"`
WarrantyExpires time.Time `json:"warrantyExpires"`
WarrantyDetails string `json:"warrantyDetails"`
// Purchase
PurchaseTime time.Time `json:"purchaseTime"`
PurchaseFrom string `json:"purchaseFrom"`
PurchasePrice float64 `json:"purchasePrice,string"`
// Sold
SoldTime time.Time `json:"soldTime"`
SoldTo string `json:"soldTo"`
SoldPrice float64 `json:"soldPrice,string"`
SoldNotes string `json:"soldNotes"`
// Extras
Notes string `json:"notes"`
// Fields []*FieldSummary `json:"fields"`
}
ItemSummary struct {
ImportRef string `json:"-"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Quantity int `json:"quantity"`
Insured bool `json:"insured"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// Edges
Location LocationSummary `json:"location"`
Labels []LabelSummary `json:"labels"`
}
ItemOut struct {
ItemSummary
SerialNumber string `json:"serialNumber"`
ModelNumber string `json:"modelNumber"`
Manufacturer string `json:"manufacturer"`
// Warranty
LifetimeWarranty bool `json:"lifetimeWarranty"`
WarrantyExpires time.Time `json:"warrantyExpires"`
WarrantyDetails string `json:"warrantyDetails"`
// Purchase
PurchaseTime time.Time `json:"purchaseTime"`
PurchaseFrom string `json:"purchaseFrom"`
PurchasePrice float64 `json:"purchasePrice,string"`
// Sold
SoldTime time.Time `json:"soldTime"`
SoldTo string `json:"soldTo"`
SoldPrice float64 `json:"soldPrice,string"`
SoldNotes string `json:"soldNotes"`
// Extras
Notes string `json:"notes"`
Attachments []ItemAttachment `json:"attachments"`
// Future
// Fields []*FieldSummary `json:"fields"`
}
)
var (
mapItemsSummaryErr = mapTEachErrFunc(mapItemSummary)
)
func mapItemSummary(item *ent.Item) ItemSummary {
var location LocationSummary
if item.Edges.Location != nil {
location = mapLocationSummary(item.Edges.Location)
}
var labels []LabelSummary
if item.Edges.Label != nil {
labels = mapEach(item.Edges.Label, mapLabelSummary)
}
return ItemSummary{
ID: item.ID,
Name: item.Name,
Description: item.Description,
Quantity: item.Quantity,
CreatedAt: item.CreatedAt,
UpdatedAt: item.UpdatedAt,
// Edges
Location: location,
Labels: labels,
// Warranty
Insured: item.Insured,
}
}
var (
mapItemOutErr = mapTErrFunc(mapItemOut)
)
func mapItemOut(item *ent.Item) ItemOut {
var attachments []ItemAttachment
if item.Edges.Attachments != nil {
attachments = mapEach(item.Edges.Attachments, ToItemAttachment)
}
return ItemOut{
ItemSummary: mapItemSummary(item),
LifetimeWarranty: item.LifetimeWarranty,
WarrantyExpires: item.WarrantyExpires,
WarrantyDetails: item.WarrantyDetails,
// Identification
SerialNumber: item.SerialNumber,
ModelNumber: item.ModelNumber,
Manufacturer: item.Manufacturer,
// Purchase
PurchaseTime: item.PurchaseTime,
PurchaseFrom: item.PurchaseFrom,
PurchasePrice: item.PurchasePrice,
// Sold
SoldTime: item.SoldTime,
SoldTo: item.SoldTo,
SoldPrice: item.SoldPrice,
SoldNotes: item.SoldNotes,
// Extras
Notes: item.Notes,
Attachments: attachments,
}
}
func (e *ItemsRepository) getOne(ctx context.Context, where ...predicate.Item) (ItemOut, error) {
q := e.db.Item.Query().Where(where...)
return mapItemOutErr(q.
WithFields().
WithLabel().
WithLocation().
@ -24,19 +190,32 @@ func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (*ent.Item,
WithAttachments(func(aq *ent.AttachmentQuery) {
aq.WithDocument()
}).
Only(ctx)
Only(ctx),
)
}
// GetOne returns a single item by ID. If the item does not exist, an error is returned.
// See also: GetOneByGroup to ensure that the item belongs to a specific group.
func (e *ItemsRepository) GetOne(ctx context.Context, id uuid.UUID) (ItemOut, error) {
return e.getOne(ctx, item.ID(id))
}
// GetOneByGroup returns a single item by ID. If the item does not exist, an error is returned.
// GetOneByGroup ensures that the item belongs to a specific group.
func (e *ItemsRepository) GetOneByGroup(ctx context.Context, gid, id uuid.UUID) (ItemOut, error) {
return e.getOne(ctx, item.ID(id), item.HasGroupWith(group.ID(gid)))
}
// GetAll returns all the items in the database with the Labels and Locations eager loaded.
func (e *ItemsRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]*ent.Item, error) {
return e.db.Item.Query().
func (e *ItemsRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]ItemSummary, error) {
return mapItemsSummaryErr(e.db.Item.Query().
Where(item.HasGroupWith(group.ID(gid))).
WithLabel().
WithLocation().
All(ctx)
All(ctx))
}
func (e *ItemsRepository) Create(ctx context.Context, gid uuid.UUID, data types.ItemCreate) (*ent.Item, error) {
func (e *ItemsRepository) Create(ctx context.Context, gid uuid.UUID, data ItemCreate) (ItemOut, error) {
q := e.db.Item.Create().
SetName(data.Name).
SetDescription(data.Description).
@ -49,7 +228,7 @@ func (e *ItemsRepository) Create(ctx context.Context, gid uuid.UUID, data types.
result, err := q.Save(ctx)
if err != nil {
return nil, err
return ItemOut{}, err
}
return e.GetOne(ctx, result.ID)
@ -59,8 +238,18 @@ func (e *ItemsRepository) Delete(ctx context.Context, id uuid.UUID) error {
return e.db.Item.DeleteOneID(id).Exec(ctx)
}
func (e *ItemsRepository) Update(ctx context.Context, data types.ItemUpdate) (*ent.Item, error) {
q := e.db.Item.UpdateOneID(data.ID).
func (e *ItemsRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID) error {
_, err := e.db.Item.
Delete().
Where(
item.ID(id),
item.HasGroupWith(group.ID(gid)),
).Exec(ctx)
return err
}
func (e *ItemsRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data ItemUpdate) (ItemOut, error) {
q := e.db.Item.Update().Where(item.ID(data.ID), item.HasGroupWith(group.ID(gid))).
SetName(data.Name).
SetDescription(data.Description).
SetLocationID(data.LocationID).
@ -83,13 +272,13 @@ func (e *ItemsRepository) Update(ctx context.Context, data types.ItemUpdate) (*e
currentLabels, err := e.db.Item.Query().Where(item.ID(data.ID)).QueryLabel().All(ctx)
if err != nil {
return nil, err
return ItemOut{}, err
}
set := EntitiesToIDSet(currentLabels)
set := newIDSet(currentLabels)
for _, l := range data.LabelIDs {
if set.Has(l) {
if set.Contains(l) {
set.Remove(l)
continue
}
@ -102,7 +291,7 @@ func (e *ItemsRepository) Update(ctx context.Context, data types.ItemUpdate) (*e
err = q.Exec(ctx)
if err != nil {
return nil, err
return ItemOut{}, err
}
return e.GetOne(ctx, data.ID)

View file

@ -6,25 +6,23 @@ import (
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)
func itemFactory() types.ItemCreate {
return types.ItemCreate{
func itemFactory() ItemCreate {
return ItemCreate{
Name: fk.Str(10),
Description: fk.Str(100),
}
}
func useItems(t *testing.T, len int) []*ent.Item {
func useItems(t *testing.T, len int) []ItemOut {
t.Helper()
location, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
items := make([]*ent.Item, len)
items := make([]ItemOut, len)
for i := 0; i < len; i++ {
itm := itemFactory()
itm.LocationID = location.ID
@ -107,7 +105,7 @@ func TestItemsRepository_Create_Location(t *testing.T) {
foundItem, err := tRepos.Items.GetOne(context.Background(), result.ID)
assert.NoError(t, err)
assert.Equal(t, result.ID, foundItem.ID)
assert.Equal(t, location.ID, foundItem.Edges.Location.ID)
assert.Equal(t, location.ID, foundItem.Location.ID)
// Cleanup - Also deletes item
err = tRepos.Locations.Delete(context.Background(), location.ID)
@ -168,18 +166,18 @@ func TestItemsRepository_Update_Labels(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Apply all labels to entity
updateData := types.ItemUpdate{
updateData := ItemUpdate{
ID: entity.ID,
Name: entity.Name,
LocationID: entity.Edges.Location.ID,
LocationID: entity.Location.ID,
LabelIDs: tt.args.labelIds,
}
updated, err := tRepos.Items.Update(context.Background(), updateData)
updated, err := tRepos.Items.UpdateByGroup(context.Background(), tGroup.ID, updateData)
assert.NoError(t, err)
assert.Len(t, tt.want, len(updated.Edges.Label))
assert.Len(t, tt.want, len(updated.Labels))
for _, label := range updated.Edges.Label {
for _, label := range updated.Labels {
assert.Contains(t, tt.want, label.ID)
}
})
@ -192,10 +190,10 @@ func TestItemsRepository_Update(t *testing.T) {
entity := entities[0]
updateData := types.ItemUpdate{
updateData := ItemUpdate{
ID: entity.ID,
Name: entity.Name,
LocationID: entity.Edges.Location.ID,
LocationID: entity.Location.ID,
SerialNumber: fk.Str(10),
LabelIDs: nil,
ModelNumber: fk.Str(10),
@ -213,7 +211,7 @@ func TestItemsRepository_Update(t *testing.T) {
LifetimeWarranty: true,
}
updatedEntity, err := tRepos.Items.Update(context.Background(), updateData)
updatedEntity, err := tRepos.Items.UpdateByGroup(context.Background(), tGroup.ID, updateData)
assert.NoError(t, err)
got, err := tRepos.Items.GetOne(context.Background(), updatedEntity.ID)
@ -221,7 +219,7 @@ func TestItemsRepository_Update(t *testing.T) {
assert.Equal(t, updateData.ID, got.ID)
assert.Equal(t, updateData.Name, got.Name)
assert.Equal(t, updateData.LocationID, got.Edges.Location.ID)
assert.Equal(t, updateData.LocationID, got.Location.ID)
assert.Equal(t, updateData.SerialNumber, got.SerialNumber)
assert.Equal(t, updateData.ModelNumber, got.ModelNumber)
assert.Equal(t, updateData.Manufacturer, got.Manufacturer)

View file

@ -2,34 +2,94 @@ package repo
import (
"context"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/label"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/ent/predicate"
)
type LabelRepository struct {
db *ent.Client
}
type (
LabelCreate struct {
Name string `json:"name"`
Description string `json:"description"`
Color string `json:"color"`
}
func (r *LabelRepository) Get(ctx context.Context, ID uuid.UUID) (*ent.Label, error) {
return r.db.Label.Query().
Where(label.ID(ID)).
LabelUpdate struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Color string `json:"color"`
}
LabelSummary struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
LabelOut struct {
LabelSummary
Items []ItemSummary `json:"items"`
}
)
func mapLabelSummary(label *ent.Label) LabelSummary {
return LabelSummary{
ID: label.ID,
Name: label.Name,
Description: label.Description,
CreatedAt: label.CreatedAt,
UpdatedAt: label.UpdatedAt,
}
}
var (
mapLabelOutErr = mapTErrFunc(mapLabelOut)
mapLabelsOut = mapTEachErrFunc(mapLabelSummary)
)
func mapLabelOut(label *ent.Label) LabelOut {
return LabelOut{
LabelSummary: mapLabelSummary(label),
Items: mapEach(label.Edges.Items, mapItemSummary),
}
}
func (r *LabelRepository) getOne(ctx context.Context, where ...predicate.Label) (LabelOut, error) {
return mapLabelOutErr(r.db.Label.Query().
Where(where...).
WithGroup().
WithItems().
Only(ctx)
Only(ctx),
)
}
func (r *LabelRepository) GetAll(ctx context.Context, groupId uuid.UUID) ([]*ent.Label, error) {
return r.db.Label.Query().
func (r *LabelRepository) GetOne(ctx context.Context, ID uuid.UUID) (LabelOut, error) {
return r.getOne(ctx, label.ID(ID))
}
func (r *LabelRepository) GetOneByGroup(ctx context.Context, gid, ld uuid.UUID) (LabelOut, error) {
return r.getOne(ctx, label.ID(ld), label.HasGroupWith(group.ID(gid)))
}
func (r *LabelRepository) GetAll(ctx context.Context, groupId uuid.UUID) ([]LabelSummary, error) {
return mapLabelsOut(r.db.Label.Query().
Where(label.HasGroupWith(group.ID(groupId))).
WithGroup().
All(ctx)
All(ctx),
)
}
func (r *LabelRepository) Create(ctx context.Context, groupdId uuid.UUID, data types.LabelCreate) (*ent.Label, error) {
func (r *LabelRepository) Create(ctx context.Context, groupdId uuid.UUID, data LabelCreate) (LabelOut, error) {
label, err := r.db.Label.Create().
SetName(data.Name).
SetDescription(data.Description).
@ -37,11 +97,15 @@ func (r *LabelRepository) Create(ctx context.Context, groupdId uuid.UUID, data t
SetGroupID(groupdId).
Save(ctx)
if err != nil {
return LabelOut{}, err
}
label.Edges.Group = &ent.Group{ID: groupdId} // bootstrap group ID
return label, err
return mapLabelOut(label), err
}
func (r *LabelRepository) Update(ctx context.Context, data types.LabelUpdate) (*ent.Label, error) {
func (r *LabelRepository) Update(ctx context.Context, data LabelUpdate) (LabelOut, error) {
_, err := r.db.Label.UpdateOneID(data.ID).
SetName(data.Name).
SetDescription(data.Description).
@ -49,10 +113,10 @@ func (r *LabelRepository) Update(ctx context.Context, data types.LabelUpdate) (*
Save(ctx)
if err != nil {
return nil, err
return LabelOut{}, err
}
return r.Get(ctx, data.ID)
return r.GetOne(ctx, data.ID)
}
func (r *LabelRepository) Delete(ctx context.Context, id uuid.UUID) error {

View file

@ -4,22 +4,20 @@ import (
"context"
"testing"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)
func labelFactory() types.LabelCreate {
return types.LabelCreate{
func labelFactory() LabelCreate {
return LabelCreate{
Name: fk.Str(10),
Description: fk.Str(100),
}
}
func useLabels(t *testing.T, len int) []*ent.Label {
func useLabels(t *testing.T, len int) []LabelOut {
t.Helper()
labels := make([]*ent.Label, len)
labels := make([]LabelOut, len)
for i := 0; i < len; i++ {
itm := labelFactory()
@ -42,7 +40,7 @@ func TestLabelRepository_Get(t *testing.T) {
label := labels[0]
// Get by ID
foundLoc, err := tRepos.Labels.Get(context.Background(), label.ID)
foundLoc, err := tRepos.Labels.GetOne(context.Background(), label.ID)
assert.NoError(t, err)
assert.Equal(t, label.ID, foundLoc.ID)
}
@ -60,7 +58,7 @@ func TestLabelRepository_Create(t *testing.T) {
assert.NoError(t, err)
// Get by ID
foundLoc, err := tRepos.Labels.Get(context.Background(), loc.ID)
foundLoc, err := tRepos.Labels.GetOne(context.Background(), loc.ID)
assert.NoError(t, err)
assert.Equal(t, loc.ID, foundLoc.ID)
@ -72,7 +70,7 @@ func TestLabelRepository_Update(t *testing.T) {
loc, err := tRepos.Labels.Create(context.Background(), tGroup.ID, labelFactory())
assert.NoError(t, err)
updateData := types.LabelUpdate{
updateData := LabelUpdate{
ID: loc.ID,
Name: fk.Str(10),
Description: fk.Str(100),
@ -81,7 +79,7 @@ func TestLabelRepository_Update(t *testing.T) {
update, err := tRepos.Labels.Update(context.Background(), updateData)
assert.NoError(t, err)
foundLoc, err := tRepos.Labels.Get(context.Background(), loc.ID)
foundLoc, err := tRepos.Labels.GetOne(context.Background(), loc.ID)
assert.NoError(t, err)
assert.Equal(t, update.ID, foundLoc.ID)
@ -99,6 +97,6 @@ func TestLabelRepository_Delete(t *testing.T) {
err = tRepos.Labels.Delete(context.Background(), loc.ID)
assert.NoError(t, err)
_, err = tRepos.Labels.Get(context.Background(), loc.ID)
_, err = tRepos.Labels.GetOne(context.Background(), loc.ID)
assert.Error(t, err)
}

View file

@ -2,24 +2,79 @@ package repo
import (
"context"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/location"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/ent/predicate"
)
type LocationRepository struct {
db *ent.Client
}
type LocationWithCount struct {
*ent.Location
ItemCount int `json:"itemCount"`
type (
LocationCreate struct {
Name string `json:"name"`
Description string `json:"description"`
}
LocationUpdate struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
}
LocationSummary struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
LocationOutCount struct {
LocationSummary
ItemCount int `json:"itemCount"`
}
LocationOut struct {
LocationSummary
Items []ItemSummary `json:"items"`
}
)
func mapLocationSummary(location *ent.Location) LocationSummary {
return LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
}
}
var (
mapLocationOutErr = mapTErrFunc(mapLocationOut)
)
func mapLocationOut(location *ent.Location) LocationOut {
return LocationOut{
LocationSummary: LocationSummary{
ID: location.ID,
Name: location.Name,
Description: location.Description,
CreatedAt: location.CreatedAt,
UpdatedAt: location.UpdatedAt,
},
Items: mapEach(location.Edges.Items, mapItemSummary),
}
}
// GetALlWithCount returns all locations with item count field populated
func (r *LocationRepository) GetAll(ctx context.Context, groupId uuid.UUID) ([]LocationWithCount, error) {
func (r *LocationRepository) GetAll(ctx context.Context, groupId uuid.UUID) ([]LocationOutCount, error) {
query := `--sql
SELECT
id,
@ -46,54 +101,62 @@ func (r *LocationRepository) GetAll(ctx context.Context, groupId uuid.UUID) ([]L
return nil, err
}
list := []LocationWithCount{}
list := []LocationOutCount{}
for rows.Next() {
var loc ent.Location
var ct LocationWithCount
err := rows.Scan(&loc.ID, &loc.Name, &loc.Description, &loc.CreatedAt, &loc.UpdatedAt, &ct.ItemCount)
var ct LocationOutCount
err := rows.Scan(&ct.ID, &ct.Name, &ct.Description, &ct.CreatedAt, &ct.UpdatedAt, &ct.ItemCount)
if err != nil {
return nil, err
}
ct.Location = &loc
list = append(list, ct)
}
return list, err
}
func (r *LocationRepository) Get(ctx context.Context, ID uuid.UUID) (*ent.Location, error) {
return r.db.Location.Query().
Where(location.ID(ID)).
func (r *LocationRepository) getOne(ctx context.Context, where ...predicate.Location) (LocationOut, error) {
return mapLocationOutErr(r.db.Location.Query().
Where(where...).
WithGroup().
WithItems(func(iq *ent.ItemQuery) {
iq.WithLabel()
}).
Only(ctx)
Only(ctx))
}
func (r *LocationRepository) Create(ctx context.Context, groupdId uuid.UUID, data types.LocationCreate) (*ent.Location, error) {
func (r *LocationRepository) Get(ctx context.Context, ID uuid.UUID) (LocationOut, error) {
return r.getOne(ctx, location.ID(ID))
}
func (r *LocationRepository) GetOneByGroup(ctx context.Context, GID, ID uuid.UUID) (LocationOut, error) {
return r.getOne(ctx, location.ID(ID), location.HasGroupWith(group.ID(GID)))
}
func (r *LocationRepository) Create(ctx context.Context, gid uuid.UUID, data LocationCreate) (LocationOut, error) {
location, err := r.db.Location.Create().
SetName(data.Name).
SetDescription(data.Description).
SetGroupID(groupdId).
SetGroupID(gid).
Save(ctx)
if err != nil {
return nil, err
return LocationOut{}, err
}
location.Edges.Group = &ent.Group{ID: groupdId} // bootstrap group ID
return location, err
location.Edges.Group = &ent.Group{ID: gid} // bootstrap group ID
return mapLocationOut(location), nil
}
func (r *LocationRepository) Update(ctx context.Context, data types.LocationUpdate) (*ent.Location, error) {
func (r *LocationRepository) Update(ctx context.Context, data LocationUpdate) (LocationOut, error) {
_, err := r.db.Location.UpdateOneID(data.ID).
SetName(data.Name).
SetDescription(data.Description).
Save(ctx)
if err != nil {
return nil, err
return LocationOut{}, err
}
return r.Get(ctx, data.ID)

View file

@ -4,12 +4,11 @@ import (
"context"
"testing"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)
func locationFactory() types.LocationCreate {
return types.LocationCreate{
func locationFactory() LocationCreate {
return LocationCreate{
Name: fk.Str(10),
Description: fk.Str(100),
}
@ -30,13 +29,13 @@ func TestLocationRepository_Get(t *testing.T) {
func TestLocationRepositoryGetAllWithCount(t *testing.T) {
ctx := context.Background()
result, err := tRepos.Locations.Create(ctx, tGroup.ID, types.LocationCreate{
result, err := tRepos.Locations.Create(ctx, tGroup.ID, LocationCreate{
Name: fk.Str(10),
Description: fk.Str(100),
})
assert.NoError(t, err)
_, err = tRepos.Items.Create(ctx, tGroup.ID, types.ItemCreate{
_, err = tRepos.Items.Create(ctx, tGroup.ID, ItemCreate{
Name: fk.Str(10),
Description: fk.Str(100),
LocationID: result.ID,
@ -72,7 +71,7 @@ func TestLocationRepository_Update(t *testing.T) {
loc, err := tRepos.Locations.Create(context.Background(), tGroup.ID, locationFactory())
assert.NoError(t, err)
updateData := types.LocationUpdate{
updateData := LocationUpdate{
ID: loc.ID,
Name: fk.Str(10),
Description: fk.Str(100),

View file

@ -4,17 +4,34 @@ import (
"context"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/authtokens"
"github.com/hay-kot/homebox/backend/internal/types"
)
type TokenRepository struct {
db *ent.Client
}
type (
UserAuthTokenCreate struct {
TokenHash []byte `json:"token"`
UserID uuid.UUID `json:"userId"`
ExpiresAt time.Time `json:"expiresAt"`
}
UserAuthToken struct {
UserAuthTokenCreate
CreatedAt time.Time `json:"createdAt"`
}
)
func (u UserAuthToken) IsExpired() bool {
return u.ExpiresAt.Before(time.Now())
}
// GetUserFromToken get's a user from a token
func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (*ent.User, error) {
func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (UserOut, error) {
user, err := r.db.AuthTokens.Query().
Where(authtokens.Token(token)).
Where(authtokens.ExpiresAtGTE(time.Now())).
@ -24,15 +41,14 @@ func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (*
Only(ctx)
if err != nil {
return nil, err
return UserOut{}, err
}
return user, nil
return mapUserOut(user), nil
}
// Creates a token for a user
func (r *TokenRepository) CreateToken(ctx context.Context, createToken types.UserAuthTokenCreate) (types.UserAuthToken, error) {
tokenOut := types.UserAuthToken{}
func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthTokenCreate) (UserAuthToken, error) {
dbToken, err := r.db.AuthTokens.Create().
SetToken(createToken.TokenHash).
@ -41,15 +57,17 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken types.Use
Save(ctx)
if err != nil {
return tokenOut, err
return UserAuthToken{}, err
}
tokenOut.TokenHash = dbToken.Token
tokenOut.UserID = createToken.UserID
tokenOut.CreatedAt = dbToken.CreatedAt
tokenOut.ExpiresAt = dbToken.ExpiresAt
return tokenOut, nil
return UserAuthToken{
UserAuthTokenCreate: UserAuthTokenCreate{
TokenHash: dbToken.Token,
UserID: createToken.UserID,
ExpiresAt: dbToken.ExpiresAt,
},
CreatedAt: dbToken.CreatedAt,
}, nil
}
// DeleteToken remove a single token from the database - equivalent to revoke or logout

View file

@ -5,7 +5,6 @@ import (
"testing"
"time"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/hay-kot/homebox/backend/pkgs/hasher"
"github.com/stretchr/testify/assert"
)
@ -22,7 +21,7 @@ func TestAuthTokenRepo_CreateToken(t *testing.T) {
generatedToken := hasher.GenerateToken()
token, err := tRepos.AuthTokens.CreateToken(ctx, types.UserAuthTokenCreate{
token, err := tRepos.AuthTokens.CreateToken(ctx, UserAuthTokenCreate{
TokenHash: generatedToken.Hash,
ExpiresAt: expiresAt,
UserID: userOut.ID,
@ -50,7 +49,7 @@ func TestAuthTokenRepo_DeleteToken(t *testing.T) {
generatedToken := hasher.GenerateToken()
_, err = tRepos.AuthTokens.CreateToken(ctx, types.UserAuthTokenCreate{
_, err = tRepos.AuthTokens.CreateToken(ctx, UserAuthTokenCreate{
TokenHash: generatedToken.Hash,
ExpiresAt: expiresAt,
UserID: userOut.ID,
@ -72,7 +71,7 @@ func TestAuthTokenRepo_GetUserByToken(t *testing.T) {
expiresAt := time.Now().Add(time.Hour)
generatedToken := hasher.GenerateToken()
token, err := tRepos.AuthTokens.CreateToken(ctx, types.UserAuthTokenCreate{
token, err := tRepos.AuthTokens.CreateToken(ctx, UserAuthTokenCreate{
TokenHash: generatedToken.Hash,
ExpiresAt: expiresAt,
UserID: userOut.ID,
@ -101,13 +100,13 @@ func TestAuthTokenRepo_PurgeExpiredTokens(t *testing.T) {
user := userFactory()
userOut, _ := tRepos.Users.Create(ctx, user)
createdTokens := []types.UserAuthToken{}
createdTokens := []UserAuthToken{}
for i := 0; i < 5; i++ {
expiresAt := time.Now()
generatedToken := hasher.GenerateToken()
createdToken, err := tRepos.AuthTokens.CreateToken(ctx, types.UserAuthTokenCreate{
createdToken, err := tRepos.AuthTokens.CreateToken(ctx, UserAuthTokenCreate{
TokenHash: generatedToken.Hash,
ExpiresAt: expiresAt,
UserID: userOut.ID,

View file

@ -6,37 +6,77 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/user"
"github.com/hay-kot/homebox/backend/internal/types"
)
type UserRepository struct {
db *ent.Client
}
func (e *UserRepository) GetOneId(ctx context.Context, id uuid.UUID) (*ent.User, error) {
return e.db.User.Query().
Where(user.ID(id)).
WithGroup().
Only(ctx)
}
func (e *UserRepository) GetOneEmail(ctx context.Context, email string) (*ent.User, error) {
return e.db.User.Query().
Where(user.Email(email)).
WithGroup().
Only(ctx)
}
func (e *UserRepository) GetAll(ctx context.Context) ([]*ent.User, error) {
return e.db.User.Query().WithGroup().All(ctx)
}
func (e *UserRepository) Create(ctx context.Context, usr types.UserCreate) (*ent.User, error) {
err := usr.Validate()
if err != nil {
return &ent.User{}, err
type (
// UserCreate is the Data object contain the requirements of creating a user
// in the database. It should to create users from an API unless the user has
// rights to create SuperUsers. For regular user in data use the UserIn struct.
UserCreate struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
IsSuperuser bool `json:"isSuperuser"`
GroupID uuid.UUID `json:"groupID"`
}
UserUpdate struct {
Name string `json:"name"`
Email string `json:"email"`
}
UserOut struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
IsSuperuser bool `json:"isSuperuser"`
GroupID uuid.UUID `json:"groupId"`
GroupName string `json:"groupName"`
PasswordHash string `json:"-"`
}
)
var (
mapUserOutErr = mapTErrFunc(mapUserOut)
mapUsersOutErr = mapTEachErrFunc(mapUserOut)
)
func mapUserOut(user *ent.User) UserOut {
return UserOut{
ID: user.ID,
Name: user.Name,
Email: user.Email,
IsSuperuser: user.IsSuperuser,
GroupID: user.Edges.Group.ID,
GroupName: user.Edges.Group.Name,
PasswordHash: user.Password,
}
}
func (e *UserRepository) GetOneId(ctx context.Context, id uuid.UUID) (UserOut, error) {
return mapUserOutErr(e.db.User.Query().
Where(user.ID(id)).
WithGroup().
Only(ctx))
}
func (e *UserRepository) GetOneEmail(ctx context.Context, email string) (UserOut, error) {
return mapUserOutErr(e.db.User.Query().
Where(user.Email(email)).
WithGroup().
Only(ctx),
)
}
func (e *UserRepository) GetAll(ctx context.Context) ([]UserOut, error) {
return mapUsersOutErr(e.db.User.Query().WithGroup().All(ctx))
}
func (e *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, error) {
entUser, err := e.db.User.
Create().
SetName(usr.Name).
@ -46,13 +86,13 @@ func (e *UserRepository) Create(ctx context.Context, usr types.UserCreate) (*ent
SetGroupID(usr.GroupID).
Save(ctx)
if err != nil {
return entUser, err
return UserOut{}, err
}
return e.GetOneId(ctx, entUser.ID)
}
func (e *UserRepository) Update(ctx context.Context, ID uuid.UUID, data types.UserUpdate) error {
func (e *UserRepository) Update(ctx context.Context, ID uuid.UUID, data UserUpdate) error {
q := e.db.User.Update().
Where(user.ID(ID)).
SetName(data.Name).

View file

@ -5,14 +5,11 @@ import (
"fmt"
"testing"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/internal/types"
"github.com/stretchr/testify/assert"
)
func userFactory() types.UserCreate {
return types.UserCreate{
func userFactory() UserCreate {
return UserCreate{
Name: fk.Str(10),
Email: fk.Email(),
Password: fk.Str(10),
@ -61,7 +58,7 @@ func TestUserRepo_GetOneId(t *testing.T) {
func TestUserRepo_GetAll(t *testing.T) {
// Setup
toCreate := []types.UserCreate{
toCreate := []UserCreate{
userFactory(),
userFactory(),
userFactory(),
@ -70,7 +67,7 @@ func TestUserRepo_GetAll(t *testing.T) {
ctx := context.Background()
created := []*ent.User{}
created := []UserOut{}
for _, usr := range toCreate {
usrOut, _ := tRepos.Users.Create(ctx, usr)
@ -90,7 +87,7 @@ func TestUserRepo_GetAll(t *testing.T) {
assert.Equal(t, usr.Email, usr2.Email)
// Check groups are loaded
assert.NotNil(t, usr2.Edges.Group)
assert.NotNil(t, usr2.GroupID)
}
}
}
@ -108,7 +105,7 @@ func TestUserRepo_Update(t *testing.T) {
user, err := tRepos.Users.Create(context.Background(), userFactory())
assert.NoError(t, err)
updateData := types.UserUpdate{
updateData := UserUpdate{
Name: fk.Str(10),
Email: fk.Email(),
}

View file

@ -15,7 +15,7 @@ type AllRepos struct {
Attachments *AttachmentRepo
}
func EntAllRepos(db *ent.Client) *AllRepos {
func EntAllRepos(db *ent.Client, root string) *AllRepos {
return &AllRepos{
Users: &UserRepository{db},
AuthTokens: &TokenRepository{db},
@ -23,7 +23,7 @@ func EntAllRepos(db *ent.Client) *AllRepos {
Locations: &LocationRepository{db},
Labels: &LabelRepository{db},
Items: &ItemsRepository{db},
Docs: &DocumentRepository{db},
Docs: &DocumentRepository{db, root},
DocTokens: &DocumentTokensRepository{db},
Attachments: &AttachmentRepo{db},
}