Skip to content

Commit

Permalink
Add better error messages
Browse files Browse the repository at this point in the history
Don't make a request if the API token is missing
  • Loading branch information
kyleconroy committed Feb 28, 2022
1 parent 4967bcd commit 8d8a5a3
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions internal/bundler/upload.go
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
Expand All @@ -12,13 +13,15 @@ import (
)

type Uploader struct {
token string
configPath string
config *config.Config
dir string
}

func NewUploader(configPath, dir string, conf *config.Config) *Uploader {
return &Uploader{
token: os.Getenv("SQLC_AUTH_TOKEN"),
configPath: configPath,
config: conf,
dir: dir,
Expand All @@ -27,7 +30,10 @@ func NewUploader(configPath, dir string, conf *config.Config) *Uploader {

func (up *Uploader) Validate() error {
if up.config.Project.ID == "" {
return fmt.Errorf("project ID is not set")
return fmt.Errorf("project.id is not set")
}
if up.token == "" {
return fmt.Errorf("SQLC_AUTH_TOKEN environment variable is not set")
}
return nil
}
Expand All @@ -40,24 +46,22 @@ func (up *Uploader) Upload(ctx context.Context, result map[string]string) error

w := multipart.NewWriter(body)
defer w.Close()

if err := writeInputs(w, up.configPath, up.config); err != nil {
return err
}
if err := writeOutputs(w, up.dir, result); err != nil {
return err
}

w.Close()

req, err := http.NewRequest("POST", "http://localhost:8090/upload", body)
req, err := http.NewRequest("POST", "https://api.sqlc.dev/upload", body)
if err != nil {
return err
}

// Set sqlc-version header
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", os.Getenv("SQLC_AUTH_TOKEN")))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", up.token))
req = req.WithContext(ctx)

client := &http.Client{}
Expand All @@ -66,7 +70,12 @@ func (up *Uploader) Upload(ctx context.Context, result map[string]string) error
return err
}
if resp.StatusCode >= 400 {
return fmt.Errorf("upload endpiont returned non-200 status code: %d", resp.StatusCode)
body, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return fmt.Errorf("upload error: endpoint returned non-200 status code: %d", resp.StatusCode)
}
return fmt.Errorf("upload error: %d: %s", resp.StatusCode, string(body))
}
return nil
}

0 comments on commit 8d8a5a3

Please sign in to comment.