aboutsummaryrefslogtreecommitdiff
path: root/internal/image/service.go
blob: dabbfe71a49047db52177f89e42b31906bdc9710 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package image

import (
	"io/ioutil"
	"log"
	"path"
	"time"

	"github.com/matoous/go-nanoid"
)

// Servicer image management
type Servicer interface {
	NewID() (string, error)
	AddFile(filename string, fileBytes []byte) error
}

// NewService new image service
func NewService(repo Repo, storagePath string) *Service {
	return &Service{repo,
		storagePath,
	}
}

// Service a container for working with images
type Service struct {
	db          Repo
	storagePath string
}

// NewID create an uniqueish ID
func (is *Service) NewID() (string, error) {
	return gonanoid.Nanoid()
}

// AddFile writes to disk, writes meta to db
func (is *Service) AddFile(fileName string, fileBytes []byte) error {
	filePath := path.Join(is.storagePath, fileName)
	if err := ioutil.WriteFile(filePath, fileBytes, 0750); err != nil {
		log.Fatal(err)
		return err
	}
	t := time.Now().UTC()
	postMeta := &PostMeta{
		FilePath:  fileName,
		CreatedAt: t.Format(time.RFC3339),
		UserID:    "1",
	}
	is.db.AddNewFile(fileName, postMeta, 946080000)
	if err := is.db.AddNewFile(fileName, postMeta, 946080000); err != nil {
		log.Fatal(err)
		return err
	}
	return nil
}