documents.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package aws
  2. import (
  3. "bytes"
  4. "context"
  5. "excalidraw-complete/core"
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "github.com/aws/aws-sdk-go-v2/aws"
  10. "github.com/aws/aws-sdk-go-v2/config"
  11. "github.com/aws/aws-sdk-go-v2/service/s3"
  12. "github.com/oklog/ulid/v2"
  13. )
  14. type documentStore struct {
  15. s3Client *s3.Client
  16. bucket string // Name of the S3 bucket
  17. }
  18. func NewDocumentStore(bucketName string) core.DocumentStore {
  19. cfg, err := config.LoadDefaultConfig(context.TODO())
  20. if err != nil {
  21. log.Fatalf("unable to load SDK config, %v", err)
  22. }
  23. s3Client := s3.NewFromConfig(cfg)
  24. return &documentStore{
  25. s3Client: s3Client,
  26. bucket: bucketName,
  27. }
  28. }
  29. func (s *documentStore) FindID(ctx context.Context, id string) (*core.Document, error) {
  30. resp, err := s.s3Client.GetObject(ctx, &s3.GetObjectInput{
  31. Bucket: aws.String(s.bucket),
  32. Key: aws.String(id),
  33. })
  34. if err != nil {
  35. return nil, fmt.Errorf("failed to get document with id %s: %v", id, err)
  36. }
  37. defer resp.Body.Close()
  38. data, err := ioutil.ReadAll(resp.Body)
  39. if err != nil {
  40. return nil, fmt.Errorf("failed to read document data: %v", err)
  41. }
  42. document := core.Document{
  43. Data: *bytes.NewBuffer(data),
  44. }
  45. return &document, nil
  46. }
  47. func (s *documentStore) Create(ctx context.Context, document *core.Document) (string, error) {
  48. id := ulid.Make().String()
  49. _, err := s.s3Client.PutObject(ctx, &s3.PutObjectInput{
  50. Bucket: aws.String(s.bucket),
  51. Key: aws.String(id),
  52. Body: bytes.NewReader(document.Data.Bytes()),
  53. })
  54. if err != nil {
  55. return "", fmt.Errorf("failed to upload document: %v", err)
  56. }
  57. return id, nil
  58. }