├── .gitignore
├── pkg
├── decryption
│ ├── encrypted_report_example1.bin
│ ├── decrypted_report_example1.bin
│ ├── decryptor.go
│ └── decryptor_test.go
├── types
│ ├── date.go
│ ├── email.go
│ ├── date_test.go
│ ├── email_test.go
│ └── regexes.go
├── runtime
│ ├── deepobject_test.go
│ ├── bindstring.go
│ ├── bindstring_test.go
│ ├── styleparam.go
│ ├── bindparam_test.go
│ ├── deepobject.go
│ └── styleparam_test.go
└── selling-partner
│ └── selling-partner.go
├── go.mod
├── LICENSE
├── go.sum
├── authorization
├── types.gen.go
└── api.gen.go
├── uploads
├── types.gen.go
└── api.gen.go
├── sellers
├── types.gen.go
└── api.gen.go
├── solicitations
├── types.gen.go
└── api.gen.go
├── sales
├── types.gen.go
└── api.gen.go
├── smallAndLight
└── types.gen.go
├── fees
└── types.gen.go
├── notifications
└── types.gen.go
├── fbaInventory
├── types.gen.go
└── api.gen.go
├── feeds
└── types.gen.go
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | /main.go
2 | .idea
3 |
--------------------------------------------------------------------------------
/pkg/decryption/encrypted_report_example1.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amzapi/selling-partner-api-sdk/HEAD/pkg/decryption/encrypted_report_example1.bin
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/amzapi/selling-partner-api-sdk
2 |
3 | go 1.16
4 |
5 | require (
6 | github.com/kr/pretty v0.1.0 // indirect
7 | github.com/pkg/errors v0.9.1
8 | github.com/stretchr/testify v1.6.1
9 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
10 | )
11 |
--------------------------------------------------------------------------------
/pkg/decryption/decrypted_report_example1.bin:
--------------------------------------------------------------------------------
1 | amazon-order-id merchant-order-id purchase-date last-updated-date order-status fulfillment-channel sales-channel order-channel ship-service-level product-name sku asin item-status quantity currency item-price item-tax shipping-price shipping-tax gift-wrap-price gift-wrap-tax item-promotion-discount ship-promotion-discount ship-city ship-state ship-postal-code ship-country promotion-ids is-business-order purchase-order-number price-designation
2 |
--------------------------------------------------------------------------------
/pkg/types/date.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import (
4 | "encoding/json"
5 | "time"
6 | )
7 |
8 | const DateFormat = "2006-01-02"
9 |
10 | type Date struct {
11 | time.Time
12 | }
13 |
14 | func (d Date) MarshalJSON() ([]byte, error) {
15 | return json.Marshal(d.Time.Format(DateFormat))
16 | }
17 |
18 | func (d *Date) UnmarshalJSON(data []byte) error {
19 | var dateStr string
20 | err := json.Unmarshal(data, &dateStr)
21 | if err != nil {
22 | return err
23 | }
24 | parsed, err := time.Parse(DateFormat, dateStr)
25 | if err != nil {
26 | return err
27 | }
28 | d.Time = parsed
29 | return nil
30 | }
31 |
--------------------------------------------------------------------------------
/pkg/types/email.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | )
7 |
8 | type Email string
9 |
10 | func (e Email) MarshalJSON() ([]byte, error) {
11 | if !emailRegex.MatchString(string(e)) {
12 | return nil, errors.New("email: failed to pass regex validation")
13 | }
14 | return json.Marshal(string(e))
15 | }
16 |
17 | func (e *Email) UnmarshalJSON(data []byte) error {
18 | var s string
19 | if err := json.Unmarshal(data, &s); err != nil {
20 | return err
21 | }
22 | if !emailRegex.MatchString(s) {
23 | return errors.New("email: failed to pass regex validation")
24 | }
25 | *e = Email(s)
26 | return nil
27 | }
28 |
--------------------------------------------------------------------------------
/pkg/decryption/decryptor.go:
--------------------------------------------------------------------------------
1 | package decryption
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "encoding/base64"
7 | )
8 |
9 | func Decrypt(encryptionKey string, initVector string, dataToDecrypt []byte) ([]byte, error) {
10 | iv, err := base64.StdEncoding.DecodeString(initVector)
11 | if err != nil {
12 | return nil, err
13 | }
14 |
15 | key, err := base64.StdEncoding.DecodeString(encryptionKey)
16 | if err != nil {
17 | return nil, err
18 | }
19 |
20 | cipherBlock, err := aes.NewCipher(key)
21 | if err != nil {
22 | return nil, err
23 | }
24 |
25 | decryptedData := make([]byte, len(dataToDecrypt))
26 | cipher.NewCBCDecrypter(cipherBlock, iv).CryptBlocks(decryptedData, dataToDecrypt)
27 | return decryptedData, nil
28 | }
29 |
--------------------------------------------------------------------------------
/pkg/types/date_test.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 | "time"
7 |
8 | "github.com/stretchr/testify/assert"
9 | )
10 |
11 | func TestDate_MarshalJSON(t *testing.T) {
12 | testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
13 | b := struct {
14 | DateField Date `json:"date"`
15 | }{
16 | DateField: Date{testDate},
17 | }
18 | jsonBytes, err := json.Marshal(b)
19 | assert.NoError(t, err)
20 | assert.JSONEq(t, `{"date":"2019-04-01"}`, string(jsonBytes))
21 | }
22 |
23 | func TestDate_UnmarshalJSON(t *testing.T) {
24 | testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
25 | jsonStr := `{"date":"2019-04-01"}`
26 | b := struct {
27 | DateField Date `json:"date"`
28 | }{}
29 | err := json.Unmarshal([]byte(jsonStr), &b)
30 | assert.NoError(t, err)
31 | assert.Equal(t, testDate, b.DateField.Time)
32 | }
33 |
--------------------------------------------------------------------------------
/pkg/types/email_test.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 |
7 | "github.com/stretchr/testify/assert"
8 | )
9 |
10 | func TestEmail_MarshalJSON(t *testing.T) {
11 | testEmail := "gaben@valvesoftware.com"
12 | b := struct {
13 | EmailField Email `json:"email"`
14 | }{
15 | EmailField: Email(testEmail),
16 | }
17 | jsonBytes, err := json.Marshal(b)
18 | assert.NoError(t, err)
19 | assert.JSONEq(t, `{"email":"gaben@valvesoftware.com"}`, string(jsonBytes))
20 | }
21 |
22 | func TestEmail_UnmarshalJSON(t *testing.T) {
23 | testEmail := Email("gaben@valvesoftware.com")
24 | jsonStr := `{"email":"gaben@valvesoftware.com"}`
25 | b := struct {
26 | EmailField Email `json:"email"`
27 | }{}
28 | err := json.Unmarshal([]byte(jsonStr), &b)
29 | assert.NoError(t, err)
30 | assert.Equal(t, testEmail, b.EmailField)
31 | }
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 selling-partner-api-sdk
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/pkg/types/regexes.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import "regexp"
4 |
5 | const (
6 | emailRegexString = "^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$"
7 | )
8 |
9 | var (
10 | emailRegex = regexp.MustCompile(emailRegexString)
11 | )
12 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
4 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
5 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
6 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
7 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
8 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
9 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
10 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
11 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
13 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
14 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
15 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
16 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
17 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
18 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
19 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
20 |
--------------------------------------------------------------------------------
/pkg/runtime/deepobject_test.go:
--------------------------------------------------------------------------------
1 | package runtime
2 |
3 | import (
4 | "net/url"
5 | "strings"
6 | "testing"
7 |
8 | "github.com/stretchr/testify/assert"
9 | "github.com/stretchr/testify/require"
10 | )
11 |
12 | type InnerObject struct {
13 | Name string
14 | ID int
15 | }
16 |
17 | // These are all possible field types, mandatory and optional.
18 | type AllFields struct {
19 | I int `json:"i"`
20 | Oi *int `json:"oi,omitempty"`
21 | F float32 `json:"f"`
22 | Of *float32 `json:"of,omitempty"`
23 | B bool `json:"b"`
24 | Ob *bool `json:"ob,omitempty"`
25 | As []string `json:"as"`
26 | Oas *[]string `json:"oas,omitempty"`
27 | O InnerObject `json:"o"`
28 | Oo *InnerObject `json:"oo,omitempty"`
29 | }
30 |
31 | func TestDeepObject(t *testing.T) {
32 | oi := int(5)
33 | of := float32(3.7)
34 | ob := true
35 | oas := []string{"foo", "bar"}
36 | oo := InnerObject{
37 | Name: "Marcin Romaszewicz",
38 | ID: 123,
39 | }
40 |
41 | srcObj := AllFields{
42 | I: 12,
43 | Oi: &oi,
44 | F: 4.2,
45 | Of: &of,
46 | B: true,
47 | Ob: &ob,
48 | As: []string{"hello", "world"},
49 | Oas: &oas,
50 | O: InnerObject{
51 | Name: "Joe Schmoe",
52 | ID: 456,
53 | },
54 | Oo: &oo,
55 | }
56 |
57 | marshaled, err := MarshalDeepObject(srcObj, "p")
58 | require.NoError(t, err)
59 | t.Log(marshaled)
60 |
61 | params := make(url.Values)
62 | marshaledParts := strings.Split(marshaled, "&")
63 | for _, p := range marshaledParts {
64 | parts := strings.Split(p, "=")
65 | require.Equal(t, 2, len(parts))
66 | params.Set(parts[0], parts[1])
67 | }
68 |
69 | var dstObj AllFields
70 | err = UnmarshalDeepObject(&dstObj, "p", params)
71 | require.NoError(t, err)
72 | assert.EqualValues(t, srcObj, dstObj)
73 | }
74 |
--------------------------------------------------------------------------------
/authorization/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package authorization provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package authorization
5 |
6 | // AuthorizationCode defines model for AuthorizationCode.
7 | type AuthorizationCode struct {
8 |
9 | // A Login with Amazon (LWA) authorization code that can be exchanged for a refresh token and access token that authorize you to make calls to a Selling Partner API.
10 | AuthorizationCode *string `json:"authorizationCode,omitempty"`
11 | }
12 |
13 | // Error defines model for Error.
14 | type Error struct {
15 |
16 | // An error code that identifies the type of error that occurred.
17 | Code string `json:"code"`
18 |
19 | // Additional details that can help the caller understand or fix the issue.
20 | Details *string `json:"details,omitempty"`
21 |
22 | // A message that describes the error condition in a human-readable form.
23 | Message string `json:"message"`
24 | }
25 |
26 | // ErrorList defines model for ErrorList.
27 | type ErrorList []Error
28 |
29 | // GetAuthorizationCodeResponse defines model for GetAuthorizationCodeResponse.
30 | type GetAuthorizationCodeResponse struct {
31 |
32 | // A list of error responses returned when a request is unsuccessful.
33 | Errors *ErrorList `json:"errors,omitempty"`
34 |
35 | // A Login with Amazon (LWA) authorization code.
36 | Payload *AuthorizationCode `json:"payload,omitempty"`
37 | }
38 |
39 | // GetAuthorizationCodeParams defines parameters for GetAuthorizationCode.
40 | type GetAuthorizationCodeParams struct {
41 |
42 | // The seller ID of the seller for whom you are requesting Selling Partner API authorization. This must be the seller ID of the seller who authorized your application on the Marketplace Appstore.
43 | SellingPartnerId string `json:"sellingPartnerId"`
44 |
45 | // Your developer ID. This must be one of the developer ID values that you provided when you registered your application in Developer Central.
46 | DeveloperId string `json:"developerId"`
47 |
48 | // The MWS Auth Token that was generated when the seller authorized your application on the Marketplace Appstore.
49 | MwsAuthToken string `json:"mwsAuthToken"`
50 | }
51 |
--------------------------------------------------------------------------------
/uploads/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package uploads provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package uploads
5 |
6 | // CreateUploadDestinationResponse defines model for CreateUploadDestinationResponse.
7 | type CreateUploadDestinationResponse struct {
8 |
9 | // A list of error responses returned when a request is unsuccessful.
10 | Errors *ErrorList `json:"errors,omitempty"`
11 |
12 | // Information about an upload destination.
13 | Payload *UploadDestination `json:"payload,omitempty"`
14 | }
15 |
16 | // Error defines model for Error.
17 | type Error struct {
18 |
19 | // An error code that identifies the type of error that occurred.
20 | Code string `json:"code"`
21 |
22 | // Additional details that can help the caller understand or fix the issue.
23 | Details *string `json:"details,omitempty"`
24 |
25 | // A message that describes the error condition in a human-readable form.
26 | Message string `json:"message"`
27 | }
28 |
29 | // ErrorList defines model for ErrorList.
30 | type ErrorList []Error
31 |
32 | // UploadDestination defines model for UploadDestination.
33 | type UploadDestination struct {
34 |
35 | // The headers to include in the upload request.
36 | Headers *map[string]interface{} `json:"headers,omitempty"`
37 |
38 | // The unique identifier for the upload destination.
39 | UploadDestinationId *string `json:"uploadDestinationId,omitempty"`
40 |
41 | // The URL for the upload destination.
42 | Url *string `json:"url,omitempty"`
43 | }
44 |
45 | // CreateUploadDestinationForResourceParams defines parameters for CreateUploadDestinationForResource.
46 | type CreateUploadDestinationForResourceParams struct {
47 |
48 | // A list of marketplace identifiers. This specifies the marketplaces where the upload will be available. Only one marketplace can be specified.
49 | MarketplaceIds []string `json:"marketplaceIds"`
50 |
51 | // An MD5 hash of the content to be submitted to the upload destination. This value is used to determine if the data has been corrupted or tampered with during transit.
52 | ContentMD5 string `json:"contentMD5"`
53 |
54 | // The content type of the file to be uploaded.
55 | ContentType *string `json:"contentType,omitempty"`
56 | }
57 |
--------------------------------------------------------------------------------
/pkg/decryption/decryptor_test.go:
--------------------------------------------------------------------------------
1 | package decryption
2 |
3 | import (
4 | "io/ioutil"
5 | "reflect"
6 | "testing"
7 | )
8 |
9 | const ecryptedFileName1 = "./encrypted_report_example1.bin"
10 | const decryptedFileName1 = "./decrypted_report_example1.bin"
11 |
12 | func Test_decrypt(t *testing.T) {
13 | type args struct {
14 | encryptionKey string
15 | initVector string
16 | dataToDecrypt []byte
17 | }
18 |
19 | encryptedData1, err := ioutil.ReadFile(ecryptedFileName1)
20 | if err != nil {
21 | t.Fatal("Failed to read the file " +ecryptedFileName1+ ": ", err )
22 | }
23 | expectedDecryptedData1, err := ioutil.ReadFile(decryptedFileName1)
24 | if err != nil {
25 | t.Fatal("Failed to read the file " +decryptedFileName1+ ": ", err )
26 | }
27 | tests := []struct {
28 | name string
29 | args args
30 | want []byte
31 | wantErr bool
32 | }{
33 | {
34 | name: "Successful decryption of a report",
35 | args : args{
36 | encryptionKey:"5XgmfCcQSWn5q4u69kM5O0XTsgP2Fzbq+GcHpWJOGR0=",
37 | initVector:"bXCrfJN8QrsWVRZ7J9aPIg==",
38 | dataToDecrypt: encryptedData1,
39 | },
40 | want : expectedDecryptedData1,
41 | wantErr: false,
42 | },
43 | {
44 | name: "Decryption of a report failed: invalid base64 key encoding",
45 | args : args{
46 | encryptionKey:"5XgmfCcQSWn5q4u69kM5O0XTsgP2Fzbq+GcHpWJOGR0=%",
47 | initVector:"bXCrfJN8QrsWVRZ7J9aPIg==",
48 | dataToDecrypt: encryptedData1,
49 | },
50 | want : nil,
51 | wantErr: true,
52 | },
53 | {
54 | name: "Decryption of a report failed: invalid base64 init vector encoding",
55 | args : args{
56 | encryptionKey:"5XgmfCcQSWn5q4u69kM5O0XTsgP2Fzbq+GcHpWJOGR0=",
57 | initVector:"bXCrfJN8QrsWVRZ7J9aPIg==%",
58 | dataToDecrypt: encryptedData1,
59 | },
60 | want : nil,
61 | wantErr: true,
62 | },
63 | {
64 | name: "Decryption of a report failed: invalid key length",
65 | args : args{
66 | encryptionKey:"dGVzdHdyb25na2V5",
67 | initVector:"bXCrfJN8QrsWVRZ7J9aPIg==",
68 | dataToDecrypt: encryptedData1,
69 | },
70 | want : nil,
71 | wantErr: true,
72 | },
73 | }
74 | for _, tt := range tests {
75 | t.Run(tt.name, func(t *testing.T) {
76 | got, err := Decrypt(tt.args.encryptionKey, tt.args.initVector, tt.args.dataToDecrypt)
77 | if (err != nil) != tt.wantErr {
78 | t.Errorf("decrypt() error = %v, wantErr %v", err, tt.wantErr)
79 | return
80 | }
81 | if !reflect.DeepEqual(got, tt.want) {
82 | t.Errorf("decrypt() got = %v, want %v", got, tt.want)
83 | }
84 | })
85 | }
86 | }
--------------------------------------------------------------------------------
/sellers/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package sellers provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package sellers
5 |
6 | // Error defines model for Error.
7 | type Error struct {
8 |
9 | // An error code that identifies the type of error that occured.
10 | Code string `json:"code"`
11 |
12 | // Additional details that can help the caller understand or fix the issue.
13 | Details *string `json:"details,omitempty"`
14 |
15 | // A message that describes the error condition in a human-readable form.
16 | Message string `json:"message"`
17 | }
18 |
19 | // ErrorList defines model for ErrorList.
20 | type ErrorList []Error
21 |
22 | // GetMarketplaceParticipationsResponse defines model for GetMarketplaceParticipationsResponse.
23 | type GetMarketplaceParticipationsResponse struct {
24 |
25 | // A list of error responses returned when a request is unsuccessful.
26 | Errors *ErrorList `json:"errors,omitempty"`
27 |
28 | // List of marketplace participations.
29 | Payload *MarketplaceParticipationList `json:"payload,omitempty"`
30 | }
31 |
32 | // Marketplace defines model for Marketplace.
33 | type Marketplace struct {
34 |
35 | // The ISO 3166-1 alpha-2 format country code of the marketplace.
36 | CountryCode string `json:"countryCode"`
37 |
38 | // The ISO 4217 format currency code of the marketplace.
39 | DefaultCurrencyCode string `json:"defaultCurrencyCode"`
40 |
41 | // The ISO 639-1 format language code of the marketplace.
42 | DefaultLanguageCode string `json:"defaultLanguageCode"`
43 |
44 | // The domain name of the marketplace.
45 | DomainName string `json:"domainName"`
46 |
47 | // The encrypted marketplace value.
48 | Id string `json:"id"`
49 |
50 | // Marketplace name.
51 | Name string `json:"name"`
52 | }
53 |
54 | // MarketplaceParticipation defines model for MarketplaceParticipation.
55 | type MarketplaceParticipation struct {
56 |
57 | // Detailed information about an Amazon market where a seller can list items for sale and customers can view and purchase items.
58 | Marketplace Marketplace `json:"marketplace"`
59 |
60 | // Detailed information that is specific to a seller in a Marketplace.
61 | Participation Participation `json:"participation"`
62 | }
63 |
64 | // MarketplaceParticipationList defines model for MarketplaceParticipationList.
65 | type MarketplaceParticipationList []MarketplaceParticipation
66 |
67 | // Participation defines model for Participation.
68 | type Participation struct {
69 |
70 | // Specifies if the seller has suspended listings. True if the seller Listing Status is set to Inactive, otherwise False.
71 | HasSuspendedListings bool `json:"hasSuspendedListings"`
72 | IsParticipating bool `json:"isParticipating"`
73 | }
74 |
--------------------------------------------------------------------------------
/pkg/selling-partner/selling-partner.go:
--------------------------------------------------------------------------------
1 | package selling_partner
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "errors"
7 | "fmt"
8 | "io"
9 | "net/http"
10 | "time"
11 | )
12 |
13 | type AccessTokenResponse struct {
14 | AccessToken string `json:"access_token"`
15 | RefreshToken string `json:"refresh_token"`
16 | TokenType string `json:"token_type"`
17 | ExpiresIn int `json:"expires_in"`
18 | Error string `json:"error"`
19 | ErrorDescription string `json:"error_description"`
20 | }
21 |
22 | type Config struct {
23 | ClientID string //SP-API
24 | ClientSecret string //SP-API
25 | RefreshToken string //
26 | }
27 |
28 | func (o Config) IsValid() (bool, error) {
29 | if o.RefreshToken == "" {
30 | return false, errors.New("refresh token is required")
31 | }
32 | if o.ClientID == "" {
33 | return false, errors.New("client id is required")
34 | }
35 | if o.ClientSecret == "" {
36 | return false, errors.New("client secret is required")
37 | }
38 | return true, nil
39 | }
40 |
41 | type SellingPartner struct {
42 | cfg *Config
43 | accessToken string
44 | accessTokenExpiry time.Time
45 | }
46 |
47 | func NewSellingPartner(cfg *Config) (*SellingPartner, error) {
48 | if isValid, err := cfg.IsValid(); !isValid {
49 | return nil, err
50 | }
51 |
52 | sp := &SellingPartner{}
53 | sp.cfg = cfg
54 |
55 | return sp, nil
56 | }
57 |
58 | func (s *SellingPartner) RefreshToken() error {
59 |
60 | reqBody, _ := json.Marshal(map[string]string{
61 | "grant_type": "refresh_token",
62 | "refresh_token": s.cfg.RefreshToken,
63 | "client_id": s.cfg.ClientID,
64 | "client_secret": s.cfg.ClientSecret,
65 | })
66 |
67 | resp, err := http.Post(
68 | "https://api.amazon.com/auth/o2/token",
69 | "application/json",
70 | bytes.NewBuffer(reqBody))
71 |
72 | if err != nil {
73 | return errors.New("RefreshToken call failed with error " + err.Error())
74 | }
75 |
76 | defer func(Body io.ReadCloser) {
77 | _ = Body.Close()
78 | }(resp.Body)
79 |
80 | respBodyBytes, err := io.ReadAll(resp.Body)
81 | if err != nil {
82 | return errors.New("RefreshToken read response with error " + err.Error())
83 | }
84 |
85 | theResp := &AccessTokenResponse{}
86 |
87 | if err = json.Unmarshal(respBodyBytes, theResp); err != nil {
88 | return errors.New("RefreshToken response parse failed. Body: " + string(respBodyBytes))
89 | }
90 |
91 | if theResp.AccessToken != "" {
92 | s.accessToken = theResp.AccessToken
93 | s.accessTokenExpiry = time.Now().UTC().Add(time.Duration(theResp.ExpiresIn) * time.Second) //set expiration time
94 | } else if theResp.Error != "" {
95 | return errors.New(fmt.Sprintf("RefreshToken failed with code %s, description %s", theResp.Error, theResp.ErrorDescription))
96 | } else {
97 | return errors.New(fmt.Sprintf("RefreshToken failed with unknown reason. Body: %s", string(respBodyBytes)))
98 | }
99 |
100 | return nil
101 | }
102 |
103 | // expiryDelta determines how earlier a token should be considered
104 | // expired than its actual expiration time. It is used to avoid late
105 | // expirations due to client-server time mismatches.
106 | const expiryDelta = 1 * time.Minute
107 |
108 | func (s *SellingPartner) AuthorizeRequest(r *http.Request) error {
109 |
110 | if s.accessToken == "" ||
111 | s.accessTokenExpiry.IsZero() ||
112 | s.accessTokenExpiry.Round(0).Add(-expiryDelta).Before(time.Now().UTC()) {
113 | if err := s.RefreshToken(); err != nil {
114 | return fmt.Errorf("cannot refresh token. Error: %s", err.Error())
115 | }
116 | }
117 |
118 | r.Header.Add("X-Amz-Access-Token", s.accessToken)
119 |
120 | return nil
121 | }
122 |
--------------------------------------------------------------------------------
/pkg/runtime/bindstring.go:
--------------------------------------------------------------------------------
1 | // Copyright 2019 DeepMap, Inc.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 | package runtime
15 |
16 | import (
17 | "errors"
18 | "fmt"
19 | "reflect"
20 | "strconv"
21 | "time"
22 |
23 | "github.com/amzapi/selling-partner-api-sdk/pkg/types"
24 | )
25 |
26 | // This function takes a string, and attempts to assign it to the destination
27 | // interface via whatever type conversion is necessary. We have to do this
28 | // via reflection instead of a much simpler type switch so that we can handle
29 | // type aliases. This function was the easy way out, the better way, since we
30 | // know the destination type each place that we use this, is to generate code
31 | // to read each specific type.
32 | func BindStringToObject(src string, dst interface{}) error {
33 | var err error
34 |
35 | v := reflect.ValueOf(dst)
36 | t := reflect.TypeOf(dst)
37 |
38 | // We need to dereference pointers
39 | if t.Kind() == reflect.Ptr {
40 | v = reflect.Indirect(v)
41 | t = v.Type()
42 | }
43 |
44 | // The resulting type must be settable. reflect will catch issues like
45 | // passing the destination by value.
46 | if !v.CanSet() {
47 | return errors.New("destination is not settable")
48 | }
49 |
50 | switch t.Kind() {
51 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
52 | var val int64
53 | val, err = strconv.ParseInt(src, 10, 64)
54 | if err == nil {
55 | v.SetInt(val)
56 | }
57 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
58 | var val uint64
59 | val, err = strconv.ParseUint(src, 10, 64)
60 | if err == nil {
61 | v.SetUint(val)
62 | }
63 | case reflect.String:
64 | v.SetString(src)
65 | err = nil
66 | case reflect.Float64, reflect.Float32:
67 | var val float64
68 | val, err = strconv.ParseFloat(src, 64)
69 | if err == nil {
70 | v.SetFloat(val)
71 | }
72 | case reflect.Bool:
73 | var val bool
74 | val, err = strconv.ParseBool(src)
75 | if err == nil {
76 | v.SetBool(val)
77 | }
78 | case reflect.Struct:
79 | if t.ConvertibleTo(reflect.TypeOf(time.Time{})) {
80 | // Don't fail on empty string.
81 | if src == "" {
82 | return nil
83 | }
84 | // Time is a special case of a struct that we handle
85 | parsedTime, err := time.Parse(time.RFC3339Nano, src)
86 | if err != nil {
87 | parsedTime, err = time.Parse(types.DateFormat, src)
88 | if err != nil {
89 | return fmt.Errorf("error parsing '%s' as RFC3339 or 2006-01-02 time: %s", src, err)
90 | }
91 | }
92 | // So, assigning this gets a little fun. We have a value to the
93 | // dereferenced destination. We can't do a conversion to
94 | // time.Time because the result isn't assignable, so we need to
95 | // convert pointers.
96 | if t != reflect.TypeOf(time.Time{}) {
97 | vPtr := v.Addr()
98 | vtPtr := vPtr.Convert(reflect.TypeOf(&time.Time{}))
99 | v = reflect.Indirect(vtPtr)
100 | }
101 | v.Set(reflect.ValueOf(parsedTime))
102 | return nil
103 | }
104 |
105 | if t.ConvertibleTo(reflect.TypeOf(types.Date{})) {
106 | // Don't fail on empty string.
107 | if src == "" {
108 | return nil
109 | }
110 | parsedTime, err := time.Parse(types.DateFormat, src)
111 | if err != nil {
112 | return fmt.Errorf("error parsing '%s' as date: %s", src, err)
113 | }
114 | parsedDate := types.Date{Time: parsedTime}
115 |
116 | // We have to do the same dance here to assign, just like with times
117 | // above.
118 | if t != reflect.TypeOf(types.Date{}) {
119 | vPtr := v.Addr()
120 | vtPtr := vPtr.Convert(reflect.TypeOf(&types.Date{}))
121 | v = reflect.Indirect(vtPtr)
122 | }
123 | v.Set(reflect.ValueOf(parsedDate))
124 | return nil
125 | }
126 |
127 | // We fall through to the error case below if we haven't handled the
128 | // destination type above.
129 | fallthrough
130 | default:
131 | // We've got a bunch of types unimplemented, don't fail silently.
132 | err = fmt.Errorf("can not bind to destination of type: %s", t.Kind())
133 | }
134 | if err != nil {
135 | return fmt.Errorf("error binding string parameter: %s", err)
136 | }
137 | return nil
138 | }
139 |
--------------------------------------------------------------------------------
/pkg/runtime/bindstring_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2019 DeepMap, Inc.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 | package runtime
15 |
16 | import (
17 | "testing"
18 | "time"
19 |
20 | "github.com/stretchr/testify/assert"
21 |
22 | "github.com/amzapi/selling-partner-api-sdk/pkg/types"
23 | )
24 |
25 | func TestBindStringToObject(t *testing.T) {
26 | var i int
27 | assert.NoError(t, BindStringToObject("5", &i))
28 | assert.Equal(t, 5, i)
29 |
30 | // Let's make sure we error out on things that can't be the correct
31 | // type. Since we're using reflect package setters, we'll have similar
32 | // unassignable type errors.
33 | assert.Error(t, BindStringToObject("5.7", &i))
34 | assert.Error(t, BindStringToObject("foo", &i))
35 | assert.Error(t, BindStringToObject("1,2,3", &i))
36 |
37 | var i8 int8
38 | assert.NoError(t, BindStringToObject("12", &i8))
39 | assert.Equal(t, int8(12), i8)
40 |
41 | assert.Error(t, BindStringToObject("5.7", &i8))
42 | assert.Error(t, BindStringToObject("foo", &i8))
43 | assert.Error(t, BindStringToObject("1,2,3", &i8))
44 |
45 | var i16 int16
46 | assert.NoError(t, BindStringToObject("12", &i16))
47 | assert.Equal(t, int16(12), i16)
48 |
49 | assert.Error(t, BindStringToObject("5.7", &i16))
50 | assert.Error(t, BindStringToObject("foo", &i16))
51 | assert.Error(t, BindStringToObject("1,2,3", &i16))
52 |
53 | var i32 int32
54 | assert.NoError(t, BindStringToObject("12", &i32))
55 | assert.Equal(t, int32(12), i32)
56 |
57 | assert.Error(t, BindStringToObject("5.7", &i32))
58 | assert.Error(t, BindStringToObject("foo", &i32))
59 | assert.Error(t, BindStringToObject("1,2,3", &i32))
60 |
61 | var i64 int64
62 | assert.NoError(t, BindStringToObject("124", &i64))
63 | assert.Equal(t, int64(124), i64)
64 |
65 | assert.Error(t, BindStringToObject("5.7", &i64))
66 | assert.Error(t, BindStringToObject("foo", &i64))
67 | assert.Error(t, BindStringToObject("1,2,3", &i64))
68 |
69 | var u uint
70 | assert.NoError(t, BindStringToObject("5", &u))
71 | assert.Equal(t, uint(5), u)
72 |
73 | assert.Error(t, BindStringToObject("5.7", &u))
74 | assert.Error(t, BindStringToObject("foo", &u))
75 | assert.Error(t, BindStringToObject("1,2,3", &u))
76 |
77 | var u8 uint8
78 | assert.NoError(t, BindStringToObject("12", &u8))
79 | assert.Equal(t, uint8(12), u8)
80 |
81 | assert.Error(t, BindStringToObject("5.7", &u8))
82 | assert.Error(t, BindStringToObject("foo", &u8))
83 | assert.Error(t, BindStringToObject("1,2,3", &u8))
84 |
85 | var u16 uint16
86 | assert.NoError(t, BindStringToObject("12", &u16))
87 | assert.Equal(t, uint16(12), u16)
88 |
89 | assert.Error(t, BindStringToObject("5.7", &u16))
90 | assert.Error(t, BindStringToObject("foo", &u16))
91 | assert.Error(t, BindStringToObject("1,2,3", &u16))
92 |
93 | var u32 uint32
94 | assert.NoError(t, BindStringToObject("12", &u32))
95 | assert.Equal(t, uint32(12), u32)
96 |
97 | assert.Error(t, BindStringToObject("5.7", &u32))
98 | assert.Error(t, BindStringToObject("foo", &u32))
99 | assert.Error(t, BindStringToObject("1,2,3", &u32))
100 |
101 | var u64 uint64
102 | assert.NoError(t, BindStringToObject("124", &u64))
103 | assert.Equal(t, uint64(124), u64)
104 |
105 | assert.Error(t, BindStringToObject("5.7", &u64))
106 | assert.Error(t, BindStringToObject("foo", &u64))
107 | assert.Error(t, BindStringToObject("1,2,3", &u64))
108 |
109 | var b bool
110 | assert.NoError(t, BindStringToObject("True", &b))
111 | assert.Equal(t, true, b)
112 | assert.NoError(t, BindStringToObject("true", &b))
113 | assert.Equal(t, true, b)
114 | assert.NoError(t, BindStringToObject("1", &b))
115 | assert.Equal(t, true, b)
116 |
117 | var f64 float64
118 | assert.NoError(t, BindStringToObject("1.25", &f64))
119 | assert.Equal(t, float64(1.25), f64)
120 |
121 | assert.Error(t, BindStringToObject("foo", &f64))
122 | assert.Error(t, BindStringToObject("1,2,3", &f64))
123 |
124 | var f32 float32
125 | assert.NoError(t, BindStringToObject("3.125", &f32))
126 | assert.Equal(t, float32(3.125), f32)
127 |
128 | assert.Error(t, BindStringToObject("foo", &f32))
129 | assert.Error(t, BindStringToObject("1,2,3", &f32))
130 |
131 | // This checks whether binding works through a type alias.
132 | type SomeType int
133 | var st SomeType
134 | assert.NoError(t, BindStringToObject("5", &st))
135 | assert.Equal(t, SomeType(5), st)
136 |
137 | // Check time binding
138 | now := time.Now().UTC()
139 | strTime := now.Format(time.RFC3339Nano)
140 | var parsedTime time.Time
141 | assert.NoError(t, BindStringToObject(strTime, &parsedTime))
142 | parsedTime = parsedTime.UTC()
143 | assert.EqualValues(t, now, parsedTime)
144 |
145 | now = now.Truncate(time.Second)
146 | strTime = now.Format(time.RFC3339)
147 | assert.NoError(t, BindStringToObject(strTime, &parsedTime))
148 | parsedTime = parsedTime.UTC()
149 | assert.EqualValues(t, now, parsedTime)
150 |
151 | // Checks whether time binding works through a type alias.
152 | type AliasedTime time.Time
153 | var aliasedTime AliasedTime
154 | assert.NoError(t, BindStringToObject(strTime, &aliasedTime))
155 | assert.EqualValues(t, now, aliasedTime)
156 |
157 | // Checks whether date binding works directly and through an alias.
158 | dateString := "2020-11-05"
159 | var dstDate types.Date
160 | assert.NoError(t, BindStringToObject(dateString, &dstDate))
161 | type AliasedDate types.Date
162 | var dstAliasedDate AliasedDate
163 | assert.NoError(t, BindStringToObject(dateString, &dstAliasedDate))
164 | }
165 |
--------------------------------------------------------------------------------
/solicitations/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package solicitations provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package solicitations
5 |
6 | import (
7 | "encoding/json"
8 | "fmt"
9 |
10 | "github.com/pkg/errors"
11 | )
12 |
13 | // CreateProductReviewAndSellerFeedbackSolicitationResponse defines model for CreateProductReviewAndSellerFeedbackSolicitationResponse.
14 | type CreateProductReviewAndSellerFeedbackSolicitationResponse struct {
15 |
16 | // A list of error responses returned when a request is unsuccessful.
17 | Errors *ErrorList `json:"errors,omitempty"`
18 | }
19 |
20 | // Error defines model for Error.
21 | type Error struct {
22 |
23 | // An error code that identifies the type of error that occurred.
24 | Code string `json:"code"`
25 |
26 | // Additional details that can help the caller understand or fix the issue.
27 | Details *string `json:"details,omitempty"`
28 |
29 | // A message that describes the error condition in a human-readable form.
30 | Message string `json:"message"`
31 | }
32 |
33 | // ErrorList defines model for ErrorList.
34 | type ErrorList []Error
35 |
36 | // GetSchemaResponse defines model for GetSchemaResponse.
37 | type GetSchemaResponse struct {
38 | Links *struct {
39 |
40 | // A Link object.
41 | Self LinkObject `json:"self"`
42 | } `json:"_links,omitempty"`
43 |
44 | // A list of error responses returned when a request is unsuccessful.
45 | Errors *ErrorList `json:"errors,omitempty"`
46 |
47 | // A JSON schema document describing the expected payload of the action. This object can be validated against http://json-schema.org/draft-04/schema.
48 | Payload *Schema `json:"payload,omitempty"`
49 | }
50 |
51 | // GetSolicitationActionResponse defines model for GetSolicitationActionResponse.
52 | type GetSolicitationActionResponse struct {
53 | Embedded *struct {
54 | Schema *GetSchemaResponse `json:"schema,omitempty"`
55 | } `json:"_embedded,omitempty"`
56 | Links *struct {
57 |
58 | // A Link object.
59 | Schema LinkObject `json:"schema"`
60 |
61 | // A Link object.
62 | Self LinkObject `json:"self"`
63 | } `json:"_links,omitempty"`
64 |
65 | // A list of error responses returned when a request is unsuccessful.
66 | Errors *ErrorList `json:"errors,omitempty"`
67 |
68 | // A simple object containing the name of the template.
69 | Payload *SolicitationsAction `json:"payload,omitempty"`
70 | }
71 |
72 | // GetSolicitationActionsForOrderResponse defines model for GetSolicitationActionsForOrderResponse.
73 | type GetSolicitationActionsForOrderResponse struct {
74 | Embedded *struct {
75 | Actions []GetSolicitationActionResponse `json:"actions"`
76 | } `json:"_embedded,omitempty"`
77 | Links *struct {
78 |
79 | // Eligible actions for the specified amazonOrderId.
80 | Actions []LinkObject `json:"actions"`
81 |
82 | // A Link object.
83 | Self LinkObject `json:"self"`
84 | } `json:"_links,omitempty"`
85 |
86 | // A list of error responses returned when a request is unsuccessful.
87 | Errors *ErrorList `json:"errors,omitempty"`
88 | }
89 |
90 | // LinkObject defines model for LinkObject.
91 | type LinkObject struct {
92 |
93 | // A URI for this object.
94 | Href string `json:"href"`
95 |
96 | // An identifier for this object.
97 | Name *string `json:"name,omitempty"`
98 | }
99 |
100 | // Schema defines model for Schema.
101 | type Schema struct {
102 | AdditionalProperties map[string]interface{} `json:"-"`
103 | }
104 |
105 | // SolicitationsAction defines model for SolicitationsAction.
106 | type SolicitationsAction struct {
107 | Name string `json:"name"`
108 | }
109 |
110 | // GetSolicitationActionsForOrderParams defines parameters for GetSolicitationActionsForOrder.
111 | type GetSolicitationActionsForOrderParams struct {
112 |
113 | // A marketplace identifier. This specifies the marketplace in which the order was placed. Only one marketplace can be specified.
114 | MarketplaceIds []string `json:"marketplaceIds"`
115 | }
116 |
117 | // CreateProductReviewAndSellerFeedbackSolicitationParams defines parameters for CreateProductReviewAndSellerFeedbackSolicitation.
118 | type CreateProductReviewAndSellerFeedbackSolicitationParams struct {
119 |
120 | // A marketplace identifier. This specifies the marketplace in which the order was placed. Only one marketplace can be specified.
121 | MarketplaceIds []string `json:"marketplaceIds"`
122 | }
123 |
124 | // Getter for additional properties for Schema. Returns the specified
125 | // element and whether it was found
126 | func (a Schema) Get(fieldName string) (value interface{}, found bool) {
127 | if a.AdditionalProperties != nil {
128 | value, found = a.AdditionalProperties[fieldName]
129 | }
130 | return
131 | }
132 |
133 | // Setter for additional properties for Schema
134 | func (a *Schema) Set(fieldName string, value interface{}) {
135 | if a.AdditionalProperties == nil {
136 | a.AdditionalProperties = make(map[string]interface{})
137 | }
138 | a.AdditionalProperties[fieldName] = value
139 | }
140 |
141 | // Override default JSON handling for Schema to handle AdditionalProperties
142 | func (a *Schema) UnmarshalJSON(b []byte) error {
143 | object := make(map[string]json.RawMessage)
144 | err := json.Unmarshal(b, &object)
145 | if err != nil {
146 | return err
147 | }
148 |
149 | if len(object) != 0 {
150 | a.AdditionalProperties = make(map[string]interface{})
151 | for fieldName, fieldBuf := range object {
152 | var fieldVal interface{}
153 | err := json.Unmarshal(fieldBuf, &fieldVal)
154 | if err != nil {
155 | return errors.Wrap(err, fmt.Sprintf("error unmarshaling field %s", fieldName))
156 | }
157 | a.AdditionalProperties[fieldName] = fieldVal
158 | }
159 | }
160 | return nil
161 | }
162 |
163 | // Override default JSON handling for Schema to handle AdditionalProperties
164 | func (a Schema) MarshalJSON() ([]byte, error) {
165 | var err error
166 | object := make(map[string]json.RawMessage)
167 |
168 | for fieldName, field := range a.AdditionalProperties {
169 | object[fieldName], err = json.Marshal(field)
170 | if err != nil {
171 | return nil, errors.Wrap(err, fmt.Sprintf("error marshaling '%s'", fieldName))
172 | }
173 | }
174 | return json.Marshal(object)
175 | }
176 |
--------------------------------------------------------------------------------
/sales/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package sales provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package sales
5 |
6 | // Decimal defines model for Decimal.
7 | type Decimal string
8 |
9 | // Error defines model for Error.
10 | type Error struct {
11 |
12 | // An error code that identifies the type of error that occured.
13 | Code string `json:"code"`
14 |
15 | // Additional details that can help the caller understand or fix the issue.
16 | Details *string `json:"details,omitempty"`
17 |
18 | // A message that describes the error condition in a human-readable form.
19 | Message string `json:"message"`
20 | }
21 |
22 | // ErrorList defines model for ErrorList.
23 | type ErrorList []Error
24 |
25 | // GetOrderMetricsResponse defines model for GetOrderMetricsResponse.
26 | type GetOrderMetricsResponse struct {
27 |
28 | // A list of error responses returned when a request is unsuccessful.
29 | Errors *ErrorList `json:"errors,omitempty"`
30 |
31 | // A set of order metrics, each scoped to a particular time interval.
32 | Payload *OrderMetricsList `json:"payload,omitempty"`
33 | }
34 |
35 | // Money defines model for Money.
36 | type Money struct {
37 |
38 | // A decimal number with no loss of precision. Useful when precision loss is unacceptable, as with currencies. Follows RFC7159 for number representation.
**Pattern** : `^-?(0|([1-9]\d*))(\.\d+)?([eE][+-]?\d+)?$`.
39 | Amount Decimal `json:"amount"`
40 |
41 | // Three-digit currency code. In ISO 4217 format.
42 | CurrencyCode string `json:"currencyCode"`
43 | }
44 |
45 | // OrderMetricsInterval defines model for OrderMetricsInterval.
46 | type OrderMetricsInterval struct {
47 |
48 | // The currency type and the amount.
49 | AverageUnitPrice Money `json:"averageUnitPrice"`
50 |
51 | // The interval of time based on requested granularity (ex. Hour, Day, etc.) If this is the first or the last interval from the list, it might contain incomplete data if the requested interval doesn't align with the requested granularity (ex. request interval 2018-09-01T02:00:00Z--2018-09-04T19:00:00Z and granularity day will result in Sept 1st UTC day and Sept 4th UTC days having partial data).
52 | Interval string `json:"interval"`
53 |
54 | // The number of orders based on the specified filters.
55 | OrderCount int `json:"orderCount"`
56 |
57 | // The number of order items based on the specified filters.
58 | OrderItemCount int `json:"orderItemCount"`
59 |
60 | // The currency type and the amount.
61 | TotalSales Money `json:"totalSales"`
62 |
63 | // The number of units in orders based on the specified filters.
64 | UnitCount int `json:"unitCount"`
65 | }
66 |
67 | // OrderMetricsList defines model for OrderMetricsList.
68 | type OrderMetricsList []OrderMetricsInterval
69 |
70 | // GetOrderMetricsParams defines parameters for GetOrderMetrics.
71 | type GetOrderMetricsParams struct {
72 |
73 | // A list of marketplace identifiers. Example: ATVPDKIKX0DER indicates the US marketplace.
74 | MarketplaceIds []string `json:"marketplaceIds"`
75 |
76 | // A time interval used for selecting order metrics. This takes the form of two dates separated by two hyphens (first date is inclusive; second date is exclusive). Dates are in ISO8601 format and must represent absolute time (either Z notation or offset notation). Example: 2018-09-01T00:00:00-07:00--2018-09-04T00:00:00-07:00 requests order metrics for Sept 1st, 2nd and 3rd in the -07:00 zone.
77 | Interval string `json:"interval"`
78 |
79 | // An IANA-compatible time zone for determining the day boundary. Required when specifying a granularity value greater than Hour. The granularityTimeZone value must align with the offset of the specified interval value. For example, if the interval value uses Z notation, then granularityTimeZone must be UTC. If the interval value uses an offset, then granularityTimeZone must be an IANA-compatible time zone that matches the offset. Example: US/Pacific to compute day boundaries, accounting for daylight time savings, for US/Pacific zone.
80 | GranularityTimeZone *string `json:"granularityTimeZone,omitempty"`
81 |
82 | // The granularity of the grouping of order metrics, based on a unit of time. Specifying granularity=Hour results in a successful request only if the interval specified is less than or equal to 30 days from now. For all other granularities, the interval specified must be less or equal to 2 years from now. Specifying granularity=Total results in order metrics that are aggregated over the entire interval that you specify. If the interval start and end date don’t align with the specified granularity, the head and tail end of the response interval will contain partial data. Example: Day to get a daily breakdown of the request interval, where the day boundary is defined by the granularityTimeZone.
83 | Granularity string `json:"granularity"`
84 |
85 | // Filters the results by the buyer type that you specify, B2B (business to business) or B2C (business to customer). Example: B2B, if you want the response to include order metrics for only B2B buyers.
86 | BuyerType *string `json:"buyerType,omitempty"`
87 |
88 | // Filters the results by the fulfillment network that you specify, MFN (merchant fulfillment network) or AFN (Amazon fulfillment network). Do not include this filter if you want the response to include order metrics for all fulfillment networks. Example: AFN, if you want the response to include order metrics for only Amazon fulfillment network.
89 | FulfillmentNetwork *string `json:"fulfillmentNetwork,omitempty"`
90 |
91 | // Specifies the day that the week starts on when granularity=Week, either Monday or Sunday. Default: Monday. Example: Sunday, if you want the week to start on a Sunday.
92 | FirstDayOfWeek *string `json:"firstDayOfWeek,omitempty"`
93 |
94 | // Filters the results by the ASIN that you specify. Specifying both ASIN and SKU returns an error. Do not include this filter if you want the response to include order metrics for all ASINs. Example: B0792R1RSN, if you want the response to include order metrics for only ASIN B0792R1RSN.
95 | Asin *string `json:"asin,omitempty"`
96 |
97 | // Filters the results by the SKU that you specify. Specifying both ASIN and SKU returns an error. Do not include this filter if you want the response to include order metrics for all SKUs. Example: TestSKU, if you want the response to include order metrics for only SKU TestSKU.
98 | Sku *string `json:"sku,omitempty"`
99 | }
100 |
--------------------------------------------------------------------------------
/smallAndLight/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package smallAndLight provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package smallAndLight
5 |
6 | // Error defines model for Error.
7 | type Error struct {
8 |
9 | // An error code that identifies the type of error that occurred.
10 | Code string `json:"code"`
11 |
12 | // Additional information that can help the caller understand or fix the issue.
13 | Details *string `json:"details,omitempty"`
14 |
15 | // A message that describes the error condition in a human-readable form.
16 | Message string `json:"message"`
17 | }
18 |
19 | // ErrorList defines model for ErrorList.
20 | type ErrorList struct {
21 | Errors *[]Error `json:"errors,omitempty"`
22 | }
23 |
24 | // FeeLineItem defines model for FeeLineItem.
25 | type FeeLineItem struct {
26 | FeeCharge MoneyType `json:"feeCharge"`
27 |
28 | // The type of fee charged to the seller.
29 | FeeType string `json:"feeType"`
30 | }
31 |
32 | // FeePreview defines model for FeePreview.
33 | type FeePreview struct {
34 |
35 | // The Amazon Standard Identification Number (ASIN) value used to identify the item.
36 | Asin *string `json:"asin,omitempty"`
37 |
38 | // A list of error responses returned when a request is unsuccessful.
39 | Errors *ErrorList `json:"errors,omitempty"`
40 |
41 | // A list of the Small and Light fees for the item.
42 | FeeBreakdown *[]FeeLineItem `json:"feeBreakdown,omitempty"`
43 | Price *MoneyType `json:"price,omitempty"`
44 | TotalFees *MoneyType `json:"totalFees,omitempty"`
45 | }
46 |
47 | // Item defines model for Item.
48 | type Item struct {
49 |
50 | // The Amazon Standard Identification Number (ASIN) value used to identify the item.
51 | Asin string `json:"asin"`
52 | Price MoneyType `json:"price"`
53 | }
54 |
55 | // MarketplaceId defines model for MarketplaceId.
56 | type MarketplaceId string
57 |
58 | // MoneyType defines model for MoneyType.
59 | type MoneyType struct {
60 |
61 | // The monetary value.
62 | Amount *float32 `json:"amount,omitempty"`
63 |
64 | // The currency code in ISO 4217 format.
65 | CurrencyCode *string `json:"currencyCode,omitempty"`
66 | }
67 |
68 | // SellerSKU defines model for SellerSKU.
69 | type SellerSKU string
70 |
71 | // SmallAndLightEligibility defines model for SmallAndLightEligibility.
72 | type SmallAndLightEligibility struct {
73 |
74 | // A marketplace identifier.
75 | MarketplaceId MarketplaceId `json:"marketplaceId"`
76 |
77 | // Identifies an item in the given marketplace. SellerSKU is qualified by the seller's SellerId, which is included with every operation that you submit.
78 | SellerSKU SellerSKU `json:"sellerSKU"`
79 |
80 | // The Small and Light eligibility status of the item.
81 | Status SmallAndLightEligibilityStatus `json:"status"`
82 | }
83 |
84 | // SmallAndLightEligibilityStatus defines model for SmallAndLightEligibilityStatus.
85 | type SmallAndLightEligibilityStatus string
86 |
87 | // List of SmallAndLightEligibilityStatus
88 | const (
89 | SmallAndLightEligibilityStatus_ELIGIBLE SmallAndLightEligibilityStatus = "ELIGIBLE"
90 | SmallAndLightEligibilityStatus_NOT_ELIGIBLE SmallAndLightEligibilityStatus = "NOT_ELIGIBLE"
91 | )
92 |
93 | // SmallAndLightEnrollment defines model for SmallAndLightEnrollment.
94 | type SmallAndLightEnrollment struct {
95 |
96 | // A marketplace identifier.
97 | MarketplaceId MarketplaceId `json:"marketplaceId"`
98 |
99 | // Identifies an item in the given marketplace. SellerSKU is qualified by the seller's SellerId, which is included with every operation that you submit.
100 | SellerSKU SellerSKU `json:"sellerSKU"`
101 |
102 | // The Small and Light enrollment status of the item.
103 | Status SmallAndLightEnrollmentStatus `json:"status"`
104 | }
105 |
106 | // SmallAndLightEnrollmentStatus defines model for SmallAndLightEnrollmentStatus.
107 | type SmallAndLightEnrollmentStatus string
108 |
109 | // List of SmallAndLightEnrollmentStatus
110 | const (
111 | SmallAndLightEnrollmentStatus_ENROLLED SmallAndLightEnrollmentStatus = "ENROLLED"
112 | SmallAndLightEnrollmentStatus_NOT_ENROLLED SmallAndLightEnrollmentStatus = "NOT_ENROLLED"
113 | )
114 |
115 | // SmallAndLightFeePreviewRequest defines model for SmallAndLightFeePreviewRequest.
116 | type SmallAndLightFeePreviewRequest struct {
117 |
118 | // A list of items for which to retrieve fee estimates (limit: 25).
119 | Items []Item `json:"items"`
120 |
121 | // A marketplace identifier.
122 | MarketplaceId MarketplaceId `json:"marketplaceId"`
123 | }
124 |
125 | // SmallAndLightFeePreviews defines model for SmallAndLightFeePreviews.
126 | type SmallAndLightFeePreviews struct {
127 |
128 | // A list of fee estimates for the requested items. The order of the fee estimates will follow the same order as the items in the request, with duplicates removed.
129 | Data *[]FeePreview `json:"data,omitempty"`
130 | }
131 |
132 | // GetSmallAndLightEligibilityBySellerSKUParams defines parameters for GetSmallAndLightEligibilityBySellerSKU.
133 | type GetSmallAndLightEligibilityBySellerSKUParams struct {
134 |
135 | // The marketplace for which the eligibility status is retrieved. NOTE: Accepts a single marketplace only.
136 | MarketplaceIds []string `json:"marketplaceIds"`
137 | }
138 |
139 | // DeleteSmallAndLightEnrollmentBySellerSKUParams defines parameters for DeleteSmallAndLightEnrollmentBySellerSKU.
140 | type DeleteSmallAndLightEnrollmentBySellerSKUParams struct {
141 |
142 | // The marketplace in which to remove the item from the Small and Light program. Note: Accepts a single marketplace only.
143 | MarketplaceIds []string `json:"marketplaceIds"`
144 | }
145 |
146 | // GetSmallAndLightEnrollmentBySellerSKUParams defines parameters for GetSmallAndLightEnrollmentBySellerSKU.
147 | type GetSmallAndLightEnrollmentBySellerSKUParams struct {
148 |
149 | // The marketplace for which the enrollment status is retrieved. Note: Accepts a single marketplace only.
150 | MarketplaceIds []string `json:"marketplaceIds"`
151 | }
152 |
153 | // PutSmallAndLightEnrollmentBySellerSKUParams defines parameters for PutSmallAndLightEnrollmentBySellerSKU.
154 | type PutSmallAndLightEnrollmentBySellerSKUParams struct {
155 |
156 | // The marketplace in which to enroll the item. Note: Accepts a single marketplace only.
157 | MarketplaceIds []string `json:"marketplaceIds"`
158 | }
159 |
160 | // GetSmallAndLightFeePreviewJSONBody defines parameters for GetSmallAndLightFeePreview.
161 | type GetSmallAndLightFeePreviewJSONBody SmallAndLightFeePreviewRequest
162 |
163 | // GetSmallAndLightFeePreviewRequestBody defines body for GetSmallAndLightFeePreview for application/json ContentType.
164 | type GetSmallAndLightFeePreviewJSONRequestBody GetSmallAndLightFeePreviewJSONBody
165 |
--------------------------------------------------------------------------------
/fees/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package fees provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package fees
5 |
6 | import (
7 | "time"
8 | )
9 |
10 | // Error defines model for Error.
11 | type Error struct {
12 |
13 | // An error code that identifies the type of error that occurred.
14 | Code string `json:"code"`
15 |
16 | // Additional information that can help the caller understand or fix the issue.
17 | Details *string `json:"details,omitempty"`
18 |
19 | // A message that describes the error condition.
20 | Message string `json:"message"`
21 | }
22 |
23 | // ErrorList defines model for ErrorList.
24 | type ErrorList []Error
25 |
26 | // FeeDetail defines model for FeeDetail.
27 | type FeeDetail struct {
28 | FeeAmount MoneyType `json:"FeeAmount"`
29 | FeePromotion *MoneyType `json:"FeePromotion,omitempty"`
30 |
31 | // The type of fee charged to a seller.
32 | FeeType string `json:"FeeType"`
33 | FinalFee MoneyType `json:"FinalFee"`
34 |
35 | // A list of other fees that contribute to a given fee.
36 | IncludedFeeDetailList *IncludedFeeDetailList `json:"IncludedFeeDetailList,omitempty"`
37 | TaxAmount *MoneyType `json:"TaxAmount,omitempty"`
38 | }
39 |
40 | // FeeDetailList defines model for FeeDetailList.
41 | type FeeDetailList []FeeDetail
42 |
43 | // FeesEstimate defines model for FeesEstimate.
44 | type FeesEstimate struct {
45 |
46 | // A list of other fees that contribute to a given fee.
47 | FeeDetailList *FeeDetailList `json:"FeeDetailList,omitempty"`
48 |
49 | // The time for which the fees were estimated. This defaults to the time the request is made.
50 | TimeOfFeesEstimation time.Time `json:"TimeOfFeesEstimation"`
51 | TotalFeesEstimate *MoneyType `json:"TotalFeesEstimate,omitempty"`
52 | }
53 |
54 | // FeesEstimateError defines model for FeesEstimateError.
55 | type FeesEstimateError struct {
56 |
57 | // An error code that identifies the type of error that occurred.
58 | Code string `json:"Code"`
59 |
60 | // Additional information that can help the caller understand or fix the issue.
61 | Detail FeesEstimateErrorDetail `json:"Detail"`
62 |
63 | // A message that describes the error condition in a human-readable form.
64 | Message string `json:"Message"`
65 |
66 | // An error type, identifying either the receiver or the sender as the originator of the error.
67 | Type string `json:"Type"`
68 | }
69 |
70 | // FeesEstimateErrorDetail defines model for FeesEstimateErrorDetail.
71 | type FeesEstimateErrorDetail []map[string]interface{}
72 |
73 | // FeesEstimateIdentifier defines model for FeesEstimateIdentifier.
74 | type FeesEstimateIdentifier struct {
75 |
76 | // The type of item identifier specified.
77 | IdType *string `json:"IdType,omitempty"`
78 |
79 | // The item identifier.
80 | IdValue *string `json:"IdValue,omitempty"`
81 |
82 | // When true, the offer is fulfilled by Amazon.
83 | IsAmazonFulfilled *bool `json:"IsAmazonFulfilled,omitempty"`
84 |
85 | // A marketplace identifier.
86 | MarketplaceId *string `json:"MarketplaceId,omitempty"`
87 |
88 | // Price information for an item, used to estimate fees.
89 | PriceToEstimateFees *PriceToEstimateFees `json:"PriceToEstimateFees,omitempty"`
90 |
91 | // The seller identifier.
92 | SellerId *string `json:"SellerId,omitempty"`
93 |
94 | // A unique identifier provided by the caller to track this request.
95 | SellerInputIdentifier *string `json:"SellerInputIdentifier,omitempty"`
96 | }
97 |
98 | // FeesEstimateRequest defines model for FeesEstimateRequest.
99 | type FeesEstimateRequest struct {
100 |
101 | // The product price on which the fee estimate is based.
102 | Identifier string `json:"Identifier"`
103 |
104 | // When true, the offer is fulfilled by Amazon.
105 | IsAmazonFulfilled *bool `json:"IsAmazonFulfilled,omitempty"`
106 |
107 | // A marketplace identifier.
108 | MarketplaceId string `json:"MarketplaceId"`
109 |
110 | // Price information for an item, used to estimate fees.
111 | PriceToEstimateFees PriceToEstimateFees `json:"PriceToEstimateFees"`
112 | }
113 |
114 | // FeesEstimateResult defines model for FeesEstimateResult.
115 | type FeesEstimateResult struct {
116 |
117 | // An unexpected error occurred during this operation.
118 | Error *FeesEstimateError `json:"Error,omitempty"`
119 |
120 | // The total estimated fees for an item and a list of details.
121 | FeesEstimate *FeesEstimate `json:"FeesEstimate,omitempty"`
122 |
123 | // An item identifier, marketplace, time of request, and other details that identify an estimate.
124 | FeesEstimateIdentifier *FeesEstimateIdentifier `json:"FeesEstimateIdentifier,omitempty"`
125 |
126 | // The status of the fee request. Possible values: Success, ClientError, ServiceError.
127 | Status *string `json:"Status,omitempty"`
128 | }
129 |
130 | // GetMyFeesEstimateRequest defines model for GetMyFeesEstimateRequest.
131 | type GetMyFeesEstimateRequest struct {
132 | FeesEstimateRequest *FeesEstimateRequest `json:"FeesEstimateRequest,omitempty"`
133 | }
134 |
135 | // GetMyFeesEstimateResponse defines model for GetMyFeesEstimateResponse.
136 | type GetMyFeesEstimateResponse struct {
137 |
138 | // A list of error responses returned when a request is unsuccessful.
139 | Errors *ErrorList `json:"errors,omitempty"`
140 |
141 | // Response schema.
142 | Payload *GetMyFeesEstimateResult `json:"payload,omitempty"`
143 | }
144 |
145 | // GetMyFeesEstimateResult defines model for GetMyFeesEstimateResult.
146 | type GetMyFeesEstimateResult struct {
147 |
148 | // An item identifier and the estimated fees for the item.
149 | FeesEstimateResult *FeesEstimateResult `json:"FeesEstimateResult,omitempty"`
150 | }
151 |
152 | // IncludedFeeDetail defines model for IncludedFeeDetail.
153 | type IncludedFeeDetail struct {
154 | FeeAmount MoneyType `json:"FeeAmount"`
155 | FeePromotion *MoneyType `json:"FeePromotion,omitempty"`
156 |
157 | // The type of fee charged to a seller.
158 | FeeType string `json:"FeeType"`
159 | FinalFee MoneyType `json:"FinalFee"`
160 | TaxAmount *MoneyType `json:"TaxAmount,omitempty"`
161 | }
162 |
163 | // IncludedFeeDetailList defines model for IncludedFeeDetailList.
164 | type IncludedFeeDetailList []IncludedFeeDetail
165 |
166 | // MoneyType defines model for MoneyType.
167 | type MoneyType struct {
168 |
169 | // The monetary value.
170 | Amount *float32 `json:"Amount,omitempty"`
171 |
172 | // The currency code in ISO 4217 format.
173 | CurrencyCode *string `json:"CurrencyCode,omitempty"`
174 | }
175 |
176 | // Points defines model for Points.
177 | type Points struct {
178 | PointsMonetaryValue *MoneyType `json:"PointsMonetaryValue,omitempty"`
179 | PointsNumber *int32 `json:"PointsNumber,omitempty"`
180 | }
181 |
182 | // PriceToEstimateFees defines model for PriceToEstimateFees.
183 | type PriceToEstimateFees struct {
184 | ListingPrice MoneyType `json:"ListingPrice"`
185 | Points *Points `json:"Points,omitempty"`
186 | Shipping *MoneyType `json:"Shipping,omitempty"`
187 | }
188 |
189 | // GetMyFeesEstimateForASINJSONBody defines parameters for GetMyFeesEstimateForASIN.
190 | type GetMyFeesEstimateForASINJSONBody GetMyFeesEstimateRequest
191 |
192 | // GetMyFeesEstimateForSKUJSONBody defines parameters for GetMyFeesEstimateForSKU.
193 | type GetMyFeesEstimateForSKUJSONBody GetMyFeesEstimateRequest
194 |
195 | // GetMyFeesEstimateForASINRequestBody defines body for GetMyFeesEstimateForASIN for application/json ContentType.
196 | type GetMyFeesEstimateForASINJSONRequestBody GetMyFeesEstimateForASINJSONBody
197 |
198 | // GetMyFeesEstimateForSKURequestBody defines body for GetMyFeesEstimateForSKU for application/json ContentType.
199 | type GetMyFeesEstimateForSKUJSONRequestBody GetMyFeesEstimateForSKUJSONBody
200 |
--------------------------------------------------------------------------------
/sellers/api.gen.go:
--------------------------------------------------------------------------------
1 | // Package sellers provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package sellers
5 |
6 | import (
7 | "context"
8 | "encoding/json"
9 | "fmt"
10 | "io/ioutil"
11 | "net/http"
12 | "net/url"
13 | runt "runtime"
14 | "strings"
15 | )
16 |
17 | // RequestBeforeFn is the function signature for the RequestBefore callback function
18 | type RequestBeforeFn func(ctx context.Context, req *http.Request) error
19 |
20 | // ResponseAfterFn is the function signature for the ResponseAfter callback function
21 | type ResponseAfterFn func(ctx context.Context, rsp *http.Response) error
22 |
23 | // Doer performs HTTP requests.
24 | //
25 | // The standard http.Client implements this interface.
26 | type HttpRequestDoer interface {
27 | Do(req *http.Request) (*http.Response, error)
28 | }
29 |
30 | // Client which conforms to the OpenAPI3 specification for this service.
31 | type Client struct {
32 | // The endpoint of the server conforming to this interface, with scheme,
33 | // https://api.deepmap.com for example. This can contain a path relative
34 | // to the server, such as https://api.deepmap.com/dev-test, and all the
35 | // paths in the swagger spec will be appended to the server.
36 | Endpoint string
37 |
38 | // Doer for performing requests, typically a *http.Client with any
39 | // customized settings, such as certificate chains.
40 | Client HttpRequestDoer
41 |
42 | // A callback for modifying requests which are generated before sending over
43 | // the network.
44 | RequestBefore RequestBeforeFn
45 |
46 | // A callback for modifying response which are generated before sending over
47 | // the network.
48 | ResponseAfter ResponseAfterFn
49 |
50 | // The user agent header identifies your application, its version number, and the platform and programming language you are using.
51 | // You must include a user agent header in each request submitted to the sales partner API.
52 | UserAgent string
53 | }
54 |
55 | // ClientOption allows setting custom parameters during construction
56 | type ClientOption func(*Client) error
57 |
58 | // Creates a new Client, with reasonable defaults
59 | func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
60 | // create a client with sane default values
61 | client := Client{
62 | Endpoint: endpoint,
63 | }
64 | // mutate client and add all optional params
65 | for _, o := range opts {
66 | if err := o(&client); err != nil {
67 | return nil, err
68 | }
69 | }
70 | // ensure the endpoint URL always has a trailing slash
71 | if !strings.HasSuffix(client.Endpoint, "/") {
72 | client.Endpoint += "/"
73 | }
74 | // create httpClient, if not already present
75 | if client.Client == nil {
76 | client.Client = http.DefaultClient
77 | }
78 | // setting the default useragent
79 | if client.UserAgent == "" {
80 | client.UserAgent = fmt.Sprintf("selling-partner-api-sdk/v1.0 (Language=%s; Platform=%s-%s)", strings.Replace(runt.Version(), "go", "go/", -1), runt.GOOS, runt.GOARCH)
81 | }
82 | return &client, nil
83 | }
84 |
85 | // WithHTTPClient allows overriding the default Doer, which is
86 | // automatically created using http.Client. This is useful for tests.
87 | func WithHTTPClient(doer HttpRequestDoer) ClientOption {
88 | return func(c *Client) error {
89 | c.Client = doer
90 | return nil
91 | }
92 | }
93 |
94 | // WithUserAgent set up useragent
95 | // add user agent to every request automatically
96 | func WithUserAgent(userAgent string) ClientOption {
97 | return func(c *Client) error {
98 | c.UserAgent = userAgent
99 | return nil
100 | }
101 | }
102 |
103 | // WithRequestBefore allows setting up a callback function, which will be
104 | // called right before sending the request. This can be used to mutate the request.
105 | func WithRequestBefore(fn RequestBeforeFn) ClientOption {
106 | return func(c *Client) error {
107 | c.RequestBefore = fn
108 | return nil
109 | }
110 | }
111 |
112 | // WithResponseAfter allows setting up a callback function, which will be
113 | // called right after get response the request. This can be used to log.
114 | func WithResponseAfter(fn ResponseAfterFn) ClientOption {
115 | return func(c *Client) error {
116 | c.ResponseAfter = fn
117 | return nil
118 | }
119 | }
120 |
121 | // The interface specification for the client above.
122 | type ClientInterface interface {
123 | // GetMarketplaceParticipations request
124 | GetMarketplaceParticipations(ctx context.Context) (*http.Response, error)
125 | }
126 |
127 | func (c *Client) GetMarketplaceParticipations(ctx context.Context) (*http.Response, error) {
128 | req, err := NewGetMarketplaceParticipationsRequest(c.Endpoint)
129 | if err != nil {
130 | return nil, err
131 | }
132 |
133 | req = req.WithContext(ctx)
134 | req.Header.Set("User-Agent", c.UserAgent)
135 | if c.RequestBefore != nil {
136 | err = c.RequestBefore(ctx, req)
137 | if err != nil {
138 | return nil, err
139 | }
140 | }
141 |
142 | rsp, err := c.Client.Do(req)
143 | if err != nil {
144 | return nil, err
145 | }
146 |
147 | if c.ResponseAfter != nil {
148 | err = c.ResponseAfter(ctx, rsp)
149 | if err != nil {
150 | return nil, err
151 | }
152 | }
153 | return rsp, nil
154 | }
155 |
156 | // NewGetMarketplaceParticipationsRequest generates requests for GetMarketplaceParticipations
157 | func NewGetMarketplaceParticipationsRequest(endpoint string) (*http.Request, error) {
158 | var err error
159 |
160 | queryUrl, err := url.Parse(endpoint)
161 | if err != nil {
162 | return nil, err
163 | }
164 |
165 | basePath := fmt.Sprintf("/sellers/v1/marketplaceParticipations")
166 | if basePath[0] == '/' {
167 | basePath = basePath[1:]
168 | }
169 |
170 | queryUrl, err = queryUrl.Parse(basePath)
171 | if err != nil {
172 | return nil, err
173 | }
174 |
175 | req, err := http.NewRequest("GET", queryUrl.String(), nil)
176 | if err != nil {
177 | return nil, err
178 | }
179 |
180 | return req, nil
181 | }
182 |
183 | // ClientWithResponses builds on ClientInterface to offer response payloads
184 | type ClientWithResponses struct {
185 | ClientInterface
186 | }
187 |
188 | // NewClientWithResponses creates a new ClientWithResponses, which wraps
189 | // Client with return type handling
190 | func NewClientWithResponses(endpoint string, opts ...ClientOption) (*ClientWithResponses, error) {
191 | client, err := NewClient(endpoint, opts...)
192 | if err != nil {
193 | return nil, err
194 | }
195 | return &ClientWithResponses{client}, nil
196 | }
197 |
198 | // WithBaseURL overrides the baseURL.
199 | func WithBaseURL(baseURL string) ClientOption {
200 | return func(c *Client) error {
201 | newBaseURL, err := url.Parse(baseURL)
202 | if err != nil {
203 | return err
204 | }
205 | c.Endpoint = newBaseURL.String()
206 | return nil
207 | }
208 | }
209 |
210 | // ClientWithResponsesInterface is the interface specification for the client with responses above.
211 | type ClientWithResponsesInterface interface {
212 | // GetMarketplaceParticipations request
213 | GetMarketplaceParticipationsWithResponse(ctx context.Context) (*GetMarketplaceParticipationsResp, error)
214 | }
215 |
216 | type GetMarketplaceParticipationsResp struct {
217 | Body []byte
218 | HTTPResponse *http.Response
219 | Model *GetMarketplaceParticipationsResponse
220 | }
221 |
222 | // Status returns HTTPResponse.Status
223 | func (r GetMarketplaceParticipationsResp) Status() string {
224 | if r.HTTPResponse != nil {
225 | return r.HTTPResponse.Status
226 | }
227 | return http.StatusText(0)
228 | }
229 |
230 | // StatusCode returns HTTPResponse.StatusCode
231 | func (r GetMarketplaceParticipationsResp) StatusCode() int {
232 | if r.HTTPResponse != nil {
233 | return r.HTTPResponse.StatusCode
234 | }
235 | return 0
236 | }
237 |
238 | // GetMarketplaceParticipationsWithResponse request returning *GetMarketplaceParticipationsResponse
239 | func (c *ClientWithResponses) GetMarketplaceParticipationsWithResponse(ctx context.Context) (*GetMarketplaceParticipationsResp, error) {
240 | rsp, err := c.GetMarketplaceParticipations(ctx)
241 | if err != nil {
242 | return nil, err
243 | }
244 | return ParseGetMarketplaceParticipationsResp(rsp)
245 | }
246 |
247 | // ParseGetMarketplaceParticipationsResp parses an HTTP response from a GetMarketplaceParticipationsWithResponse call
248 | func ParseGetMarketplaceParticipationsResp(rsp *http.Response) (*GetMarketplaceParticipationsResp, error) {
249 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
250 | defer rsp.Body.Close()
251 | if err != nil {
252 | return nil, err
253 | }
254 |
255 | response := &GetMarketplaceParticipationsResp{
256 | Body: bodyBytes,
257 | HTTPResponse: rsp,
258 | }
259 |
260 | var dest GetMarketplaceParticipationsResponse
261 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
262 | return nil, err
263 | }
264 |
265 | response.Model = &dest
266 |
267 | if rsp.StatusCode >= 300 {
268 | err = fmt.Errorf(rsp.Status)
269 | }
270 |
271 | return response, err
272 | }
273 |
--------------------------------------------------------------------------------
/notifications/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package notifications provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package notifications
5 |
6 | // CreateDestinationRequest defines model for CreateDestinationRequest.
7 | type CreateDestinationRequest struct {
8 |
9 | // A developer-defined name to help identify this destination.
10 | Name string `json:"name"`
11 |
12 | // The information required to create a destination resource. Applications should use one resource type (sqs or eventBridge) per destination.
13 | ResourceSpecification DestinationResourceSpecification `json:"resourceSpecification"`
14 | }
15 |
16 | // CreateDestinationResponse defines model for CreateDestinationResponse.
17 | type CreateDestinationResponse struct {
18 |
19 | // A list of error responses returned when a request is unsuccessful.
20 | Errors *ErrorList `json:"errors,omitempty"`
21 |
22 | // Represents a destination created when you call the createDestination operation.
23 | Payload *Destination `json:"payload,omitempty"`
24 | }
25 |
26 | // CreateSubscriptionRequest defines model for CreateSubscriptionRequest.
27 | type CreateSubscriptionRequest struct {
28 |
29 | // The identifier for the destination where notifications will be delivered.
30 | DestinationId *string `json:"destinationId,omitempty"`
31 |
32 | // The version of the payload object to be used in the notification.
33 | PayloadVersion *string `json:"payloadVersion,omitempty"`
34 | }
35 |
36 | // CreateSubscriptionResponse defines model for CreateSubscriptionResponse.
37 | type CreateSubscriptionResponse struct {
38 |
39 | // A list of error responses returned when a request is unsuccessful.
40 | Errors *ErrorList `json:"errors,omitempty"`
41 |
42 | // Represents a subscription to receive notifications.
43 | Payload *Subscription `json:"payload,omitempty"`
44 | }
45 |
46 | // DeleteDestinationResponse defines model for DeleteDestinationResponse.
47 | type DeleteDestinationResponse struct {
48 |
49 | // A list of error responses returned when a request is unsuccessful.
50 | Errors *ErrorList `json:"errors,omitempty"`
51 | }
52 |
53 | // DeleteSubscriptionByIdResponse defines model for DeleteSubscriptionByIdResponse.
54 | type DeleteSubscriptionByIdResponse struct {
55 |
56 | // A list of error responses returned when a request is unsuccessful.
57 | Errors *ErrorList `json:"errors,omitempty"`
58 | }
59 |
60 | // Destination defines model for Destination.
61 | type Destination struct {
62 |
63 | // The destination identifier generated when you created the destination.
64 | DestinationId string `json:"destinationId"`
65 |
66 | // The developer-defined name for this destination.
67 | Name string `json:"name"`
68 |
69 | // The destination resource types.
70 | Resource DestinationResource `json:"resource"`
71 | }
72 |
73 | // DestinationList defines model for DestinationList.
74 | type DestinationList []Destination
75 |
76 | // DestinationResource defines model for DestinationResource.
77 | type DestinationResource struct {
78 |
79 | // Represents an Amazon EventBridge destination.
80 | EventBridge *EventBridgeResource `json:"eventBridge,omitempty"`
81 |
82 | // The information required to create an Amazon Simple Queue Service (Amazon SQS) queue destination.
83 | Sqs *SqsResource `json:"sqs,omitempty"`
84 | }
85 |
86 | // DestinationResourceSpecification defines model for DestinationResourceSpecification.
87 | type DestinationResourceSpecification struct {
88 |
89 | // The information required to create an Amazon EventBridge destination.
90 | EventBridge *EventBridgeResourceSpecification `json:"eventBridge,omitempty"`
91 |
92 | // The information required to create an Amazon Simple Queue Service (Amazon SQS) queue destination.
93 | Sqs *SqsResource `json:"sqs,omitempty"`
94 | }
95 |
96 | // Error defines model for Error.
97 | type Error struct {
98 |
99 | // An error code that identifies the type of error that occurred.
100 | Code string `json:"code"`
101 |
102 | // Additional details that can help the caller understand or fix the issue.
103 | Details *string `json:"details,omitempty"`
104 |
105 | // A message that describes the error condition in a human-readable form.
106 | Message string `json:"message"`
107 | }
108 |
109 | // ErrorList defines model for ErrorList.
110 | type ErrorList []Error
111 |
112 | // EventBridgeResource defines model for EventBridgeResource.
113 | type EventBridgeResource struct {
114 |
115 | // The identifier for the AWS account that is responsible for charges related to receiving notifications.
116 | AccountId string `json:"accountId"`
117 |
118 | // The name of the partner event source associated with the destination.
119 | Name string `json:"name"`
120 |
121 | // The AWS region in which you receive the notifications. For AWS regions that are supported in Amazon EventBridge, see https://docs.aws.amazon.com/general/latest/gr/ev.html.
122 | Region string `json:"region"`
123 | }
124 |
125 | // EventBridgeResourceSpecification defines model for EventBridgeResourceSpecification.
126 | type EventBridgeResourceSpecification struct {
127 |
128 | // The identifier for the AWS account that is responsible for charges related to receiving notifications.
129 | AccountId string `json:"accountId"`
130 |
131 | // The AWS region in which you will be receiving the notifications.
132 | Region string `json:"region"`
133 | }
134 |
135 | // GetDestinationResponse defines model for GetDestinationResponse.
136 | type GetDestinationResponse struct {
137 |
138 | // A list of error responses returned when a request is unsuccessful.
139 | Errors *ErrorList `json:"errors,omitempty"`
140 |
141 | // Represents a destination created when you call the createDestination operation.
142 | Payload *Destination `json:"payload,omitempty"`
143 | }
144 |
145 | // GetDestinationsResponse defines model for GetDestinationsResponse.
146 | type GetDestinationsResponse struct {
147 |
148 | // A list of error responses returned when a request is unsuccessful.
149 | Errors *ErrorList `json:"errors,omitempty"`
150 |
151 | // A list of destinations.
152 | Payload *DestinationList `json:"payload,omitempty"`
153 | }
154 |
155 | // GetSubscriptionByIdResponse defines model for GetSubscriptionByIdResponse.
156 | type GetSubscriptionByIdResponse struct {
157 |
158 | // A list of error responses returned when a request is unsuccessful.
159 | Errors *ErrorList `json:"errors,omitempty"`
160 |
161 | // Represents a subscription to receive notifications.
162 | Payload *Subscription `json:"payload,omitempty"`
163 | }
164 |
165 | // GetSubscriptionResponse defines model for GetSubscriptionResponse.
166 | type GetSubscriptionResponse struct {
167 |
168 | // A list of error responses returned when a request is unsuccessful.
169 | Errors *ErrorList `json:"errors,omitempty"`
170 |
171 | // Represents a subscription to receive notifications.
172 | Payload *Subscription `json:"payload,omitempty"`
173 | }
174 |
175 | // SqsResource defines model for SqsResource.
176 | type SqsResource struct {
177 |
178 | // The Amazon Resource Name (ARN) associated with the SQS queue.
179 | Arn string `json:"arn"`
180 | }
181 |
182 | // Subscription defines model for Subscription.
183 | type Subscription struct {
184 |
185 | // The identifier for the destination where notifications will be delivered.
186 | DestinationId string `json:"destinationId"`
187 |
188 | // The version of the payload object to be used in the notification.
189 | PayloadVersion string `json:"payloadVersion"`
190 |
191 | // The subscription identifier generated when the subscription is created.
192 | SubscriptionId string `json:"subscriptionId"`
193 | }
194 |
195 | // NotificationType defines model for NotificationType.
196 | type NotificationType string
197 |
198 | // List of NotificationType
199 | const (
200 | NotificationType_ANY_OFFER_CHANGED NotificationType = "ANY_OFFER_CHANGED"
201 | NotificationType_B2B_ANY_OFFER_CHANGED NotificationType = "B2B_ANY_OFFER_CHANGED"
202 | NotificationType_BRANDED_ITEM_CONTENT_CHANGE NotificationType = "BRANDED_ITEM_CONTENT_CHANGE"
203 | NotificationType_FBA_OUTBOUND_SHIPMENT_STATUS NotificationType = "FBA_OUTBOUND_SHIPMENT_STATUS"
204 | NotificationType_FEED_PROCESSING_FINISHED NotificationType = "FEED_PROCESSING_FINISHED"
205 | NotificationType_FEE_PROMOTION NotificationType = "FEE_PROMOTION"
206 | NotificationType_FULFILLMENT_ORDER_STATUS NotificationType = "FULFILLMENT_ORDER_STATUS"
207 | NotificationType_ITEM_PRODUCT_TYPE_CHANGE NotificationType = "ITEM_PRODUCT_TYPE_CHANGE"
208 | NotificationType_MFN_ORDER_STATUS_CHANGE NotificationType = "MFN_ORDER_STATUS_CHANGE"
209 | NotificationType_REPORT_PROCESSING_FINISHED NotificationType = "REPORT_PROCESSING_FINISHED"
210 | )
211 |
212 | // CreateDestinationJSONBody defines parameters for CreateDestination.
213 | type CreateDestinationJSONBody CreateDestinationRequest
214 |
215 | // CreateSubscriptionJSONBody defines parameters for CreateSubscription.
216 | type CreateSubscriptionJSONBody CreateSubscriptionRequest
217 |
218 | // CreateDestinationRequestBody defines body for CreateDestination for application/json ContentType.
219 | type CreateDestinationJSONRequestBody CreateDestinationJSONBody
220 |
221 | // CreateSubscriptionRequestBody defines body for CreateSubscription for application/json ContentType.
222 | type CreateSubscriptionJSONRequestBody CreateSubscriptionJSONBody
223 |
--------------------------------------------------------------------------------
/fbaInventory/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package fbaInventory provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package fbaInventory
5 |
6 | import (
7 | "time"
8 | )
9 |
10 | // Error defines model for Error.
11 | type Error struct {
12 |
13 | // An error code that identifies the type of error that occurred.
14 | Code string `json:"code"`
15 |
16 | // Additional information that can help the caller understand or fix the issue.
17 | Details *string `json:"details,omitempty"`
18 |
19 | // A message that describes the error condition in a human-readable form.
20 | Message *string `json:"message,omitempty"`
21 | }
22 |
23 | // ErrorList defines model for ErrorList.
24 | type ErrorList []Error
25 |
26 | // GetInventorySummariesResponse defines model for GetInventorySummariesResponse.
27 | type GetInventorySummariesResponse struct {
28 |
29 | // A list of error responses returned when a request is unsuccessful.
30 | Errors *ErrorList `json:"errors,omitempty"`
31 |
32 | // The process of returning the results to a request in batches of a defined size called pages. This is done to exercise some control over result size and overall throughput. It's a form of traffic management.
33 | Pagination *Pagination `json:"pagination,omitempty"`
34 |
35 | // The payload schema for the getInventorySummaries operation.
36 | Payload *GetInventorySummariesResult `json:"payload,omitempty"`
37 | }
38 |
39 | // GetInventorySummariesResult defines model for GetInventorySummariesResult.
40 | type GetInventorySummariesResult struct {
41 |
42 | // Describes a granularity at which inventory data can be aggregated. For example, if you use Marketplace granularity, the fulfillable quantity will reflect inventory that could be fulfilled in the given marketplace.
43 | Granularity Granularity `json:"granularity"`
44 |
45 | // A list of inventory summaries.
46 | InventorySummaries InventorySummaries `json:"inventorySummaries"`
47 | }
48 |
49 | // Granularity defines model for Granularity.
50 | type Granularity struct {
51 |
52 | // The granularity ID for the specified granularity type. When granularityType is Marketplace, specify the marketplaceId.
53 | GranularityId *string `json:"granularityId,omitempty"`
54 |
55 | // The granularity type for the inventory aggregation level.
56 | GranularityType *string `json:"granularityType,omitempty"`
57 | }
58 |
59 | // InventoryDetails defines model for InventoryDetails.
60 | type InventoryDetails struct {
61 |
62 | // The item quantity that can be picked, packed, and shipped.
63 | FulfillableQuantity *int `json:"fulfillableQuantity,omitempty"`
64 |
65 | // The number of units that have not yet been received at an Amazon fulfillment center for processing, but are part of an inbound shipment with some units that have already been received and processed.
66 | InboundReceivingQuantity *int `json:"inboundReceivingQuantity,omitempty"`
67 |
68 | // The number of units in an inbound shipment that you have notified Amazon about and have provided a tracking number.
69 | InboundShippedQuantity *int `json:"inboundShippedQuantity,omitempty"`
70 |
71 | // The number of units in an inbound shipment for which you have notified Amazon.
72 | InboundWorkingQuantity *int `json:"inboundWorkingQuantity,omitempty"`
73 |
74 | // The number of misplaced or warehouse damaged units that are actively being confirmed at our fulfillment centers.
75 | ResearchingQuantity *ResearchingQuantity `json:"researchingQuantity,omitempty"`
76 |
77 | // The quantity of reserved inventory.
78 | ReservedQuantity *ReservedQuantity `json:"reservedQuantity,omitempty"`
79 |
80 | // The quantity of unfulfillable inventory.
81 | UnfulfillableQuantity *UnfulfillableQuantity `json:"unfulfillableQuantity,omitempty"`
82 | }
83 |
84 | // InventorySummaries defines model for InventorySummaries.
85 | type InventorySummaries []InventorySummary
86 |
87 | // InventorySummary defines model for InventorySummary.
88 | type InventorySummary struct {
89 |
90 | // The Amazon Standard Identification Number (ASIN) of an item.
91 | Asin *string `json:"asin,omitempty"`
92 |
93 | // The condition of the item as described by the seller (for example, New Item).
94 | Condition *string `json:"condition,omitempty"`
95 |
96 | // Amazon's fulfillment network SKU identifier.
97 | FnSku *string `json:"fnSku,omitempty"`
98 |
99 | // Summarized inventory details. This object will not appear if the details parameter in the request is false.
100 | InventoryDetails *InventoryDetails `json:"inventoryDetails,omitempty"`
101 |
102 | // The date and time that any quantity was last updated.
103 | LastUpdatedTime *time.Time `json:"lastUpdatedTime,omitempty"`
104 |
105 | // The localized language product title of the item within the specific marketplace.
106 | ProductName *string `json:"productName,omitempty"`
107 |
108 | // The seller SKU of the item.
109 | SellerSku *string `json:"sellerSku,omitempty"`
110 |
111 | // The total number of units in an inbound shipment or in Amazon fulfillment centers.
112 | TotalQuantity *int `json:"totalQuantity,omitempty"`
113 | }
114 |
115 | // Pagination defines model for Pagination.
116 | type Pagination struct {
117 |
118 | // A generated string used to retrieve the next page of the result. If nextToken is returned, pass the value of nextToken to the next request. If nextToken is not returned, there are no more items to return.
119 | NextToken *string `json:"nextToken,omitempty"`
120 | }
121 |
122 | // ResearchingQuantity defines model for ResearchingQuantity.
123 | type ResearchingQuantity struct {
124 |
125 | // A list of quantity details for items currently being researched.
126 | ResearchingQuantityBreakdown *[]ResearchingQuantityEntry `json:"researchingQuantityBreakdown,omitempty"`
127 |
128 | // The total number of units currently being researched in Amazon's fulfillment network.
129 | TotalResearchingQuantity *int `json:"totalResearchingQuantity,omitempty"`
130 | }
131 |
132 | // ResearchingQuantityEntry defines model for ResearchingQuantityEntry.
133 | type ResearchingQuantityEntry struct {
134 |
135 | // The duration of the research.
136 | Name string `json:"name"`
137 |
138 | // The number of units.
139 | Quantity int `json:"quantity"`
140 | }
141 |
142 | // ReservedQuantity defines model for ReservedQuantity.
143 | type ReservedQuantity struct {
144 |
145 | // The number of units that have been sidelined at the fulfillment center for additional processing.
146 | FcProcessingQuantity *int `json:"fcProcessingQuantity,omitempty"`
147 |
148 | // The number of units reserved for customer orders.
149 | PendingCustomerOrderQuantity *int `json:"pendingCustomerOrderQuantity,omitempty"`
150 |
151 | // The number of units being transferred from one fulfillment center to another.
152 | PendingTransshipmentQuantity *int `json:"pendingTransshipmentQuantity,omitempty"`
153 |
154 | // The total number of units in Amazon's fulfillment network that are currently being picked, packed, and shipped; or are sidelined for measurement, sampling, or other internal processes.
155 | TotalReservedQuantity *int `json:"totalReservedQuantity,omitempty"`
156 | }
157 |
158 | // UnfulfillableQuantity defines model for UnfulfillableQuantity.
159 | type UnfulfillableQuantity struct {
160 |
161 | // The number of units in carrier damaged disposition.
162 | CarrierDamagedQuantity *int `json:"carrierDamagedQuantity,omitempty"`
163 |
164 | // The number of units in customer damaged disposition.
165 | CustomerDamagedQuantity *int `json:"customerDamagedQuantity,omitempty"`
166 |
167 | // The number of units in defective disposition.
168 | DefectiveQuantity *int `json:"defectiveQuantity,omitempty"`
169 |
170 | // The number of units in distributor damaged disposition.
171 | DistributorDamagedQuantity *int `json:"distributorDamagedQuantity,omitempty"`
172 |
173 | // The number of units in expired disposition.
174 | ExpiredQuantity *int `json:"expiredQuantity,omitempty"`
175 |
176 | // The total number of units in Amazon's fulfillment network in unsellable condition.
177 | TotalUnfulfillableQuantity *int `json:"totalUnfulfillableQuantity,omitempty"`
178 |
179 | // The number of units in warehouse damaged disposition.
180 | WarehouseDamagedQuantity *int `json:"warehouseDamagedQuantity,omitempty"`
181 | }
182 |
183 | // GetInventorySummariesParams defines parameters for GetInventorySummaries.
184 | type GetInventorySummariesParams struct {
185 |
186 | // true to return inventory summaries with additional summarized inventory details and quantities. Otherwise, returns inventory summaries only (default value).
187 | Details *bool `json:"details,omitempty"`
188 |
189 | // The granularity type for the inventory aggregation level.
190 | GranularityType string `json:"granularityType"`
191 |
192 | // The granularity ID for the inventory aggregation level.
193 | GranularityId string `json:"granularityId"`
194 |
195 | // A start date and time in ISO8601 format. If specified, all inventory summaries that have changed since then are returned. You must specify a date and time that is no earlier than 18 months prior to the date and time when you call the API. Note: Changes in inboundWorkingQuantity, inboundShippedQuantity and inboundReceivingQuantity are not detected.
196 | StartDateTime *time.Time `json:"startDateTime,omitempty"`
197 |
198 | // A list of seller SKUs for which to return inventory summaries. You may specify up to 50 SKUs.
199 | SellerSkus *[]string `json:"sellerSkus,omitempty"`
200 |
201 | // String token returned in the response of your previous request.
202 | NextToken *string `json:"nextToken,omitempty"`
203 |
204 | // The marketplace ID for the marketplace for which to return inventory summaries.
205 | MarketplaceIds []string `json:"marketplaceIds"`
206 | }
207 |
--------------------------------------------------------------------------------
/pkg/runtime/styleparam.go:
--------------------------------------------------------------------------------
1 | // Copyright 2019 DeepMap, Inc.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 | package runtime
15 |
16 | import (
17 | "fmt"
18 | "net/url"
19 | "reflect"
20 | "sort"
21 | "strconv"
22 | "strings"
23 | "time"
24 |
25 | "github.com/pkg/errors"
26 | )
27 |
28 | // Given an input value, such as a primitive type, array or object, turn it
29 | // into a parameter based on style/explode definition.
30 | func StyleParam(style string, explode bool, paramName string, value interface{}) (string, error) {
31 | t := reflect.TypeOf(value)
32 | v := reflect.ValueOf(value)
33 |
34 | // Things may be passed in by pointer, we need to dereference, so return
35 | // error on nil.
36 | if t.Kind() == reflect.Ptr {
37 | if v.IsNil() {
38 | return "", fmt.Errorf("value is a nil pointer")
39 | }
40 | v = reflect.Indirect(v)
41 | t = v.Type()
42 | }
43 |
44 | switch t.Kind() {
45 | case reflect.Slice:
46 | n := v.Len()
47 | sliceVal := make([]interface{}, n)
48 | for i := 0; i < n; i++ {
49 | sliceVal[i] = v.Index(i).Interface()
50 | }
51 | return styleSlice(style, explode, paramName, sliceVal)
52 | case reflect.Struct:
53 | return styleStruct(style, explode, paramName, value)
54 | case reflect.Map:
55 | return styleMap(style, explode, paramName, value)
56 | default:
57 | return stylePrimitive(style, explode, paramName, value)
58 | }
59 | }
60 |
61 | func styleSlice(style string, explode bool, paramName string, values []interface{}) (string, error) {
62 | if style == "deepObject" {
63 | if !explode {
64 | return "", errors.New("deepObjects must be exploded")
65 | }
66 | return MarshalDeepObject(values, paramName)
67 | }
68 |
69 | var prefix string
70 | var separator string
71 |
72 | switch style {
73 | case "simple":
74 | separator = ","
75 | case "label":
76 | prefix = "."
77 | if explode {
78 | separator = "."
79 | } else {
80 | separator = ","
81 | }
82 | case "matrix":
83 | prefix = fmt.Sprintf(";%s=", paramName)
84 | if explode {
85 | separator = prefix
86 | } else {
87 | separator = ","
88 | }
89 | case "form":
90 | prefix = fmt.Sprintf("%s=", paramName)
91 | if explode {
92 | separator = "&" + prefix
93 | } else {
94 | separator = ","
95 | }
96 | case "spaceDelimited":
97 | prefix = fmt.Sprintf("%s=", paramName)
98 | if explode {
99 | separator = "&" + prefix
100 | } else {
101 | separator = " "
102 | }
103 | case "pipeDelimited":
104 | prefix = fmt.Sprintf("%s=", paramName)
105 | if explode {
106 | separator = "&" + prefix
107 | } else {
108 | separator = "|"
109 | }
110 | default:
111 | return "", fmt.Errorf("unsupported style '%s'", style)
112 | }
113 |
114 | // We're going to assume here that the array is one of simple types.
115 | var err error
116 | parts := make([]string, len(values))
117 | for i, v := range values {
118 | parts[i], err = primitiveToString(v)
119 | if err != nil {
120 | return "", fmt.Errorf("error formatting '%s': %s", paramName, err)
121 | }
122 | }
123 | return prefix + strings.Join(parts, separator), nil
124 | }
125 |
126 | func sortedKeys(strMap map[string]string) []string {
127 | keys := make([]string, len(strMap))
128 | i := 0
129 | for k := range strMap {
130 | keys[i] = k
131 | i++
132 | }
133 | sort.Strings(keys)
134 | return keys
135 | }
136 |
137 | // This is a special case. The struct may be a time, in which case, marshal
138 | // it in RFC3339 format.
139 | func marshalTimeValue(value interface{}) (string, bool) {
140 | if timeVal, ok := value.(*time.Time); ok {
141 | return timeVal.Format(time.RFC3339Nano), true
142 | }
143 |
144 | if timeVal, ok := value.(time.Time); ok {
145 | return timeVal.Format(time.RFC3339Nano), true
146 | }
147 |
148 | return "", false
149 | }
150 |
151 | func styleStruct(style string, explode bool, paramName string, value interface{}) (string, error) {
152 | if timeVal, ok := marshalTimeValue(value); ok {
153 | styledVal, err := stylePrimitive(style, explode, paramName, url.QueryEscape(timeVal))
154 | if err != nil {
155 | return "", errors.Wrap(err, "failed to style time")
156 | }
157 | return styledVal, nil
158 | }
159 |
160 | if style == "deepObject" {
161 | if !explode {
162 | return "", errors.New("deepObjects must be exploded")
163 | }
164 | return MarshalDeepObject(value, paramName)
165 | }
166 |
167 | // Otherwise, we need to build a dictionary of the struct's fields. Each
168 | // field may only be a primitive value.
169 | v := reflect.ValueOf(value)
170 | t := reflect.TypeOf(value)
171 | fieldDict := make(map[string]string)
172 |
173 | for i := 0; i < t.NumField(); i++ {
174 | fieldT := t.Field(i)
175 | // Find the json annotation on the field, and use the json specified
176 | // name if available, otherwise, just the field name.
177 | tag := fieldT.Tag.Get("json")
178 | fieldName := fieldT.Name
179 | if tag != "" {
180 | tagParts := strings.Split(tag, ",")
181 | name := tagParts[0]
182 | if name != "" {
183 | fieldName = name
184 | }
185 | }
186 | f := v.Field(i)
187 |
188 | // Unset optional fields will be nil pointers, skip over those.
189 | if f.Type().Kind() == reflect.Ptr && f.IsNil() {
190 | continue
191 | }
192 | str, err := primitiveToString(f.Interface())
193 | if err != nil {
194 | return "", fmt.Errorf("error formatting '%s': %s", paramName, err)
195 | }
196 | fieldDict[fieldName] = str
197 | }
198 |
199 | return processFieldDict(style, explode, paramName, fieldDict)
200 | }
201 |
202 | func styleMap(style string, explode bool, paramName string, value interface{}) (string, error) {
203 | if style == "deepObject" {
204 | if !explode {
205 | return "", errors.New("deepObjects must be exploded")
206 | }
207 | return MarshalDeepObject(value, paramName)
208 | }
209 |
210 | dict, ok := value.(map[string]interface{})
211 | if !ok {
212 | return "", errors.New("map not of type map[string]interface{}")
213 | }
214 |
215 | fieldDict := make(map[string]string)
216 | for fieldName, value := range dict {
217 | str, err := primitiveToString(value)
218 | if err != nil {
219 | return "", fmt.Errorf("error formatting '%s': %s", paramName, err)
220 | }
221 | fieldDict[fieldName] = str
222 | }
223 |
224 | return processFieldDict(style, explode, paramName, fieldDict)
225 | }
226 |
227 | func processFieldDict(style string, explode bool, paramName string, fieldDict map[string]string) (string, error) {
228 | var parts []string
229 |
230 | // This works for everything except deepObject. We'll handle that one
231 | // separately.
232 | if style != "deepObject" {
233 | if explode {
234 | for _, k := range sortedKeys(fieldDict) {
235 | v := fieldDict[k]
236 | parts = append(parts, k+"="+v)
237 | }
238 | } else {
239 | for _, k := range sortedKeys(fieldDict) {
240 | v := fieldDict[k]
241 | parts = append(parts, k)
242 | parts = append(parts, v)
243 | }
244 | }
245 | }
246 |
247 | var prefix string
248 | var separator string
249 |
250 | switch style {
251 | case "simple":
252 | separator = ","
253 | case "label":
254 | prefix = "."
255 | if explode {
256 | separator = prefix
257 | } else {
258 | separator = ","
259 | }
260 | case "matrix":
261 | if explode {
262 | separator = ";"
263 | prefix = ";"
264 | } else {
265 | separator = ","
266 | prefix = fmt.Sprintf(";%s=", paramName)
267 | }
268 | case "form":
269 | if explode {
270 | separator = "&"
271 | } else {
272 | prefix = fmt.Sprintf("%s=", paramName)
273 | separator = ","
274 | }
275 | case "deepObject":
276 | {
277 | if !explode {
278 | return "", fmt.Errorf("deepObject parameters must be exploded")
279 | }
280 | for _, k := range sortedKeys(fieldDict) {
281 | v := fieldDict[k]
282 | part := fmt.Sprintf("%s[%s]=%s", paramName, k, v)
283 | parts = append(parts, part)
284 | }
285 | separator = "&"
286 | }
287 | default:
288 | return "", fmt.Errorf("unsupported style '%s'", style)
289 | }
290 |
291 | return prefix + strings.Join(parts, separator), nil
292 | }
293 |
294 | func stylePrimitive(style string, explode bool, paramName string, value interface{}) (string, error) {
295 | strVal, err := primitiveToString(value)
296 | if err != nil {
297 | return "", err
298 | }
299 |
300 | var prefix string
301 | switch style {
302 | case "simple":
303 | case "label":
304 | prefix = "."
305 | case "matrix":
306 | prefix = fmt.Sprintf(";%s=", paramName)
307 | case "form":
308 | prefix = fmt.Sprintf("%s=", paramName)
309 | default:
310 | return "", fmt.Errorf("unsupported style '%s'", style)
311 | }
312 | return prefix + strVal, nil
313 | }
314 |
315 | // Converts a primitive value to a string. We need to do this based on the
316 | // Kind of an interface, not the Type to work with aliased types.
317 | func primitiveToString(value interface{}) (string, error) {
318 | var output string
319 |
320 | // Values may come in by pointer for optionals, so make sure to dereferene.
321 | v := reflect.Indirect(reflect.ValueOf(value))
322 | t := v.Type()
323 | kind := t.Kind()
324 |
325 | switch kind {
326 | case reflect.Int8, reflect.Int32, reflect.Int64, reflect.Int:
327 | output = strconv.FormatInt(v.Int(), 10)
328 | case reflect.Float32, reflect.Float64:
329 | output = strconv.FormatFloat(v.Float(), 'f', -1, 64)
330 | case reflect.Bool:
331 | if v.Bool() {
332 | output = "true"
333 | } else {
334 | output = "false"
335 | }
336 | case reflect.String:
337 | output = v.String()
338 | default:
339 | return "", fmt.Errorf("unsupported type %s", reflect.TypeOf(value).String())
340 | }
341 | return output, nil
342 | }
343 |
--------------------------------------------------------------------------------
/authorization/api.gen.go:
--------------------------------------------------------------------------------
1 | // Package authorization provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package authorization
5 |
6 | import (
7 | "context"
8 | "encoding/json"
9 | "fmt"
10 | "io/ioutil"
11 | "net/http"
12 | "net/url"
13 | runt "runtime"
14 | "strings"
15 |
16 | "github.com/amzapi/selling-partner-api-sdk/pkg/runtime"
17 | )
18 |
19 | // RequestBeforeFn is the function signature for the RequestBefore callback function
20 | type RequestBeforeFn func(ctx context.Context, req *http.Request) error
21 |
22 | // ResponseAfterFn is the function signature for the ResponseAfter callback function
23 | type ResponseAfterFn func(ctx context.Context, rsp *http.Response) error
24 |
25 | // Doer performs HTTP requests.
26 | //
27 | // The standard http.Client implements this interface.
28 | type HttpRequestDoer interface {
29 | Do(req *http.Request) (*http.Response, error)
30 | }
31 |
32 | // Client which conforms to the OpenAPI3 specification for this service.
33 | type Client struct {
34 | // The endpoint of the server conforming to this interface, with scheme,
35 | // https://api.deepmap.com for example. This can contain a path relative
36 | // to the server, such as https://api.deepmap.com/dev-test, and all the
37 | // paths in the swagger spec will be appended to the server.
38 | Endpoint string
39 |
40 | // Doer for performing requests, typically a *http.Client with any
41 | // customized settings, such as certificate chains.
42 | Client HttpRequestDoer
43 |
44 | // A callback for modifying requests which are generated before sending over
45 | // the network.
46 | RequestBefore RequestBeforeFn
47 |
48 | // A callback for modifying response which are generated before sending over
49 | // the network.
50 | ResponseAfter ResponseAfterFn
51 |
52 | // The user agent header identifies your application, its version number, and the platform and programming language you are using.
53 | // You must include a user agent header in each request submitted to the sales partner API.
54 | UserAgent string
55 | }
56 |
57 | // ClientOption allows setting custom parameters during construction
58 | type ClientOption func(*Client) error
59 |
60 | // Creates a new Client, with reasonable defaults
61 | func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
62 | // create a client with sane default values
63 | client := Client{
64 | Endpoint: endpoint,
65 | }
66 | // mutate client and add all optional params
67 | for _, o := range opts {
68 | if err := o(&client); err != nil {
69 | return nil, err
70 | }
71 | }
72 | // ensure the endpoint URL always has a trailing slash
73 | if !strings.HasSuffix(client.Endpoint, "/") {
74 | client.Endpoint += "/"
75 | }
76 | // create httpClient, if not already present
77 | if client.Client == nil {
78 | client.Client = http.DefaultClient
79 | }
80 | // setting the default useragent
81 | if client.UserAgent == "" {
82 | client.UserAgent = fmt.Sprintf("selling-partner-api-sdk/v1.0 (Language=%s; Platform=%s-%s)", strings.Replace(runt.Version(), "go", "go/", -1), runt.GOOS, runt.GOARCH)
83 | }
84 | return &client, nil
85 | }
86 |
87 | // WithHTTPClient allows overriding the default Doer, which is
88 | // automatically created using http.Client. This is useful for tests.
89 | func WithHTTPClient(doer HttpRequestDoer) ClientOption {
90 | return func(c *Client) error {
91 | c.Client = doer
92 | return nil
93 | }
94 | }
95 |
96 | // WithUserAgent set up useragent
97 | // add user agent to every request automatically
98 | func WithUserAgent(userAgent string) ClientOption {
99 | return func(c *Client) error {
100 | c.UserAgent = userAgent
101 | return nil
102 | }
103 | }
104 |
105 | // WithRequestBefore allows setting up a callback function, which will be
106 | // called right before sending the request. This can be used to mutate the request.
107 | func WithRequestBefore(fn RequestBeforeFn) ClientOption {
108 | return func(c *Client) error {
109 | c.RequestBefore = fn
110 | return nil
111 | }
112 | }
113 |
114 | // WithResponseAfter allows setting up a callback function, which will be
115 | // called right after get response the request. This can be used to log.
116 | func WithResponseAfter(fn ResponseAfterFn) ClientOption {
117 | return func(c *Client) error {
118 | c.ResponseAfter = fn
119 | return nil
120 | }
121 | }
122 |
123 | // The interface specification for the client above.
124 | type ClientInterface interface {
125 | // GetAuthorizationCode request
126 | GetAuthorizationCode(ctx context.Context, params *GetAuthorizationCodeParams) (*http.Response, error)
127 | }
128 |
129 | func (c *Client) GetAuthorizationCode(ctx context.Context, params *GetAuthorizationCodeParams) (*http.Response, error) {
130 | req, err := NewGetAuthorizationCodeRequest(c.Endpoint, params)
131 | if err != nil {
132 | return nil, err
133 | }
134 |
135 | req = req.WithContext(ctx)
136 | req.Header.Set("User-Agent", c.UserAgent)
137 | if c.RequestBefore != nil {
138 | err = c.RequestBefore(ctx, req)
139 | if err != nil {
140 | return nil, err
141 | }
142 | }
143 |
144 | rsp, err := c.Client.Do(req)
145 | if err != nil {
146 | return nil, err
147 | }
148 |
149 | if c.ResponseAfter != nil {
150 | err = c.ResponseAfter(ctx, rsp)
151 | if err != nil {
152 | return nil, err
153 | }
154 | }
155 | return rsp, nil
156 | }
157 |
158 | // NewGetAuthorizationCodeRequest generates requests for GetAuthorizationCode
159 | func NewGetAuthorizationCodeRequest(endpoint string, params *GetAuthorizationCodeParams) (*http.Request, error) {
160 | var err error
161 |
162 | queryUrl, err := url.Parse(endpoint)
163 | if err != nil {
164 | return nil, err
165 | }
166 |
167 | basePath := fmt.Sprintf("/authorization/v1/authorizationCode")
168 | if basePath[0] == '/' {
169 | basePath = basePath[1:]
170 | }
171 |
172 | queryUrl, err = queryUrl.Parse(basePath)
173 | if err != nil {
174 | return nil, err
175 | }
176 |
177 | queryValues := queryUrl.Query()
178 |
179 | if queryFrag, err := runtime.StyleParam("form", true, "sellingPartnerId", params.SellingPartnerId); err != nil {
180 | return nil, err
181 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
182 | return nil, err
183 | } else {
184 | for k, v := range parsed {
185 | for _, v2 := range v {
186 | queryValues.Add(k, v2)
187 | }
188 | }
189 | }
190 |
191 | if queryFrag, err := runtime.StyleParam("form", true, "developerId", params.DeveloperId); err != nil {
192 | return nil, err
193 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
194 | return nil, err
195 | } else {
196 | for k, v := range parsed {
197 | for _, v2 := range v {
198 | queryValues.Add(k, v2)
199 | }
200 | }
201 | }
202 |
203 | if queryFrag, err := runtime.StyleParam("form", true, "mwsAuthToken", params.MwsAuthToken); err != nil {
204 | return nil, err
205 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
206 | return nil, err
207 | } else {
208 | for k, v := range parsed {
209 | for _, v2 := range v {
210 | queryValues.Add(k, v2)
211 | }
212 | }
213 | }
214 |
215 | queryUrl.RawQuery = queryValues.Encode()
216 |
217 | req, err := http.NewRequest("GET", queryUrl.String(), nil)
218 | if err != nil {
219 | return nil, err
220 | }
221 |
222 | return req, nil
223 | }
224 |
225 | // ClientWithResponses builds on ClientInterface to offer response payloads
226 | type ClientWithResponses struct {
227 | ClientInterface
228 | }
229 |
230 | // NewClientWithResponses creates a new ClientWithResponses, which wraps
231 | // Client with return type handling
232 | func NewClientWithResponses(endpoint string, opts ...ClientOption) (*ClientWithResponses, error) {
233 | client, err := NewClient(endpoint, opts...)
234 | if err != nil {
235 | return nil, err
236 | }
237 | return &ClientWithResponses{client}, nil
238 | }
239 |
240 | // WithBaseURL overrides the baseURL.
241 | func WithBaseURL(baseURL string) ClientOption {
242 | return func(c *Client) error {
243 | newBaseURL, err := url.Parse(baseURL)
244 | if err != nil {
245 | return err
246 | }
247 | c.Endpoint = newBaseURL.String()
248 | return nil
249 | }
250 | }
251 |
252 | // ClientWithResponsesInterface is the interface specification for the client with responses above.
253 | type ClientWithResponsesInterface interface {
254 | // GetAuthorizationCode request
255 | GetAuthorizationCodeWithResponse(ctx context.Context, params *GetAuthorizationCodeParams) (*GetAuthorizationCodeResp, error)
256 | }
257 |
258 | type GetAuthorizationCodeResp struct {
259 | Body []byte
260 | HTTPResponse *http.Response
261 | Model *GetAuthorizationCodeResponse
262 | }
263 |
264 | // Status returns HTTPResponse.Status
265 | func (r GetAuthorizationCodeResp) Status() string {
266 | if r.HTTPResponse != nil {
267 | return r.HTTPResponse.Status
268 | }
269 | return http.StatusText(0)
270 | }
271 |
272 | // StatusCode returns HTTPResponse.StatusCode
273 | func (r GetAuthorizationCodeResp) StatusCode() int {
274 | if r.HTTPResponse != nil {
275 | return r.HTTPResponse.StatusCode
276 | }
277 | return 0
278 | }
279 |
280 | // GetAuthorizationCodeWithResponse request returning *GetAuthorizationCodeResponse
281 | func (c *ClientWithResponses) GetAuthorizationCodeWithResponse(ctx context.Context, params *GetAuthorizationCodeParams) (*GetAuthorizationCodeResp, error) {
282 | rsp, err := c.GetAuthorizationCode(ctx, params)
283 | if err != nil {
284 | return nil, err
285 | }
286 | return ParseGetAuthorizationCodeResp(rsp)
287 | }
288 |
289 | // ParseGetAuthorizationCodeResp parses an HTTP response from a GetAuthorizationCodeWithResponse call
290 | func ParseGetAuthorizationCodeResp(rsp *http.Response) (*GetAuthorizationCodeResp, error) {
291 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
292 | defer rsp.Body.Close()
293 | if err != nil {
294 | return nil, err
295 | }
296 |
297 | response := &GetAuthorizationCodeResp{
298 | Body: bodyBytes,
299 | HTTPResponse: rsp,
300 | }
301 |
302 | var dest GetAuthorizationCodeResponse
303 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
304 | return nil, err
305 | }
306 |
307 | response.Model = &dest
308 |
309 | if rsp.StatusCode >= 300 {
310 | err = fmt.Errorf(rsp.Status)
311 | }
312 |
313 | return response, err
314 | }
315 |
--------------------------------------------------------------------------------
/uploads/api.gen.go:
--------------------------------------------------------------------------------
1 | // Package uploads provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package uploads
5 |
6 | import (
7 | "context"
8 | "encoding/json"
9 | "fmt"
10 | "io/ioutil"
11 | "net/http"
12 | "net/url"
13 | runt "runtime"
14 | "strings"
15 |
16 | "github.com/amzapi/selling-partner-api-sdk/pkg/runtime"
17 | )
18 |
19 | // RequestBeforeFn is the function signature for the RequestBefore callback function
20 | type RequestBeforeFn func(ctx context.Context, req *http.Request) error
21 |
22 | // ResponseAfterFn is the function signature for the ResponseAfter callback function
23 | type ResponseAfterFn func(ctx context.Context, rsp *http.Response) error
24 |
25 | // Doer performs HTTP requests.
26 | //
27 | // The standard http.Client implements this interface.
28 | type HttpRequestDoer interface {
29 | Do(req *http.Request) (*http.Response, error)
30 | }
31 |
32 | // Client which conforms to the OpenAPI3 specification for this service.
33 | type Client struct {
34 | // The endpoint of the server conforming to this interface, with scheme,
35 | // https://api.deepmap.com for example. This can contain a path relative
36 | // to the server, such as https://api.deepmap.com/dev-test, and all the
37 | // paths in the swagger spec will be appended to the server.
38 | Endpoint string
39 |
40 | // Doer for performing requests, typically a *http.Client with any
41 | // customized settings, such as certificate chains.
42 | Client HttpRequestDoer
43 |
44 | // A callback for modifying requests which are generated before sending over
45 | // the network.
46 | RequestBefore RequestBeforeFn
47 |
48 | // A callback for modifying response which are generated before sending over
49 | // the network.
50 | ResponseAfter ResponseAfterFn
51 |
52 | // The user agent header identifies your application, its version number, and the platform and programming language you are using.
53 | // You must include a user agent header in each request submitted to the sales partner API.
54 | UserAgent string
55 | }
56 |
57 | // ClientOption allows setting custom parameters during construction
58 | type ClientOption func(*Client) error
59 |
60 | // Creates a new Client, with reasonable defaults
61 | func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
62 | // create a client with sane default values
63 | client := Client{
64 | Endpoint: endpoint,
65 | }
66 | // mutate client and add all optional params
67 | for _, o := range opts {
68 | if err := o(&client); err != nil {
69 | return nil, err
70 | }
71 | }
72 | // ensure the endpoint URL always has a trailing slash
73 | if !strings.HasSuffix(client.Endpoint, "/") {
74 | client.Endpoint += "/"
75 | }
76 | // create httpClient, if not already present
77 | if client.Client == nil {
78 | client.Client = http.DefaultClient
79 | }
80 | // setting the default useragent
81 | if client.UserAgent == "" {
82 | client.UserAgent = fmt.Sprintf("selling-partner-api-sdk/v1.0 (Language=%s; Platform=%s-%s)", strings.Replace(runt.Version(), "go", "go/", -1), runt.GOOS, runt.GOARCH)
83 | }
84 | return &client, nil
85 | }
86 |
87 | // WithHTTPClient allows overriding the default Doer, which is
88 | // automatically created using http.Client. This is useful for tests.
89 | func WithHTTPClient(doer HttpRequestDoer) ClientOption {
90 | return func(c *Client) error {
91 | c.Client = doer
92 | return nil
93 | }
94 | }
95 |
96 | // WithUserAgent set up useragent
97 | // add user agent to every request automatically
98 | func WithUserAgent(userAgent string) ClientOption {
99 | return func(c *Client) error {
100 | c.UserAgent = userAgent
101 | return nil
102 | }
103 | }
104 |
105 | // WithRequestBefore allows setting up a callback function, which will be
106 | // called right before sending the request. This can be used to mutate the request.
107 | func WithRequestBefore(fn RequestBeforeFn) ClientOption {
108 | return func(c *Client) error {
109 | c.RequestBefore = fn
110 | return nil
111 | }
112 | }
113 |
114 | // WithResponseAfter allows setting up a callback function, which will be
115 | // called right after get response the request. This can be used to log.
116 | func WithResponseAfter(fn ResponseAfterFn) ClientOption {
117 | return func(c *Client) error {
118 | c.ResponseAfter = fn
119 | return nil
120 | }
121 | }
122 |
123 | // The interface specification for the client above.
124 | type ClientInterface interface {
125 | // CreateUploadDestinationForResource request
126 | CreateUploadDestinationForResource(ctx context.Context, resource string, params *CreateUploadDestinationForResourceParams) (*http.Response, error)
127 | }
128 |
129 | func (c *Client) CreateUploadDestinationForResource(ctx context.Context, resource string, params *CreateUploadDestinationForResourceParams) (*http.Response, error) {
130 | req, err := NewCreateUploadDestinationForResourceRequest(c.Endpoint, resource, params)
131 | if err != nil {
132 | return nil, err
133 | }
134 |
135 | req = req.WithContext(ctx)
136 | req.Header.Set("User-Agent", c.UserAgent)
137 | if c.RequestBefore != nil {
138 | err = c.RequestBefore(ctx, req)
139 | if err != nil {
140 | return nil, err
141 | }
142 | }
143 |
144 | rsp, err := c.Client.Do(req)
145 | if err != nil {
146 | return nil, err
147 | }
148 |
149 | if c.ResponseAfter != nil {
150 | err = c.ResponseAfter(ctx, rsp)
151 | if err != nil {
152 | return nil, err
153 | }
154 | }
155 | return rsp, nil
156 | }
157 |
158 | // NewCreateUploadDestinationForResourceRequest generates requests for CreateUploadDestinationForResource
159 | func NewCreateUploadDestinationForResourceRequest(endpoint string, resource string, params *CreateUploadDestinationForResourceParams) (*http.Request, error) {
160 | var err error
161 |
162 | var pathParam0 string
163 |
164 | pathParam0, err = runtime.StyleParam("simple", false, "resource", resource)
165 | if err != nil {
166 | return nil, err
167 | }
168 |
169 | queryUrl, err := url.Parse(endpoint)
170 | if err != nil {
171 | return nil, err
172 | }
173 |
174 | basePath := fmt.Sprintf("/uploads/2020-11-01/uploadDestinations/%s", pathParam0)
175 | if basePath[0] == '/' {
176 | basePath = basePath[1:]
177 | }
178 |
179 | queryUrl, err = queryUrl.Parse(basePath)
180 | if err != nil {
181 | return nil, err
182 | }
183 |
184 | queryValues := queryUrl.Query()
185 |
186 | if queryFrag, err := runtime.StyleParam("form", true, "marketplaceIds", params.MarketplaceIds); err != nil {
187 | return nil, err
188 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
189 | return nil, err
190 | } else {
191 | for k, v := range parsed {
192 | for _, v2 := range v {
193 | queryValues.Add(k, v2)
194 | }
195 | }
196 | }
197 |
198 | if queryFrag, err := runtime.StyleParam("form", true, "contentMD5", params.ContentMD5); err != nil {
199 | return nil, err
200 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
201 | return nil, err
202 | } else {
203 | for k, v := range parsed {
204 | for _, v2 := range v {
205 | queryValues.Add(k, v2)
206 | }
207 | }
208 | }
209 |
210 | if params.ContentType != nil {
211 |
212 | if queryFrag, err := runtime.StyleParam("form", true, "contentType", *params.ContentType); err != nil {
213 | return nil, err
214 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
215 | return nil, err
216 | } else {
217 | for k, v := range parsed {
218 | for _, v2 := range v {
219 | queryValues.Add(k, v2)
220 | }
221 | }
222 | }
223 |
224 | }
225 |
226 | queryUrl.RawQuery = queryValues.Encode()
227 |
228 | req, err := http.NewRequest("POST", queryUrl.String(), nil)
229 | if err != nil {
230 | return nil, err
231 | }
232 |
233 | return req, nil
234 | }
235 |
236 | // ClientWithResponses builds on ClientInterface to offer response payloads
237 | type ClientWithResponses struct {
238 | ClientInterface
239 | }
240 |
241 | // NewClientWithResponses creates a new ClientWithResponses, which wraps
242 | // Client with return type handling
243 | func NewClientWithResponses(endpoint string, opts ...ClientOption) (*ClientWithResponses, error) {
244 | client, err := NewClient(endpoint, opts...)
245 | if err != nil {
246 | return nil, err
247 | }
248 | return &ClientWithResponses{client}, nil
249 | }
250 |
251 | // WithBaseURL overrides the baseURL.
252 | func WithBaseURL(baseURL string) ClientOption {
253 | return func(c *Client) error {
254 | newBaseURL, err := url.Parse(baseURL)
255 | if err != nil {
256 | return err
257 | }
258 | c.Endpoint = newBaseURL.String()
259 | return nil
260 | }
261 | }
262 |
263 | // ClientWithResponsesInterface is the interface specification for the client with responses above.
264 | type ClientWithResponsesInterface interface {
265 | // CreateUploadDestinationForResource request
266 | CreateUploadDestinationForResourceWithResponse(ctx context.Context, resource string, params *CreateUploadDestinationForResourceParams) (*CreateUploadDestinationForResourceResp, error)
267 | }
268 |
269 | type CreateUploadDestinationForResourceResp struct {
270 | Body []byte
271 | HTTPResponse *http.Response
272 | Model *CreateUploadDestinationResponse
273 | }
274 |
275 | // Status returns HTTPResponse.Status
276 | func (r CreateUploadDestinationForResourceResp) Status() string {
277 | if r.HTTPResponse != nil {
278 | return r.HTTPResponse.Status
279 | }
280 | return http.StatusText(0)
281 | }
282 |
283 | // StatusCode returns HTTPResponse.StatusCode
284 | func (r CreateUploadDestinationForResourceResp) StatusCode() int {
285 | if r.HTTPResponse != nil {
286 | return r.HTTPResponse.StatusCode
287 | }
288 | return 0
289 | }
290 |
291 | // CreateUploadDestinationForResourceWithResponse request returning *CreateUploadDestinationForResourceResponse
292 | func (c *ClientWithResponses) CreateUploadDestinationForResourceWithResponse(ctx context.Context, resource string, params *CreateUploadDestinationForResourceParams) (*CreateUploadDestinationForResourceResp, error) {
293 | rsp, err := c.CreateUploadDestinationForResource(ctx, resource, params)
294 | if err != nil {
295 | return nil, err
296 | }
297 | return ParseCreateUploadDestinationForResourceResp(rsp)
298 | }
299 |
300 | // ParseCreateUploadDestinationForResourceResp parses an HTTP response from a CreateUploadDestinationForResourceWithResponse call
301 | func ParseCreateUploadDestinationForResourceResp(rsp *http.Response) (*CreateUploadDestinationForResourceResp, error) {
302 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
303 | defer rsp.Body.Close()
304 | if err != nil {
305 | return nil, err
306 | }
307 |
308 | response := &CreateUploadDestinationForResourceResp{
309 | Body: bodyBytes,
310 | HTTPResponse: rsp,
311 | }
312 |
313 | var dest CreateUploadDestinationResponse
314 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
315 | return nil, err
316 | }
317 |
318 | response.Model = &dest
319 |
320 | if rsp.StatusCode >= 300 {
321 | err = fmt.Errorf(rsp.Status)
322 | }
323 |
324 | return response, err
325 | }
326 |
--------------------------------------------------------------------------------
/feeds/types.gen.go:
--------------------------------------------------------------------------------
1 | // Package feeds provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package feeds
5 |
6 | import (
7 | "encoding/json"
8 | "fmt"
9 | "time"
10 |
11 | "github.com/pkg/errors"
12 | )
13 |
14 | // CancelFeedResponse defines model for CancelFeedResponse.
15 | type CancelFeedResponse struct {
16 |
17 | // A list of error responses returned when a request is unsuccessful.
18 | Errors *ErrorList `json:"errors,omitempty"`
19 | }
20 |
21 | // CreateFeedDocumentResponse defines model for CreateFeedDocumentResponse.
22 | type CreateFeedDocumentResponse struct {
23 |
24 | // The identifier of the feed document.
25 | FeedDocumentId string `json:"feedDocumentId"`
26 |
27 | // The presigned URL for uploading the feed contents. This URL expires after 5 minutes.
28 | Url string `json:"url"`
29 | }
30 |
31 | // CreateFeedDocumentSpecification defines model for CreateFeedDocumentSpecification.
32 | type CreateFeedDocumentSpecification struct {
33 |
34 | // The content type of the feed.
35 | ContentType string `json:"contentType"`
36 | }
37 |
38 | // CreateFeedResponse defines model for CreateFeedResponse.
39 | type CreateFeedResponse struct {
40 |
41 | // The identifier for the feed. This identifier is unique only in combination with a seller ID.
42 | FeedId string `json:"feedId"`
43 | }
44 |
45 | // CreateFeedSpecification defines model for CreateFeedSpecification.
46 | type CreateFeedSpecification struct {
47 |
48 | // Additional options to control the feed. These vary by feed type.
49 | FeedOptions *FeedOptions `json:"feedOptions,omitempty"`
50 |
51 | // The feed type.
52 | FeedType string `json:"feedType"`
53 |
54 | // The document identifier returned by the createFeedDocument operation. Encrypt and upload the feed document contents before calling the createFeed operation.
55 | InputFeedDocumentId string `json:"inputFeedDocumentId"`
56 |
57 | // A list of identifiers for marketplaces that you want the feed to be applied to.
58 | MarketplaceIds []string `json:"marketplaceIds"`
59 | }
60 |
61 | // Error defines model for Error.
62 | type Error struct {
63 |
64 | // An error code that identifies the type of error that occurred.
65 | Code string `json:"code"`
66 |
67 | // Additional details that can help the caller understand or fix the issue.
68 | Details *string `json:"details,omitempty"`
69 |
70 | // A message that describes the error condition in a human-readable form.
71 | Message string `json:"message"`
72 | }
73 |
74 | // ErrorList defines model for ErrorList.
75 | type ErrorList []Error
76 |
77 | // Feed defines model for Feed.
78 | type Feed struct {
79 |
80 | // The date and time when the feed was created, in ISO 8601 date time format.
81 | CreatedTime time.Time `json:"createdTime"`
82 |
83 | // The identifier for the feed. This identifier is unique only in combination with a seller ID.
84 | FeedId string `json:"feedId"`
85 |
86 | // The feed type.
87 | FeedType string `json:"feedType"`
88 |
89 | // A list of identifiers for the marketplaces that the feed is applied to.
90 | MarketplaceIds *[]string `json:"marketplaceIds,omitempty"`
91 |
92 | // The date and time when feed processing completed, in ISO 8601 date time format.
93 | ProcessingEndTime *time.Time `json:"processingEndTime,omitempty"`
94 |
95 | // The date and time when feed processing started, in ISO 8601 date time format.
96 | ProcessingStartTime *time.Time `json:"processingStartTime,omitempty"`
97 |
98 | // The processing status of the feed.
99 | ProcessingStatus string `json:"processingStatus"`
100 |
101 | // The identifier for the feed document. This identifier is unique only in combination with a seller ID.
102 | ResultFeedDocumentId *string `json:"resultFeedDocumentId,omitempty"`
103 | }
104 |
105 | // FeedDocumentEncryptionDetails defines model for FeedDocumentEncryptionDetails.
106 | type FeedDocumentEncryptionDetails struct {
107 |
108 | // The vector to encrypt or decrypt the document contents using Cipher Block Chaining (CBC).
109 | InitializationVector string `json:"initializationVector"`
110 |
111 | // The encryption key used to encrypt or decrypt the document contents.
112 | Key string `json:"key"`
113 |
114 | // The encryption standard required to encrypt or decrypt the document contents.
115 | Standard string `json:"standard"`
116 | }
117 |
118 | // FeedList defines model for FeedList.
119 | type FeedList []Feed
120 |
121 | // FeedOptions defines model for FeedOptions.
122 | type FeedOptions struct {
123 | AdditionalProperties map[string]string `json:"-"`
124 | }
125 |
126 | // GetFeedDocumentResponse defines model for GetFeedDocumentResponse.
127 | type GetFeedDocumentResponse struct {
128 |
129 | // A list of error responses returned when a request is unsuccessful.
130 | Errors *ErrorList `json:"errors,omitempty"`
131 |
132 | // If present, the feed document contents are compressed using the indicated algorithm.
133 | CompressionAlgorithm *string `json:"compressionAlgorithm,omitempty"`
134 |
135 | // The identifier for the feed document. This identifier is unique only in combination with a seller ID.
136 | FeedDocumentId string `json:"feedDocumentId"`
137 |
138 | // A presigned URL for the feed document. This URL expires after 5 minutes.
139 | Url string `json:"url"`
140 | }
141 |
142 | // GetFeedResponse defines model for GetFeedResponse.
143 | type GetFeedResponse struct {
144 |
145 | // A list of error responses returned when a request is unsuccessful.
146 | Errors *ErrorList `json:"errors,omitempty"`
147 |
148 | // The date and time when the feed was created, in ISO 8601 date time format.
149 | CreatedTime time.Time `json:"createdTime"`
150 |
151 | // The identifier for the feed. This identifier is unique only in combination with a seller ID.
152 | FeedId string `json:"feedId"`
153 |
154 | // The feed type.
155 | FeedType string `json:"feedType"`
156 |
157 | // A list of identifiers for the marketplaces that the feed is applied to.
158 | MarketplaceIds *[]string `json:"marketplaceIds,omitempty"`
159 |
160 | // The date and time when feed processing completed, in ISO 8601 date time format.
161 | ProcessingEndTime *time.Time `json:"processingEndTime,omitempty"`
162 |
163 | // The date and time when feed processing started, in ISO 8601 date time format.
164 | ProcessingStartTime *time.Time `json:"processingStartTime,omitempty"`
165 |
166 | // The processing status of the feed.
167 | ProcessingStatus string `json:"processingStatus"`
168 |
169 | // The identifier for the feed document. This identifier is unique only in combination with a seller ID.
170 | ResultFeedDocumentId *string `json:"resultFeedDocumentId,omitempty"`
171 | }
172 |
173 | // GetFeedsResponse defines model for GetFeedsResponse.
174 | type GetFeedsResponse struct {
175 |
176 | // A list of error responses returned when a request is unsuccessful.
177 | Errors *ErrorList `json:"errors,omitempty"`
178 |
179 | // Returned when the number of results exceeds pageSize. To get the next page of results, call the getFeeds operation with this token as the only parameter.
180 | NextToken *string `json:"nextToken,omitempty"`
181 | Payload *FeedList `json:"payload,omitempty"`
182 | }
183 |
184 | // CreateFeedDocumentJSONBody defines parameters for CreateFeedDocument.
185 | type CreateFeedDocumentJSONBody CreateFeedDocumentSpecification
186 |
187 | // GetFeedsParams defines parameters for GetFeeds.
188 | type GetFeedsParams struct {
189 |
190 | // A list of feed types used to filter feeds. When feedTypes is provided, the other filter parameters (processingStatuses, marketplaceIds, createdSince, createdUntil) and pageSize may also be provided. Either feedTypes or nextToken is required.
191 | FeedTypes *[]string `json:"feedTypes,omitempty"`
192 |
193 | // A list of marketplace identifiers used to filter feeds. The feeds returned will match at least one of the marketplaces that you specify.
194 | MarketplaceIds *[]string `json:"marketplaceIds,omitempty"`
195 |
196 | // The maximum number of feeds to return in a single call.
197 | PageSize *int `json:"pageSize,omitempty"`
198 |
199 | // A list of processing statuses used to filter feeds.
200 | ProcessingStatuses *[]string `json:"processingStatuses,omitempty"`
201 |
202 | // The earliest feed creation date and time for feeds included in the response, in ISO 8601 format. The default is 90 days ago. Feeds are retained for a maximum of 90 days.
203 | CreatedSince *time.Time `json:"createdSince,omitempty"`
204 |
205 | // The latest feed creation date and time for feeds included in the response, in ISO 8601 format. The default is now.
206 | CreatedUntil *time.Time `json:"createdUntil,omitempty"`
207 |
208 | // A string token returned in the response to your previous request. nextToken is returned when the number of results exceeds the specified pageSize value. To get the next page of results, call the getFeeds operation and include this token as the only parameter. Specifying nextToken with any other parameters will cause the request to fail.
209 | NextToken *string `json:"nextToken,omitempty"`
210 | }
211 |
212 | // CreateFeedJSONBody defines parameters for CreateFeed.
213 | type CreateFeedJSONBody CreateFeedSpecification
214 |
215 | // CreateFeedDocumentRequestBody defines body for CreateFeedDocument for application/json ContentType.
216 | type CreateFeedDocumentJSONRequestBody CreateFeedDocumentJSONBody
217 |
218 | // CreateFeedRequestBody defines body for CreateFeed for application/json ContentType.
219 | type CreateFeedJSONRequestBody CreateFeedJSONBody
220 |
221 | // Getter for additional properties for FeedOptions. Returns the specified
222 | // element and whether it was found
223 | func (a FeedOptions) Get(fieldName string) (value string, found bool) {
224 | if a.AdditionalProperties != nil {
225 | value, found = a.AdditionalProperties[fieldName]
226 | }
227 | return
228 | }
229 |
230 | // Setter for additional properties for FeedOptions
231 | func (a *FeedOptions) Set(fieldName string, value string) {
232 | if a.AdditionalProperties == nil {
233 | a.AdditionalProperties = make(map[string]string)
234 | }
235 | a.AdditionalProperties[fieldName] = value
236 | }
237 |
238 | // Override default JSON handling for FeedOptions to handle AdditionalProperties
239 | func (a *FeedOptions) UnmarshalJSON(b []byte) error {
240 | object := make(map[string]json.RawMessage)
241 | err := json.Unmarshal(b, &object)
242 | if err != nil {
243 | return err
244 | }
245 |
246 | if len(object) != 0 {
247 | a.AdditionalProperties = make(map[string]string)
248 | for fieldName, fieldBuf := range object {
249 | var fieldVal string
250 | err := json.Unmarshal(fieldBuf, &fieldVal)
251 | if err != nil {
252 | return errors.Wrap(err, fmt.Sprintf("error unmarshaling field %s", fieldName))
253 | }
254 | a.AdditionalProperties[fieldName] = fieldVal
255 | }
256 | }
257 | return nil
258 | }
259 |
260 | // Override default JSON handling for FeedOptions to handle AdditionalProperties
261 | func (a FeedOptions) MarshalJSON() ([]byte, error) {
262 | var err error
263 | object := make(map[string]json.RawMessage)
264 |
265 | for fieldName, field := range a.AdditionalProperties {
266 | object[fieldName], err = json.Marshal(field)
267 | if err != nil {
268 | return nil, errors.Wrap(err, fmt.Sprintf("error marshaling '%s'", fieldName))
269 | }
270 | }
271 | return json.Marshal(object)
272 | }
273 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Amazon's Selling Partner API (SP-API) Golang SDK
2 |
3 | [](https://pkg.go.dev/gopkg.me/selling-partner-api-sdk)
4 |
5 | ## Installation
6 |
7 | ~~~~
8 | go get -u github.com/amzapi/selling-partner-api-sdk
9 | ~~~~
10 |
11 | ## Progress
12 |
13 | * [X] authorization ([authorization-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/authorization-api-model/authorization.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/authorization-api/authorization.md))
14 | * [X] catalog ([catalog-items-api-model](https://github.com/amzn/selling-partner-api-docs/blob/main/references/catalog-items-api/catalogItemsV0.md) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/catalog-items-api/catalogItemsV0.md))
15 | * [X] fbaInbound ([fulfillment-inbound-api-model](https://github.com/amzn/selling-partner-api-docs/blob/main/references/fulfillment-inbound-api/fulfillmentInboundV0.md) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/fulfillment-inbound-api/fulfillmentInboundV0.md))
16 | * [X] fbaInventory ([fba-inventory-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/fba-inventory-api-model/fbaInventory.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/fba-inventory-api/fbaInventory.md))
17 | * [X] fbaOutbound ([fulfillment-outbound-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/fulfillment-outbound-api-model/fulfillmentOutbound_2020-07-01.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/fulfillment-outbound-api/fulfillmentOutbound_2020-07-01.md))
18 | * [X] feeds ([feeds-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/feeds-api-model/feeds_2021-06-30.json) [DOC](https://github.com/amzn/selling-partner-api-docs/tree/main/references/feeds-api))
19 | * [X] fees ([product-fees-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/product-fees-api-model/productFeesV0.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/product-fees-api/productFeesV0.md))
20 | * [X] finances ([finances-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/finances-api-model/financesV0.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/finances-api/financesV0.md))
21 | * [X] merchantFulfillment ([merchant-fulfillment-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/merchant-fulfillment-api-model/merchantFulfillmentV0.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/merchant-fulfillment-api/merchantFulfillmentV0.md))
22 | * [X] messaging ([messaging-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/messaging-api-model/messaging.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/messaging-api/messaging.md))
23 | * [X] notifications ([notifications-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/notifications-api-model/notifications.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/notifications-api/notifications.md))
24 | * [X] ordersV0 ([orders-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/orders-api-model/ordersV0.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/orders-api/ordersV0.md))
25 | * [X] productPricing ([product-pricing-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/product-pricing-api-model/productPricingV0.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/product-pricing-api/productPricingV0.md))
26 | * [X] reports ([reports-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/reports-api-model/reports_2020-09-04.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/reports-api/reports_2020-09-04.md))
27 | * [X] sales ([sales-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/sales-api-model/sales.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/sales-api/sales.md))
28 | * [X] sellers ([sellers-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/sellers-api-model/sellers.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/sellers-api/sellers.md))
29 | * [X] service ([services-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/services-api-model/services.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/services-api/services.md))
30 | * [X] shipping ([shipping-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/shipping-api-model/shipping.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/shipping-api/shipping.md))
31 | * [ ] smallAndLight ([fba-small-and-light-api](https://github.com/amzn/selling-partner-api-models/blob/main/models/fba-small-and-light-api-model/fbaSmallandLight.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/fba-small-and-light-api/fbaSmallandLight.md))
32 | * [X] solicitations ([solicitations-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/solicitations-api-model/solicitations.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/solicitations-api/solicitations.md))
33 | * [X] uploads ([uploads-api-model](https://github.com/amzn/selling-partner-api-models/blob/main/models/uploads-api-model/uploads_2020-11-01.json) [DOC](https://github.com/amzn/selling-partner-api-docs/blob/main/references/uploads-api/uploads_2020-11-01.md))
34 |
35 | ## Example
36 |
37 | ```go
38 | package main
39 |
40 | import (
41 | "context"
42 | "log"
43 | "net/http"
44 | "net/http/httputil"
45 |
46 | sp "github.com/amzapi/selling-partner-api-sdk/pkg/selling-partner"
47 | "github.com/amzapi/selling-partner-api-sdk/sellers"
48 |
49 | "github.com/google/uuid"
50 | "github.com/pkg/errors"
51 | )
52 |
53 | func main() {
54 |
55 | sellingPartner, err := sp.NewSellingPartner(&sp.Config{
56 | ClientID: "",
57 | ClientSecret: "",
58 | RefreshToken: "",
59 | })
60 |
61 | if err != nil {
62 | panic(err)
63 | }
64 |
65 | endpoint := "https://sellingpartnerapi-fe.amazon.com"
66 |
67 | seller, err := sellers.NewClientWithResponses(endpoint,
68 | sellers.WithRequestBefore(func(ctx context.Context, req *http.Request) error {
69 | req.Header.Add("X-Amzn-Requestid", uuid.New().String()) //tracking requests
70 | err = sellingPartner.AuthorizeRequest(req)
71 | if err != nil {
72 | return errors.Wrap(err, "sign error")
73 | }
74 | dump, err := httputil.DumpRequest(req, true)
75 | if err != nil {
76 | return errors.Wrap(err, "DumpRequest Error")
77 | }
78 | log.Printf("DumpRequest = %s", dump)
79 | return nil
80 | }),
81 | sellers.WithResponseAfter(func(ctx context.Context, rsp *http.Response) error {
82 | dump, err := httputil.DumpResponse(rsp, true)
83 | if err != nil {
84 | return errors.Wrap(err, "DumpResponse Error")
85 | }
86 | log.Printf("DumpResponse = %s", dump)
87 | return nil
88 | }),
89 | )
90 |
91 | if err != nil {
92 | panic(err)
93 | }
94 |
95 | ctx := context.Background()
96 | _, err = seller.GetMarketplaceParticipationsWithResponse(ctx)
97 |
98 | if err != nil {
99 | panic(err)
100 | }
101 | }
102 |
103 | ```
104 |
105 | #Report Decryption
106 | Amazon specification of version `2020-09-04` returns encrypted reports. To decrypt the reports you could use [the Decrypt function of the decryption package](./pkg/decryption/decryptor.go).
107 | ### Test example
108 | The test example uses `amzn.GetReportDocumentResponse` from [Amazon models](https://github.com/amzn/selling-partner-api-models/blob/main/models/reports-api-model/reports_2020-09-04.json#L137) and the
109 | Decrypt function to download, decrypt and dump report.
110 | ```go
111 | func TestSellingPartnerGetReportDocumentThirdParty(t *testing.T) {
112 | sellingPartner, err := sp.NewSellingPartner(&sp.Config{
113 | ClientID: "***",
114 | ClientSecret: "***",
115 | RefreshToken: "***",
116 | })
117 |
118 | if err != nil {
119 | t.Fatal("Failed to create NewSellingPartner: ", err)
120 | }
121 |
122 | report, err := reports.NewClientWithResponses(spiHost,
123 | reports.WithRequestBefore(func(ctx context.Context, req *http.Request) error {
124 | err = sellingPartner.AuthorizeRequest(req)
125 | if err != nil {
126 | return errors.Wrap(err, "sign error")
127 | }
128 | dump, err := httputil.DumpRequest(req, true)
129 | if err != nil {
130 | return errors.Wrap(err, "DumpRequest Error")
131 | }
132 | ioutil.WriteFile("test-samples/3dumpedThirdPartyReqGetReports.txt", dump, 0777)
133 | return nil
134 | }),
135 | reports.WithResponseAfter(func(ctx context.Context, rsp *http.Response) error {
136 | dump, err := httputil.DumpResponse(rsp, true)
137 | if err != nil {
138 | return errors.Wrap(err, "DumpResponse Error")
139 | }
140 | ioutil.WriteFile("test-samples/3dumpedThirdPartyRespGetReports.txt", dump, 0777)
141 | return nil
142 | }),
143 | )
144 | if err != nil {
145 | t.Fatal("Failed to create NewClientWithResponses: ", err)
146 | }
147 | ctx := context.Background()
148 | reportDocumentId := "***"
149 | resp, err := report.GetReportDocument(ctx, reportDocumentId)
150 | if err != nil {
151 | t.Fatal("Failed to make GetReportDocument request: ", err)
152 | }
153 | if resp.StatusCode < 200 || resp.StatusCode > 299 {
154 | t.Fatal("Service returned a status that isn't 2xx: ", resp.StatusCode)
155 | }
156 | defer resp.Body.Close()
157 | var bodyData []byte
158 | resp.Body.Read(bodyData)
159 | content, err := ioutil.ReadAll(resp.Body)
160 | if err != nil {
161 | t.Fatal("Failed to read GetReportDocument response body: ", err)
162 | }
163 | var reportDocumentResp amzn.GetReportDocumentResponse
164 | err = json.Unmarshal(content, &reportDocumentResp)
165 | if err != nil {
166 | t.Fatal("Failed to unmarshall GetReportDocument response: ", err)
167 | }
168 | if reportDocumentResp.Errors != nil {
169 | t.Fatal("Got errors in the GetReportDocument response: ", reportDocumentResp.Errors)
170 | }
171 | respWithDocContent, err := http.Get(reportDocumentResp.Payload.Url)
172 | if err != nil {
173 | t.Fatal("failed to make request to "+reportDocumentResp.Payload.Url+" : ", err)
174 | }
175 | if respWithDocContent.StatusCode < 200 || respWithDocContent.StatusCode > 299 {
176 | t.Fatal("Service returned a status that isn't 2xx: ", respWithDocContent.StatusCode)
177 | }
178 | defer respWithDocContent.Body.Close()
179 |
180 | reportContentBytes, err := ioutil.ReadAll(respWithDocContent.Body)
181 | if err != nil {
182 | t.Fatal("Failed to read Report content body: ", err)
183 | }
184 | ioutil.WriteFile("test-samples/3_encrypted_"+reportDocumentId+"_"+reportType+"_report.txt", reportContentBytes, 0777)
185 | decryptedFilecontent, err := decryption.Decrypt(reportDocumentResp.Payload.EncryptionDetails.Key, reportDocumentResp.Payload.EncryptionDetails.InitializationVector, reportContentBytes)
186 | if err != nil {
187 | t.Fatal("Failed to decrypt file content: ", err)
188 | }
189 | ioutil.WriteFile("test-samples/3_"+reportDocumentId+"_"+reportType+"_report.txt", decryptedFilecontent, 0777)
190 | }
191 | ```
192 |
--------------------------------------------------------------------------------
/pkg/runtime/bindparam_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2019 DeepMap, Inc.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 | package runtime
15 |
16 | import (
17 | "net/url"
18 | "testing"
19 | "time"
20 |
21 | "github.com/stretchr/testify/assert"
22 | "github.com/stretchr/testify/require"
23 |
24 | "github.com/amzapi/selling-partner-api-sdk/pkg/types"
25 | )
26 |
27 | func TestSplitParameter(t *testing.T) {
28 | // Please see the parameter serialization docs to understand these test
29 | // cases
30 |
31 | expectedPrimitive := []string{"5"}
32 | expectedArray := []string{"3", "4", "5"}
33 | expectedObject := []string{"role", "admin", "firstName", "Alex"}
34 | expectedExplodedObject := []string{"role=admin", "firstName=Alex"}
35 |
36 | var result []string
37 | var err error
38 | // ------------------------ simple style ---------------------------------
39 | result, err = splitStyledParameter("simple",
40 | false,
41 | false,
42 | "id",
43 | "5")
44 | assert.NoError(t, err)
45 | assert.EqualValues(t, expectedPrimitive, result)
46 |
47 | result, err = splitStyledParameter("simple",
48 | false,
49 | false,
50 | "id",
51 | "3,4,5")
52 | assert.NoError(t, err)
53 | assert.EqualValues(t, expectedArray, result)
54 |
55 | result, err = splitStyledParameter("simple",
56 | false,
57 | true,
58 | "id",
59 | "role,admin,firstName,Alex")
60 | assert.NoError(t, err)
61 | assert.EqualValues(t, expectedObject, result)
62 |
63 | result, err = splitStyledParameter("simple",
64 | true,
65 | false,
66 | "id",
67 | "5")
68 | assert.NoError(t, err)
69 | assert.EqualValues(t, expectedPrimitive, result)
70 |
71 | result, err = splitStyledParameter("simple",
72 | true,
73 | false,
74 | "id",
75 | "3,4,5")
76 | assert.NoError(t, err)
77 | assert.EqualValues(t, expectedArray, result)
78 |
79 | result, err = splitStyledParameter("simple",
80 | true,
81 | true,
82 | "id",
83 | "role=admin,firstName=Alex")
84 | assert.NoError(t, err)
85 | assert.EqualValues(t, expectedExplodedObject, result)
86 |
87 | // ------------------------ label style ---------------------------------
88 | result, err = splitStyledParameter("label",
89 | false,
90 | false,
91 | "id",
92 | ".5")
93 | assert.NoError(t, err)
94 | assert.EqualValues(t, expectedPrimitive, result)
95 |
96 | result, err = splitStyledParameter("label",
97 | false,
98 | false,
99 | "id",
100 | ".3,4,5")
101 | assert.NoError(t, err)
102 | assert.EqualValues(t, expectedArray, result)
103 |
104 | result, err = splitStyledParameter("label",
105 | false,
106 | true,
107 | "id",
108 | ".role,admin,firstName,Alex")
109 | assert.NoError(t, err)
110 | assert.EqualValues(t, expectedObject, result)
111 |
112 | result, err = splitStyledParameter("label",
113 | true,
114 | false,
115 | "id",
116 | ".5")
117 | assert.NoError(t, err)
118 | assert.EqualValues(t, expectedPrimitive, result)
119 |
120 | result, err = splitStyledParameter("label",
121 | true,
122 | false,
123 | "id",
124 | ".3.4.5")
125 | assert.NoError(t, err)
126 | assert.EqualValues(t, expectedArray, result)
127 |
128 | result, err = splitStyledParameter("label",
129 | true,
130 | true,
131 | "id",
132 | ".role=admin.firstName=Alex")
133 | assert.NoError(t, err)
134 | assert.EqualValues(t, expectedExplodedObject, result)
135 |
136 | // ------------------------ matrix style ---------------------------------
137 | result, err = splitStyledParameter("matrix",
138 | false,
139 | false,
140 | "id",
141 | ";id=5")
142 | assert.NoError(t, err)
143 | assert.EqualValues(t, expectedPrimitive, result)
144 |
145 | result, err = splitStyledParameter("matrix",
146 | false,
147 | false,
148 | "id",
149 | ";id=3,4,5")
150 | assert.NoError(t, err)
151 | assert.EqualValues(t, expectedArray, result)
152 |
153 | result, err = splitStyledParameter("matrix",
154 | false,
155 | true,
156 | "id",
157 | ";id=role,admin,firstName,Alex")
158 | assert.NoError(t, err)
159 | assert.EqualValues(t, expectedObject, result)
160 |
161 | result, err = splitStyledParameter("matrix",
162 | true,
163 | false,
164 | "id",
165 | ";id=5")
166 | assert.NoError(t, err)
167 | assert.EqualValues(t, expectedPrimitive, result)
168 |
169 | result, err = splitStyledParameter("matrix",
170 | true,
171 | false,
172 | "id",
173 | ";id=3;id=4;id=5")
174 | assert.NoError(t, err)
175 | assert.EqualValues(t, expectedArray, result)
176 |
177 | result, err = splitStyledParameter("matrix",
178 | true,
179 | true,
180 | "id",
181 | ";role=admin;firstName=Alex")
182 | assert.NoError(t, err)
183 | assert.EqualValues(t, expectedExplodedObject, result)
184 |
185 | // ------------------------ form style ---------------------------------
186 | result, err = splitStyledParameter("form",
187 | false,
188 | false,
189 | "id",
190 | "id=5")
191 | assert.NoError(t, err)
192 | assert.EqualValues(t, expectedPrimitive, result)
193 |
194 | result, err = splitStyledParameter("form",
195 | false,
196 | false,
197 | "id",
198 | "id=3,4,5")
199 | assert.NoError(t, err)
200 | assert.EqualValues(t, expectedArray, result)
201 |
202 | result, err = splitStyledParameter("form",
203 | false,
204 | true,
205 | "id",
206 | "id=role,admin,firstName,Alex")
207 | assert.NoError(t, err)
208 | assert.EqualValues(t, expectedObject, result)
209 |
210 | result, err = splitStyledParameter("form",
211 | true,
212 | false,
213 | "id",
214 | "id=5")
215 | assert.NoError(t, err)
216 | assert.EqualValues(t, expectedPrimitive, result)
217 |
218 | result, err = splitStyledParameter("form",
219 | true,
220 | false,
221 | "id",
222 | "id=3&id=4&id=5")
223 | assert.NoError(t, err)
224 | assert.EqualValues(t, expectedArray, result)
225 |
226 | result, err = splitStyledParameter("form",
227 | true,
228 | true,
229 | "id",
230 | "role=admin&firstName=Alex")
231 | assert.NoError(t, err)
232 | assert.EqualValues(t, expectedExplodedObject, result)
233 | }
234 |
235 | func TestBindQueryParameter(t *testing.T) {
236 | t.Run("deepObject", func(t *testing.T) {
237 | type ID struct {
238 | FirstName *string `json:"firstName"`
239 | LastName *string `json:"lastName"`
240 | Role string `json:"role"`
241 | Birthday *types.Date `json:"birthday"`
242 | }
243 |
244 | expectedName := "Alex"
245 | expectedDeepObject := &ID{
246 | FirstName: &expectedName,
247 | Role: "admin",
248 | Birthday: &types.Date{time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)},
249 | }
250 |
251 | actual := new(ID)
252 | paramName := "id"
253 | queryParams := url.Values{
254 | "id[firstName]": {"Alex"},
255 | "id[role]": {"admin"},
256 | "foo": {"bar"},
257 | "id[birthday]": {"2020-01-01"},
258 | }
259 |
260 | err := BindQueryParameter("deepObject", true, false, paramName, queryParams, &actual)
261 | assert.NoError(t, err)
262 | assert.Equal(t, expectedDeepObject, actual)
263 | })
264 |
265 | t.Run("form", func(t *testing.T) {
266 | expected := &types.Date{time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)}
267 | birthday := &types.Date{}
268 | queryParams := url.Values{
269 | "birthday": {"2020-01-01"},
270 | }
271 | err := BindQueryParameter("form", true, false, "birthday", queryParams, &birthday)
272 | assert.NoError(t, err)
273 | assert.Equal(t, expected, birthday)
274 | })
275 | }
276 |
277 | func TestBindParameterViaAlias(t *testing.T) {
278 | // We don't need to check every parameter format type here, since the binding
279 | // code is identical irrespective of parameter type, buy we do want to test
280 | // a bunch of types.
281 | type AString string
282 | type Aint int
283 | type Afloat float64
284 | type Atime time.Time
285 | type Adate types.Date
286 |
287 | type AliasTortureTest struct {
288 | S AString `json:"s"`
289 | Sp *AString `json:"sp,omitempty"`
290 | I Aint `json:"i"`
291 | Ip *Aint `json:"ip,omitempty"`
292 | F Afloat `json:"f"`
293 | Fp *Afloat `json:"fp,omitempty"`
294 | T Atime `json:"t"`
295 | Tp *Atime `json:"tp,omitempty"`
296 | D Adate `json:"d"`
297 | Dp *Adate `json:"dp,omitempty"`
298 | }
299 |
300 | now := time.Now().UTC()
301 | later := now.Add(time.Hour)
302 |
303 | queryParams := url.Values{
304 | "alias[s]": {"str"},
305 | "alias[sp]": {"strp"},
306 | "alias[i]": {"1"},
307 | "alias[ip]": {"2"},
308 | "alias[f]": {"3.5"},
309 | "alias[fp]": {"4.5"},
310 | "alias[t]": {now.Format(time.RFC3339Nano)},
311 | "alias[tp]": {later.Format(time.RFC3339Nano)},
312 | "alias[d]": {"2020-11-06"},
313 | "alias[dp]": {"2020-11-07"},
314 | }
315 |
316 | dst := new(AliasTortureTest)
317 |
318 | err := BindQueryParameter("deepObject", true, false, "alias", queryParams, &dst)
319 | require.NoError(t, err)
320 |
321 | var sp AString = "strp"
322 | var ip Aint = 2
323 | var fp Afloat = 4.5
324 | dp := Adate{Time: time.Date(2020, 11, 7, 0, 0, 0, 0, time.UTC)}
325 |
326 | expected := AliasTortureTest{
327 | S: "str",
328 | Sp: &sp,
329 | I: 1,
330 | Ip: &ip,
331 | F: 3.5,
332 | Fp: &fp,
333 | T: Atime(now),
334 | Tp: (*Atime)(&later),
335 | D: Adate{Time: time.Date(2020, 11, 6, 0, 0, 0, 0, time.UTC)},
336 | Dp: &dp,
337 | }
338 |
339 | // Compare field by field, makes errors easier to track.
340 | assert.EqualValues(t, expected.S, dst.S)
341 | assert.EqualValues(t, expected.Sp, dst.Sp)
342 | assert.EqualValues(t, expected.I, dst.I)
343 | assert.EqualValues(t, expected.Ip, dst.Ip)
344 | assert.EqualValues(t, expected.F, dst.F)
345 | assert.EqualValues(t, expected.Fp, dst.Fp)
346 | assert.EqualValues(t, expected.T, dst.T)
347 | assert.EqualValues(t, expected.Tp, dst.Tp)
348 | assert.EqualValues(t, expected.D, dst.D)
349 | assert.EqualValues(t, expected.Dp, dst.Dp)
350 | }
351 |
352 | // bindParamsToExplodedObject has to special case some types. Make sure that
353 | // these non-object types are handled correctly. The other parts of the functionality
354 | // are tested via more generic code above.
355 | func TestBindParamsToExplodedObject(t *testing.T) {
356 | now := time.Now().UTC()
357 | values := url.Values{
358 | "time": {now.Format(time.RFC3339Nano)},
359 | "date": {"2020-11-06"},
360 | }
361 |
362 | var dstTime time.Time
363 | err := bindParamsToExplodedObject("time", values, &dstTime)
364 | assert.NoError(t, err)
365 | assert.EqualValues(t, now, dstTime)
366 |
367 | type AliasedTime time.Time
368 | var aDstTime AliasedTime
369 | err = bindParamsToExplodedObject("time", values, &aDstTime)
370 | assert.NoError(t, err)
371 | assert.EqualValues(t, now, aDstTime)
372 |
373 | var dstDate types.Date
374 | expectedDate := types.Date{time.Date(2020, 11, 6, 0, 0, 0, 0, time.UTC)}
375 | err = bindParamsToExplodedObject("date", values, &dstDate)
376 | assert.EqualValues(t, expectedDate, dstDate)
377 |
378 | type AliasedDate types.Date
379 | var aDstDate AliasedDate
380 | err = bindParamsToExplodedObject("date", values, &aDstDate)
381 | assert.EqualValues(t, expectedDate, aDstDate)
382 |
383 | }
384 |
--------------------------------------------------------------------------------
/pkg/runtime/deepobject.go:
--------------------------------------------------------------------------------
1 | package runtime
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "net/url"
7 | "reflect"
8 | "sort"
9 | "strconv"
10 | "strings"
11 | "time"
12 |
13 | "github.com/pkg/errors"
14 |
15 | "github.com/amzapi/selling-partner-api-sdk/pkg/types"
16 | )
17 |
18 | func marshalDeepObject(in interface{}, path []string) ([]string, error) {
19 | var result []string
20 |
21 | switch t := in.(type) {
22 | case []interface{}:
23 | // For the array, we will use numerical subscripts of the form [x],
24 | // in the same order as the array.
25 | for i, iface := range t {
26 | newPath := append(path, strconv.Itoa(i))
27 | fields, err := marshalDeepObject(iface, newPath)
28 | if err != nil {
29 | return nil, errors.Wrap(err, "error traversing array")
30 | }
31 | result = append(result, fields...)
32 | }
33 | case map[string]interface{}:
34 | // For a map, each key (field name) becomes a member of the path, and
35 | // we recurse. First, sort the keys.
36 | keys := make([]string, len(t))
37 | i := 0
38 | for k := range t {
39 | keys[i] = k
40 | i++
41 | }
42 | sort.Strings(keys)
43 |
44 | // Now, for each key, we recursively marshal it.
45 | for _, k := range keys {
46 | newPath := append(path, k)
47 | fields, err := marshalDeepObject(t[k], newPath)
48 | if err != nil {
49 | return nil, errors.Wrap(err, "error traversing map")
50 | }
51 | result = append(result, fields...)
52 | }
53 | default:
54 | // Now, for a concrete value, we will turn the path elements
55 | // into a deepObject style set of subscripts. [a, b, c] turns into
56 | // [a][b][c]
57 | prefix := "[" + strings.Join(path, "][") + "]"
58 | result = []string{
59 | prefix + fmt.Sprintf("=%v", t),
60 | }
61 | }
62 | return result, nil
63 | }
64 |
65 | func MarshalDeepObject(i interface{}, paramName string) (string, error) {
66 | // We're going to marshal to JSON and unmarshal into an interface{},
67 | // which will use the json pkg to deal with all the field annotations. We
68 | // can then walk the generic object structure to produce a deepObject. This
69 | // isn't efficient and it would be more efficient to reflect on our own,
70 | // but it's complicated, error-prone code.
71 | buf, err := json.Marshal(i)
72 | if err != nil {
73 | return "", errors.Wrap(err, "failed to marshal input to JSON")
74 | }
75 | var i2 interface{}
76 | err = json.Unmarshal(buf, &i2)
77 | if err != nil {
78 | return "", errors.Wrap(err, "failed to unmarshal JSON")
79 | }
80 | fields, err := marshalDeepObject(i2, nil)
81 | if err != nil {
82 | return "", errors.Wrap(err, "error traversing JSON structure")
83 | }
84 |
85 | // Prefix the param name to each subscripted field.
86 | for i := range fields {
87 | fields[i] = paramName + fields[i]
88 | }
89 | return strings.Join(fields, "&"), nil
90 | }
91 |
92 | type fieldOrValue struct {
93 | fields map[string]fieldOrValue
94 | value string
95 | }
96 |
97 | func (f *fieldOrValue) appendPathValue(path []string, value string) {
98 | fieldName := path[0]
99 | if len(path) == 1 {
100 | f.fields[fieldName] = fieldOrValue{value: value}
101 | return
102 | }
103 |
104 | pv, found := f.fields[fieldName]
105 | if !found {
106 | pv = fieldOrValue{
107 | fields: make(map[string]fieldOrValue),
108 | }
109 | f.fields[fieldName] = pv
110 | }
111 | pv.appendPathValue(path[1:], value)
112 | }
113 |
114 | func makeFieldOrValue(paths [][]string, values []string) fieldOrValue {
115 |
116 | f := fieldOrValue{
117 | fields: make(map[string]fieldOrValue),
118 | }
119 | for i := range paths {
120 | path := paths[i]
121 | value := values[i]
122 | f.appendPathValue(path, value)
123 | }
124 | return f
125 | }
126 |
127 | func UnmarshalDeepObject(dst interface{}, paramName string, params url.Values) error {
128 | // Params are all the query args, so we need those that look like
129 | // "paramName["...
130 | var fieldNames []string
131 | var fieldValues []string
132 | searchStr := paramName + "["
133 | for pName, pValues := range params {
134 | if strings.HasPrefix(pName, searchStr) {
135 | // trim the parameter name from the full name.
136 | pName = pName[len(paramName):]
137 | fieldNames = append(fieldNames, pName)
138 | if len(pValues) != 1 {
139 | return fmt.Errorf("%s has multiple values", pName)
140 | }
141 | fieldValues = append(fieldValues, pValues[0])
142 | }
143 | }
144 |
145 | // Now, for each field, reconstruct its subscript path and value
146 | paths := make([][]string, len(fieldNames))
147 | for i, path := range fieldNames {
148 | path = strings.TrimLeft(path, "[")
149 | path = strings.TrimRight(path, "]")
150 | paths[i] = strings.Split(path, "][")
151 | }
152 |
153 | fieldPaths := makeFieldOrValue(paths, fieldValues)
154 | err := assignPathValues(dst, fieldPaths)
155 | if err != nil {
156 | return errors.Wrap(err, "error assigning value to destination")
157 | }
158 |
159 | return nil
160 | }
161 |
162 | // This returns a field name, either using the variable name, or the json
163 | // annotation if that exists.
164 | func getFieldName(f reflect.StructField) string {
165 | n := f.Name
166 | tag, found := f.Tag.Lookup("json")
167 | if found {
168 | // If we have a json field, and the first part of it before the
169 | // first comma is non-empty, that's our field name.
170 | parts := strings.Split(tag, ",")
171 | if parts[0] != "" {
172 | n = parts[0]
173 | }
174 | }
175 | return n
176 | }
177 |
178 | // Create a map of field names that we'll see in the deepObject to reflect
179 | // field indices on the given type.
180 | func fieldIndicesByJsonTag(i interface{}) (map[string]int, error) {
181 | t := reflect.TypeOf(i)
182 | if t.Kind() != reflect.Struct {
183 | return nil, errors.New("expected a struct as input")
184 | }
185 |
186 | n := t.NumField()
187 | fieldMap := make(map[string]int)
188 | for i := 0; i < n; i++ {
189 | field := t.Field(i)
190 | fieldName := getFieldName(field)
191 | fieldMap[fieldName] = i
192 | }
193 | return fieldMap, nil
194 | }
195 |
196 | func assignPathValues(dst interface{}, pathValues fieldOrValue) error {
197 | //t := reflect.TypeOf(dst)
198 | v := reflect.ValueOf(dst)
199 |
200 | iv := reflect.Indirect(v)
201 | it := iv.Type()
202 |
203 | switch it.Kind() {
204 | case reflect.Slice:
205 | sliceLength := len(pathValues.fields)
206 | dstSlice := reflect.MakeSlice(it, sliceLength, sliceLength)
207 | err := assignSlice(dstSlice, pathValues)
208 | if err != nil {
209 | return errors.Wrap(err, "error assigning slice")
210 | }
211 | iv.Set(dstSlice)
212 | return nil
213 | case reflect.Struct:
214 | // Some special types we care about are structs. Handle them
215 | // here. They may be aliased, so we need to do some hoop
216 | // jumping. If the types are aliased, we need to type convert
217 | // the pointer, then set the value of the dereferenced pointer.
218 | if it.ConvertibleTo(reflect.TypeOf(types.Date{})) {
219 | var date types.Date
220 | var err error
221 | date.Time, err = time.Parse(types.DateFormat, pathValues.value)
222 | if err != nil {
223 | return errors.Wrap(err, "invalid date format")
224 | }
225 | dst := iv
226 | if it != reflect.TypeOf(types.Date{}) {
227 | // Types are aliased, convert the pointers.
228 | ivPtr := iv.Addr()
229 | aPtr := ivPtr.Convert(reflect.TypeOf(&types.Date{}))
230 | dst = reflect.Indirect(aPtr)
231 | }
232 | dst.Set(reflect.ValueOf(date))
233 | }
234 |
235 | if it.ConvertibleTo(reflect.TypeOf(time.Time{})) {
236 | var tm time.Time
237 | var err error
238 | tm, err = time.Parse(time.RFC3339Nano, pathValues.value)
239 | if err != nil {
240 | // Fall back to parsing it as a date.
241 | tm, err = time.Parse(types.DateFormat, pathValues.value)
242 | if err != nil {
243 | return fmt.Errorf("error parsing tim as RFC3339 or 2006-01-02 time: %s", err)
244 | }
245 | return errors.Wrap(err, "invalid date format")
246 | }
247 | dst := iv
248 | if it != reflect.TypeOf(time.Time{}) {
249 | // Types are aliased, convert the pointers.
250 | ivPtr := iv.Addr()
251 | aPtr := ivPtr.Convert(reflect.TypeOf(&time.Time{}))
252 | dst = reflect.Indirect(aPtr)
253 | }
254 | dst.Set(reflect.ValueOf(tm))
255 | }
256 |
257 | fieldMap, err := fieldIndicesByJsonTag(iv.Interface())
258 | if err != nil {
259 | return errors.Wrap(err, "failed enumerating fields")
260 | }
261 | for _, fieldName := range sortedFieldOrValueKeys(pathValues.fields) {
262 | fieldValue := pathValues.fields[fieldName]
263 | fieldIndex, found := fieldMap[fieldName]
264 | if !found {
265 | return fmt.Errorf("field [%s] is not present in destination object", fieldName)
266 | }
267 | field := iv.Field(fieldIndex)
268 | err = assignPathValues(field.Addr().Interface(), fieldValue)
269 | if err != nil {
270 | return errors.Wrapf(err, "error assigning field [%s]", fieldName)
271 | }
272 | }
273 | return nil
274 | case reflect.Ptr:
275 | // If we have a pointer after redirecting, it means we're dealing with
276 | // an optional field, such as *string, which was passed in as &foo. We
277 | // will allocate it if necessary, and call ourselves with a different
278 | // interface.
279 | dstVal := reflect.New(it.Elem())
280 | dstPtr := dstVal.Interface()
281 | err := assignPathValues(dstPtr, pathValues)
282 | iv.Set(dstVal)
283 | return err
284 | case reflect.Bool:
285 | val, err := strconv.ParseBool(pathValues.value)
286 | if err != nil {
287 | return fmt.Errorf("expected a valid bool, got %s", pathValues.value)
288 | }
289 | iv.SetBool(val)
290 | return nil
291 | case reflect.Float32:
292 | val, err := strconv.ParseFloat(pathValues.value, 32)
293 | if err != nil {
294 | return fmt.Errorf("expected a valid float, got %s", pathValues.value)
295 | }
296 | iv.SetFloat(val)
297 | return nil
298 | case reflect.Float64:
299 | val, err := strconv.ParseFloat(pathValues.value, 64)
300 | if err != nil {
301 | return fmt.Errorf("expected a valid float, got %s", pathValues.value)
302 | }
303 | iv.SetFloat(val)
304 | return nil
305 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
306 | val, err := strconv.ParseInt(pathValues.value, 10, 64)
307 | if err != nil {
308 | return fmt.Errorf("expected a valid int, got %s", pathValues.value)
309 | }
310 | iv.SetInt(val)
311 | return nil
312 | case reflect.String:
313 | iv.SetString(pathValues.value)
314 | return nil
315 | default:
316 | return errors.New("unhandled type: " + it.String())
317 | }
318 | }
319 |
320 | func assignSlice(dst reflect.Value, pathValues fieldOrValue) error {
321 | // Gather up the values
322 | nValues := len(pathValues.fields)
323 | values := make([]string, nValues)
324 | // We expect to have consecutive array indices in the map
325 | for i := 0; i < nValues; i++ {
326 | indexStr := strconv.Itoa(i)
327 | fv, found := pathValues.fields[indexStr]
328 | if !found {
329 | return errors.New("array deepObjects must have consecutive indices")
330 | }
331 | values[i] = fv.value
332 | }
333 |
334 | // This could be cleaner, but we can call into assignPathValues to
335 | // avoid recreating this logic.
336 | for i := 0; i < nValues; i++ {
337 | dstElem := dst.Index(i).Addr()
338 | err := assignPathValues(dstElem.Interface(), fieldOrValue{value: values[i]})
339 | if err != nil {
340 | return errors.Wrap(err, "error binding array")
341 | }
342 | }
343 |
344 | return nil
345 | }
346 |
347 | func sortedFieldOrValueKeys(m map[string]fieldOrValue) []string {
348 | keys := make([]string, 0, len(m))
349 | for k := range m {
350 | keys = append(keys, k)
351 | }
352 | sort.Strings(keys)
353 | return keys
354 | }
355 |
--------------------------------------------------------------------------------
/fbaInventory/api.gen.go:
--------------------------------------------------------------------------------
1 | // Package fbaInventory provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package fbaInventory
5 |
6 | import (
7 | "context"
8 | "encoding/json"
9 | "fmt"
10 | "io/ioutil"
11 | "net/http"
12 | "net/url"
13 | runt "runtime"
14 | "strings"
15 |
16 | "github.com/amzapi/selling-partner-api-sdk/pkg/runtime"
17 | )
18 |
19 | // RequestBeforeFn is the function signature for the RequestBefore callback function
20 | type RequestBeforeFn func(ctx context.Context, req *http.Request) error
21 |
22 | // ResponseAfterFn is the function signature for the ResponseAfter callback function
23 | type ResponseAfterFn func(ctx context.Context, rsp *http.Response) error
24 |
25 | // Doer performs HTTP requests.
26 | //
27 | // The standard http.Client implements this interface.
28 | type HttpRequestDoer interface {
29 | Do(req *http.Request) (*http.Response, error)
30 | }
31 |
32 | // Client which conforms to the OpenAPI3 specification for this service.
33 | type Client struct {
34 | // The endpoint of the server conforming to this interface, with scheme,
35 | // https://api.deepmap.com for example. This can contain a path relative
36 | // to the server, such as https://api.deepmap.com/dev-test, and all the
37 | // paths in the swagger spec will be appended to the server.
38 | Endpoint string
39 |
40 | // Doer for performing requests, typically a *http.Client with any
41 | // customized settings, such as certificate chains.
42 | Client HttpRequestDoer
43 |
44 | // A callback for modifying requests which are generated before sending over
45 | // the network.
46 | RequestBefore RequestBeforeFn
47 |
48 | // A callback for modifying response which are generated before sending over
49 | // the network.
50 | ResponseAfter ResponseAfterFn
51 |
52 | // The user agent header identifies your application, its version number, and the platform and programming language you are using.
53 | // You must include a user agent header in each request submitted to the sales partner API.
54 | UserAgent string
55 | }
56 |
57 | // ClientOption allows setting custom parameters during construction
58 | type ClientOption func(*Client) error
59 |
60 | // Creates a new Client, with reasonable defaults
61 | func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
62 | // create a client with sane default values
63 | client := Client{
64 | Endpoint: endpoint,
65 | }
66 | // mutate client and add all optional params
67 | for _, o := range opts {
68 | if err := o(&client); err != nil {
69 | return nil, err
70 | }
71 | }
72 | // ensure the endpoint URL always has a trailing slash
73 | if !strings.HasSuffix(client.Endpoint, "/") {
74 | client.Endpoint += "/"
75 | }
76 | // create httpClient, if not already present
77 | if client.Client == nil {
78 | client.Client = http.DefaultClient
79 | }
80 | // setting the default useragent
81 | if client.UserAgent == "" {
82 | client.UserAgent = fmt.Sprintf("selling-partner-api-sdk/v1.0 (Language=%s; Platform=%s-%s)", strings.Replace(runt.Version(), "go", "go/", -1), runt.GOOS, runt.GOARCH)
83 | }
84 | return &client, nil
85 | }
86 |
87 | // WithHTTPClient allows overriding the default Doer, which is
88 | // automatically created using http.Client. This is useful for tests.
89 | func WithHTTPClient(doer HttpRequestDoer) ClientOption {
90 | return func(c *Client) error {
91 | c.Client = doer
92 | return nil
93 | }
94 | }
95 |
96 | // WithUserAgent set up useragent
97 | // add user agent to every request automatically
98 | func WithUserAgent(userAgent string) ClientOption {
99 | return func(c *Client) error {
100 | c.UserAgent = userAgent
101 | return nil
102 | }
103 | }
104 |
105 | // WithRequestBefore allows setting up a callback function, which will be
106 | // called right before sending the request. This can be used to mutate the request.
107 | func WithRequestBefore(fn RequestBeforeFn) ClientOption {
108 | return func(c *Client) error {
109 | c.RequestBefore = fn
110 | return nil
111 | }
112 | }
113 |
114 | // WithResponseAfter allows setting up a callback function, which will be
115 | // called right after get response the request. This can be used to log.
116 | func WithResponseAfter(fn ResponseAfterFn) ClientOption {
117 | return func(c *Client) error {
118 | c.ResponseAfter = fn
119 | return nil
120 | }
121 | }
122 |
123 | // The interface specification for the client above.
124 | type ClientInterface interface {
125 | // GetInventorySummaries request
126 | GetInventorySummaries(ctx context.Context, params *GetInventorySummariesParams) (*http.Response, error)
127 | }
128 |
129 | func (c *Client) GetInventorySummaries(ctx context.Context, params *GetInventorySummariesParams) (*http.Response, error) {
130 | req, err := NewGetInventorySummariesRequest(c.Endpoint, params)
131 | if err != nil {
132 | return nil, err
133 | }
134 |
135 | req = req.WithContext(ctx)
136 | req.Header.Set("User-Agent", c.UserAgent)
137 | if c.RequestBefore != nil {
138 | err = c.RequestBefore(ctx, req)
139 | if err != nil {
140 | return nil, err
141 | }
142 | }
143 |
144 | rsp, err := c.Client.Do(req)
145 | if err != nil {
146 | return nil, err
147 | }
148 |
149 | if c.ResponseAfter != nil {
150 | err = c.ResponseAfter(ctx, rsp)
151 | if err != nil {
152 | return nil, err
153 | }
154 | }
155 | return rsp, nil
156 | }
157 |
158 | // NewGetInventorySummariesRequest generates requests for GetInventorySummaries
159 | func NewGetInventorySummariesRequest(endpoint string, params *GetInventorySummariesParams) (*http.Request, error) {
160 | var err error
161 |
162 | queryUrl, err := url.Parse(endpoint)
163 | if err != nil {
164 | return nil, err
165 | }
166 |
167 | basePath := fmt.Sprintf("/fba/inventory/v1/summaries")
168 | if basePath[0] == '/' {
169 | basePath = basePath[1:]
170 | }
171 |
172 | queryUrl, err = queryUrl.Parse(basePath)
173 | if err != nil {
174 | return nil, err
175 | }
176 |
177 | queryValues := queryUrl.Query()
178 |
179 | if params.Details != nil {
180 |
181 | if queryFrag, err := runtime.StyleParam("form", true, "details", *params.Details); err != nil {
182 | return nil, err
183 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
184 | return nil, err
185 | } else {
186 | for k, v := range parsed {
187 | for _, v2 := range v {
188 | queryValues.Add(k, v2)
189 | }
190 | }
191 | }
192 |
193 | }
194 |
195 | if queryFrag, err := runtime.StyleParam("form", true, "granularityType", params.GranularityType); err != nil {
196 | return nil, err
197 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
198 | return nil, err
199 | } else {
200 | for k, v := range parsed {
201 | for _, v2 := range v {
202 | queryValues.Add(k, v2)
203 | }
204 | }
205 | }
206 |
207 | if queryFrag, err := runtime.StyleParam("form", true, "granularityId", params.GranularityId); err != nil {
208 | return nil, err
209 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
210 | return nil, err
211 | } else {
212 | for k, v := range parsed {
213 | for _, v2 := range v {
214 | queryValues.Add(k, v2)
215 | }
216 | }
217 | }
218 |
219 | if params.StartDateTime != nil {
220 |
221 | if queryFrag, err := runtime.StyleParam("form", true, "startDateTime", *params.StartDateTime); err != nil {
222 | return nil, err
223 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
224 | return nil, err
225 | } else {
226 | for k, v := range parsed {
227 | for _, v2 := range v {
228 | queryValues.Add(k, v2)
229 | }
230 | }
231 | }
232 |
233 | }
234 |
235 | if params.SellerSkus != nil {
236 |
237 | if queryFrag, err := runtime.StyleParam("form", true, "sellerSkus", *params.SellerSkus); err != nil {
238 | return nil, err
239 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
240 | return nil, err
241 | } else {
242 | for k, v := range parsed {
243 | for _, v2 := range v {
244 | queryValues.Add(k, v2)
245 | }
246 | }
247 | }
248 |
249 | }
250 |
251 | if params.NextToken != nil {
252 |
253 | if queryFrag, err := runtime.StyleParam("form", true, "nextToken", *params.NextToken); err != nil {
254 | return nil, err
255 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
256 | return nil, err
257 | } else {
258 | for k, v := range parsed {
259 | for _, v2 := range v {
260 | queryValues.Add(k, v2)
261 | }
262 | }
263 | }
264 |
265 | }
266 |
267 | if queryFrag, err := runtime.StyleParam("form", true, "marketplaceIds", params.MarketplaceIds); err != nil {
268 | return nil, err
269 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
270 | return nil, err
271 | } else {
272 | for k, v := range parsed {
273 | for _, v2 := range v {
274 | queryValues.Add(k, v2)
275 | }
276 | }
277 | }
278 |
279 | queryUrl.RawQuery = queryValues.Encode()
280 |
281 | req, err := http.NewRequest("GET", queryUrl.String(), nil)
282 | if err != nil {
283 | return nil, err
284 | }
285 |
286 | return req, nil
287 | }
288 |
289 | // ClientWithResponses builds on ClientInterface to offer response payloads
290 | type ClientWithResponses struct {
291 | ClientInterface
292 | }
293 |
294 | // NewClientWithResponses creates a new ClientWithResponses, which wraps
295 | // Client with return type handling
296 | func NewClientWithResponses(endpoint string, opts ...ClientOption) (*ClientWithResponses, error) {
297 | client, err := NewClient(endpoint, opts...)
298 | if err != nil {
299 | return nil, err
300 | }
301 | return &ClientWithResponses{client}, nil
302 | }
303 |
304 | // WithBaseURL overrides the baseURL.
305 | func WithBaseURL(baseURL string) ClientOption {
306 | return func(c *Client) error {
307 | newBaseURL, err := url.Parse(baseURL)
308 | if err != nil {
309 | return err
310 | }
311 | c.Endpoint = newBaseURL.String()
312 | return nil
313 | }
314 | }
315 |
316 | // ClientWithResponsesInterface is the interface specification for the client with responses above.
317 | type ClientWithResponsesInterface interface {
318 | // GetInventorySummaries request
319 | GetInventorySummariesWithResponse(ctx context.Context, params *GetInventorySummariesParams) (*GetInventorySummariesResp, error)
320 | }
321 |
322 | type GetInventorySummariesResp struct {
323 | Body []byte
324 | HTTPResponse *http.Response
325 | Model *GetInventorySummariesResponse
326 | }
327 |
328 | // Status returns HTTPResponse.Status
329 | func (r GetInventorySummariesResp) Status() string {
330 | if r.HTTPResponse != nil {
331 | return r.HTTPResponse.Status
332 | }
333 | return http.StatusText(0)
334 | }
335 |
336 | // StatusCode returns HTTPResponse.StatusCode
337 | func (r GetInventorySummariesResp) StatusCode() int {
338 | if r.HTTPResponse != nil {
339 | return r.HTTPResponse.StatusCode
340 | }
341 | return 0
342 | }
343 |
344 | // GetInventorySummariesWithResponse request returning *GetInventorySummariesResponse
345 | func (c *ClientWithResponses) GetInventorySummariesWithResponse(ctx context.Context, params *GetInventorySummariesParams) (*GetInventorySummariesResp, error) {
346 | rsp, err := c.GetInventorySummaries(ctx, params)
347 | if err != nil {
348 | return nil, err
349 | }
350 | return ParseGetInventorySummariesResp(rsp)
351 | }
352 |
353 | // ParseGetInventorySummariesResp parses an HTTP response from a GetInventorySummariesWithResponse call
354 | func ParseGetInventorySummariesResp(rsp *http.Response) (*GetInventorySummariesResp, error) {
355 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
356 | defer rsp.Body.Close()
357 | if err != nil {
358 | return nil, err
359 | }
360 |
361 | response := &GetInventorySummariesResp{
362 | Body: bodyBytes,
363 | HTTPResponse: rsp,
364 | }
365 |
366 | var dest GetInventorySummariesResponse
367 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
368 | return nil, err
369 | }
370 |
371 | response.Model = &dest
372 |
373 | if rsp.StatusCode >= 300 {
374 | err = fmt.Errorf(rsp.Status)
375 | }
376 |
377 | return response, err
378 | }
379 |
--------------------------------------------------------------------------------
/sales/api.gen.go:
--------------------------------------------------------------------------------
1 | // Package sales provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package sales
5 |
6 | import (
7 | "context"
8 | "encoding/json"
9 | "fmt"
10 | "io/ioutil"
11 | "net/http"
12 | "net/url"
13 | runt "runtime"
14 | "strings"
15 |
16 | "github.com/amzapi/selling-partner-api-sdk/pkg/runtime"
17 | )
18 |
19 | // RequestBeforeFn is the function signature for the RequestBefore callback function
20 | type RequestBeforeFn func(ctx context.Context, req *http.Request) error
21 |
22 | // ResponseAfterFn is the function signature for the ResponseAfter callback function
23 | type ResponseAfterFn func(ctx context.Context, rsp *http.Response) error
24 |
25 | // Doer performs HTTP requests.
26 | //
27 | // The standard http.Client implements this interface.
28 | type HttpRequestDoer interface {
29 | Do(req *http.Request) (*http.Response, error)
30 | }
31 |
32 | // Client which conforms to the OpenAPI3 specification for this service.
33 | type Client struct {
34 | // The endpoint of the server conforming to this interface, with scheme,
35 | // https://api.deepmap.com for example. This can contain a path relative
36 | // to the server, such as https://api.deepmap.com/dev-test, and all the
37 | // paths in the swagger spec will be appended to the server.
38 | Endpoint string
39 |
40 | // Doer for performing requests, typically a *http.Client with any
41 | // customized settings, such as certificate chains.
42 | Client HttpRequestDoer
43 |
44 | // A callback for modifying requests which are generated before sending over
45 | // the network.
46 | RequestBefore RequestBeforeFn
47 |
48 | // A callback for modifying response which are generated before sending over
49 | // the network.
50 | ResponseAfter ResponseAfterFn
51 |
52 | // The user agent header identifies your application, its version number, and the platform and programming language you are using.
53 | // You must include a user agent header in each request submitted to the sales partner API.
54 | UserAgent string
55 | }
56 |
57 | // ClientOption allows setting custom parameters during construction
58 | type ClientOption func(*Client) error
59 |
60 | // Creates a new Client, with reasonable defaults
61 | func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
62 | // create a client with sane default values
63 | client := Client{
64 | Endpoint: endpoint,
65 | }
66 | // mutate client and add all optional params
67 | for _, o := range opts {
68 | if err := o(&client); err != nil {
69 | return nil, err
70 | }
71 | }
72 | // ensure the endpoint URL always has a trailing slash
73 | if !strings.HasSuffix(client.Endpoint, "/") {
74 | client.Endpoint += "/"
75 | }
76 | // create httpClient, if not already present
77 | if client.Client == nil {
78 | client.Client = http.DefaultClient
79 | }
80 | // setting the default useragent
81 | if client.UserAgent == "" {
82 | client.UserAgent = fmt.Sprintf("selling-partner-api-sdk/v1.0 (Language=%s; Platform=%s-%s)", strings.Replace(runt.Version(), "go", "go/", -1), runt.GOOS, runt.GOARCH)
83 | }
84 | return &client, nil
85 | }
86 |
87 | // WithHTTPClient allows overriding the default Doer, which is
88 | // automatically created using http.Client. This is useful for tests.
89 | func WithHTTPClient(doer HttpRequestDoer) ClientOption {
90 | return func(c *Client) error {
91 | c.Client = doer
92 | return nil
93 | }
94 | }
95 |
96 | // WithUserAgent set up useragent
97 | // add user agent to every request automatically
98 | func WithUserAgent(userAgent string) ClientOption {
99 | return func(c *Client) error {
100 | c.UserAgent = userAgent
101 | return nil
102 | }
103 | }
104 |
105 | // WithRequestBefore allows setting up a callback function, which will be
106 | // called right before sending the request. This can be used to mutate the request.
107 | func WithRequestBefore(fn RequestBeforeFn) ClientOption {
108 | return func(c *Client) error {
109 | c.RequestBefore = fn
110 | return nil
111 | }
112 | }
113 |
114 | // WithResponseAfter allows setting up a callback function, which will be
115 | // called right after get response the request. This can be used to log.
116 | func WithResponseAfter(fn ResponseAfterFn) ClientOption {
117 | return func(c *Client) error {
118 | c.ResponseAfter = fn
119 | return nil
120 | }
121 | }
122 |
123 | // The interface specification for the client above.
124 | type ClientInterface interface {
125 | // GetOrderMetrics request
126 | GetOrderMetrics(ctx context.Context, params *GetOrderMetricsParams) (*http.Response, error)
127 | }
128 |
129 | func (c *Client) GetOrderMetrics(ctx context.Context, params *GetOrderMetricsParams) (*http.Response, error) {
130 | req, err := NewGetOrderMetricsRequest(c.Endpoint, params)
131 | if err != nil {
132 | return nil, err
133 | }
134 |
135 | req = req.WithContext(ctx)
136 | req.Header.Set("User-Agent", c.UserAgent)
137 | if c.RequestBefore != nil {
138 | err = c.RequestBefore(ctx, req)
139 | if err != nil {
140 | return nil, err
141 | }
142 | }
143 |
144 | rsp, err := c.Client.Do(req)
145 | if err != nil {
146 | return nil, err
147 | }
148 |
149 | if c.ResponseAfter != nil {
150 | err = c.ResponseAfter(ctx, rsp)
151 | if err != nil {
152 | return nil, err
153 | }
154 | }
155 | return rsp, nil
156 | }
157 |
158 | // NewGetOrderMetricsRequest generates requests for GetOrderMetrics
159 | func NewGetOrderMetricsRequest(endpoint string, params *GetOrderMetricsParams) (*http.Request, error) {
160 | var err error
161 |
162 | queryUrl, err := url.Parse(endpoint)
163 | if err != nil {
164 | return nil, err
165 | }
166 |
167 | basePath := fmt.Sprintf("/sales/v1/orderMetrics")
168 | if basePath[0] == '/' {
169 | basePath = basePath[1:]
170 | }
171 |
172 | queryUrl, err = queryUrl.Parse(basePath)
173 | if err != nil {
174 | return nil, err
175 | }
176 |
177 | queryValues := queryUrl.Query()
178 |
179 | if queryFrag, err := runtime.StyleParam("form", true, "marketplaceIds", params.MarketplaceIds); err != nil {
180 | return nil, err
181 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
182 | return nil, err
183 | } else {
184 | for k, v := range parsed {
185 | for _, v2 := range v {
186 | queryValues.Add(k, v2)
187 | }
188 | }
189 | }
190 |
191 | if queryFrag, err := runtime.StyleParam("form", true, "interval", params.Interval); err != nil {
192 | return nil, err
193 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
194 | return nil, err
195 | } else {
196 | for k, v := range parsed {
197 | for _, v2 := range v {
198 | queryValues.Add(k, v2)
199 | }
200 | }
201 | }
202 |
203 | if params.GranularityTimeZone != nil {
204 |
205 | if queryFrag, err := runtime.StyleParam("form", true, "granularityTimeZone", *params.GranularityTimeZone); err != nil {
206 | return nil, err
207 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
208 | return nil, err
209 | } else {
210 | for k, v := range parsed {
211 | for _, v2 := range v {
212 | queryValues.Add(k, v2)
213 | }
214 | }
215 | }
216 |
217 | }
218 |
219 | if queryFrag, err := runtime.StyleParam("form", true, "granularity", params.Granularity); err != nil {
220 | return nil, err
221 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
222 | return nil, err
223 | } else {
224 | for k, v := range parsed {
225 | for _, v2 := range v {
226 | queryValues.Add(k, v2)
227 | }
228 | }
229 | }
230 |
231 | if params.BuyerType != nil {
232 |
233 | if queryFrag, err := runtime.StyleParam("form", true, "buyerType", *params.BuyerType); err != nil {
234 | return nil, err
235 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
236 | return nil, err
237 | } else {
238 | for k, v := range parsed {
239 | for _, v2 := range v {
240 | queryValues.Add(k, v2)
241 | }
242 | }
243 | }
244 |
245 | }
246 |
247 | if params.FulfillmentNetwork != nil {
248 |
249 | if queryFrag, err := runtime.StyleParam("form", true, "fulfillmentNetwork", *params.FulfillmentNetwork); err != nil {
250 | return nil, err
251 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
252 | return nil, err
253 | } else {
254 | for k, v := range parsed {
255 | for _, v2 := range v {
256 | queryValues.Add(k, v2)
257 | }
258 | }
259 | }
260 |
261 | }
262 |
263 | if params.FirstDayOfWeek != nil {
264 |
265 | if queryFrag, err := runtime.StyleParam("form", true, "firstDayOfWeek", *params.FirstDayOfWeek); err != nil {
266 | return nil, err
267 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
268 | return nil, err
269 | } else {
270 | for k, v := range parsed {
271 | for _, v2 := range v {
272 | queryValues.Add(k, v2)
273 | }
274 | }
275 | }
276 |
277 | }
278 |
279 | if params.Asin != nil {
280 |
281 | if queryFrag, err := runtime.StyleParam("form", true, "asin", *params.Asin); err != nil {
282 | return nil, err
283 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
284 | return nil, err
285 | } else {
286 | for k, v := range parsed {
287 | for _, v2 := range v {
288 | queryValues.Add(k, v2)
289 | }
290 | }
291 | }
292 |
293 | }
294 |
295 | if params.Sku != nil {
296 |
297 | if queryFrag, err := runtime.StyleParam("form", true, "sku", *params.Sku); err != nil {
298 | return nil, err
299 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
300 | return nil, err
301 | } else {
302 | for k, v := range parsed {
303 | for _, v2 := range v {
304 | queryValues.Add(k, v2)
305 | }
306 | }
307 | }
308 |
309 | }
310 |
311 | queryUrl.RawQuery = queryValues.Encode()
312 |
313 | req, err := http.NewRequest("GET", queryUrl.String(), nil)
314 | if err != nil {
315 | return nil, err
316 | }
317 |
318 | return req, nil
319 | }
320 |
321 | // ClientWithResponses builds on ClientInterface to offer response payloads
322 | type ClientWithResponses struct {
323 | ClientInterface
324 | }
325 |
326 | // NewClientWithResponses creates a new ClientWithResponses, which wraps
327 | // Client with return type handling
328 | func NewClientWithResponses(endpoint string, opts ...ClientOption) (*ClientWithResponses, error) {
329 | client, err := NewClient(endpoint, opts...)
330 | if err != nil {
331 | return nil, err
332 | }
333 | return &ClientWithResponses{client}, nil
334 | }
335 |
336 | // WithBaseURL overrides the baseURL.
337 | func WithBaseURL(baseURL string) ClientOption {
338 | return func(c *Client) error {
339 | newBaseURL, err := url.Parse(baseURL)
340 | if err != nil {
341 | return err
342 | }
343 | c.Endpoint = newBaseURL.String()
344 | return nil
345 | }
346 | }
347 |
348 | // ClientWithResponsesInterface is the interface specification for the client with responses above.
349 | type ClientWithResponsesInterface interface {
350 | // GetOrderMetrics request
351 | GetOrderMetricsWithResponse(ctx context.Context, params *GetOrderMetricsParams) (*GetOrderMetricsResp, error)
352 | }
353 |
354 | type GetOrderMetricsResp struct {
355 | Body []byte
356 | HTTPResponse *http.Response
357 | Model *GetOrderMetricsResponse
358 | }
359 |
360 | // Status returns HTTPResponse.Status
361 | func (r GetOrderMetricsResp) Status() string {
362 | if r.HTTPResponse != nil {
363 | return r.HTTPResponse.Status
364 | }
365 | return http.StatusText(0)
366 | }
367 |
368 | // StatusCode returns HTTPResponse.StatusCode
369 | func (r GetOrderMetricsResp) StatusCode() int {
370 | if r.HTTPResponse != nil {
371 | return r.HTTPResponse.StatusCode
372 | }
373 | return 0
374 | }
375 |
376 | // GetOrderMetricsWithResponse request returning *GetOrderMetricsResponse
377 | func (c *ClientWithResponses) GetOrderMetricsWithResponse(ctx context.Context, params *GetOrderMetricsParams) (*GetOrderMetricsResp, error) {
378 | rsp, err := c.GetOrderMetrics(ctx, params)
379 | if err != nil {
380 | return nil, err
381 | }
382 | return ParseGetOrderMetricsResp(rsp)
383 | }
384 |
385 | // ParseGetOrderMetricsResp parses an HTTP response from a GetOrderMetricsWithResponse call
386 | func ParseGetOrderMetricsResp(rsp *http.Response) (*GetOrderMetricsResp, error) {
387 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
388 | defer rsp.Body.Close()
389 | if err != nil {
390 | return nil, err
391 | }
392 |
393 | response := &GetOrderMetricsResp{
394 | Body: bodyBytes,
395 | HTTPResponse: rsp,
396 | }
397 |
398 | var dest GetOrderMetricsResponse
399 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
400 | return nil, err
401 | }
402 |
403 | response.Model = &dest
404 |
405 | if rsp.StatusCode >= 300 {
406 | err = fmt.Errorf(rsp.Status)
407 | }
408 |
409 | return response, err
410 | }
411 |
--------------------------------------------------------------------------------
/pkg/runtime/styleparam_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2019 DeepMap, Inc.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 | package runtime
15 |
16 | import (
17 | "testing"
18 | "time"
19 |
20 | "github.com/stretchr/testify/assert"
21 | )
22 |
23 | func TestStyleParam(t *testing.T) {
24 | primitive := 5
25 | array := []int{3, 4, 5}
26 | type TestObject struct {
27 | FirstName string `json:"firstName"`
28 | Role string `json:"role"`
29 | }
30 | object := TestObject{
31 | FirstName: "Alex",
32 | Role: "admin",
33 | }
34 | dict := map[string]interface{}{}
35 | dict["firstName"] = "Alex"
36 | dict["role"] = "admin"
37 | timestamp, _ := time.Parse(time.RFC3339, "2020-01-01T22:00:00+02:00")
38 |
39 | // ---------------------------- Simple Style -------------------------------
40 |
41 | result, err := StyleParam("simple", false, "id", primitive)
42 | assert.NoError(t, err)
43 | assert.EqualValues(t, "5", result)
44 |
45 | result, err = StyleParam("simple", true, "id", primitive)
46 | assert.NoError(t, err)
47 | assert.EqualValues(t, "5", result)
48 |
49 | result, err = StyleParam("simple", false, "id", array)
50 | assert.NoError(t, err)
51 | assert.EqualValues(t, "3,4,5", result)
52 |
53 | result, err = StyleParam("simple", true, "id", array)
54 | assert.NoError(t, err)
55 | assert.EqualValues(t, "3,4,5", result)
56 |
57 | result, err = StyleParam("simple", false, "id", object)
58 | assert.NoError(t, err)
59 | assert.EqualValues(t, "firstName,Alex,role,admin", result)
60 |
61 | result, err = StyleParam("simple", true, "id", object)
62 | assert.NoError(t, err)
63 | assert.EqualValues(t, "firstName=Alex,role=admin", result)
64 |
65 | result, err = StyleParam("simple", false, "id", dict)
66 | assert.NoError(t, err)
67 | assert.EqualValues(t, "firstName,Alex,role,admin", result)
68 |
69 | result, err = StyleParam("simple", true, "id", dict)
70 | assert.NoError(t, err)
71 | assert.EqualValues(t, "firstName=Alex,role=admin", result)
72 |
73 | result, err = StyleParam("simple", false, "id", timestamp)
74 | assert.NoError(t, err)
75 | assert.EqualValues(t, "2020-01-01T22%3A00%3A00%2B02%3A00", result)
76 |
77 | result, err = StyleParam("simple", true, "id", timestamp)
78 | assert.NoError(t, err)
79 | assert.EqualValues(t, "2020-01-01T22%3A00%3A00%2B02%3A00", result)
80 |
81 | result, err = StyleParam("simple", false, "id", ×tamp)
82 | assert.NoError(t, err)
83 | assert.EqualValues(t, "2020-01-01T22%3A00%3A00%2B02%3A00", result)
84 |
85 | result, err = StyleParam("simple", true, "id", ×tamp)
86 | assert.NoError(t, err)
87 | assert.EqualValues(t, "2020-01-01T22%3A00%3A00%2B02%3A00", result)
88 |
89 | // ----------------------------- Label Style -------------------------------
90 |
91 | result, err = StyleParam("label", false, "id", primitive)
92 | assert.NoError(t, err)
93 | assert.EqualValues(t, ".5", result)
94 |
95 | result, err = StyleParam("label", true, "id", primitive)
96 | assert.NoError(t, err)
97 | assert.EqualValues(t, ".5", result)
98 |
99 | result, err = StyleParam("label", false, "id", array)
100 | assert.NoError(t, err)
101 | assert.EqualValues(t, ".3,4,5", result)
102 |
103 | result, err = StyleParam("label", true, "id", array)
104 | assert.NoError(t, err)
105 | assert.EqualValues(t, ".3.4.5", result)
106 |
107 | result, err = StyleParam("label", false, "id", object)
108 | assert.NoError(t, err)
109 | assert.EqualValues(t, ".firstName,Alex,role,admin", result)
110 |
111 | result, err = StyleParam("label", true, "id", object)
112 | assert.NoError(t, err)
113 | assert.EqualValues(t, ".firstName=Alex.role=admin", result)
114 |
115 | result, err = StyleParam("label", false, "id", dict)
116 | assert.NoError(t, err)
117 | assert.EqualValues(t, ".firstName,Alex,role,admin", result)
118 |
119 | result, err = StyleParam("label", true, "id", dict)
120 | assert.NoError(t, err)
121 | assert.EqualValues(t, ".firstName=Alex.role=admin", result)
122 |
123 | result, err = StyleParam("label", false, "id", timestamp)
124 | assert.NoError(t, err)
125 | assert.EqualValues(t, ".2020-01-01T22%3A00%3A00%2B02%3A00", result)
126 |
127 | result, err = StyleParam("label", true, "id", timestamp)
128 | assert.NoError(t, err)
129 | assert.EqualValues(t, ".2020-01-01T22%3A00%3A00%2B02%3A00", result)
130 |
131 | result, err = StyleParam("label", false, "id", ×tamp)
132 | assert.NoError(t, err)
133 | assert.EqualValues(t, ".2020-01-01T22%3A00%3A00%2B02%3A00", result)
134 |
135 | result, err = StyleParam("label", true, "id", ×tamp)
136 | assert.NoError(t, err)
137 | assert.EqualValues(t, ".2020-01-01T22%3A00%3A00%2B02%3A00", result)
138 |
139 | // ----------------------------- Matrix Style ------------------------------
140 |
141 | result, err = StyleParam("matrix", false, "id", primitive)
142 | assert.NoError(t, err)
143 | assert.EqualValues(t, ";id=5", result)
144 |
145 | result, err = StyleParam("matrix", true, "id", primitive)
146 | assert.NoError(t, err)
147 | assert.EqualValues(t, ";id=5", result)
148 |
149 | result, err = StyleParam("matrix", false, "id", array)
150 | assert.NoError(t, err)
151 | assert.EqualValues(t, ";id=3,4,5", result)
152 |
153 | result, err = StyleParam("matrix", true, "id", array)
154 | assert.NoError(t, err)
155 | assert.EqualValues(t, ";id=3;id=4;id=5", result)
156 |
157 | result, err = StyleParam("matrix", false, "id", object)
158 | assert.NoError(t, err)
159 | assert.EqualValues(t, ";id=firstName,Alex,role,admin", result)
160 |
161 | result, err = StyleParam("matrix", true, "id", object)
162 | assert.NoError(t, err)
163 | assert.EqualValues(t, ";firstName=Alex;role=admin", result)
164 |
165 | result, err = StyleParam("matrix", false, "id", dict)
166 | assert.NoError(t, err)
167 | assert.EqualValues(t, ";id=firstName,Alex,role,admin", result)
168 |
169 | result, err = StyleParam("matrix", true, "id", dict)
170 | assert.NoError(t, err)
171 | assert.EqualValues(t, ";firstName=Alex;role=admin", result)
172 |
173 | result, err = StyleParam("matrix", false, "id", timestamp)
174 | assert.NoError(t, err)
175 | assert.EqualValues(t, ";id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
176 |
177 | result, err = StyleParam("matrix", true, "id", timestamp)
178 | assert.NoError(t, err)
179 | assert.EqualValues(t, ";id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
180 |
181 | result, err = StyleParam("matrix", false, "id", ×tamp)
182 | assert.NoError(t, err)
183 | assert.EqualValues(t, ";id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
184 |
185 | result, err = StyleParam("matrix", true, "id", ×tamp)
186 | assert.NoError(t, err)
187 | assert.EqualValues(t, ";id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
188 |
189 | // ------------------------------ Form Style -------------------------------
190 | result, err = StyleParam("form", false, "id", primitive)
191 | assert.NoError(t, err)
192 | assert.EqualValues(t, "id=5", result)
193 |
194 | result, err = StyleParam("form", true, "id", primitive)
195 | assert.NoError(t, err)
196 | assert.EqualValues(t, "id=5", result)
197 |
198 | result, err = StyleParam("form", false, "id", array)
199 | assert.NoError(t, err)
200 | assert.EqualValues(t, "id=3,4,5", result)
201 |
202 | result, err = StyleParam("form", true, "id", array)
203 | assert.NoError(t, err)
204 | assert.EqualValues(t, "id=3&id=4&id=5", result)
205 |
206 | result, err = StyleParam("form", false, "id", object)
207 | assert.NoError(t, err)
208 | assert.EqualValues(t, "id=firstName,Alex,role,admin", result)
209 |
210 | result, err = StyleParam("form", true, "id", object)
211 | assert.NoError(t, err)
212 | assert.EqualValues(t, "firstName=Alex&role=admin", result)
213 |
214 | result, err = StyleParam("form", false, "id", dict)
215 | assert.NoError(t, err)
216 | assert.EqualValues(t, "id=firstName,Alex,role,admin", result)
217 |
218 | result, err = StyleParam("form", true, "id", dict)
219 | assert.NoError(t, err)
220 | assert.EqualValues(t, "firstName=Alex&role=admin", result)
221 |
222 | result, err = StyleParam("form", false, "id", timestamp)
223 | assert.NoError(t, err)
224 | assert.EqualValues(t, "id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
225 |
226 | result, err = StyleParam("form", true, "id", timestamp)
227 | assert.NoError(t, err)
228 | assert.EqualValues(t, "id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
229 |
230 | result, err = StyleParam("form", false, "id", ×tamp)
231 | assert.NoError(t, err)
232 | assert.EqualValues(t, "id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
233 |
234 | result, err = StyleParam("form", true, "id", ×tamp)
235 | assert.NoError(t, err)
236 | assert.EqualValues(t, "id=2020-01-01T22%3A00%3A00%2B02%3A00", result)
237 |
238 | // ------------------------ spaceDelimited Style --------------------------
239 |
240 | result, err = StyleParam("spaceDelimited", false, "id", primitive)
241 | assert.Error(t, err)
242 |
243 | result, err = StyleParam("spaceDelimited", true, "id", primitive)
244 | assert.Error(t, err)
245 |
246 | result, err = StyleParam("spaceDelimited", false, "id", array)
247 | assert.NoError(t, err)
248 | assert.EqualValues(t, "id=3 4 5", result)
249 |
250 | result, err = StyleParam("spaceDelimited", true, "id", array)
251 | assert.NoError(t, err)
252 | assert.EqualValues(t, "id=3&id=4&id=5", result)
253 |
254 | result, err = StyleParam("spaceDelimited", false, "id", object)
255 | assert.Error(t, err)
256 |
257 | result, err = StyleParam("spaceDelimited", true, "id", object)
258 | assert.Error(t, err)
259 |
260 | result, err = StyleParam("spaceDelimited", false, "id", dict)
261 | assert.Error(t, err)
262 |
263 | result, err = StyleParam("spaceDelimited", true, "id", dict)
264 | assert.Error(t, err)
265 |
266 | result, err = StyleParam("spaceDelimited", false, "id", timestamp)
267 | assert.Error(t, err)
268 |
269 | result, err = StyleParam("spaceDelimited", true, "id", timestamp)
270 | assert.Error(t, err)
271 |
272 | result, err = StyleParam("spaceDelimited", false, "id", ×tamp)
273 | assert.Error(t, err)
274 |
275 | result, err = StyleParam("spaceDelimited", true, "id", ×tamp)
276 | assert.Error(t, err)
277 |
278 | // ------------------------- pipeDelimited Style --------------------------
279 |
280 | result, err = StyleParam("pipeDelimited", false, "id", primitive)
281 | assert.Error(t, err)
282 |
283 | result, err = StyleParam("pipeDelimited", true, "id", primitive)
284 | assert.Error(t, err)
285 |
286 | result, err = StyleParam("pipeDelimited", false, "id", array)
287 | assert.NoError(t, err)
288 | assert.EqualValues(t, "id=3|4|5", result)
289 |
290 | result, err = StyleParam("pipeDelimited", true, "id", array)
291 | assert.NoError(t, err)
292 | assert.EqualValues(t, "id=3&id=4&id=5", result)
293 |
294 | result, err = StyleParam("pipeDelimited", false, "id", object)
295 | assert.Error(t, err)
296 |
297 | result, err = StyleParam("pipeDelimited", true, "id", object)
298 | assert.Error(t, err)
299 |
300 | result, err = StyleParam("pipeDelimited", false, "id", dict)
301 | assert.Error(t, err)
302 |
303 | result, err = StyleParam("pipeDelimited", true, "id", dict)
304 | assert.Error(t, err)
305 |
306 | result, err = StyleParam("pipeDelimited", false, "id", timestamp)
307 | assert.Error(t, err)
308 |
309 | result, err = StyleParam("pipeDelimited", true, "id", timestamp)
310 | assert.Error(t, err)
311 |
312 | result, err = StyleParam("pipeDelimited", false, "id", ×tamp)
313 | assert.Error(t, err)
314 |
315 | result, err = StyleParam("pipeDelimited", true, "id", ×tamp)
316 | assert.Error(t, err)
317 |
318 | // --------------------------- deepObject Style ---------------------------
319 | result, err = StyleParam("deepObject", false, "id", primitive)
320 | assert.Error(t, err)
321 |
322 | result, err = StyleParam("deepObject", true, "id", primitive)
323 | assert.Error(t, err)
324 |
325 | result, err = StyleParam("deepObject", false, "id", array)
326 | assert.Error(t, err)
327 |
328 | result, err = StyleParam("deepObject", true, "id", array)
329 | assert.NoError(t, err)
330 | assert.EqualValues(t, "id[0]=3&id[1]=4&id[2]=5", result)
331 |
332 | result, err = StyleParam("deepObject", false, "id", object)
333 | assert.Error(t, err)
334 |
335 | result, err = StyleParam("deepObject", true, "id", object)
336 | assert.NoError(t, err)
337 | assert.EqualValues(t, "id[firstName]=Alex&id[role]=admin", result)
338 |
339 | result, err = StyleParam("deepObject", true, "id", dict)
340 | assert.NoError(t, err)
341 | assert.EqualValues(t, "id[firstName]=Alex&id[role]=admin", result)
342 |
343 | result, err = StyleParam("deepObject", false, "id", timestamp)
344 | assert.Error(t, err)
345 |
346 | result, err = StyleParam("deepObject", true, "id", timestamp)
347 | assert.Error(t, err)
348 |
349 | result, err = StyleParam("deepObject", false, "id", ×tamp)
350 | assert.Error(t, err)
351 |
352 | result, err = StyleParam("deepObject", true, "id", ×tamp)
353 | assert.Error(t, err)
354 |
355 | // Misc tests
356 | // Test type aliases
357 | type StrType string
358 | result, err = StyleParam("simple", false, "foo", StrType("test"))
359 | assert.NoError(t, err)
360 | assert.EqualValues(t, "test", result)
361 |
362 | type IntType int32
363 | result, err = StyleParam("simple", false, "foo", IntType(7))
364 | assert.NoError(t, err)
365 | assert.EqualValues(t, "7", result)
366 |
367 | type FloatType float64
368 | result, err = StyleParam("simple", false, "foo", FloatType(7.5))
369 | assert.NoError(t, err)
370 | assert.EqualValues(t, "7.5", result)
371 |
372 | // Test that we handle optional fields
373 | type TestObject2 struct {
374 | FirstName *string `json:"firstName"`
375 | Role *string `json:"role"`
376 | }
377 | name := "Alex"
378 | role := "admin"
379 | object2 := TestObject2{
380 | FirstName: &name,
381 | Role: &role,
382 | }
383 | result, err = StyleParam("simple", false, "id", object2)
384 | assert.NoError(t, err)
385 | assert.EqualValues(t, "firstName,Alex,role,admin", result)
386 |
387 | // Nullable fields need to be excluded when null
388 | object2.Role = nil
389 | result, err = StyleParam("simple", false, "id", object2)
390 | assert.NoError(t, err)
391 | assert.EqualValues(t, "firstName,Alex", result)
392 | }
393 |
--------------------------------------------------------------------------------
/solicitations/api.gen.go:
--------------------------------------------------------------------------------
1 | // Package solicitations provides primitives to interact the openapi HTTP API.
2 | //
3 | // Code generated by go-sdk-codegen DO NOT EDIT.
4 | package solicitations
5 |
6 | import (
7 | "context"
8 | "encoding/json"
9 | "fmt"
10 | "io/ioutil"
11 | "net/http"
12 | "net/url"
13 | runt "runtime"
14 | "strings"
15 |
16 | "github.com/amzapi/selling-partner-api-sdk/pkg/runtime"
17 | )
18 |
19 | // RequestBeforeFn is the function signature for the RequestBefore callback function
20 | type RequestBeforeFn func(ctx context.Context, req *http.Request) error
21 |
22 | // ResponseAfterFn is the function signature for the ResponseAfter callback function
23 | type ResponseAfterFn func(ctx context.Context, rsp *http.Response) error
24 |
25 | // Doer performs HTTP requests.
26 | //
27 | // The standard http.Client implements this interface.
28 | type HttpRequestDoer interface {
29 | Do(req *http.Request) (*http.Response, error)
30 | }
31 |
32 | // Client which conforms to the OpenAPI3 specification for this service.
33 | type Client struct {
34 | // The endpoint of the server conforming to this interface, with scheme,
35 | // https://api.deepmap.com for example. This can contain a path relative
36 | // to the server, such as https://api.deepmap.com/dev-test, and all the
37 | // paths in the swagger spec will be appended to the server.
38 | Endpoint string
39 |
40 | // Doer for performing requests, typically a *http.Client with any
41 | // customized settings, such as certificate chains.
42 | Client HttpRequestDoer
43 |
44 | // A callback for modifying requests which are generated before sending over
45 | // the network.
46 | RequestBefore RequestBeforeFn
47 |
48 | // A callback for modifying response which are generated before sending over
49 | // the network.
50 | ResponseAfter ResponseAfterFn
51 |
52 | // The user agent header identifies your application, its version number, and the platform and programming language you are using.
53 | // You must include a user agent header in each request submitted to the sales partner API.
54 | UserAgent string
55 | }
56 |
57 | // ClientOption allows setting custom parameters during construction
58 | type ClientOption func(*Client) error
59 |
60 | // Creates a new Client, with reasonable defaults
61 | func NewClient(endpoint string, opts ...ClientOption) (*Client, error) {
62 | // create a client with sane default values
63 | client := Client{
64 | Endpoint: endpoint,
65 | }
66 | // mutate client and add all optional params
67 | for _, o := range opts {
68 | if err := o(&client); err != nil {
69 | return nil, err
70 | }
71 | }
72 | // ensure the endpoint URL always has a trailing slash
73 | if !strings.HasSuffix(client.Endpoint, "/") {
74 | client.Endpoint += "/"
75 | }
76 | // create httpClient, if not already present
77 | if client.Client == nil {
78 | client.Client = http.DefaultClient
79 | }
80 | // setting the default useragent
81 | if client.UserAgent == "" {
82 | client.UserAgent = fmt.Sprintf("selling-partner-api-sdk/v1.0 (Language=%s; Platform=%s-%s)", strings.Replace(runt.Version(), "go", "go/", -1), runt.GOOS, runt.GOARCH)
83 | }
84 | return &client, nil
85 | }
86 |
87 | // WithHTTPClient allows overriding the default Doer, which is
88 | // automatically created using http.Client. This is useful for tests.
89 | func WithHTTPClient(doer HttpRequestDoer) ClientOption {
90 | return func(c *Client) error {
91 | c.Client = doer
92 | return nil
93 | }
94 | }
95 |
96 | // WithUserAgent set up useragent
97 | // add user agent to every request automatically
98 | func WithUserAgent(userAgent string) ClientOption {
99 | return func(c *Client) error {
100 | c.UserAgent = userAgent
101 | return nil
102 | }
103 | }
104 |
105 | // WithRequestBefore allows setting up a callback function, which will be
106 | // called right before sending the request. This can be used to mutate the request.
107 | func WithRequestBefore(fn RequestBeforeFn) ClientOption {
108 | return func(c *Client) error {
109 | c.RequestBefore = fn
110 | return nil
111 | }
112 | }
113 |
114 | // WithResponseAfter allows setting up a callback function, which will be
115 | // called right after get response the request. This can be used to log.
116 | func WithResponseAfter(fn ResponseAfterFn) ClientOption {
117 | return func(c *Client) error {
118 | c.ResponseAfter = fn
119 | return nil
120 | }
121 | }
122 |
123 | // The interface specification for the client above.
124 | type ClientInterface interface {
125 | // GetSolicitationActionsForOrder request
126 | GetSolicitationActionsForOrder(ctx context.Context, amazonOrderId string, params *GetSolicitationActionsForOrderParams) (*http.Response, error)
127 |
128 | // CreateProductReviewAndSellerFeedbackSolicitation request
129 | CreateProductReviewAndSellerFeedbackSolicitation(ctx context.Context, amazonOrderId string, params *CreateProductReviewAndSellerFeedbackSolicitationParams) (*http.Response, error)
130 | }
131 |
132 | func (c *Client) GetSolicitationActionsForOrder(ctx context.Context, amazonOrderId string, params *GetSolicitationActionsForOrderParams) (*http.Response, error) {
133 | req, err := NewGetSolicitationActionsForOrderRequest(c.Endpoint, amazonOrderId, params)
134 | if err != nil {
135 | return nil, err
136 | }
137 |
138 | req = req.WithContext(ctx)
139 | req.Header.Set("User-Agent", c.UserAgent)
140 | if c.RequestBefore != nil {
141 | err = c.RequestBefore(ctx, req)
142 | if err != nil {
143 | return nil, err
144 | }
145 | }
146 |
147 | rsp, err := c.Client.Do(req)
148 | if err != nil {
149 | return nil, err
150 | }
151 |
152 | if c.ResponseAfter != nil {
153 | err = c.ResponseAfter(ctx, rsp)
154 | if err != nil {
155 | return nil, err
156 | }
157 | }
158 | return rsp, nil
159 | }
160 |
161 | func (c *Client) CreateProductReviewAndSellerFeedbackSolicitation(ctx context.Context, amazonOrderId string, params *CreateProductReviewAndSellerFeedbackSolicitationParams) (*http.Response, error) {
162 | req, err := NewCreateProductReviewAndSellerFeedbackSolicitationRequest(c.Endpoint, amazonOrderId, params)
163 | if err != nil {
164 | return nil, err
165 | }
166 |
167 | req = req.WithContext(ctx)
168 | req.Header.Set("User-Agent", c.UserAgent)
169 | if c.RequestBefore != nil {
170 | err = c.RequestBefore(ctx, req)
171 | if err != nil {
172 | return nil, err
173 | }
174 | }
175 |
176 | rsp, err := c.Client.Do(req)
177 | if err != nil {
178 | return nil, err
179 | }
180 |
181 | if c.ResponseAfter != nil {
182 | err = c.ResponseAfter(ctx, rsp)
183 | if err != nil {
184 | return nil, err
185 | }
186 | }
187 | return rsp, nil
188 | }
189 |
190 | // NewGetSolicitationActionsForOrderRequest generates requests for GetSolicitationActionsForOrder
191 | func NewGetSolicitationActionsForOrderRequest(endpoint string, amazonOrderId string, params *GetSolicitationActionsForOrderParams) (*http.Request, error) {
192 | var err error
193 |
194 | var pathParam0 string
195 |
196 | pathParam0, err = runtime.StyleParam("simple", false, "amazonOrderId", amazonOrderId)
197 | if err != nil {
198 | return nil, err
199 | }
200 |
201 | queryUrl, err := url.Parse(endpoint)
202 | if err != nil {
203 | return nil, err
204 | }
205 |
206 | basePath := fmt.Sprintf("/solicitations/v1/orders/%s", pathParam0)
207 | if basePath[0] == '/' {
208 | basePath = basePath[1:]
209 | }
210 |
211 | queryUrl, err = queryUrl.Parse(basePath)
212 | if err != nil {
213 | return nil, err
214 | }
215 |
216 | queryValues := queryUrl.Query()
217 |
218 | if queryFrag, err := runtime.StyleParam("form", true, "marketplaceIds", params.MarketplaceIds); err != nil {
219 | return nil, err
220 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
221 | return nil, err
222 | } else {
223 | for k, v := range parsed {
224 | for _, v2 := range v {
225 | queryValues.Add(k, v2)
226 | }
227 | }
228 | }
229 |
230 | queryUrl.RawQuery = queryValues.Encode()
231 |
232 | req, err := http.NewRequest("GET", queryUrl.String(), nil)
233 | if err != nil {
234 | return nil, err
235 | }
236 |
237 | return req, nil
238 | }
239 |
240 | // NewCreateProductReviewAndSellerFeedbackSolicitationRequest generates requests for CreateProductReviewAndSellerFeedbackSolicitation
241 | func NewCreateProductReviewAndSellerFeedbackSolicitationRequest(endpoint string, amazonOrderId string, params *CreateProductReviewAndSellerFeedbackSolicitationParams) (*http.Request, error) {
242 | var err error
243 |
244 | var pathParam0 string
245 |
246 | pathParam0, err = runtime.StyleParam("simple", false, "amazonOrderId", amazonOrderId)
247 | if err != nil {
248 | return nil, err
249 | }
250 |
251 | queryUrl, err := url.Parse(endpoint)
252 | if err != nil {
253 | return nil, err
254 | }
255 |
256 | basePath := fmt.Sprintf("/solicitations/v1/orders/%s/solicitations/productReviewAndSellerFeedback", pathParam0)
257 | if basePath[0] == '/' {
258 | basePath = basePath[1:]
259 | }
260 |
261 | queryUrl, err = queryUrl.Parse(basePath)
262 | if err != nil {
263 | return nil, err
264 | }
265 |
266 | queryValues := queryUrl.Query()
267 |
268 | if queryFrag, err := runtime.StyleParam("form", true, "marketplaceIds", params.MarketplaceIds); err != nil {
269 | return nil, err
270 | } else if parsed, err := url.ParseQuery(queryFrag); err != nil {
271 | return nil, err
272 | } else {
273 | for k, v := range parsed {
274 | for _, v2 := range v {
275 | queryValues.Add(k, v2)
276 | }
277 | }
278 | }
279 |
280 | queryUrl.RawQuery = queryValues.Encode()
281 |
282 | req, err := http.NewRequest("POST", queryUrl.String(), nil)
283 | if err != nil {
284 | return nil, err
285 | }
286 |
287 | return req, nil
288 | }
289 |
290 | // ClientWithResponses builds on ClientInterface to offer response payloads
291 | type ClientWithResponses struct {
292 | ClientInterface
293 | }
294 |
295 | // NewClientWithResponses creates a new ClientWithResponses, which wraps
296 | // Client with return type handling
297 | func NewClientWithResponses(endpoint string, opts ...ClientOption) (*ClientWithResponses, error) {
298 | client, err := NewClient(endpoint, opts...)
299 | if err != nil {
300 | return nil, err
301 | }
302 | return &ClientWithResponses{client}, nil
303 | }
304 |
305 | // WithBaseURL overrides the baseURL.
306 | func WithBaseURL(baseURL string) ClientOption {
307 | return func(c *Client) error {
308 | newBaseURL, err := url.Parse(baseURL)
309 | if err != nil {
310 | return err
311 | }
312 | c.Endpoint = newBaseURL.String()
313 | return nil
314 | }
315 | }
316 |
317 | // ClientWithResponsesInterface is the interface specification for the client with responses above.
318 | type ClientWithResponsesInterface interface {
319 | // GetSolicitationActionsForOrder request
320 | GetSolicitationActionsForOrderWithResponse(ctx context.Context, amazonOrderId string, params *GetSolicitationActionsForOrderParams) (*GetSolicitationActionsForOrderResp, error)
321 |
322 | // CreateProductReviewAndSellerFeedbackSolicitation request
323 | CreateProductReviewAndSellerFeedbackSolicitationWithResponse(ctx context.Context, amazonOrderId string, params *CreateProductReviewAndSellerFeedbackSolicitationParams) (*CreateProductReviewAndSellerFeedbackSolicitationResp, error)
324 | }
325 |
326 | type GetSolicitationActionsForOrderResp struct {
327 | Body []byte
328 | HTTPResponse *http.Response
329 | Model *GetSolicitationActionsForOrderResponse
330 | }
331 |
332 | // Status returns HTTPResponse.Status
333 | func (r GetSolicitationActionsForOrderResp) Status() string {
334 | if r.HTTPResponse != nil {
335 | return r.HTTPResponse.Status
336 | }
337 | return http.StatusText(0)
338 | }
339 |
340 | // StatusCode returns HTTPResponse.StatusCode
341 | func (r GetSolicitationActionsForOrderResp) StatusCode() int {
342 | if r.HTTPResponse != nil {
343 | return r.HTTPResponse.StatusCode
344 | }
345 | return 0
346 | }
347 |
348 | type CreateProductReviewAndSellerFeedbackSolicitationResp struct {
349 | Body []byte
350 | HTTPResponse *http.Response
351 | Model *CreateProductReviewAndSellerFeedbackSolicitationResponse
352 | }
353 |
354 | // Status returns HTTPResponse.Status
355 | func (r CreateProductReviewAndSellerFeedbackSolicitationResp) Status() string {
356 | if r.HTTPResponse != nil {
357 | return r.HTTPResponse.Status
358 | }
359 | return http.StatusText(0)
360 | }
361 |
362 | // StatusCode returns HTTPResponse.StatusCode
363 | func (r CreateProductReviewAndSellerFeedbackSolicitationResp) StatusCode() int {
364 | if r.HTTPResponse != nil {
365 | return r.HTTPResponse.StatusCode
366 | }
367 | return 0
368 | }
369 |
370 | // GetSolicitationActionsForOrderWithResponse request returning *GetSolicitationActionsForOrderResponse
371 | func (c *ClientWithResponses) GetSolicitationActionsForOrderWithResponse(ctx context.Context, amazonOrderId string, params *GetSolicitationActionsForOrderParams) (*GetSolicitationActionsForOrderResp, error) {
372 | rsp, err := c.GetSolicitationActionsForOrder(ctx, amazonOrderId, params)
373 | if err != nil {
374 | return nil, err
375 | }
376 | return ParseGetSolicitationActionsForOrderResp(rsp)
377 | }
378 |
379 | // CreateProductReviewAndSellerFeedbackSolicitationWithResponse request returning *CreateProductReviewAndSellerFeedbackSolicitationResponse
380 | func (c *ClientWithResponses) CreateProductReviewAndSellerFeedbackSolicitationWithResponse(ctx context.Context, amazonOrderId string, params *CreateProductReviewAndSellerFeedbackSolicitationParams) (*CreateProductReviewAndSellerFeedbackSolicitationResp, error) {
381 | rsp, err := c.CreateProductReviewAndSellerFeedbackSolicitation(ctx, amazonOrderId, params)
382 | if err != nil {
383 | return nil, err
384 | }
385 | return ParseCreateProductReviewAndSellerFeedbackSolicitationResp(rsp)
386 | }
387 |
388 | // ParseGetSolicitationActionsForOrderResp parses an HTTP response from a GetSolicitationActionsForOrderWithResponse call
389 | func ParseGetSolicitationActionsForOrderResp(rsp *http.Response) (*GetSolicitationActionsForOrderResp, error) {
390 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
391 | defer rsp.Body.Close()
392 | if err != nil {
393 | return nil, err
394 | }
395 |
396 | response := &GetSolicitationActionsForOrderResp{
397 | Body: bodyBytes,
398 | HTTPResponse: rsp,
399 | }
400 |
401 | var dest GetSolicitationActionsForOrderResponse
402 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
403 | return nil, err
404 | }
405 |
406 | response.Model = &dest
407 |
408 | if rsp.StatusCode >= 300 {
409 | err = fmt.Errorf(rsp.Status)
410 | }
411 |
412 | return response, err
413 | }
414 |
415 | // ParseCreateProductReviewAndSellerFeedbackSolicitationResp parses an HTTP response from a CreateProductReviewAndSellerFeedbackSolicitationWithResponse call
416 | func ParseCreateProductReviewAndSellerFeedbackSolicitationResp(rsp *http.Response) (*CreateProductReviewAndSellerFeedbackSolicitationResp, error) {
417 | bodyBytes, err := ioutil.ReadAll(rsp.Body)
418 | defer rsp.Body.Close()
419 | if err != nil {
420 | return nil, err
421 | }
422 |
423 | response := &CreateProductReviewAndSellerFeedbackSolicitationResp{
424 | Body: bodyBytes,
425 | HTTPResponse: rsp,
426 | }
427 |
428 | var dest CreateProductReviewAndSellerFeedbackSolicitationResponse
429 | if err := json.Unmarshal(bodyBytes, &dest); err != nil {
430 | return nil, err
431 | }
432 |
433 | response.Model = &dest
434 |
435 | if rsp.StatusCode != 201 {
436 | err = fmt.Errorf(rsp.Status)
437 | }
438 |
439 | return response, err
440 | }
441 |
--------------------------------------------------------------------------------