documents.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "github.com/sirupsen/logrus"
  12. )
  13. type documentStore struct {
  14. basePath string // Directory where documents are stored.
  15. }
  16. func NewDocumentStore(basePath string) core.DocumentStore {
  17. if err := os.MkdirAll(basePath, 0755); err != nil {
  18. log.Fatalf("failed to create base directory: %v", err)
  19. }
  20. return &documentStore{basePath: basePath}
  21. }
  22. func (s *documentStore) FindID(ctx context.Context, id string) (*core.Document, error) {
  23. filePath := filepath.Join(s.basePath, id)
  24. log := logrus.WithField("document_id", id)
  25. log.WithField("file_path", filePath).Info("Retrieving document by ID")
  26. data, err := os.ReadFile(filePath)
  27. if err != nil {
  28. if os.IsNotExist(err) {
  29. log.WithField("error", "document not found").Warn("Document with specified ID not found")
  30. return nil, fmt.Errorf("document with id %s not found", id)
  31. }
  32. log.WithField("error", err).Error("Failed to retrieve document")
  33. return nil, err
  34. }
  35. document := core.Document{
  36. Data: *bytes.NewBuffer(data),
  37. }
  38. log.Info("Document retrieved successfully")
  39. return &document, nil
  40. }
  41. func (s *documentStore) Create(ctx context.Context, document *core.Document) (string, error) {
  42. id := ulid.Make().String()
  43. filePath := filepath.Join(s.basePath, id)
  44. log := logrus.WithFields(logrus.Fields{
  45. "document_id": id,
  46. "file_path": filePath,
  47. })
  48. log.Info("Creating new document")
  49. if err := os.WriteFile(filePath, document.Data.Bytes(), 0644); err != nil {
  50. log.WithField("error", err).Error("Failed to create document")
  51. return "", err
  52. }
  53. log.Info("Document created successfully")
  54. return id, nil
  55. }