Add dependency injection

This commit is contained in:
Archer Fox
2025-03-10 22:20:06 +03:00
parent 91e54c1674
commit 699be23766
3 changed files with 55 additions and 31 deletions

View File

@@ -14,27 +14,41 @@ type Vault struct {
UpdatedAt time.Time `json:"updatedAt"`
}
func NewVault() *Vault {
file, err := files.FileRead("data.json")
type VaultWithDb struct {
Vault
db files.JsonDb
}
func NewVault(db *files.JsonDb) *VaultWithDb {
file, err := db.Read()
if err != nil {
return &Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
return &VaultWithDb{
Vault: Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
},
db: *db,
}
}
var vault Vault
err = json.Unmarshal(file, &vault)
if err != nil {
color.Red("Не удалось разобрать файл data.json")
return &Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
return &VaultWithDb{
Vault: Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
},
db: *db,
}
}
return &vault
return &VaultWithDb{
Vault: vault,
db: *db,
}
}
func (vault *Vault) AddAccount(acc Account) {
func (vault *VaultWithDb) AddAccount(acc Account) {
vault.Accounts = append(vault.Accounts, acc)
vault.save()
}
@@ -47,7 +61,7 @@ func (vault *Vault) ToBytes() ([]byte, error) {
return file, nil
}
func (vault *Vault) FindAccountsByUrl(url string) []Account {
func (vault *VaultWithDb) FindAccountsByUrl(url string) []Account {
var accounts []Account
for _, account := range vault.Accounts {
isMatched := strings.Contains(account.Url, url)
@@ -58,7 +72,7 @@ func (vault *Vault) FindAccountsByUrl(url string) []Account {
return accounts
}
func (vault *Vault) DeleteAccountByUrl(url string) bool {
func (vault *VaultWithDb) DeleteAccountByUrl(url string) bool {
var accounts []Account
isDeleted := false
for _, account := range vault.Accounts {
@@ -74,11 +88,11 @@ func (vault *Vault) DeleteAccountByUrl(url string) bool {
return isDeleted
}
func (vault *Vault) save() {
func (vault *VaultWithDb) save() {
vault.UpdatedAt = time.Now()
data, err := vault.ToBytes()
data, err := vault.Vault.ToBytes()
if err != nil {
color.Red("Не удалось преобразовать")
}
files.FileWrite(data, "data.json")
vault.db.Write(data)
}