documents.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package filesystem
  2. import (
  3. "bytes"
  4. "context"
  5. "excalidraw-complete/core"
  6. "fmt"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "github.com/oklog/ulid/v2"
  11. )
  12. type documentStore struct {
  13. basePath string // Directory where documents are stored.
  14. }
  15. func NewDocumentStore(basePath string) core.DocumentStore {
  16. if err := os.MkdirAll(basePath, 0755); err != nil {
  17. log.Fatalf("failed to create base directory: %v", err)
  18. }
  19. return &documentStore{basePath: basePath}
  20. }
  21. func (s *documentStore) FindID(ctx context.Context, id string) (*core.Document, error) {
  22. filePath := filepath.Join(s.basePath, id)
  23. data, err := os.ReadFile(filePath)
  24. if err != nil {
  25. if os.IsNotExist(err) {
  26. return nil, fmt.Errorf("document with id %s not found", id)
  27. }
  28. return nil, err
  29. }
  30. document := core.Document{
  31. Data: *bytes.NewBuffer(data),
  32. }
  33. return &document, nil
  34. }
  35. func (s *documentStore) Create(ctx context.Context, document *core.Document) (string, error) {
  36. id := ulid.Make().String()
  37. filePath := filepath.Join(s.basePath, id)
  38. if err := os.WriteFile(filePath, document.Data.Bytes(), 0644); err != nil {
  39. return "", err
  40. }
  41. return id, nil
  42. }