-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5c1b55b
commit b27622d
Showing
3 changed files
with
125 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
package db | ||
|
||
import ( | ||
"encoding/json" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
type ChatInfo struct { | ||
ChatID int64 | ||
} | ||
|
||
type DB struct { | ||
path string | ||
chatsIDs map[int64]ChatInfo | ||
} | ||
|
||
// NewDB open and load db if exist, or create new one if not exist | ||
func NewDB(path string) (DB, error) { | ||
if err := os.MkdirAll(path, 0777); err != nil { | ||
return DB{}, err | ||
} | ||
|
||
chatsIDs := make(map[int64]ChatInfo) | ||
path = filepath.Join(path, "db.json") | ||
|
||
data, err := os.ReadFile(path) | ||
if os.IsNotExist(err) || len(data) == 0 { | ||
return DB{ | ||
path: path, | ||
chatsIDs: chatsIDs, | ||
}, nil | ||
} | ||
if err != nil { | ||
return DB{}, err | ||
} | ||
|
||
if err := json.Unmarshal(data, &chatsIDs); err != nil { | ||
return DB{}, err | ||
} | ||
|
||
return DB{ | ||
path: path, | ||
chatsIDs: chatsIDs, | ||
}, nil | ||
} | ||
|
||
func (db *DB) Save() error { | ||
file, err := json.MarshalIndent(db.chatsIDs, "", " ") | ||
if err != nil { | ||
return err | ||
} | ||
|
||
err = os.WriteFile(db.path, file, 0777) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (db *DB) Get(key int64) ChatInfo { | ||
val, ok := db.chatsIDs[key] | ||
if !ok { | ||
return ChatInfo{} | ||
} | ||
return val | ||
} | ||
|
||
func (db *DB) Update(key int64, value ChatInfo) { | ||
db.chatsIDs[key] = value | ||
} | ||
|
||
func (db *DB) Delete(key int64) { | ||
delete(db.chatsIDs, key) | ||
} | ||
|
||
func (db *DB) List() []ChatInfo { | ||
chatsInfo := make([]ChatInfo, 0, len(db.chatsIDs)) | ||
for _, val := range db.chatsIDs { | ||
chatsInfo = append(chatsInfo, val) | ||
} | ||
return chatsInfo | ||
} |