summaryrefslogtreecommitdiff
path: root/pkg/db/client.go
blob: 4f43403d89a3f3b50426d1b2bddd2a178da359b9 (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
package db

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/xlgmokha/x/pkg/env"
	"github.com/xlgmokha/x/pkg/serde"
	"github.com/xlgmokha/x/pkg/x"
)

type Paramable interface {
	ToParam() string
}

type Storage[T Paramable] struct {
	dir string
}

func New[T Paramable](dir string) *Storage[T] {
	fullPath := x.Must(filepath.Abs(dir))
	x.Check(os.MkdirAll(fullPath, 0700))

	return &Storage[T]{
		dir: fullPath,
	}
}

func (db *Storage[T]) Save(item T) error {
	w := new(bytes.Buffer)
	x.Check(serde.To(w, item, serde.YAML))
	if env.Fetch("DUMP", "") != "" {
		fmt.Println(w.String())
	}
	return ioutil.WriteFile(
		fmt.Sprintf("%v/%v.yaml", db.dir, item.ToParam()),
		w.Bytes(),
		0700,
	)
}