Skip to main content

Persist an InMemory Repository

warning

This is only recommended while prototyping and to run local demos not for production use.

Persist Repository

main.go
package main

import (
"context"
"os"

"github.com/brianvoe/gofakeit/v6"
"github.com/google/uuid"

"github.com/go-arrower/arrower/repository"
)

type (
EntityID string

Entity struct {
ID EntityID
Name string
}
)

func main() {
dir := os.TempDir()

store := repository.NewJSONStore(dir)
repo := repository.NewMemoryRepository[Entity, EntityID](
repository.WithStore(store),
repository.WithStoreFilename("Entity.json"), // optional, defaults to struct name + `.json`
)

err := repo.Save(context.Background(), Entity{
ID: EntityID(uuid.New().String()),
Name: gofakeit.Name(),
})
if err != nil {
panic(err)
}
}

Check filesystem

cat /tmp/Entity.json

Content

{
"5eda35ed-544e-4d94-8981-97ceb866d4b6": {
"ID": "5eda35ed-544e-4d94-8981-97ceb866d4b6",
"Name": "Rosie Dickens"
}
}

Restore Repository Data

main.go
package main

import (
"context"
"fmt"
"os"

"github.com/go-arrower/arrower/repository"
)

type (
EntityID string

Entity struct {
ID EntityID
Name string
}
)

func main() {
dir := os.TempDir()

store := repository.NewJSONStore(dir)
repo := repository.NewMemoryRepository[Entity, EntityID](repository.WithStore(store))

entities, err := repo.All(context.Background())
if err != nil {
panic(err)
}

fmt.Println(entities)
}

Output

[{5eda35ed-544e-4d94-8981-97ceb866d4b6 Rosie Dickens}]