🗃️ Simplify Resource creation in static repository

This commit is contained in:
Maxim Lebedev 2023-11-10 09:06:46 +06:00
parent d2a7e3beb5
commit e35053f2d0
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
1 changed files with 21 additions and 40 deletions

View File

@ -1,17 +1,13 @@
package fs
import (
"bytes"
"context"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"io/fs"
"path/filepath"
"strings"
_ "golang.org/x/image/bmp"
_ "golang.org/x/image/webp"
@ -33,7 +29,7 @@ func NewFileServerStaticRepository(root fs.FS) static.Repository {
func (repo *fileServerStaticRepository) Get(ctx context.Context, p string) (*domain.Resource, error) {
info, err := fs.Stat(repo.root, p)
if err != nil {
return nil, fmt.Errorf("cannot read static info on path '%s': %w", p, err)
return nil, fmt.Errorf("cannot stat static on path '%s': %w", p, err)
}
f, err := repo.root.Open(p)
@ -47,46 +43,31 @@ func (repo *fileServerStaticRepository) Get(ctx context.Context, p string) (*dom
return nil, fmt.Errorf("cannot read static content on path '%s': %w", p, err)
}
out := &domain.Resource{
Path: p,
Updated: info.ModTime(),
Content: content,
}
parts := strings.Split(out.MediaType(), "/")
if len(parts) < 2 || parts[0] != "image" {
return out, nil
}
config, _, err := image.DecodeConfig(bytes.NewReader(content))
if err != nil {
return out, nil
}
out.Width, out.Height = config.Width, config.Height
return out, nil
return domain.NewResource(info.ModTime(), content, p), nil
}
func (repo *fileServerStaticRepository) Fetch(ctx context.Context, d string) (domain.Resources, int, error) {
entries, err := fs.ReadDir(repo.root, d)
if err != nil {
return nil, 0, fmt.Errorf("cannot read directory on path '%s': %w", d, err)
func (repo *fileServerStaticRepository) Fetch(ctx context.Context, dir string) (domain.Resources, int, error) {
targets := make([]string, 0)
if err := fs.WalkDir(repo.root, dir, func(path string, de fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("received error while walking through '%s': %w", dir, err)
}
if de.IsDir() {
return nil
}
targets = append(targets, path)
return nil
}); err != nil {
return nil, 0, fmt.Errorf("cannot read directory on path '%s': %w", dir, err)
}
out := make(domain.Resources, 0, len(entries))
out := make(domain.Resources, len(targets))
for _, entry := range entries {
if entry.IsDir() {
continue
}
f, err := repo.Get(ctx, filepath.Join(d, entry.Name()))
if err != nil {
continue
}
out = append(out, f)
for i := range targets {
out[i], _ = repo.Get(ctx, targets[i])
}
return out, len(out), nil