Skip to content

Commit

Permalink
refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
hatredholder committed Dec 26, 2024
1 parent 51eee5c commit a9e2e94
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 18 deletions.
5 changes: 3 additions & 2 deletions cmd/book.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ Example:
os.Exit(0)
}

if os.Getenv("HARDCOVER_API_KEY") == "" {
apiKey := os.Getenv("HARDCOVER_API_KEY")
if apiKey == "" {
fmt.Println("HARDCOVER_API_KEY environment variable must be set")
fmt.Println("get an API key at https://hardcover.app/account/api")
os.Exit(0)
Expand All @@ -37,7 +38,7 @@ Example:
}
tmplPath := utils.GetTmplPath(tmplName)

hits := api.Query(args)
hits := api.Query(args, apiKey)
book := internal.Chooser(hits)
result := internal.Format(book, tmplPath)

Expand Down
5 changes: 2 additions & 3 deletions internal/api/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package api
import (
"context"
"log"
"os"
"strings"

"github.com/machinebox/graphql"
Expand Down Expand Up @@ -52,7 +51,7 @@ type QueryResponse struct {
}
}

func Query(args []string) Hits {
func Query(args []string, apiKey string) Hits {
// set endpoint
client := graphql.NewClient("https://api.hardcover.app/v1/graphql")

Expand All @@ -70,7 +69,7 @@ func Query(args []string) Hits {

// set header fields
req.Header.Set("content-type", "application/json")
req.Header.Set("authorization", os.Getenv("HARDCOVER_API_KEY"))
req.Header.Set("authorization", apiKey)

// define a Context for the request
ctx := context.Background()
Expand Down
22 changes: 9 additions & 13 deletions internal/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,30 @@ import (
"github.com/hatredholder/mediabrowse/internal/templates"
)

func Process(t *template.Template, vars interface{}) string {
func processTmpl(book api.Document, tmpl *template.Template) string {
var tmplBytes bytes.Buffer

err := t.Execute(&tmplBytes, vars)
err := tmpl.Execute(&tmplBytes, book)
if err != nil {
log.Fatal(err)
}

return tmplBytes.String()
}

func ProcessFile(tmplPath string, funcMap template.FuncMap, vars interface{}) string {
func Format(book api.Document, tmplPath string) string {
tmplFile := filepath.Base(tmplPath)

tmpl, err := template.New(tmplFile).Funcs(funcMap).ParseFiles(tmplPath)
if err != nil {
log.Fatal(err)
}

return Process(tmpl, vars)
}

func Format(book api.Document, tmplPath string) string {
funcMap := template.FuncMap{
"commify": templates.Commify,
"truncate": templates.Truncate,
"formatRating": templates.FormatRating,
}

return ProcessFile(tmplPath, funcMap, book)
tmpl, err := template.New(tmplFile).Funcs(funcMap).ParseFiles(tmplPath)
if err != nil {
log.Fatal(err)
}

return processTmpl(book, tmpl)
}

0 comments on commit a9e2e94

Please sign in to comment.