Skip to content

Commit

Permalink
Linter fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
brycekahle committed Jul 14, 2017
1 parent 93d4244 commit ba8d5bc
Show file tree
Hide file tree
Showing 39 changed files with 277 additions and 147 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
help: ## Show this help.
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {sub("\\\\n",sprintf("\n%22c"," "), $$2);printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)

all: test build ## Run the tests and build the binary.
all: lint test build ## Run the tests and build the binary.

os = darwin
arch = amd64
Expand Down
2 changes: 1 addition & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func NewAPIWithVersion(ctx context.Context, config *conf.GlobalConfiguration, db
mux.Get("/downloads", api.DownloadList)
mux.Get("/orders/:order_id/downloads", api.DownloadList)

mux.Get("/vatnumbers/:number", api.VatnumberLookup)
mux.Get("/vatnumbers/:number", api.VatNumberLookup)

mux.Get("/payments", api.PaymentList)
mux.Get("/payments/:pay_id", api.PaymentView)
Expand Down
1 change: 1 addition & 0 deletions api/coupons.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func (a *API) lookupCoupon(ctx context.Context, w http.ResponseWriter, code stri
return coupon, nil
}

// CouponView returns information about a single coupon code.
func (a *API) CouponView(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log := gcontext.GetLogger(ctx)
code := kami.Param(ctx, "code")
Expand Down
13 changes: 10 additions & 3 deletions api/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import (
"github.com/netlify/gocommerce/models"
)

const MaxIPsPerDay = 50
const maxIPsPerDay = 50

// DownloadURL returns a signed URL to download a purchased asset.
func (a *API) DownloadURL(ctx context.Context, w http.ResponseWriter, r *http.Request) {
id := kami.Param(ctx, "id")
log := gcontext.GetLogger(ctx).WithField("download_id", id)
Expand Down Expand Up @@ -66,9 +67,14 @@ func (a *API) DownloadURL(ctx context.Context, w http.ResponseWriter, r *http.Re
}
var count uint64
for rows.Next() {
rows.Scan(&count)
err = rows.Scan(&count)
if err != nil {
log.WithError(err).Warnf("Error while signing download: %s", err)
internalServerError(w, "Error signing download: %v", err)
return
}
}
if count > MaxIPsPerDay {
if count > maxIPsPerDay {
unauthorizedError(w, "This download has been accessed from too many IPs within the last day")
return
}
Expand All @@ -87,6 +93,7 @@ func (a *API) DownloadURL(ctx context.Context, w http.ResponseWriter, r *http.Re
sendJSON(w, http.StatusOK, download)
}

// DownloadList lists all purchased downloads for an order or a user.
func (a *API) DownloadList(ctx context.Context, w http.ResponseWriter, r *http.Request) {
orderID := kami.Param(ctx, "order_id")
log := gcontext.GetLogger(ctx)
Expand Down
15 changes: 3 additions & 12 deletions api/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,13 @@ import (
"encoding/json"
"net/http"

jwt "github.com/dgrijalva/jwt-go"
"github.com/netlify/gocommerce/claims"
"github.com/Sirupsen/logrus"
)

func sendJSON(w http.ResponseWriter, status int, obj interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
encoder := json.NewEncoder(w)
encoder.Encode(obj)
}

func userIDFromToken(token *jwt.Token) string {
if token == nil {
return ""
if err := json.NewEncoder(w).Encode(obj); err != nil {
logrus.WithError(err).Errorf("Error encoding json response: %v", obj)
}

claims := token.Claims.(*claims.JWTClaims)
return claims.ID
}
28 changes: 15 additions & 13 deletions api/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@ import (
// MaxConcurrentLookups controls the number of simultaneous HTTP Order lookups
const MaxConcurrentLookups = 10

type OrderLineItem struct {
type orderLineItem struct {
Sku string `json:"sku"`
Path string `json:"path"`
Quantity uint64 `json:"quantity"`
Addons []OrderAddon `json:"addons"`
Addons []orderAddon `json:"addons"`
MetaData map[string]interface{} `json:"meta"`
}

type OrderAddon struct {
type orderAddon struct {
Sku string `json:"sku"`
}

type OrderParams struct {
type orderRequestParams struct {
SessionID string `json:"session_id"`

Email string `json:"email"`
Expand All @@ -51,7 +51,7 @@ type OrderParams struct {

MetaData map[string]interface{} `json:"meta"`

LineItems []*OrderLineItem `json:"line_items"`
LineItems []*orderLineItem `json:"line_items"`

Currency string `json:"currency"`

Expand All @@ -60,7 +60,7 @@ type OrderParams struct {
CouponCode string `json:"coupon"`
}

type ReceiptParams struct {
type receiptParams struct {
Email string `json:"email"`
}

Expand Down Expand Up @@ -148,12 +148,13 @@ func (a *API) ClaimOrders(ctx context.Context, w http.ResponseWriter, r *http.Re
sendJSON(w, http.StatusNoContent, "")
}

// ResendOrderReceipt resends the email receipt for an order
func (a *API) ResendOrderReceipt(ctx context.Context, w http.ResponseWriter, r *http.Request) {
id := kami.Param(ctx, "order_id")
log := gcontext.GetLogger(ctx)
claims := gcontext.GetClaims(ctx)

params := &ReceiptParams{}
params := &receiptParams{}
jsonDecoder := json.NewDecoder(r.Body)
err := jsonDecoder.Decode(params)
if err != nil {
Expand Down Expand Up @@ -208,6 +209,7 @@ func (a *API) ResendOrderReceipt(ctx context.Context, w http.ResponseWriter, r *
// - email
// - items

// OrderList lists orders selected by the query parameters provided.
func (a *API) OrderList(ctx context.Context, w http.ResponseWriter, r *http.Request) {
log := gcontext.GetLogger(ctx)

Expand Down Expand Up @@ -305,7 +307,7 @@ func (a *API) OrderCreate(ctx context.Context, w http.ResponseWriter, r *http.Re
log := gcontext.GetLogger(ctx)
config := gcontext.GetConfig(ctx)

params := &OrderParams{Currency: "USD"}
params := &orderRequestParams{Currency: "USD"}
jsonDecoder := json.NewDecoder(r.Body)
err := jsonDecoder.Decode(params)
if err != nil {
Expand Down Expand Up @@ -433,7 +435,7 @@ func (a *API) OrderUpdate(ctx context.Context, w http.ResponseWriter, r *http.Re
return
}

orderParams := new(OrderParams)
orderParams := new(orderRequestParams)
err := json.NewDecoder(r.Body).Decode(orderParams)
if err != nil {
log.WithError(err).Infof("Failed to deserialize order params: %s", err.Error())
Expand Down Expand Up @@ -559,7 +561,7 @@ func (a *API) OrderUpdate(ctx context.Context, w http.ResponseWriter, r *http.Re
//
// handle the line items
//
updatedItems := make(map[string]*OrderLineItem)
updatedItems := make(map[string]*orderLineItem)
for _, item := range orderParams.LineItems {
updatedItems[item.Sku] = item
}
Expand Down Expand Up @@ -640,7 +642,7 @@ func setOrderEmail(tx *gorm.DB, order *models.Order, claims *claims.JWTClaims, l
return nil
}

func (a *API) createLineItems(ctx context.Context, tx *gorm.DB, order *models.Order, items []*OrderLineItem) *HTTPError {
func (a *API) createLineItems(ctx context.Context, tx *gorm.DB, order *models.Order, items []*orderLineItem) *HTTPError {
sem := make(chan int, MaxConcurrentLookups)
var wg sync.WaitGroup
sharedErr := verificationError{}
Expand All @@ -655,7 +657,7 @@ func (a *API) createLineItems(ctx context.Context, tx *gorm.DB, order *models.Or
order.LineItems = append(order.LineItems, lineItem)
sem <- 1
wg.Add(1)
go func(item *models.LineItem, orderItem *OrderLineItem) {
go func(item *models.LineItem, orderItem *orderLineItem) {
defer func() {
wg.Done()
<-sem
Expand Down Expand Up @@ -751,7 +753,7 @@ func (a *API) processAddress(tx *gorm.DB, order *models.Order, name string, addr
return address, nil
}

func (a *API) processLineItem(ctx context.Context, order *models.Order, item *models.LineItem, orderItem *OrderLineItem) error {
func (a *API) processLineItem(ctx context.Context, order *models.Order, item *models.LineItem, orderItem *orderLineItem) error {
config := gcontext.GetConfig(ctx)
jwtClaims := gcontext.GetClaimsAsMap(ctx)
resp, err := a.httpClient.Get(config.SiteURL + item.Path)
Expand Down
33 changes: 14 additions & 19 deletions api/order_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ func TestOrderCreationWithSimpleOrder(t *testing.T) {
order := &models.Order{}
extractPayload(t, http.StatusCreated, recorder, order)

var total uint64
total = 999
var total uint64 = 999
assert.Equal(t, "info@example.com", order.Email, "Total should be info@example.com, was %v", order.Email)
assert.Equal(t, total, order.Total, fmt.Sprintf("Total should be 999, was %v", order.Total))
if len(order.LineItems) != 1 {
Expand Down Expand Up @@ -84,10 +83,8 @@ func TestOrderCreationWithTaxes(t *testing.T) {
order := &models.Order{}
extractPayload(t, http.StatusCreated, recorder, order)

var total uint64
total = 1069
var taxes uint64
taxes = 70
var total uint64 = 1069
var taxes uint64 = 70
assert.Equal(t, "info@example.com", order.Email, "Total should be info@example.com, was %v", order.Email)
assert.Equal(t, "Germany", order.ShippingAddress.Country)
assert.Equal(t, "Germany", order.BillingAddress.Country)
Expand Down Expand Up @@ -117,10 +114,8 @@ func TestOrderCreationForBundleWithTaxes(t *testing.T) {
order := &models.Order{}
extractPayload(t, http.StatusCreated, recorder, order)

var total uint64
total = 1105
var taxes uint64
taxes = 106
var total uint64 = 1105
var taxes uint64 = 106
assert.Equal(t, "info@example.com", order.Email, "Total should be info@example.com, was %v", order.Email)
assert.Equal(t, "Germany", order.ShippingAddress.Country)
assert.Equal(t, "Germany", order.BillingAddress.Country)
Expand Down Expand Up @@ -471,7 +466,7 @@ func TestOrderUpdateFields(t *testing.T) {
defer db.Save(firstOrder)
assert := assert.New(t)

recorder := runUpdate(t, db, firstOrder, &OrderParams{
recorder := runUpdate(t, db, firstOrder, &orderRequestParams{
Email: "mrfreeze@dc.com",
Currency: "monopoly-dollars",
})
Expand Down Expand Up @@ -504,17 +499,17 @@ func TestOrderUpdateAddress_ExistingAddress(t *testing.T) {
newAddr := getTestAddress()
newAddr.ID = "new-addr"
newAddr.UserID = firstOrder.UserID
rsp := db.Create(newAddr)
db.Create(newAddr)
defer db.Unscoped().Delete(newAddr)

recorder := runUpdate(t, db, firstOrder, &OrderParams{
recorder := runUpdate(t, db, firstOrder, &orderRequestParams{
BillingAddressID: newAddr.ID,
})
rspOrder := new(models.Order)
extractPayload(t, http.StatusOK, recorder, rspOrder)

saved := new(models.Order)
rsp = db.First(saved, "id = ?", firstOrder.ID)
rsp := db.First(saved, "id = ?", firstOrder.ID)
assert.False(rsp.RecordNotFound())

// now we load the addresses
Expand All @@ -534,7 +529,7 @@ func TestOrderUpdateAddress_NewAddress(t *testing.T) {
assert := assert.New(t)

paramsAddress := getTestAddress()
recorder := runUpdate(t, db, firstOrder, &OrderParams{
recorder := runUpdate(t, db, firstOrder, &orderRequestParams{
// should create a new address associated with the order's user
ShippingAddress: paramsAddress,
})
Expand All @@ -561,7 +556,7 @@ func TestOrderUpdateAsNonAdmin(t *testing.T) {
ctx := testContext(testToken("villian", "villian@wayneindustries.com"), config, false)
ctx = kami.SetParam(ctx, "id", firstOrder.ID)

params := &OrderParams{
params := &orderRequestParams{
Email: "mrfreeze@dc.com",
Currency: "monopoly-dollars",
}
Expand All @@ -584,7 +579,7 @@ func TestOrderUpdateWithNoCreds(t *testing.T) {
ctx := testContext(nil, config, false)
ctx = kami.SetParam(ctx, "id", firstOrder.ID)

params := &OrderParams{
params := &orderRequestParams{
Email: "mrfreeze@dc.com",
Currency: "monopoly-dollars",
}
Expand All @@ -605,7 +600,7 @@ func TestOrderUpdateWithNoCreds(t *testing.T) {
func TestOrderUpdateWithNewData(t *testing.T) {
db, _, _ := db(t)
assert := assert.New(t)
op := &OrderParams{
op := &orderRequestParams{
MetaData: map[string]interface{}{
"thing": float64(1),
"red": "fish",
Expand Down Expand Up @@ -709,7 +704,7 @@ func TestClaimOrdersMultipleTimes(t *testing.T) {
// HELPERS
// -------------------------------------------------------------------------------------------------------------------

func runUpdate(t *testing.T, db *gorm.DB, order *models.Order, params *OrderParams) *httptest.ResponseRecorder {
func runUpdate(t *testing.T, db *gorm.DB, order *models.Order, params *orderRequestParams) *httptest.ResponseRecorder {
globalConfig, config := testConfig()
ctx := testContext(testToken("admin-yo", "admin@wayneindustries.com"), config, true)
ctx = kami.SetParam(ctx, "id", order.ID)
Expand Down
4 changes: 2 additions & 2 deletions api/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/jinzhu/gorm"
)

const DEFAULT_PER_PAGE = 50
const defaultPerPage = 50

func calculateTotalPages(perPage, total uint64) uint64 {
pages := total / perPage
Expand Down Expand Up @@ -42,7 +42,7 @@ func paginate(w http.ResponseWriter, r *http.Request, query *gorm.DB) (offset in
queryPage := params.Get("page")
queryPerPage := params.Get("per_page")
var page uint64 = 1
var perPage uint64 = DEFAULT_PER_PAGE
var perPage uint64 = defaultPerPage
if queryPage != "" {
page, err = strconv.ParseUint(queryPage, 10, 64)
if err != nil {
Expand Down
20 changes: 12 additions & 8 deletions api/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import (
"github.com/netlify/gocommerce/models"
)

type sortDirection string

const ascending sortDirection = "asc"
const descending sortDirection = "desc"

var sortFields = map[string]string{
"created_at": "created_at",
"updated_at": "updated_at",
Expand Down Expand Up @@ -63,8 +68,7 @@ func parseUserQueryParams(query *gorm.DB, params url.Values) (*gorm.DB, error) {
}

func sortField(value string) string {
field, _ := sortFields[value]
return field
return sortFields[value]
}

func parseOrderParams(query *gorm.DB, params url.Values) (*gorm.DB, error) {
Expand Down Expand Up @@ -99,18 +103,18 @@ func parseOrderParams(query *gorm.DB, params url.Values) (*gorm.DB, error) {
if field == "" {
return nil, fmt.Errorf("bad field for sort '%v'", field)
}
dir := "asc"
dir := ascending
if len(parts) == 2 {
switch strings.ToLower(parts[1]) {
case "asc":
dir = "asc"
case "desc":
dir = "desc"
case string(ascending):
dir = ascending
case string(descending):
dir = descending
default:
return nil, fmt.Errorf("bad direction for sort '%v', only 'asc' and 'desc' allowed", parts[1])
}
}
query = query.Order(field + " " + dir)
query = query.Order(field + " " + string(dir))
}
} else {
fmt.Println("Sorting by created_at desc")
Expand Down
Loading

0 comments on commit ba8d5bc

Please sign in to comment.