Skip to content

Commit

Permalink
add a pluggable aws-s3 wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
northdpole committed Oct 24, 2024
1 parent 5165d35 commit 7f100b3
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/s3/mock/wrapper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package wrapper

// Client is the wrapper around s3 sdk
type Client struct {
UpsertCallback func(string, string, []byte) error
}

// NewClient returns a client
func NewMockClient(region string) (Client, error) {
// create new playwright client
return Client{}, nil
}

func (c Client) UpsertFile(filename, bucket string, pdfBytes []byte) error {
return c.UpsertCallback(filename, bucket, pdfBytes)
}
68 changes: 68 additions & 0 deletions pkg/s3/wrapper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package wrapper

import (
"bytes"
"log/slog"
"os"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/go-errors/errors"
)

// Wrapper is the wrapper interface that allows the playwright client to be pluggable
type Wrapper interface {
// UpsertFile inserts or replaces a file in s3 if it doesn't exist
UpsertFile(string, string, []byte) error
}

// Client is the wrapper around google's go-github client
type Client struct {
session *session.Session
}

// NewClient returns a client
func NewClient(region string) (Client, error) {
sess, err := session.NewSession(&aws.Config{Region: aws.String(region)})
if err != nil {
return Client{}, errors.Errorf("unable to start session with AWS API: %w", err)
}
// create new playwright client
return Client{
session: sess,
}, nil
}

func (c Client) UpsertFile(htmlFilename, bucket string, pdfBytes []byte) error {
//#nosec:G304
data, err := os.ReadFile(htmlFilename) //#nosec:G304
if err != nil {
return errors.Errorf("could not open file: %w", err)
}

uploader := s3manager.NewUploader(c.session)
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(htmlFilename),
Body: bytes.NewReader(data),
})
if err != nil {
return errors.Errorf("unable to upload %s to %s: %w", htmlFilename, bucket, err)
}
slog.Info("uploaded", "filename", htmlFilename, "to", "bucket", bucket, "successfully")

pdfFilename := strings.Replace(htmlFilename, ".html", "", -1) + ".pdf"
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(pdfFilename),
Body: bytes.NewReader(pdfBytes),
})
if err != nil {
return errors.Errorf("unable to upload %s to %s: %w", pdfBytes, bucket, err)
}

slog.Info("uploaded", "filename", pdfFilename, "to", "bucket", bucket, "successfully")
return nil
}

0 comments on commit 7f100b3

Please sign in to comment.