Added type inference

This commit is contained in:
Eduard Urbach 2023-07-06 15:02:50 +02:00
parent af35cde2d8
commit 11b4ae49ca
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
3 changed files with 11 additions and 8 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
)
@ -26,6 +27,7 @@ type collection[T any] struct {
// New creates a new collection with the given name.
func New[T any](directories ...string) (*collection[T], error) {
name := reflect.TypeOf(*new(T)).Name()
home, err := os.UserHomeDir()
if err != nil {
@ -33,6 +35,7 @@ func New[T any](directories ...string) (*collection[T], error) {
}
directories = append([]string{home, ".ocean"}, directories...)
directories = append(directories, name)
directory := filepath.Join(directories...)
err = os.MkdirAll(directory, 0700)

View File

@ -12,7 +12,7 @@ type User struct {
}
func TestCollectionGet(t *testing.T) {
users, err := ocean.New[User]("test", "User")
users, err := ocean.New[User]("test")
assert.Nil(t, err)
defer users.Clear()
@ -24,7 +24,7 @@ func TestCollectionGet(t *testing.T) {
}
func TestInteraction(t *testing.T) {
users, err := ocean.New[User]("test", "User")
users, err := ocean.New[User]("test")
assert.Nil(t, err)
defer users.Clear()
@ -53,7 +53,7 @@ func TestInteraction(t *testing.T) {
}
func TestCollectionAll(t *testing.T) {
users, err := ocean.New[User]("test", "User")
users, err := ocean.New[User]("test")
assert.Nil(t, err)
defer users.Clear()

View File

@ -20,13 +20,13 @@ type User struct {
Name string
}
// Data saved to ~/.ocean/User/
users := ocean.New[User]("User")
// Load existing data from ~/.ocean/User/
users := ocean.New[User]()
// Store key and value in memory and write ~/.ocean/User/1.json
// Store in memory and also store in ~/.ocean/User/1.json
users.Set("1", &User{Name: "User 1"})
// Read value from memory
// Read from memory
user, err := users.Get("1")
```
@ -34,7 +34,7 @@ In a real project you would usually prefix your collections with a project or co
```go
// Data saved to ~/.ocean/google/User/
users := ocean.New[User]("google", "User")
users := ocean.New[User]("google")
```
## Recommended structure