├── commercetools ├── testdata │ ├── shipping-method.create.json │ ├── shipping-zone.create.json │ ├── shipping-method.update.json │ ├── shipping-zone.update.json │ ├── tax-category.update.json │ ├── producttype.update.json │ ├── state.update.json │ ├── type.update.json │ ├── channels.json │ ├── api-client.example.json │ ├── tax-category.create.json │ ├── shipping-zone.json │ ├── shipping-method.json │ ├── project.json │ ├── tax-category.json │ ├── subscription.unknown.json │ ├── state.json │ ├── subscription.invalid.json │ ├── producttype.create.json │ ├── subscription.ironmq.json │ ├── store.json │ ├── extension.azure.json │ ├── type.create.json │ ├── producttype.size.json │ ├── producttype.color.json │ ├── subscription.sns.json │ ├── subscription.sqs.json │ ├── type.date.json │ ├── type.time.json │ ├── type.boolean.json │ ├── type.money.json │ ├── type.number.json │ ├── type.string.json │ ├── type.datetime.json │ ├── type.lstring.json │ ├── type.reference.json │ ├── type.set.json │ ├── type.enum.json │ ├── type.lenum.json │ ├── cart.json │ └── product.example.json ├── types_base.go ├── service_login_generated_test.go ├── client_expand.go ├── client_logger.go ├── service_product_projection_test.go ├── service_message.go ├── service_login.go ├── date.go ├── types_api_client.go ├── types_graph_ql.go ├── service_project.go ├── client_useragent.go ├── service_extension_actions_test.go ├── date_test.go ├── types_custom_object.go ├── utils.go ├── service_api_client.go ├── service_api_client_generated_test.go ├── client_useragent_test.go ├── service_api_client_test.go ├── client_queryinput.go ├── client_graphql.go ├── client_queryinput_test.go ├── service_custom_object.go ├── service_channel.go ├── client_expand_test.go ├── service_extension_test.go ├── service_inventory_entry.go ├── service_channel_generated_test.go ├── service_discount_code.go ├── service_inventory_entry_generated_test.go ├── service_extension_types_test.go ├── service_cart_test.go ├── service_product_factory_test.go ├── service_product_test.go ├── service_discount_code_generated_test.go ├── service_message_generated_test.go ├── service_customer_group_generated_test.go ├── service_type.go ├── service_zone.go ├── service_state.go ├── service_store.go ├── service_shopping_list_generated_test.go ├── service_store_generated_test.go ├── service_category.go ├── service_review.go ├── service_payment.go ├── service_extension.go └── service_product_type.go ├── .gitignore ├── testutil ├── fixture.go └── api.go ├── go.mod ├── Makefile ├── .github └── workflows │ └── go-test.yml ├── code-generate ├── main.go ├── prepare_yaml.py ├── utils.go ├── parse_main.go ├── generate_service_query.go ├── generate_types_main.go ├── generate_service_utils.go ├── generate_service_get.go ├── generate_service_create.go ├── generate_service_delete.go ├── parse_types.go ├── generate_service_update.go ├── generate_service_action.go └── generate_service_main.go ├── LICENSE ├── go.sum ├── README.md └── CHANGELOG.md /commercetools/testdata/shipping-method.create.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test-shipping-method" 3 | } 4 | -------------------------------------------------------------------------------- /commercetools/types_base.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | -------------------------------------------------------------------------------- /commercetools/service_login_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | -------------------------------------------------------------------------------- /commercetools/testdata/shipping-zone.create.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shipping-zone", 3 | "locations": [ 4 | { 5 | "country": "DE" 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /commercetools/testdata/shipping-method.update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "actions": [ 4 | { 5 | "action": "changeName", 6 | "name": "New Name" 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /commercetools/testdata/shipping-zone.update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "actions": [ 4 | { 5 | "action": "changeName", 6 | "name": "New Name" 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /commercetools/testdata/tax-category.update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "actions": [ 4 | { 5 | "action": "changeName", 6 | "name": "New Name" 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /commercetools/testdata/producttype.update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 3, 3 | "actions": [ 4 | { 5 | "action": "changeName", 6 | "name": "new-product-type-name" 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /commercetools/testdata/state.update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "actions": [ 4 | { 5 | "action": "setName", 6 | "name": { 7 | "en": "New Name" 8 | } 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /commercetools/testdata/type.update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "actions": [{ 4 | "action": "changeName", 5 | "name": { 6 | "en": "New Name" 7 | } 8 | }] 9 | } 10 | -------------------------------------------------------------------------------- /commercetools/testdata/channels.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "key": "commercetools", 4 | "version": 1, 5 | "roles": ["InventorySupply"], 6 | "createdAt": "2015-05-28T09:48:35.023Z", 7 | "lastModifiedAt": "2015-05-28T09:48:35.023Z" 8 | } 9 | -------------------------------------------------------------------------------- /commercetools/testdata/api-client.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "api-client-id", 3 | "name": "api-client-name", 4 | "scope": "view_products", 5 | "createdAt": "2018-01-01T00:00:00.001Z", 6 | "lastUsedAt": "2017-09-10", 7 | "secret": "secret-passphrase" 8 | } 9 | -------------------------------------------------------------------------------- /commercetools/testdata/tax-category.create.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test-tax-category", 3 | "rates": [ 4 | { 5 | "name": "test-tax-category", 6 | "amount": 0.2, 7 | "includedInPrice": true, 8 | "country": "DE" 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | run.sh 3 | code-generate/code-generate 4 | 5 | # IDE 6 | .vscode 7 | .idea 8 | 9 | # Test files 10 | coverage.txt 11 | debug.test 12 | 13 | # Temporary files 14 | commercetools-go-sdk 15 | code-generate/prepared.raml 16 | NOTES.txt 17 | /main.go 18 | /api.go 19 | -------------------------------------------------------------------------------- /testutil/fixture.go: -------------------------------------------------------------------------------- 1 | package testutil 2 | 3 | import "io/ioutil" 4 | 5 | // Fixture loads a fixture file to a string 6 | func Fixture(path string) string { 7 | b, err := ioutil.ReadFile("testdata/" + path) 8 | if err != nil { 9 | panic(err) 10 | } 11 | return string(b) 12 | } 13 | -------------------------------------------------------------------------------- /commercetools/client_expand.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import "net/url" 4 | 5 | type RequestOption func(*url.Values) 6 | 7 | func WithReferenceExpansion(references ...string) RequestOption { 8 | return func(v *url.Values) { 9 | for _, ref := range references { 10 | v.Add("expand", ref) 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /commercetools/testdata/shipping-zone.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "c60f7377-2643-4e99-adb5-b2909657444d", 3 | "version": 1, 4 | "name": "shipping-zone", 5 | "locations": [ 6 | { 7 | "country": "DE" 8 | } 9 | ], 10 | "createdAt": "2016-02-24T15:33:40.811Z", 11 | "lastModifiedAt": "2016-02-24T15:33:40.811Z" 12 | } 13 | -------------------------------------------------------------------------------- /commercetools/testdata/shipping-method.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "93153b7e-577e-11e9-a0db-4ff9c32a63cc", 3 | "version": 1, 4 | "key": "test-shipping-method", 5 | "name": "test shipping method", 6 | "description": "", 7 | "isDefault": false, 8 | "zoneRates": null, 9 | "taxCategory": null, 10 | "createdAt": "2016-02-24T15:33:40.811Z", 11 | "lastModifiedAt": "2016-02-24T15:33:40.811Z" 12 | } 13 | -------------------------------------------------------------------------------- /commercetools/testdata/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "key": "test-project", 4 | "name": "Some project name", 5 | "countries": ["DE", "US"], 6 | "currencies": ["EUR"], 7 | "languages": ["en"], 8 | "createdAt": "2013-11-01T15:14:34.325Z", 9 | "trialUntil": "2013-11-01T15:14:34.325Z", 10 | "messages": { 11 | "enabled": false 12 | }, 13 | "shippingRateInputType": { 14 | "type": "CartScore" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /commercetools/testdata/tax-category.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "c60f7377-2643-4e99-adb5-b2909657444d", 3 | "version": 1, 4 | "name": "test-tax-category", 5 | "rates": [ 6 | { 7 | "name": "test-tax-category", 8 | "amount": 0.2, 9 | "includedInPrice": true, 10 | "country": "DE", 11 | "id": "vWTk7VjT", 12 | "subRates": [] 13 | } 14 | ], 15 | "createdAt": "2016-02-24T15:33:40.811Z", 16 | "lastModifiedAt": "2016-02-24T15:33:40.811Z" 17 | } 18 | -------------------------------------------------------------------------------- /commercetools/testdata/subscription.unknown.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "8062243c-46fc-40b5-88a4-75e2216aef75", 3 | "version": 1, 4 | "destination": { 5 | "type": "SomethingNew" 6 | }, 7 | "messages": [ 8 | { 9 | "resourceTypeId": "product", 10 | "types": [] 11 | } 12 | ], 13 | "changes": [], 14 | "createdAt": "2017-01-25T14:14:22.417Z", 15 | "key": "test-queue", 16 | "lastModifiedAt": "2017-01-25T14:14:22.417Z", 17 | "lastMessageSequenceNumber": 0 18 | } 19 | -------------------------------------------------------------------------------- /commercetools/testdata/state.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "7c2e2694-aefe-43d7-888e-6a99514caaca", 3 | "version": 1, 4 | "key": "Initial", 5 | "type": "LineItemState", 6 | "roles": [], 7 | "name": { 8 | "en": "Initial" 9 | }, 10 | "description": { 11 | "en": "Initial is the first that (custom) line item gets after it's creation" 12 | }, 13 | "builtIn": true, 14 | "initial": true, 15 | "createdAt": "2015-01-21T09:22:03.906Z", 16 | "lastModifiedAt": "2015-01-21T09:22:03.906Z" 17 | } 18 | -------------------------------------------------------------------------------- /commercetools/testdata/subscription.invalid.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "8062243c-46fc-40b5-88a4-75e2216aef75", 3 | "version": 1, 4 | "destination": { 5 | "type": "IronMQ", 6 | "uri": 100 7 | }, 8 | "messages": [ 9 | { 10 | "resourceTypeId": "product", 11 | "types": [] 12 | } 13 | ], 14 | "changes": [], 15 | "createdAt": "2017-01-25T14:14:22.417Z", 16 | "key": "test-queue", 17 | "lastModifiedAt": "2017-01-25T14:14:22.417Z", 18 | "lastMessageSequenceNumber": 0 19 | } 20 | -------------------------------------------------------------------------------- /commercetools/testdata/producttype.create.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test_product_type", 3 | "description": "Test product type.", 4 | "attributes": [ 5 | { 6 | "type": { 7 | "name": "text" 8 | }, 9 | "isSearchable": false, 10 | "inputHint": "SingleLine", 11 | "name": "size", 12 | "label": { 13 | "en": "The right size is important." 14 | }, 15 | "isRequired": false, 16 | "attributeConstraint": "CombinationUnique" 17 | } 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /commercetools/testdata/subscription.ironmq.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "8062243c-46fc-40b5-88a4-75e2216aef75", 3 | "version": 1, 4 | "destination": { 5 | "type": "IronMQ", 6 | "uri": "https://queue-uri" 7 | }, 8 | "messages": [ 9 | { 10 | "resourceTypeId": "product", 11 | "types": [] 12 | } 13 | ], 14 | "changes": [], 15 | "createdAt": "2017-01-25T14:14:22.417Z", 16 | "key": "test-queue", 17 | "lastModifiedAt": "2017-01-25T14:14:22.417Z", 18 | "lastMessageSequenceNumber": 0 19 | } 20 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/labd/commercetools-go-sdk 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc 7 | github.com/dave/jennifer v1.4.0 8 | github.com/davecgh/go-spew v1.1.0 9 | github.com/iancoleman/strcase v0.0.0-20191112232945-16388991a334 10 | github.com/mitchellh/mapstructure v1.3.2 11 | github.com/pkg/errors v0.9.1 12 | github.com/stretchr/testify v1.6.1 13 | golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d 14 | gopkg.in/yaml.v2 v2.3.0 15 | ) 16 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | go build 3 | 4 | test: 5 | go test ./... 6 | 7 | coverage: 8 | go test -race -coverprofile=coverage.txt -covermode=atomic -coverpkg=./commercetools ./commercetools 9 | go tool cover -html=coverage.txt 10 | 11 | code-generate/prepared.raml: 12 | python ./code-generate/prepare_yaml.py ../commercetools-api-reference/api-specs/api/api.raml ./code-generate/prepared.raml 13 | 14 | generate: code-generate/prepared.raml 15 | go run code-generate/*.go ./code-generate/prepared.raml 16 | goimports -w commercetools/types_*.go 17 | -------------------------------------------------------------------------------- /commercetools/testdata/store.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "ba8d47e5-6591-4ca2-af4c-d547f062bf35", 3 | "version": 1, 4 | "createdAt": "2019-05-08T11:29:42.781Z", 5 | "lastModifiedAt": "2019-05-08T11:29:42.781Z", 6 | "lastModifiedBy": { 7 | "clientId": "WU-qHF_IkFYHB2W9KwKaqVpl", 8 | "isPlatformClient": false 9 | }, 10 | "createdBy": { 11 | "clientId": "WU-qHF_IkFYHB2W9KwKaqVpl", 12 | "isPlatformClient": false 13 | }, 14 | "key": "test123", 15 | "name": { 16 | "en": "test123" 17 | } 18 | } -------------------------------------------------------------------------------- /commercetools/testdata/extension.azure.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "8062243c-46fc-40b5-88a4-75e2216aef75", 3 | "version": 1, 4 | "createdAt": "2017-01-25T14:14:22.417Z", 5 | "lastModifiedAt": "2017-01-25T14:14:22.417Z", 6 | "destination": { 7 | "type": "HTTP", 8 | "url": "https://example.azurewebsites.net/api/extension", 9 | "authentication": { 10 | "type": "AzureFunctions", 11 | "key": "some-azure-function-code" 12 | } 13 | }, 14 | "triggers": [{ 15 | "resourceTypeId": "cart", 16 | "actions": ["Create", "Update"] 17 | }], 18 | "key": "my-extension" 19 | } 20 | -------------------------------------------------------------------------------- /commercetools/testdata/type.create.json: -------------------------------------------------------------------------------- 1 | { 2 | "key": "lineitemtype", 3 | "name": { 4 | "en": "lineitem" 5 | }, 6 | "description": { 7 | "en": "description" 8 | }, 9 | "resourceTypeIds": [ 10 | "line-item" 11 | ], 12 | "fieldDefinitions": [ 13 | { 14 | "name": "offer_name", 15 | "label": { 16 | "en": "offer_name" 17 | }, 18 | "required": false, 19 | "type": { 20 | "name": "String" 21 | }, 22 | "inputHint": "SingleLine" 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /commercetools/testdata/producttype.size.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "name": "test_product_type", 5 | "description": "Test product type.", 6 | "attributes": [ 7 | { 8 | "type": { 9 | "name": "text" 10 | }, 11 | "isSearchable": false, 12 | "inputHint": "SingleLine", 13 | "name": "size", 14 | "label": { 15 | "en": "The right size is important." 16 | }, 17 | "isRequired": false, 18 | "attributeConstraint": "CombinationUnique" 19 | } 20 | ], 21 | "createdAt": "1970-01-01T00:00:00.001Z", 22 | "lastModifiedAt": "1970-01-01T00:00:00.001Z" 23 | } -------------------------------------------------------------------------------- /commercetools/testdata/producttype.color.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "name": "another-test_product_type", 5 | "description": "Another test product type.", 6 | "attributes": [ 7 | { 8 | "type": { 9 | "name": "ltext" 10 | }, 11 | "isSearchable": false, 12 | "inputHint": "SingleLine", 13 | "name": "color", 14 | "label": { 15 | "en": "The right color is important." 16 | }, 17 | "isRequired": false, 18 | "attributeConstraint": "CombinationUnique" 19 | } 20 | ], 21 | "createdAt": "1970-01-01T00:00:00.001Z", 22 | "lastModifiedAt": "1970-01-01T00:00:00.001Z" 23 | } 24 | -------------------------------------------------------------------------------- /commercetools/testdata/subscription.sns.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "8062243c-46fc-40b5-88a4-75e2216aef75", 3 | "version": 1, 4 | "destination": { 5 | "type": "SNS", 6 | "topicArn": "arn:aws:sns:eu-central-1:123456789012345678:example:1", 7 | "accessKey": "AKIAIOSFODNN7EXAMPLE", 8 | "accessSecret": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" 9 | }, 10 | "messages": [ 11 | { 12 | "resourceTypeId": "product", 13 | "types": [] 14 | } 15 | ], 16 | "changes": [], 17 | "createdAt": "2017-01-25T14:14:22.417Z", 18 | "key": "test-queue", 19 | "lastModifiedAt": "2017-01-25T14:14:22.417Z", 20 | "lastMessageSequenceNumber": 0 21 | } 22 | -------------------------------------------------------------------------------- /.github/workflows/go-test.yml: -------------------------------------------------------------------------------- 1 | name: Go Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | 7 | test: 8 | runs-on: ubuntu-latest 9 | strategy: 10 | max-parallel: 4 11 | matrix: 12 | go-version: ['1.14'] 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Set up Go ${{ matrix.go-version }} 16 | uses: actions/setup-go@v2 17 | with: 18 | go-version: ${{ matrix.go-version }} 19 | - name: Install dependencies 20 | run: go get ./commercetools 21 | - name: Run tests 22 | run: go test -race -coverprofile=coverage.txt -covermode=atomic -coverpkg=./commercetools ./commercetools 23 | - name: Upload to codecov 24 | uses: codecov/codecov-action@v1.0.6 25 | -------------------------------------------------------------------------------- /commercetools/testdata/subscription.sqs.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "8062243c-46fc-40b5-88a4-75e2216aef75", 3 | "version": 1, 4 | "destination": { 5 | "type": "SQS", 6 | "uri": "https://queue-uri", 7 | "queueUrl": "https://queue.amazonaws.com/80398EXAMPLE/MyQueue", 8 | "accessKey": "AKIAIOSFODNN7EXAMPLE", 9 | "accessSecret": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" 10 | }, 11 | "messages": [ 12 | { 13 | "resourceTypeId": "product", 14 | "types": [] 15 | } 16 | ], 17 | "changes": [], 18 | "createdAt": "2017-01-25T14:14:22.417Z", 19 | "key": "test-queue", 20 | "lastModifiedAt": "2017-01-25T14:14:22.417Z", 21 | "lastMessageSequenceNumber": 0 22 | } 23 | -------------------------------------------------------------------------------- /commercetools/testdata/type.date.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_date", 17 | "label": { 18 | "en": "offer_date" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Date" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.time.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_time", 17 | "label": { 18 | "en": "offer_time" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Time" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.boolean.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "is_special", 17 | "label": { 18 | "en": "is_special" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Boolean" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.money.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_price", 17 | "label": { 18 | "en": "offer_price" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Money" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.number.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_number", 17 | "label": { 18 | "en": "offer_number" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Number" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.string.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_name", 17 | "label": { 18 | "en": "offer_name" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "String" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.datetime.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_date_time", 17 | "label": { 18 | "en": "offer_date_time" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "DateTime" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.lstring.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "translated_offer_name", 17 | "label": { 18 | "en": "translated_offer_name" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "LocalizedString" 23 | }, 24 | "inputHint": "SingleLine" 25 | } 26 | ], 27 | "createdAt": "2015-10-07T06:56:19.217Z", 28 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 29 | } 30 | -------------------------------------------------------------------------------- /commercetools/testdata/type.reference.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_reference", 17 | "label": { 18 | "en": "offer_reference" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Reference", 23 | "referenceTypeId": "product" 24 | }, 25 | "inputHint": "SingleLine" 26 | } 27 | ], 28 | "createdAt": "2015-10-07T06:56:19.217Z", 29 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 30 | } 31 | -------------------------------------------------------------------------------- /commercetools/testdata/type.set.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_set", 17 | "label": { 18 | "en": "offer_set" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Set", 23 | "elementType": { 24 | "name": "String" 25 | } 26 | }, 27 | "inputHint": "SingleLine" 28 | } 29 | ], 30 | "createdAt": "2015-10-07T06:56:19.217Z", 31 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 32 | } 33 | -------------------------------------------------------------------------------- /commercetools/testdata/type.enum.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "offer_enum", 17 | "label": { 18 | "en": "offer_enum" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "Enum", 23 | "values": [{ 24 | "key": "enum", 25 | "label": "enum" 26 | }] 27 | }, 28 | "inputHint": "SingleLine" 29 | } 30 | ], 31 | "createdAt": "2015-10-07T06:56:19.217Z", 32 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 33 | } 34 | -------------------------------------------------------------------------------- /commercetools/client_logger.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "net/http/httputil" 7 | ) 8 | 9 | const logRequestTemplate = `DEBUG: 10 | ---[ REQUEST ]-------------------------------------------------------- 11 | %s 12 | ---------------------------------------------------------------------- 13 | ` 14 | 15 | const logResponseTemplate = `DEBUG: 16 | ---[ RESPONSE ]------------------------------------------------------- 17 | %s 18 | ---------------------------------------------------------------------- 19 | ` 20 | 21 | func logRequest(r *http.Request) { 22 | body, err := httputil.DumpRequestOut(r, true) 23 | if err != nil { 24 | return 25 | } 26 | log.Printf(logRequestTemplate, body) 27 | } 28 | 29 | func logResponse(r *http.Response) { 30 | body, err := httputil.DumpResponse(r, true) 31 | if err != nil { 32 | return 33 | } 34 | log.Printf(logResponseTemplate, body) 35 | } 36 | -------------------------------------------------------------------------------- /commercetools/service_product_projection_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "net/url" 6 | "testing" 7 | 8 | "github.com/labd/commercetools-go-sdk/commercetools" 9 | "github.com/stretchr/testify/assert" 10 | 11 | "github.com/labd/commercetools-go-sdk/testutil" 12 | ) 13 | 14 | func TestProductProjectionSearch(t *testing.T) { 15 | output := testutil.RequestData{} 16 | client, server := testutil.MockClient(t, "{}", &output, nil) 17 | defer server.Close() 18 | 19 | queryInput := commercetools.ProductProjectionSearchInput{ 20 | Text: map[string]string{"nl": "foobar"}, 21 | Filter: []string{"category.id:foo", "category.id:bar"}, 22 | } 23 | _, err := client.ProductProjectionSearch(context.TODO(), &queryInput) 24 | 25 | assert.Nil(t, err) 26 | assert.Equal(t, url.Values{ 27 | "text.nl": {"foobar"}, 28 | "filter": {"category.id:foo", "category.id:bar"}, 29 | }, output.URL.Query()) 30 | } 31 | -------------------------------------------------------------------------------- /commercetools/service_message.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | ) 10 | 11 | // MessageQuery allows querying for type Message 12 | func (client *Client) MessageQuery(ctx context.Context, input *QueryInput) (result *MessagePagedQueryResponse, err error) { 13 | endpoint := "messages" 14 | err = client.query(ctx, endpoint, input.toParams(), &result) 15 | if err != nil { 16 | return nil, err 17 | } 18 | return result, nil 19 | } 20 | 21 | // MessageGetWithID for type Message 22 | func (client *Client) MessageGetWithID(ctx context.Context, id string, opts ...RequestOption) (result Message, err error) { 23 | params := url.Values{} 24 | for _, opt := range opts { 25 | opt(¶ms) 26 | } 27 | endpoint := fmt.Sprintf("messages/%s", id) 28 | err = client.get(ctx, endpoint, params, &result) 29 | if err != nil { 30 | return nil, err 31 | } 32 | return mapDiscriminatorMessage(result) 33 | } 34 | -------------------------------------------------------------------------------- /commercetools/testdata/type.lenum.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1234", 3 | "version": 1, 4 | "key": "lineitemtype", 5 | "name": { 6 | "en": "lineitem" 7 | }, 8 | "description": { 9 | "en": "description" 10 | }, 11 | "resourceTypeIds": [ 12 | "line-item" 13 | ], 14 | "fieldDefinitions": [ 15 | { 16 | "name": "translated_offer_enum", 17 | "label": { 18 | "en": "translated_offer_enum" 19 | }, 20 | "required": false, 21 | "type": { 22 | "name": "LocalizedEnum", 23 | "values": [{ 24 | "key": "enum", 25 | "label": { 26 | "en": "enum" 27 | } 28 | }] 29 | }, 30 | "inputHint": "SingleLine" 31 | } 32 | ], 33 | "createdAt": "2015-10-07T06:56:19.217Z", 34 | "lastModifiedAt": "2015-10-07T06:56:19.217Z" 35 | } 36 | -------------------------------------------------------------------------------- /commercetools/service_login.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "net/url" 8 | ) 9 | 10 | /* 11 | Login Authenticate Customer (Sign In). Retrieves the authenticated 12 | customer (a customer that matches the given email/password pair). 13 | If used with an access token for Anonymous Sessions, 14 | all orders and carts belonging to the anonymousId will be assigned to the newly created customer. 15 | If a cart is is returned as part of the CustomerSignInResult, 16 | it has been recalculated (It will have up-to-date prices, taxes and discounts, 17 | and invalid line items have been removed.). 18 | */ 19 | func (client *Client) Login(ctx context.Context, value *CustomerSignin, opts ...RequestOption) (result *CustomerSignInResult, err error) { 20 | params := url.Values{} 21 | for _, opt := range opts { 22 | opt(¶ms) 23 | } 24 | 25 | endpoint := "login" 26 | err = client.create(ctx, endpoint, params, value, &result) 27 | if err != nil { 28 | return nil, err 29 | } 30 | return result, nil 31 | } 32 | -------------------------------------------------------------------------------- /commercetools/date.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strconv" 7 | "time" 8 | ) 9 | 10 | // Date holds date information for Commercetools API format 11 | type Date struct { 12 | Year int 13 | Month time.Month 14 | Day int 15 | } 16 | 17 | // NewDate initializes a Date struct 18 | func NewDate(year int, month time.Month, day int) Date { 19 | return Date{Year: year, Month: month, Day: day} 20 | } 21 | 22 | // MarshalJSON marshals into the commercetools date format 23 | func (d *Date) MarshalJSON() ([]byte, error) { 24 | value := fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day) 25 | return []byte(strconv.Quote(value)), nil 26 | } 27 | 28 | // UnmarshalJSON decodes JSON data into a Date struct 29 | func (d *Date) UnmarshalJSON(data []byte) error { 30 | var input string 31 | err := json.Unmarshal(data, &input) 32 | if err != nil { 33 | return err 34 | } 35 | 36 | value, err := time.Parse("2006-01-02", input) 37 | if err != nil { 38 | return err 39 | } 40 | 41 | d.Year = value.Year() 42 | d.Month = value.Month() 43 | d.Day = value.Day() 44 | return nil 45 | } 46 | -------------------------------------------------------------------------------- /code-generate/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "log" 7 | "os" 8 | 9 | yaml "gopkg.in/yaml.v2" 10 | ) 11 | 12 | func main() { 13 | apiFile := os.Args[1] 14 | fmt.Printf("Generating code for file %s\n", apiFile) 15 | fi, err := os.Stat(apiFile) 16 | if err != nil { 17 | panic(err) 18 | } 19 | size := fi.Size() 20 | if size == 0 { 21 | panic(fmt.Errorf("File %s is empty", apiFile)) 22 | } 23 | 24 | f, err := ioutil.ReadFile(apiFile) 25 | if err != nil { 26 | panic(err) 27 | } 28 | 29 | t := yaml.MapSlice{} 30 | 31 | err = yaml.Unmarshal(f, &t) 32 | 33 | if err != nil { 34 | log.Fatalf("error: %v", err) 35 | } 36 | 37 | log.Println("=================[ Parsing RAML ]=================") 38 | objects, resources := parseYaml(t) 39 | postProcess(objects) 40 | log.Println("===============[ Generating types ]===============") 41 | generateTypes(objects) 42 | log.Println("==============[ Generating services ]=============") 43 | generateServices(objects, resources) 44 | log.Println("===============[ Generating tests ]===============") 45 | generateTests(objects, resources) 46 | } 47 | -------------------------------------------------------------------------------- /commercetools/types_api_client.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import "time" 6 | 7 | // APIClient is a standalone struct 8 | type APIClient struct { 9 | Secret string `json:"secret,omitempty"` 10 | Scope string `json:"scope"` 11 | Name string `json:"name"` 12 | LastUsedAt *Date `json:"lastUsedAt,omitempty"` 13 | ID string `json:"id"` 14 | DeleteAt *time.Time `json:"deleteAt,omitempty"` 15 | CreatedAt *time.Time `json:"createdAt,omitempty"` 16 | } 17 | 18 | // APIClientDraft is a standalone struct 19 | type APIClientDraft struct { 20 | Scope string `json:"scope"` 21 | Name string `json:"name"` 22 | DeleteDaysAfterCreation int `json:"deleteDaysAfterCreation,omitempty"` 23 | } 24 | 25 | // APIClientPagedQueryResponse is a standalone struct 26 | type APIClientPagedQueryResponse struct { 27 | Total int `json:"total,omitempty"` 28 | Results []APIClient `json:"results"` 29 | Offset int `json:"offset"` 30 | Limit int `json:"limit"` 31 | Count int `json:"count"` 32 | } 33 | -------------------------------------------------------------------------------- /code-generate/prepare_yaml.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import yaml 4 | 5 | 6 | class Loader(yaml.SafeLoader): 7 | def __init__(self, stream): 8 | try: 9 | self._root = os.path.split(stream.name)[0] 10 | except AttributeError: 11 | self._root = os.path.curdir 12 | super().__init__(stream) 13 | 14 | 15 | def construct_include(loader, node): 16 | filename = os.path.abspath( 17 | os.path.join(loader._root, loader.construct_scalar(node)) 18 | ) 19 | extension = os.path.splitext(filename)[1].lstrip(".") 20 | 21 | with open(filename, "r") as f: 22 | if extension in ("yml", "yaml", "raml"): 23 | return yaml.load(f, Loader) 24 | return f.read() 25 | 26 | 27 | yaml.add_constructor("!include", construct_include, Loader) 28 | 29 | 30 | if __name__ == "__main__": 31 | import sys 32 | 33 | with open(sys.argv[1], "r") as fh: 34 | data = yaml.load(fh, Loader) 35 | 36 | output = yaml.dump(data) 37 | if len(sys.argv) > 2: 38 | with open(sys.argv[2], "w") as fh: 39 | fh.write(output) 40 | else: 41 | print(output) 42 | -------------------------------------------------------------------------------- /commercetools/types_graph_ql.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | // GraphQLVariablesMap is a map 6 | type GraphQLVariablesMap map[string]interface{} 7 | 8 | // GraphQLError is a standalone struct 9 | type GraphQLError struct { 10 | Path []interface{} `json:"path"` 11 | Message string `json:"message"` 12 | Locations []GraphQLErrorLocation `json:"locations"` 13 | } 14 | 15 | func (obj GraphQLError) Error() string { 16 | return obj.Message 17 | } 18 | 19 | // GraphQLErrorLocation is a standalone struct 20 | type GraphQLErrorLocation struct { 21 | Line int `json:"line"` 22 | Column int `json:"column"` 23 | } 24 | 25 | // GraphQLRequest is a standalone struct 26 | type GraphQLRequest struct { 27 | Variables *GraphQLVariablesMap `json:"variables,omitempty"` 28 | Query string `json:"query"` 29 | OperationName string `json:"operationName,omitempty"` 30 | } 31 | 32 | // GraphQLResponse is a standalone struct 33 | type GraphQLResponse struct { 34 | Errors []GraphQLError `json:"errors,omitempty"` 35 | Data interface{} `json:"data,omitempty"` 36 | } 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018-2021 Michael van Tellingen, Lab Digital (https://labdigital.nl) 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 | -------------------------------------------------------------------------------- /commercetools/service_project.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import "context" 4 | 5 | // ProjectUpdateInput provides the data required to update a project. 6 | type ProjectUpdateInput struct { 7 | // The expected version of the project on which the changes should be 8 | // applied. If the expected version does not match the actual version, a 409 9 | // Conflict will be returned. 10 | Version int 11 | 12 | // The list of update actions to be performed on the project. 13 | Actions []ProjectUpdateAction 14 | } 15 | 16 | // ProjectGet will return the current project. OAuth2 Scopes: 17 | // view_project_settings:{projectKey} 18 | func (client *Client) ProjectGet() (result *Project, err error) { 19 | ctx := context.TODO() 20 | err = client.get(ctx, "", nil, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // ProjectUpdate will update the current project with the defined UpdateActions. OAuth2 28 | // Scopes: manage_project:{projectKey} 29 | func (client *Client) ProjectUpdate(input *ProjectUpdateInput) (result *Project, err error) { 30 | ctx := context.TODO() 31 | err = client.update(ctx, "", nil, input.Version, input.Actions, &result) 32 | if err != nil { 33 | return nil, err 34 | } 35 | return result, nil 36 | } 37 | -------------------------------------------------------------------------------- /code-generate/utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "regexp" 5 | "strings" 6 | 7 | "github.com/iancoleman/strcase" 8 | ) 9 | 10 | // CreateCodeName generates a go identifier for the given value. We also do some extra 11 | // modifications to make golint happy. 12 | func CreateCodeName(value string) string { 13 | if strings.HasPrefix(value, "/") { 14 | return value 15 | } 16 | 17 | result := strcase.ToCamel(value) 18 | translateMap := map[string]string{ 19 | "/": "", 20 | "Id$": "ID", 21 | "Sku$": "SKU", 22 | "Uri$": "URI", 23 | "Url$": "URL", 24 | "Json": "JSON", 25 | "IdAction": "IDAction", 26 | "Ttl": "TTL", 27 | "Http": "HTTP", 28 | "^Api": "API", 29 | } 30 | 31 | for key, value := range translateMap { 32 | r := regexp.MustCompile(key) 33 | result = r.ReplaceAllString(result, value) 34 | } 35 | 36 | return result 37 | } 38 | 39 | func ExtractCodeName(value string) string { 40 | values := strings.Split(value, "|") 41 | return strings.TrimSpace(values[0]) 42 | } 43 | 44 | func generateFilename(name string, suffix string) string { 45 | if name == "" { 46 | panic("No package name found") 47 | } 48 | filename := strcase.ToSnake(name) 49 | if suffix != "" { 50 | filename += suffix 51 | 52 | } 53 | return filename + ".go" 54 | } 55 | -------------------------------------------------------------------------------- /code-generate/parse_main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | yaml "gopkg.in/yaml.v2" 5 | ) 6 | 7 | // XXX: using a global variable has a smell... however, its just a code 8 | // generator, not production code 9 | var traits yaml.MapSlice 10 | 11 | func parseYaml(data yaml.MapSlice) (objects []RamlType, domains []ServiceDomain) { 12 | types := getPropertyValue(data, "types") 13 | for _, mapItem := range types.(yaml.MapSlice) { 14 | obj := createRamlType(mapItem.Key.(string), mapItem.Value.(yaml.MapSlice)) 15 | objects = append(objects, obj) 16 | } 17 | traits = getPropertyValue(data, "traits").(yaml.MapSlice) 18 | 19 | domains = make([]ServiceDomain, 0) 20 | apiResources := getPropertyValue(data, "/{projectKey}") 21 | 22 | for _, apiResource := range apiResources.(yaml.MapSlice) { 23 | serviceDomain := createService(apiResource, nil) 24 | if serviceDomain != nil { 25 | domains = append(domains, *serviceDomain) 26 | } 27 | 28 | // resourceService := createResourceService(apiResource) 29 | // if resourceService != nil { 30 | // resources = append(resources, *resourceService) 31 | // } 32 | } 33 | 34 | return 35 | } 36 | 37 | func getTrait(name string) yaml.MapSlice { 38 | for _, t := range traits { 39 | if t.Key == name { 40 | return t.Value.(yaml.MapSlice) 41 | } 42 | } 43 | return nil 44 | } 45 | -------------------------------------------------------------------------------- /commercetools/client_useragent.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "strings" 7 | ) 8 | 9 | // GetUserAgent determines the user agent for all HTTP requests. 10 | func GetUserAgent(cfg *ClientConfig) string { 11 | baseInfo := fmt.Sprintf("commercetools-go-sdk/%s", Version) 12 | systemInfo := fmt.Sprintf("Go/%s (%s; %s)", runtime.Version(), runtime.GOOS, runtime.GOARCH) 13 | 14 | libraryInfo := "" 15 | if cfg.LibraryName != "" && cfg.LibraryVersion == "" { 16 | libraryInfo = cfg.LibraryName 17 | } else if cfg.LibraryName != "" && cfg.LibraryVersion != "" { 18 | libraryInfo = fmt.Sprintf("%s/%s", cfg.LibraryName, cfg.LibraryVersion) 19 | } 20 | contactInfo := "" 21 | if cfg.ContactURL != "" && cfg.ContactEmail == "" { 22 | contactInfo = fmt.Sprintf("(+%s)", cfg.ContactURL) 23 | } else if cfg.ContactURL == "" && cfg.ContactEmail != "" { 24 | contactInfo = fmt.Sprintf("(+%s)", cfg.ContactEmail) 25 | } else if cfg.ContactURL != "" && cfg.ContactEmail != "" { 26 | contactInfo = fmt.Sprintf("(+%s; +%s)", cfg.ContactURL, cfg.ContactEmail) 27 | } 28 | 29 | s := []string{ 30 | baseInfo, 31 | systemInfo, 32 | } 33 | if libraryInfo != "" { 34 | s = append(s, libraryInfo) 35 | } 36 | if contactInfo != "" { 37 | s = append(s, contactInfo) 38 | } 39 | 40 | return strings.Join(s, " ") 41 | } 42 | -------------------------------------------------------------------------------- /code-generate/generate_service_query.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/dave/jennifer/jen" 5 | ) 6 | 7 | // Generate the `Query` function 8 | func generateServiceQuery(method ServiceMethod, objects map[string]RamlType) (code *jen.Statement) { 9 | structReceiver := jen.Id("client").Op("*").Id("Client") 10 | methodParamList := []jen.Code{ 11 | jen.Id("ctx").Qual("context", "Context"), 12 | } 13 | 14 | extraParams := generateServiceArgumentCode(method) 15 | methodParamList = append(methodParamList, extraParams...) 16 | methodParamList = append(methodParamList, 17 | jen.Id("input").Op("*").Id("QueryInput"), 18 | ) 19 | 20 | returnObject := objects[method.ReturnType] 21 | returnParams := createServiceReturnList(method, returnObject) 22 | 23 | c := jen.Commentf("%s allows querying for type %s", method.Name, method.Domain.ResourceType).Line() 24 | if method.Description != "" { 25 | c.Comment(method.Description).Line() 26 | } 27 | 28 | c.Func().Params(structReceiver).Id(method.Name).Params(jen.List(methodParamList...)).Parens(returnParams).Block( 29 | jen.Id("endpoint").Op(":=").Add(generateServicePathCode(method)), 30 | jen.Id("err").Op("=").Id("client").Op(".").Id("query").Call( 31 | jen.Id("ctx"), 32 | jen.Id("endpoint"), 33 | jen.Id("input").Op(".").Id("toParams").Call(), 34 | jen.Op("&").Id("result"), 35 | ), 36 | jen.If(jen.Err().Op("!=").Nil()).Block( 37 | jen.Return(jen.Nil(), jen.Err()), 38 | ), 39 | jen.Return(jen.Id("result"), jen.Nil()), 40 | ).Line() 41 | return c 42 | } 43 | -------------------------------------------------------------------------------- /commercetools/service_extension_actions_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "encoding/json" 5 | "testing" 6 | 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func TestSetKeyMarshall(t *testing.T) { 12 | obj := commercetools.ExtensionSetKeyAction{ 13 | Key: "my-key", 14 | } 15 | 16 | result, err := json.Marshal(obj) 17 | assert.Nil(t, err) 18 | assert.JSONEq(t, `{ 19 | "key":"my-key", 20 | "action":"setKey"}`, string(result)) 21 | } 22 | 23 | func TestChangeTriggersMarshall(t *testing.T) { 24 | obj := commercetools.ExtensionChangeTriggersAction{ 25 | Triggers: []commercetools.ExtensionTrigger{ 26 | { 27 | ResourceTypeID: "product", 28 | Actions: []commercetools.ExtensionAction{"Create", "Change"}, 29 | }, 30 | }, 31 | } 32 | 33 | result, err := json.Marshal(obj) 34 | assert.Nil(t, err) 35 | assert.JSONEq(t, `{ 36 | "triggers":[{ 37 | "resourceTypeId":"product", 38 | "actions":["Create", "Change"] 39 | }], 40 | "action":"changeTriggers"}`, string(result)) 41 | } 42 | 43 | func TestChangeDestinationMarshall(t *testing.T) { 44 | obj := commercetools.ExtensionChangeDestinationAction{ 45 | Destination: commercetools.ExtensionHTTPDestination{ 46 | URL: "http://example.com", 47 | }, 48 | } 49 | 50 | result, err := json.Marshal(obj) 51 | assert.Nil(t, err) 52 | assert.JSONEq(t, `{ 53 | "destination":{ 54 | "type": "HTTP", 55 | "url":"http://example.com" 56 | }, 57 | "action":"changeDestination"}`, string(result)) 58 | } 59 | -------------------------------------------------------------------------------- /commercetools/testdata/cart.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "Cart", 3 | "id": "debd77c9-ef14-4595-8614-5d123429f9e1", 4 | "version": 3, 5 | "createdAt": "2019-05-07T15:47:34.356Z", 6 | "lastModifiedAt": "2019-05-07T15:47:34.356Z", 7 | "lastModifiedBy": { 8 | "clientId": "WU-qHF_IkFYHB2W9KwKaqVpl", 9 | "isPlatformClient": false 10 | }, 11 | "createdBy": { 12 | "clientId": "WU-qHF_IkFYHB2W9KwKaqVpl", 13 | "isPlatformClient": false 14 | }, 15 | "lineItems": [], 16 | "cartState": "Active", 17 | "totalPrice": { 18 | "type": "centPrecision", 19 | "currencyCode": "EUR", 20 | "centAmount": 0, 21 | "fractionDigits": 2 22 | }, 23 | "taxedPrice": { 24 | "totalNet": { 25 | "type": "centPrecision", 26 | "currencyCode": "EUR", 27 | "centAmount": 0, 28 | "fractionDigits": 2 29 | }, 30 | "totalGross": { 31 | "type": "centPrecision", 32 | "currencyCode": "EUR", 33 | "centAmount": 0, 34 | "fractionDigits": 2 35 | }, 36 | "taxPortions": [] 37 | }, 38 | "customLineItems": [], 39 | "discountCodes": [], 40 | "custom": { 41 | "type": { 42 | "typeId": "type", 43 | "id": "a97fb5a2-f4dd-462e-b113-59e7c9d9aa67" 44 | }, 45 | "fields": { 46 | "allowOrder": false 47 | } 48 | }, 49 | "inventoryMode": "None", 50 | "taxMode": "Platform", 51 | "taxRoundingMode": "HalfEven", 52 | "taxCalculationMode": "LineItemLevel", 53 | "refusedGifts": [], 54 | "origin": "Customer", 55 | "shippingAddress": { 56 | "country": "DE" 57 | }, 58 | "itemShippingAddresses": [] 59 | } -------------------------------------------------------------------------------- /code-generate/generate_types_main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/dave/jennifer/jen" 7 | ) 8 | 9 | // Entry point to generate code object for a specific RamlType 10 | func generateTypes(objects []RamlType) { 11 | items := map[string][]*RamlType{} 12 | 13 | for i := range objects { 14 | item := objects[i] 15 | items[item.Package] = append(items[item.Package], &item) 16 | } 17 | 18 | for pkg, packageObjects := range items { 19 | filename := generateFilename(pkg, "") 20 | log.Printf("Writing commercetools/%s\n", filename) 21 | f := jen.NewFile("commercetools") 22 | f.HeaderComment("Automatically generated, do not edit") 23 | 24 | enumObjects := map[string]jen.Code{} 25 | mapObjects := map[string]jen.Code{} 26 | stringObjects := map[string]jen.Code{} 27 | structObjects := map[string]jen.Code{} 28 | 29 | for _, object := range packageObjects { 30 | var stmt *jen.Statement 31 | key := object.CodeName 32 | 33 | // Just to keep sorting order (bit of a hack) 34 | if object.isInterface() { 35 | key = "Abstract" + key 36 | } 37 | 38 | if object.asMap { 39 | stmt = generateMap(*object) 40 | mapObjects[key] = stmt 41 | } else if len(object.EnumValues) > 0 { 42 | stmt := generateEnum(*object) 43 | enumObjects[key] = stmt 44 | } else if object.TypeName == "string" { 45 | stmt := generateString(*object) 46 | stringObjects[key] = stmt 47 | } else { 48 | stmt = generateStruct(*object) 49 | structObjects[key] = stmt 50 | } 51 | } 52 | 53 | addCodeObjects(f, enumObjects) 54 | addCodeObjects(f, stringObjects) 55 | addCodeObjects(f, mapObjects) 56 | addCodeObjects(f, structObjects) 57 | 58 | err := f.Save("commercetools/types_" + filename) 59 | if err != nil { 60 | panic(err) 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /code-generate/generate_service_utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | "github.com/dave/jennifer/jen" 8 | ) 9 | 10 | func createServiceReturnList(method ServiceMethod, ro RamlType) jen.Code { 11 | if ro.isInterface() { 12 | return jen.List( 13 | jen.Id("result").Id(method.ReturnType), 14 | jen.Err().Error(), 15 | ) 16 | } 17 | return jen.List( 18 | jen.Id("result").Op("*").Id(method.ReturnType), 19 | jen.Err().Error(), 20 | ) 21 | } 22 | 23 | func generateServicePathCode(method ServiceMethod) jen.Code { 24 | // Replace placeholders with %s. 25 | // E.g. "/in-store/key={storeKey}/carts/{ID}" => "/in-store/key=%s/carts/%s" 26 | var paramCodes []jen.Code 27 | 28 | var parameters []string 29 | if method.Type == "update" { 30 | parameters = append(parameters, method.Parameters[:len(method.Parameters)-1]...) 31 | lastParam := CreateCodeName(method.Parameters[len(method.Parameters)-1]) 32 | parameters = append(parameters, "input."+lastParam) 33 | } else { 34 | parameters = method.Parameters 35 | } 36 | 37 | path := method.Path 38 | for _, param := range method.Parameters { 39 | path = strings.Replace(path, fmt.Sprintf("{%s}", param), "%s", 1) 40 | } 41 | 42 | for _, param := range parameters { 43 | if param == "ID" { 44 | param = "id" 45 | } 46 | paramCodes = append(paramCodes, jen.Id(param)) 47 | } 48 | 49 | if len(paramCodes) < 1 { 50 | return jen.Lit(path[1:]) 51 | } 52 | return jen.Qual("fmt", "Sprintf").Call(jen.Lit(path[1:]), jen.List(paramCodes...)) 53 | 54 | } 55 | 56 | func generateServiceArgumentCode(method ServiceMethod) []jen.Code { 57 | var paramCodes []jen.Code 58 | for _, param := range method.Parameters { 59 | if param == "ID" { 60 | param = "id" 61 | } 62 | paramCodes = append(paramCodes, jen.Id(param).String()) 63 | } 64 | return paramCodes 65 | } 66 | -------------------------------------------------------------------------------- /commercetools/date_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "encoding/json" 5 | "testing" 6 | 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func TestDateSerialization(t *testing.T) { 12 | 13 | data := struct { 14 | String string `json:"string"` 15 | Value *commercetools.Date `json:"value"` 16 | Optional *commercetools.Date `json:"optional",omitempty` 17 | }{} 18 | data.String = "foobar" 19 | data.Value = &commercetools.Date{Year: 1983, Month: 5, Day: 10} 20 | data.Optional = &commercetools.Date{Year: 1983, Month: 5, Day: 10} 21 | 22 | m, err := json.Marshal(data) 23 | assert.NoError(t, err) 24 | 25 | expected := `{"string":"foobar","value":"1983-05-10","optional":"1983-05-10"}` 26 | assert.Equal(t, expected, string(m)) 27 | } 28 | 29 | func TestDateSerializationEmpty(t *testing.T) { 30 | 31 | data := struct { 32 | String string `json:"string"` 33 | Value *commercetools.Date `json:"value"` 34 | Optional *commercetools.Date `json:"optional,omitempty"` 35 | }{} 36 | data.String = "foobar" 37 | 38 | m, err := json.Marshal(data) 39 | assert.NoError(t, err) 40 | 41 | expected := `{"string":"foobar","value":null}` 42 | assert.Equal(t, expected, string(m)) 43 | } 44 | 45 | func TestDateDeserialization(t *testing.T) { 46 | 47 | data := struct { 48 | String string `json:"string"` 49 | Value *commercetools.Date `json:"value"` 50 | Optional *commercetools.Date `json:"optional",omitempty` 51 | }{} 52 | 53 | value := `{"string":"foobar","value":"1983-05-10"}` 54 | err := json.Unmarshal([]byte(value), &data) 55 | assert.NoError(t, err) 56 | assert.Equal(t, "foobar", data.String) 57 | assert.Equal(t, &commercetools.Date{Year: 1983, Month: 5, Day: 10}, data.Value) 58 | assert.Equal(t, (*commercetools.Date)(nil), data.Optional) 59 | } 60 | -------------------------------------------------------------------------------- /commercetools/types_custom_object.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "encoding/json" 7 | "time" 8 | ) 9 | 10 | // CustomObject is of type BaseResource 11 | type CustomObject struct { 12 | Version int `json:"version"` 13 | Value interface{} `json:"value"` 14 | LastModifiedBy *LastModifiedBy `json:"lastModifiedBy,omitempty"` 15 | LastModifiedAt time.Time `json:"lastModifiedAt"` 16 | Key string `json:"key"` 17 | ID string `json:"id"` 18 | CreatedBy *CreatedBy `json:"createdBy,omitempty"` 19 | CreatedAt time.Time `json:"createdAt"` 20 | Container string `json:"container"` 21 | } 22 | 23 | // CustomObjectDraft is a standalone struct 24 | type CustomObjectDraft struct { 25 | Version int `json:"version,omitempty"` 26 | Value interface{} `json:"value"` 27 | Key string `json:"key"` 28 | Container string `json:"container"` 29 | } 30 | 31 | // CustomObjectPagedQueryResponse is a standalone struct 32 | type CustomObjectPagedQueryResponse struct { 33 | Total int `json:"total,omitempty"` 34 | Results []CustomObject `json:"results"` 35 | Offset int `json:"offset"` 36 | Limit int `json:"limit"` 37 | Count int `json:"count"` 38 | } 39 | 40 | // CustomObjectReference implements the interface Reference 41 | type CustomObjectReference struct { 42 | ID string `json:"id"` 43 | Obj *CustomObject `json:"obj,omitempty"` 44 | } 45 | 46 | // MarshalJSON override to set the discriminator value 47 | func (obj CustomObjectReference) MarshalJSON() ([]byte, error) { 48 | type Alias CustomObjectReference 49 | return json.Marshal(struct { 50 | TypeID string `json:"typeId"` 51 | *Alias 52 | }{TypeID: "key-value-document", Alias: (*Alias)(&obj)}) 53 | } 54 | -------------------------------------------------------------------------------- /commercetools/utils.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import ( 4 | "net/url" 5 | "reflect" 6 | "regexp" 7 | "time" 8 | 9 | "github.com/appscode/go-querystring/query" 10 | mapstructure "github.com/mitchellh/mapstructure" 11 | ) 12 | 13 | var ( 14 | reSlice = regexp.MustCompile(`^([^\[]+)\[\d+\]$`) 15 | reMap = regexp.MustCompile(`^([^\[]+)\[([^\]]+)]$`) 16 | ) 17 | 18 | func serializeQueryParams(v interface{}) url.Values { 19 | values, _ := query.Values(v) 20 | 21 | newValues := url.Values{} 22 | for key, values := range values { 23 | // TODO: this is pretty ugly and should be fixed upstream 24 | newKey := reSlice.ReplaceAllString(key, "$1") 25 | newKey = reMap.ReplaceAllString(newKey, "$1.$2") 26 | for _, value := range values { 27 | newValues.Add(newKey, value) 28 | } 29 | } 30 | return newValues 31 | } 32 | 33 | func toTimeHookFunc() mapstructure.DecodeHookFunc { 34 | return func( 35 | f reflect.Type, 36 | t reflect.Type, 37 | data interface{}) (interface{}, error) { 38 | if t != reflect.TypeOf(time.Time{}) { 39 | return data, nil 40 | } 41 | 42 | switch f.Kind() { 43 | case reflect.String: 44 | return time.Parse(time.RFC3339, data.(string)) 45 | case reflect.Float64: 46 | return time.Unix(0, int64(data.(float64))*int64(time.Millisecond)), nil 47 | case reflect.Int64: 48 | return time.Unix(0, data.(int64)*int64(time.Millisecond)), nil 49 | default: 50 | return data, nil 51 | } 52 | // Convert it by parsing 53 | } 54 | } 55 | 56 | func decodeStruct(input interface{}, result interface{}) error { 57 | decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ 58 | Metadata: nil, 59 | DecodeHook: mapstructure.ComposeDecodeHookFunc( 60 | toTimeHookFunc()), 61 | Result: result, 62 | }) 63 | if err != nil { 64 | return err 65 | } 66 | 67 | if err := decoder.Decode(input); err != nil { 68 | return err 69 | } 70 | return err 71 | } 72 | -------------------------------------------------------------------------------- /commercetools/service_api_client.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | ) 10 | 11 | // APIClientCreate creates a new instance of type APIClient 12 | func (client *Client) APIClientCreate(ctx context.Context, draft *APIClientDraft, opts ...RequestOption) (result *APIClient, err error) { 13 | params := url.Values{} 14 | for _, opt := range opts { 15 | opt(¶ms) 16 | } 17 | 18 | endpoint := "api-clients" 19 | err = client.create(ctx, endpoint, params, draft, &result) 20 | if err != nil { 21 | return nil, err 22 | } 23 | return result, nil 24 | } 25 | 26 | // APIClientQuery allows querying for type ApiClient 27 | func (client *Client) APIClientQuery(ctx context.Context, input *QueryInput) (result *APIClientPagedQueryResponse, err error) { 28 | endpoint := "api-clients" 29 | err = client.query(ctx, endpoint, input.toParams(), &result) 30 | if err != nil { 31 | return nil, err 32 | } 33 | return result, nil 34 | } 35 | 36 | // APIClientDeleteWithID Delete ApiClient by ID 37 | func (client *Client) APIClientDeleteWithID(ctx context.Context, id string, opts ...RequestOption) (result *APIClient, err error) { 38 | params := url.Values{} 39 | 40 | for _, opt := range opts { 41 | opt(¶ms) 42 | } 43 | endpoint := fmt.Sprintf("api-clients/%s", id) 44 | err = client.delete(ctx, endpoint, params, &result) 45 | if err != nil { 46 | return nil, err 47 | } 48 | return result, nil 49 | } 50 | 51 | // APIClientGetWithID Get ApiClient by ID 52 | func (client *Client) APIClientGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *APIClient, err error) { 53 | params := url.Values{} 54 | for _, opt := range opts { 55 | opt(¶ms) 56 | } 57 | endpoint := fmt.Sprintf("api-clients/%s", id) 58 | err = client.get(ctx, endpoint, params, &result) 59 | if err != nil { 60 | return nil, err 61 | } 62 | return result, nil 63 | } 64 | -------------------------------------------------------------------------------- /code-generate/generate_service_get.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/dave/jennifer/jen" 7 | ) 8 | 9 | // Generate the `Get` function 10 | func generateServiceGet(method ServiceMethod, objects map[string]RamlType) (code *jen.Statement) { 11 | structReceiver := jen.Id("client").Op("*").Id("Client") 12 | 13 | // Generate function parameters 14 | extraParams := generateServiceArgumentCode(method) 15 | methodParams := []jen.Code{ 16 | jen.Id("ctx").Qual("context", "Context"), 17 | } 18 | methodParams = append(methodParams, extraParams...) 19 | methodParams = append( 20 | methodParams, 21 | jen.Id("opts").Op("...").Id("RequestOption"), 22 | ) 23 | returnObject := objects[method.ReturnType] 24 | returnParams := createServiceReturnList(method, returnObject) 25 | 26 | description := fmt.Sprintf("for type %s", method.ReturnType) 27 | if method.Description != "" { 28 | description = method.Description 29 | } 30 | c := jen.Commentf("%s %s", method.Name, description).Line() 31 | c.Func().Params(structReceiver).Id(method.Name).Params(jen.List(methodParams...)).Parens(returnParams).BlockFunc(func(d *jen.Group) { 32 | 33 | d.Id("params").Op(":=").Qual("net/url", "Values").Block() 34 | 35 | // for _, opt := range opts { 36 | // opt(¶ms) 37 | // } 38 | d.For(jen.List(jen.Id("_"), jen.Id("opt")).Op(":=").Range().Id("opts")).Block( 39 | jen.Id("opt").Call(jen.Op("&").Id("params")), 40 | ) 41 | 42 | d.Id("endpoint").Op(":=").Add(generateServicePathCode(method)) 43 | d.Id("err").Op("=").Id("client").Op(".").Id("get").Call( 44 | jen.Id("ctx"), 45 | jen.Id("endpoint"), 46 | jen.Id("params"), 47 | jen.Op("&").Id("result"), 48 | ) 49 | d.If(jen.Err().Op("!=").Nil()).Block( 50 | jen.Return(jen.Nil(), jen.Err()), 51 | ) 52 | 53 | if returnObject.isInterface() { 54 | d.Return(jen.Id(returnObject.discriminatorFunctionName()).Call(jen.Id("result"))) 55 | } else { 56 | d.Return(jen.Id("result"), jen.Nil()) 57 | } 58 | }).Line() 59 | return c 60 | } 61 | -------------------------------------------------------------------------------- /testutil/api.go: -------------------------------------------------------------------------------- 1 | package testutil 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | "net/http/httptest" 11 | "net/url" 12 | "testing" 13 | 14 | "github.com/labd/commercetools-go-sdk/commercetools" 15 | "golang.org/x/oauth2" 16 | ) 17 | 18 | // RequestData holds test HTTP request data 19 | type RequestData struct { 20 | URL url.URL 21 | Body []byte 22 | Method string 23 | JSON string 24 | } 25 | 26 | // HTTPHandler type defines callback from doing a mock HTTP request 27 | type HTTPHandler func(w http.ResponseWriter, r *http.Request) 28 | 29 | // MockClient returns a client to mock HTTP requests with a callback function 30 | func MockClient( 31 | t *testing.T, 32 | fixture string, 33 | output *RequestData, 34 | callback HTTPHandler) (*commercetools.Client, *httptest.Server) { 35 | 36 | handler := func(w http.ResponseWriter, r *http.Request) { 37 | body, err := ioutil.ReadAll(r.Body) 38 | if err != nil { 39 | t.Fatal(err) 40 | } 41 | 42 | if output != nil { 43 | output.Method = r.Method 44 | output.URL = *r.URL 45 | } 46 | 47 | if r.Method == "POST" || r.Method == "PATCH" { 48 | 49 | // Check if the body is valid JSON 50 | var dummy map[string]interface{} 51 | if err := json.Unmarshal(body, &dummy); err != nil { 52 | log.Printf("Error on unmarshal: %v\n", body) 53 | } 54 | 55 | if output != nil { 56 | output.JSON = string(body) 57 | } 58 | } 59 | 60 | if callback != nil { 61 | callback(w, r) 62 | } else { 63 | w.Header().Set("Content-Type", "application/json") 64 | w.WriteHeader(http.StatusOK) 65 | fmt.Fprint(w, fixture) 66 | } 67 | 68 | } 69 | 70 | ts := httptest.NewServer(http.HandlerFunc(handler)) 71 | 72 | httpClient := oauth2.NewClient(context.TODO(), oauth2.StaticTokenSource(&oauth2.Token{ 73 | AccessToken: "unittest", 74 | }), 75 | ) 76 | 77 | client := commercetools.New(&commercetools.Config{ 78 | ProjectKey: "unittest", 79 | URL: ts.URL, 80 | HTTPClient: httpClient, 81 | }) 82 | 83 | return client, ts 84 | } 85 | -------------------------------------------------------------------------------- /code-generate/generate_service_create.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/dave/jennifer/jen" 5 | ) 6 | 7 | // Generate the `Create` function 8 | func generateServiceCreate(method ServiceMethod, objects map[string]RamlType) (code *jen.Statement) { 9 | structReceiver := jen.Id("client").Op("*").Id("Client") 10 | methodParamList := []jen.Code{ 11 | jen.Id("ctx").Qual("context", "Context"), 12 | } 13 | extraParams := generateServiceArgumentCode(method) 14 | methodParamList = append(methodParamList, extraParams...) 15 | methodParamList = append( 16 | methodParamList, 17 | jen.Id("draft").Op("*").Id(method.InputType), 18 | jen.Id("opts").Op("...").Id("RequestOption"), 19 | ) 20 | 21 | returnObject := objects[method.ReturnType] 22 | returnParams := createServiceReturnList(method, returnObject) 23 | 24 | c := jen.Commentf("%s creates a new instance of type %s", method.Name, method.ReturnType).Line() 25 | 26 | // func (client *Client) ResourceCreate(ctx context.Context, draft *ResourceDraft, opts ...RequestOption) (result *APIClient, err error) { 27 | c.Func().Params(structReceiver).Id(method.Name).Params(jen.List(methodParamList...)).Parens(returnParams).Block( 28 | 29 | // params := url.Values{} 30 | // for _, opt := range opts { 31 | // opt(¶ms) 32 | // } 33 | jen.Id("params").Op(":=").Qual("net/url", "Values").Block(), 34 | jen.For(jen.List(jen.Id("_"), jen.Id("opt")).Op(":=").Range().Id("opts")).Block( 35 | jen.Id("opt").Call(jen.Op("&").Id("params")), 36 | ), 37 | jen.Line(), 38 | 39 | // err = client.create(ctx, ProductURLPath, params, draft, &result) 40 | jen.Id("endpoint").Op(":=").Add(generateServicePathCode(method)), 41 | jen.Id("err").Op("=").Id("client").Op(".").Id("create").Call( 42 | jen.Id("ctx"), 43 | jen.Id("endpoint"), 44 | jen.Id("params"), 45 | jen.Id("draft"), 46 | jen.Op("&").Id("result"), 47 | ), 48 | 49 | // if err != nil { 50 | // return nil, err 51 | // } 52 | jen.If(jen.Err().Op("!=").Nil()).Block( 53 | jen.Return(jen.Nil(), jen.Err()), 54 | ), 55 | 56 | // return result, nil 57 | jen.Return(jen.Id("result"), jen.Nil()), 58 | ).Line() 59 | return c 60 | } 61 | -------------------------------------------------------------------------------- /commercetools/service_api_client_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedAPIClientGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "api-client-id", 16 | "name": "api-client-name", 17 | "scope": "view_products", 18 | "createdAt": "2018-01-01T00:00:00.001Z", 19 | "lastUsedAt": "2017-09-10", 20 | "secret": "secret-passphrase" 21 | } ` 22 | client, server := testutil.MockClient(t, responseData, nil, nil) 23 | defer server.Close() 24 | api_client, err := client.APIClientGetWithID(context.TODO(), "dummy-id") 25 | if err != nil { 26 | t.Fatal(err) 27 | } 28 | assert.NotNil(t, api_client) 29 | 30 | } 31 | 32 | func TestGeneratedAPIClientDeleteWithID(t *testing.T) { 33 | responseData := ` { 34 | "id": "api-client-id", 35 | "name": "api-client-name", 36 | "scope": "view_products", 37 | "createdAt": "2018-01-01T00:00:00.001Z", 38 | "lastUsedAt": "2017-09-10", 39 | "secret": "secret-passphrase" 40 | } ` 41 | client, server := testutil.MockClient(t, responseData, nil, nil) 42 | defer server.Close() 43 | api_client, err := client.APIClientDeleteWithID(context.TODO(), "dummy-id") 44 | if err != nil { 45 | t.Fatal(err) 46 | } 47 | assert.NotNil(t, api_client) 48 | 49 | } 50 | 51 | func TestGeneratedAPIClientQuery(t *testing.T) { 52 | responseData := ` { 53 | "limit": 20, 54 | "offset": 0, 55 | "count": 1, 56 | "total": 1, 57 | "results": [ 58 | { 59 | "id": "api-client-id", 60 | "name": "api-client-name", 61 | "scope": "view_products", 62 | "createdAt": "2018-01-01T00:00:00.001Z", 63 | "lastUsedAt": "2017-09-10", 64 | "secret": "secret-passphrase" 65 | } 66 | ] 67 | } ` 68 | client, server := testutil.MockClient(t, responseData, nil, nil) 69 | defer server.Close() 70 | input := commercetools.QueryInput{} 71 | queryResult, err := client.APIClientQuery(context.TODO(), &input) 72 | if err != nil { 73 | t.Fatal(err) 74 | } 75 | assert.NotNil(t, queryResult) 76 | 77 | } 78 | -------------------------------------------------------------------------------- /commercetools/client_useragent_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | "testing" 7 | 8 | "github.com/labd/commercetools-go-sdk/commercetools" 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func TestUserAgents(t *testing.T) { 13 | testCases := []struct { 14 | cfg *commercetools.ClientConfig 15 | expectedUserAgent string 16 | }{ 17 | { 18 | cfg: &commercetools.ClientConfig{ 19 | LibraryName: "terraform-provider-commercetools", 20 | LibraryVersion: "0.1", 21 | ContactURL: "https://example.com", 22 | ContactEmail: "test@example.org", 23 | }, 24 | expectedUserAgent: fmt.Sprintf( 25 | "commercetools-go-sdk/%s Go/%s (%s; %s) terraform-provider-commercetools/0.1 (+https://example.com; +test@example.org)", 26 | commercetools.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH), 27 | }, 28 | { 29 | cfg: &commercetools.ClientConfig{ 30 | ContactURL: "https://example.com", 31 | ContactEmail: "test@example.org", 32 | }, 33 | expectedUserAgent: fmt.Sprintf( 34 | "commercetools-go-sdk/%s Go/%s (%s; %s) (+https://example.com; +test@example.org)", 35 | commercetools.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH), 36 | }, 37 | { 38 | cfg: &commercetools.ClientConfig{ 39 | LibraryName: "terraform-provider-commercetools", 40 | LibraryVersion: "0.1", 41 | ContactEmail: "test@example.org", 42 | }, 43 | expectedUserAgent: fmt.Sprintf( 44 | "commercetools-go-sdk/%s Go/%s (%s; %s) terraform-provider-commercetools/0.1 (+test@example.org)", 45 | commercetools.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH), 46 | }, 47 | { 48 | cfg: &commercetools.ClientConfig{ 49 | LibraryName: "terraform-provider-commercetools", 50 | ContactURL: "https://example.com", 51 | ContactEmail: "test@example.org", 52 | }, 53 | expectedUserAgent: fmt.Sprintf( 54 | "commercetools-go-sdk/%s Go/%s (%s; %s) terraform-provider-commercetools (+https://example.com; +test@example.org)", 55 | commercetools.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH), 56 | }, 57 | } 58 | 59 | for _, tC := range testCases { 60 | t.Run("Test user agent", func(t *testing.T) { 61 | userAgent := commercetools.GetUserAgent(tC.cfg) 62 | assert.Equal(t, tC.expectedUserAgent, userAgent) 63 | }) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /commercetools/service_api_client_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/url" 7 | "testing" 8 | "time" 9 | 10 | "github.com/labd/commercetools-go-sdk/commercetools" 11 | "github.com/stretchr/testify/assert" 12 | 13 | "github.com/labd/commercetools-go-sdk/testutil" 14 | ) 15 | 16 | func TestAPIClientCreate(t *testing.T) { 17 | output := testutil.RequestData{} 18 | 19 | client, server := testutil.MockClient(t, "{}", &output, nil) 20 | defer server.Close() 21 | 22 | input := &commercetools.APIClientDraft{ 23 | Scope: "manage_project", 24 | Name: "api-client-name", 25 | } 26 | 27 | fmt.Println(output) 28 | 29 | _, err := client.APIClientCreate(context.TODO(), input) 30 | assert.Nil(t, err) 31 | 32 | expectedBody := `{ 33 | "name": "api-client-name", 34 | "scope": "manage_project" 35 | }` 36 | 37 | assert.JSONEq(t, expectedBody, output.JSON) 38 | } 39 | 40 | func TestAPIClientDelete(t *testing.T) { 41 | output := testutil.RequestData{} 42 | client, server := testutil.MockClient(t, "{}", &output, nil) 43 | defer server.Close() 44 | 45 | _, err := client.APIClientDeleteWithID(context.TODO(), "1234") 46 | assert.Nil(t, err) 47 | 48 | assert.Equal(t, "/unittest/api-clients/1234", output.URL.Path) 49 | } 50 | 51 | func TestAPIClientGetByID(t *testing.T) { 52 | client, server := testutil.MockClient(t, testutil.Fixture("api-client.example.json"), nil, nil) 53 | defer server.Close() 54 | 55 | timestamp, _ := time.Parse(time.RFC3339, "2018-01-01T00:00:00.001Z") 56 | 57 | input := &commercetools.APIClient{ 58 | ID: "api-client-id", 59 | Scope: "view_products", 60 | Name: "api-client-name", 61 | CreatedAt: ×tamp, 62 | LastUsedAt: &commercetools.Date{Year: 2017, Month: 9, Day: 10}, 63 | Secret: "secret-passphrase", 64 | } 65 | 66 | result, err := client.APIClientGetWithID(context.TODO(), "1234") 67 | assert.Nil(t, err) 68 | assert.Equal(t, input, result) 69 | } 70 | 71 | func TestAPIClientQuery(t *testing.T) { 72 | output := testutil.RequestData{} 73 | client, server := testutil.MockClient(t, "{}", &output, nil) 74 | defer server.Close() 75 | 76 | queryInput := commercetools.QueryInput{ 77 | Limit: 500, 78 | } 79 | _, err := client.APIClientQuery(context.TODO(), &queryInput) 80 | assert.Nil(t, err) 81 | 82 | assert.Equal(t, url.Values{"limit": []string{"500"}}, output.URL.Query()) 83 | } 84 | -------------------------------------------------------------------------------- /commercetools/client_queryinput.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import ( 4 | "net/url" 5 | "strconv" 6 | ) 7 | 8 | // QueryInput provides the data required to query types. 9 | type QueryInput struct { 10 | // The queryable APIs support ad-hoc filtering of resources through flexible 11 | // predicates. They do so via the where query parameter that accepts a 12 | // predicate expression to determine whether a specific resource 13 | // representation should be included in the result. The structure of 14 | // predicates and the names of the fields follow the structure and naming of 15 | // the fields in the documented response representation of the query 16 | // results. 17 | // https://docs.commercetools.com/http-api-query-predicates.html 18 | Where string 19 | 20 | // A query endpoint that supports sorting does so through the sort query 21 | // parameter. The provided value must be a valid sort expression. The 22 | // default sort direction is ASC. The allowed sort paths are typically 23 | // listed on the specific query endpoints. If multiple sort expressions are 24 | // specified via multiple sort parameters, they are combined into a composed 25 | // sort where the results are first sorted by the first expression, followed 26 | // by equal values being sorted according to the second expression, and so 27 | // on. 28 | // https://docs.commercetools.com/http-api.html#sorting 29 | Sort []string 30 | 31 | // Reference expansion is a feature of the resources listed in the table 32 | // below that enables clients to request server-side expansion of Reference 33 | // resources, thereby reducing the number of required client-server 34 | // roundtrips to obtain the data that a client needs for a specific 35 | // use-case. Reference expansion can be used when creating, updating, 36 | // querying, and deleting these resources. 37 | // https://docs.commercetools.com/http-api.html#reference-expansion 38 | Expand []string 39 | 40 | Limit int 41 | Offset int 42 | 43 | // Extra query arguments. 44 | Extra url.Values 45 | } 46 | 47 | func (qi QueryInput) toParams() (values url.Values) { 48 | values = url.Values{} 49 | 50 | if qi.Where != "" { 51 | values.Set("where", qi.Where) 52 | } 53 | 54 | for i := range qi.Sort { 55 | values.Add("sort", qi.Sort[i]) 56 | } 57 | 58 | for i := range qi.Expand { 59 | values.Add("expand", qi.Expand[i]) 60 | } 61 | 62 | if qi.Limit != 0 { 63 | values.Set("limit", strconv.Itoa(qi.Limit)) 64 | } 65 | 66 | if qi.Offset != 0 { 67 | values.Set("offset", strconv.Itoa(qi.Offset)) 68 | } 69 | 70 | for k, v := range qi.Extra { 71 | values[k] = v 72 | } 73 | return 74 | } 75 | -------------------------------------------------------------------------------- /commercetools/client_graphql.go: -------------------------------------------------------------------------------- 1 | package commercetools 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "io/ioutil" 9 | "net/http" 10 | 11 | mapstructure "github.com/mitchellh/mapstructure" 12 | "github.com/pkg/errors" 13 | ) 14 | 15 | type GraphQLQuery struct { 16 | client *Client 17 | endpoint string 18 | query string 19 | vars GraphQLVariablesMap 20 | headers map[string]string 21 | } 22 | 23 | // NewGraphQLQuery creates a new GraphQLQuery object which can be used to 24 | // execute a GraphQL query 25 | func (client *Client) NewGraphQLQuery(query string) *GraphQLQuery { 26 | 27 | queryObject := GraphQLQuery{ 28 | client: client, 29 | endpoint: fmt.Sprintf("%s/%s/graphql", client.Endpoints().API, client.projectKey), 30 | query: query, 31 | } 32 | 33 | return &queryObject 34 | } 35 | 36 | // Bind variables to the GraphQL query 37 | func (gql *GraphQLQuery) Bind(key string, value interface{}) { 38 | if gql.vars == nil { 39 | gql.vars = make(GraphQLVariablesMap) 40 | } 41 | gql.vars[key] = value 42 | } 43 | 44 | type GraphQLOption func(o *GraphQLQuery) 45 | 46 | func (gql *GraphQLQuery) ForMerchantCenter() GraphQLOption { 47 | return func(o *GraphQLQuery) { 48 | 49 | o.endpoint = fmt.Sprintf("%s/graphql", o.client.Endpoints().MerchantCenterAPI) 50 | o.headers = make(map[string]string) 51 | o.headers["X-Project-Key"] = gql.client.ProjectKey() 52 | o.headers["X-GraphQL-Target"] = "settings" 53 | } 54 | } 55 | 56 | // Execute the GraphQL query 57 | func (gql *GraphQLQuery) Execute(respData interface{}, opts ...GraphQLOption) error { 58 | var body bytes.Buffer 59 | 60 | requestObj := GraphQLRequest{ 61 | Query: gql.query, 62 | Variables: &gql.vars, 63 | } 64 | 65 | for _, opt := range opts { 66 | opt(gql) 67 | } 68 | 69 | if err := json.NewEncoder(&body).Encode(requestObj); err != nil { 70 | return errors.Wrap(err, "encode body") 71 | } 72 | ctx := context.TODO() 73 | resp, err := gql.client.getResponse(ctx, "POST", gql.endpoint, nil, &body, gql.headers) 74 | if err != nil { 75 | return err 76 | } 77 | defer resp.Body.Close() 78 | 79 | return gql.processResponse(resp, respData) 80 | } 81 | 82 | func (gql *GraphQLQuery) processResponse(resp *http.Response, dest interface{}) error { 83 | body, err := ioutil.ReadAll(resp.Body) 84 | 85 | var output GraphQLResponse 86 | err = json.Unmarshal(body, &output) 87 | if err != nil { 88 | return err 89 | } 90 | 91 | if output.Errors != nil { 92 | return output.Errors[0] 93 | } 94 | 95 | if output.Data != nil { 96 | mapstructure.Decode(output.Data, &dest) 97 | } 98 | return nil 99 | } 100 | -------------------------------------------------------------------------------- /code-generate/generate_service_delete.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/dave/jennifer/jen" 7 | ) 8 | 9 | // Generate the `DeleteWithID` and `DeleteWithKey` functions 10 | func generateServiceDelete(method ServiceMethod, objects map[string]RamlType) (code *jen.Statement) { 11 | deleteWithVersion := true 12 | // TODO: nasty hack / incomplete API def 13 | if method.Context == "ApiClient" { 14 | deleteWithVersion = false 15 | } 16 | 17 | extraParams := generateServiceArgumentCode(method) 18 | methodParamList := []jen.Code{ 19 | jen.Id("ctx").Qual("context", "Context"), 20 | } 21 | methodParamList = append(methodParamList, extraParams...) 22 | 23 | returnObject := objects[method.ReturnType] 24 | returnParams := createServiceReturnList(method, returnObject) 25 | 26 | setVersionParam := jen.Empty() 27 | if deleteWithVersion { 28 | methodParamList = append(methodParamList, jen.Id("version").Int()) 29 | setVersionParam = jen.Id("params").Op(".").Id("Set").Call( 30 | jen.Lit("version"), 31 | jen.Qual("strconv", "Itoa").Call(jen.Id("version"))) 32 | } 33 | 34 | setDataErasure := jen.Empty() 35 | if method.HasTrait("dataErasure") { 36 | methodParamList = append(methodParamList, jen.Id("dataErasure").Bool()) 37 | setDataErasure = jen.Id("params").Op(".").Id("Set").Call( 38 | jen.Lit("dataErasure"), 39 | jen.Qual("strconv", "FormatBool").Call(jen.Id("dataErasure"))) 40 | } 41 | methodParamList = append(methodParamList, jen.Id("opts").Op("...").Id("RequestOption")) 42 | 43 | methodParams := jen.List(methodParamList...) 44 | clientMethod := "delete" 45 | 46 | structReceiver := jen.Id("client").Op("*").Id("Client") 47 | 48 | description := fmt.Sprintf("for type %s", method.ReturnType) 49 | if method.Description != "" { 50 | description = method.Description 51 | } 52 | c := jen.Commentf("%s %s", method.Name, description).Line() 53 | c.Func().Params(structReceiver).Id(method.Name).Params(methodParams).Parens(returnParams).Block( 54 | jen.Id("params").Op(":=").Qual("net/url", "Values").Block(), 55 | setVersionParam, 56 | setDataErasure, 57 | 58 | // for _, opt := range opts { 59 | // opt(¶ms) 60 | // } 61 | jen.For(jen.List(jen.Id("_"), jen.Id("opt")).Op(":=").Range().Id("opts")).Block( 62 | jen.Id("opt").Call(jen.Op("&").Id("params")), 63 | ), 64 | 65 | jen.Id("endpoint").Op(":=").Add(generateServicePathCode(method)), 66 | jen.Id("err").Op("=").Id("client").Op(".").Id(clientMethod).Call( 67 | jen.Id("ctx"), 68 | jen.Id("endpoint"), 69 | jen.Id("params"), 70 | jen.Op("&").Id("result"), 71 | ), 72 | jen.If(jen.Err().Op("!=").Nil()).Block( 73 | jen.Return(jen.Nil(), jen.Err()), 74 | ), 75 | jen.Return(jen.Id("result"), jen.Nil()), 76 | ).Line() 77 | 78 | return c 79 | } 80 | -------------------------------------------------------------------------------- /commercetools/client_queryinput_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "net/url" 6 | "testing" 7 | 8 | "github.com/labd/commercetools-go-sdk/commercetools" 9 | "github.com/labd/commercetools-go-sdk/testutil" 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestQueryInput(t *testing.T) { 14 | testCases := []struct { 15 | desc string 16 | input *commercetools.QueryInput 17 | query url.Values 18 | rawQuery string 19 | }{ 20 | { 21 | desc: "Where", 22 | input: &commercetools.QueryInput{ 23 | Where: "not (name = 'Peter' and age < 42)", 24 | }, 25 | query: url.Values{ 26 | "where": []string{"not (name = 'Peter' and age < 42)"}, 27 | }, 28 | rawQuery: "where=not+%28name+%3D+%27Peter%27+and+age+%3C+42%29", 29 | }, 30 | { 31 | desc: "Sort", 32 | input: &commercetools.QueryInput{ 33 | Sort: []string{"name desc", "dog.age asc"}, 34 | }, 35 | query: url.Values{ 36 | "sort": []string{"name desc", "dog.age asc"}, 37 | }, 38 | rawQuery: "sort=name+desc&sort=dog.age+asc", 39 | }, 40 | { 41 | desc: "Expand", 42 | input: &commercetools.QueryInput{ 43 | Expand: []string{"taxCategory", "categories[*]"}, 44 | }, 45 | query: url.Values{ 46 | "expand": []string{"taxCategory", "categories[*]"}, 47 | }, 48 | rawQuery: "expand=taxCategory&expand=categories%5B%2A%5D", 49 | }, 50 | { 51 | desc: "Limit", 52 | input: &commercetools.QueryInput{ 53 | Limit: 20, 54 | }, 55 | query: url.Values{ 56 | "limit": []string{"20"}, 57 | }, 58 | rawQuery: "limit=20", 59 | }, 60 | { 61 | desc: "Offset", 62 | input: &commercetools.QueryInput{ 63 | Offset: 20, 64 | }, 65 | query: url.Values{ 66 | "offset": []string{"20"}, 67 | }, 68 | rawQuery: "offset=20", 69 | }, 70 | { 71 | desc: "Extra", 72 | input: &commercetools.QueryInput{ 73 | Limit: 23, 74 | Offset: 42, 75 | Extra: url.Values{ 76 | "staged": []string{"true"}, 77 | }, 78 | }, 79 | query: url.Values{ 80 | "limit": []string{"23"}, 81 | "offset": []string{"42"}, 82 | "staged": []string{"true"}, 83 | }, 84 | rawQuery: "limit=23&offset=42&staged=true", 85 | }, 86 | } 87 | 88 | for _, tC := range testCases { 89 | t.Run(tC.desc, func(t *testing.T) { 90 | output := testutil.RequestData{} 91 | 92 | client, server := testutil.MockClient(t, "{}", &output, nil) 93 | defer server.Close() 94 | 95 | _, err := client.TaxCategoryQuery(context.TODO(), tC.input) 96 | 97 | assert.Nil(t, err) 98 | assert.Equal(t, tC.query, output.URL.Query()) 99 | assert.Equal(t, tC.rawQuery, output.URL.RawQuery) 100 | }) 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /commercetools/testdata/product.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "e7ba4c75-b1bb-483d-94d8-2c4a10f78472", 3 | "version": 2, 4 | "masterData": { 5 | "current": { 6 | "categories": [ 7 | { 8 | "id": "cf6d790a-f027-4f46-9a2b-4bc9a31066fb", 9 | "typeId": "category" 10 | } 11 | ], 12 | "description": { 13 | "en": "Sample description" 14 | }, 15 | "masterVariant": { 16 | "attributes": [], 17 | "id": 1, 18 | "images": [ 19 | { 20 | "dimensions": { 21 | "h": 1400, 22 | "w": 1400 23 | }, 24 | "url": "https://sphere.io/cli/data/253245821_1.jpg" 25 | } 26 | ], 27 | "prices": [ 28 | { 29 | "value": { 30 | "type": "centPrecision", 31 | "fractionDigits": 2, 32 | "centAmount": 10000, 33 | "currencyCode": "EUR" 34 | }, 35 | "id": "753472a3-ddff-4e0f-a93b-2eb29c90ba54" 36 | } 37 | ], 38 | "sku": "sku_MB_PREMIUM_TECH_T_variant1_1369226795424" 39 | }, 40 | "name": { 41 | "en": "MB PREMIUM TECH T" 42 | }, 43 | "slug": { 44 | "en": "mb-premium-tech-t1369226795424" 45 | }, 46 | "variants": [] 47 | }, 48 | "hasStagedChanges": false, 49 | "published": true, 50 | "staged": { 51 | "categories": [ 52 | { 53 | "id": "cf6d790a-f027-4f46-9a2b-4bc9a31066fb", 54 | "typeId": "category" 55 | } 56 | ], 57 | "description": { 58 | "en": "Sample description" 59 | }, 60 | "masterVariant": { 61 | "attributes": [], 62 | "id": 1, 63 | "images": [ 64 | { 65 | "dimensions": { 66 | "h": 1400, 67 | "w": 1400 68 | }, 69 | "url": "https://sphere.io/cli/data/253245821_1.jpg" 70 | } 71 | ], 72 | "prices": [ 73 | { 74 | "value": { 75 | "type": "centPrecision", 76 | "fractionDigits": 2, 77 | "centAmount": 10000, 78 | "currencyCode": "EUR" 79 | }, 80 | "id": "753472a3-ddff-4e0f-a93b-2eb29c90ba54" 81 | } 82 | ], 83 | "sku": "sku_MB_PREMIUM_TECH_T_variant1_1369226795424" 84 | }, 85 | "name": { 86 | "en": "MB PREMIUM TECH T" 87 | }, 88 | "slug": { 89 | "en": "mb-premium-tech-t1369226795424" 90 | }, 91 | "variants": [] 92 | } 93 | }, 94 | "productType": { 95 | "id": "24f510c3-f334-4099-94e2-d6224a8eb919", 96 | "typeId": "product-type" 97 | }, 98 | "taxCategory": { 99 | "id": "f1e10e3a-45eb-49d8-ad0b-fdf984202f59", 100 | "typeId": "tax-category" 101 | }, 102 | "createdAt": "1970-01-01T00:00:00.001Z", 103 | "lastModifiedAt": "1970-01-01T00:00:00.001Z" 104 | } 105 | -------------------------------------------------------------------------------- /commercetools/service_custom_object.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // CustomObjectCreate creates a new instance of type CustomObject 13 | func (client *Client) CustomObjectCreate(ctx context.Context, draft *CustomObjectDraft, opts ...RequestOption) (result *CustomObject, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "custom-objects" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // CustomObjectQuery allows querying for type CustomObject 28 | /* 29 | The query endpoint allows to retrieve custom objects in a specific container or all custom objects. 30 | For performance reasons, it is highly advisable to query only for custom objects in a container by using 31 | the container field in the where predicate. 32 | */ 33 | func (client *Client) CustomObjectQuery(ctx context.Context, input *QueryInput) (result *CustomObjectPagedQueryResponse, err error) { 34 | endpoint := "custom-objects" 35 | err = client.query(ctx, endpoint, input.toParams(), &result) 36 | if err != nil { 37 | return nil, err 38 | } 39 | return result, nil 40 | } 41 | 42 | // CustomObjectDeleteWithContainerAndKey Delete CustomObject by container and key 43 | func (client *Client) CustomObjectDeleteWithContainerAndKey(ctx context.Context, container string, key string, version int, dataErasure bool, opts ...RequestOption) (result *CustomObject, err error) { 44 | params := url.Values{} 45 | params.Set("version", strconv.Itoa(version)) 46 | params.Set("dataErasure", strconv.FormatBool(dataErasure)) 47 | for _, opt := range opts { 48 | opt(¶ms) 49 | } 50 | endpoint := fmt.Sprintf("custom-objects/%s/%s", container, key) 51 | err = client.delete(ctx, endpoint, params, &result) 52 | if err != nil { 53 | return nil, err 54 | } 55 | return result, nil 56 | } 57 | 58 | // CustomObjectGetWithContainer for type CustomObject 59 | func (client *Client) CustomObjectGetWithContainer(ctx context.Context, container string, opts ...RequestOption) (result *CustomObject, err error) { 60 | params := url.Values{} 61 | for _, opt := range opts { 62 | opt(¶ms) 63 | } 64 | endpoint := fmt.Sprintf("custom-objects/%s", container) 65 | err = client.get(ctx, endpoint, params, &result) 66 | if err != nil { 67 | return nil, err 68 | } 69 | return result, nil 70 | } 71 | 72 | // CustomObjectGetWithContainerAndKey Get CustomObject by container and key 73 | func (client *Client) CustomObjectGetWithContainerAndKey(ctx context.Context, container string, key string, opts ...RequestOption) (result *CustomObject, err error) { 74 | params := url.Values{} 75 | for _, opt := range opts { 76 | opt(¶ms) 77 | } 78 | endpoint := fmt.Sprintf("custom-objects/%s/%s", container, key) 79 | err = client.get(ctx, endpoint, params, &result) 80 | if err != nil { 81 | return nil, err 82 | } 83 | return result, nil 84 | } 85 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er+LKDHDUfU5tRvFwxH0LjPpZN8OoG8Ll+liGU= 3 | github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc/go.mod h1:w648aMHEgFYS6xb0KVMMtZ2uMeemhiKCuD2vj6gY52A= 4 | github.com/dave/jennifer v1.4.0 h1:tNJFJmLDVTLu+v05mVZ88RINa3vQqnyyWkTKWYz0CwE= 5 | github.com/dave/jennifer v1.4.0/go.mod h1:fIb+770HOpJ2fmN9EPPKOqm1vMGhB+TwXKMZhrIygKg= 6 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 7 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 9 | github.com/iancoleman/strcase v0.0.0-20191112232945-16388991a334 h1:VHgatEHNcBFEB7inlalqfNqw65aNkM1lGX2yt3NmbS8= 10 | github.com/iancoleman/strcase v0.0.0-20191112232945-16388991a334/go.mod h1:SK73tn/9oHe+/Y0h39VT4UCxmurVJkR5NA7kMEAOgSE= 11 | github.com/mitchellh/mapstructure v1.3.2 h1:mRS76wmkOn3KkKAyXDu42V+6ebnXWIztFSYGN7GeoRg= 12 | github.com/mitchellh/mapstructure v1.3.2/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 13 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 14 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 15 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 16 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 17 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 18 | github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= 19 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 20 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 21 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= 22 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 23 | golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= 24 | golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= 25 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 26 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 27 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 28 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 29 | gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= 30 | gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 31 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 32 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 33 | -------------------------------------------------------------------------------- /commercetools/service_channel.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // ChannelCreate creates a new instance of type Channel 13 | func (client *Client) ChannelCreate(ctx context.Context, draft *ChannelDraft, opts ...RequestOption) (result *Channel, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "channels" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // ChannelQuery allows querying for type Channel 28 | func (client *Client) ChannelQuery(ctx context.Context, input *QueryInput) (result *ChannelPagedQueryResponse, err error) { 29 | endpoint := "channels" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // ChannelDeleteWithID for type Channel 38 | func (client *Client) ChannelDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *Channel, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("channels/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // ChannelGetWithID for type Channel 54 | func (client *Client) ChannelGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Channel, err error) { 55 | params := url.Values{} 56 | for _, opt := range opts { 57 | opt(¶ms) 58 | } 59 | endpoint := fmt.Sprintf("channels/%s", id) 60 | err = client.get(ctx, endpoint, params, &result) 61 | if err != nil { 62 | return nil, err 63 | } 64 | return result, nil 65 | } 66 | 67 | // ChannelUpdateWithIDInput is input for function ChannelUpdateWithID 68 | type ChannelUpdateWithIDInput struct { 69 | ID string 70 | Version int 71 | Actions []ChannelUpdateAction 72 | } 73 | 74 | func (input *ChannelUpdateWithIDInput) Validate() error { 75 | if input.ID == "" { 76 | return fmt.Errorf("no valid value for ID given") 77 | } 78 | if len(input.Actions) == 0 { 79 | return fmt.Errorf("no update actions specified") 80 | } 81 | return nil 82 | } 83 | 84 | // ChannelUpdateWithID for type Channel 85 | func (client *Client) ChannelUpdateWithID(ctx context.Context, input *ChannelUpdateWithIDInput, opts ...RequestOption) (result *Channel, err error) { 86 | if err := input.Validate(); err != nil { 87 | return nil, err 88 | } 89 | 90 | params := url.Values{} 91 | for _, opt := range opts { 92 | opt(¶ms) 93 | } 94 | 95 | endpoint := fmt.Sprintf("channels/%s", input.ID) 96 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 97 | if err != nil { 98 | return nil, err 99 | } 100 | return result, nil 101 | } 102 | -------------------------------------------------------------------------------- /commercetools/client_expand_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "net/url" 6 | "testing" 7 | 8 | "github.com/labd/commercetools-go-sdk/commercetools" 9 | "github.com/labd/commercetools-go-sdk/testutil" 10 | "github.com/stretchr/testify/assert" 11 | ) 12 | 13 | func TestClientCreateWithReferenceExpansion(t *testing.T) { 14 | responseData := "{}" 15 | output := testutil.RequestData{} 16 | client, server := testutil.MockClient(t, responseData, &output, nil) 17 | defer server.Close() 18 | 19 | productDraft := &commercetools.ProductDraft{ 20 | Key: "test-product", 21 | Name: &commercetools.LocalizedString{ 22 | "nl": "Een test product", 23 | "en": "A test product", 24 | }, 25 | ProductType: &commercetools.ProductTypeResourceIdentifier{ 26 | ID: "my-product-type-id", 27 | }, 28 | Slug: &commercetools.LocalizedString{ 29 | "nl": "een-test-product", 30 | "en": "a-test-product", 31 | }, 32 | } 33 | 34 | product, err := client.ProductCreate( 35 | context.TODO(), productDraft, 36 | commercetools.WithReferenceExpansion("productType")) 37 | assert.NotNil(t, product) 38 | assert.NoError(t, err) 39 | assert.Equal(t, url.Values(url.Values{"expand": []string{"productType"}}), output.URL.Query()) 40 | } 41 | 42 | func TestClientGetWithReferenceExpansion(t *testing.T) { 43 | responseData := "{}" 44 | output := testutil.RequestData{} 45 | client, server := testutil.MockClient(t, responseData, &output, nil) 46 | defer server.Close() 47 | 48 | product, err := client.ProductGetWithID( 49 | context.TODO(), "my-id", 50 | commercetools.WithReferenceExpansion("productType")) 51 | assert.NotNil(t, product) 52 | assert.NoError(t, err) 53 | assert.Equal(t, url.Values(url.Values{"expand": []string{"productType"}}), output.URL.Query()) 54 | } 55 | 56 | func TestClientUpdateWithReferenceExpansion(t *testing.T) { 57 | responseData := "{}" 58 | output := testutil.RequestData{} 59 | client, server := testutil.MockClient(t, responseData, &output, nil) 60 | defer server.Close() 61 | 62 | product, err := client.ProductUpdateWithID( 63 | context.TODO(), &commercetools.ProductUpdateWithIDInput{ 64 | ID: "foobar", 65 | Version: 10, 66 | Actions: []commercetools.ProductUpdateAction{ 67 | commercetools.ProductChangeNameAction{ 68 | Staged: true, 69 | Name: &commercetools.LocalizedString{ 70 | "nl": "foobar", 71 | }, 72 | }, 73 | }, 74 | }, 75 | commercetools.WithReferenceExpansion("productType", "taxCategory")) 76 | assert.NotNil(t, product) 77 | assert.NoError(t, err) 78 | assert.Equal(t, url.Values(url.Values{"expand": []string{"productType", "taxCategory"}}), output.URL.Query()) 79 | } 80 | 81 | func TestClientDeleteWithReferenceExpansion(t *testing.T) { 82 | responseData := "{}" 83 | output := testutil.RequestData{} 84 | client, server := testutil.MockClient(t, responseData, &output, nil) 85 | defer server.Close() 86 | 87 | product, err := client.ProductDeleteWithID( 88 | context.TODO(), "my-id", 10, 89 | commercetools.WithReferenceExpansion("productType")) 90 | assert.NotNil(t, product) 91 | assert.NoError(t, err) 92 | assert.Equal(t, url.Values(url.Values{"expand": []string{"productType"}, "version": []string{"10"}}), output.URL.Query()) 93 | } 94 | -------------------------------------------------------------------------------- /commercetools/service_extension_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/url" 7 | "testing" 8 | 9 | "github.com/labd/commercetools-go-sdk/commercetools" 10 | 11 | "github.com/stretchr/testify/assert" 12 | 13 | "github.com/labd/commercetools-go-sdk/testutil" 14 | ) 15 | 16 | func TestExtensionCreate(t *testing.T) { 17 | client, server := testutil.MockClient(t, testutil.Fixture("extension.azure.json"), nil, nil) 18 | defer server.Close() 19 | 20 | draft := &commercetools.ExtensionDraft{ 21 | Key: "test", 22 | Destination: commercetools.ExtensionHTTPDestination{ 23 | URL: "http://example.com", 24 | }, 25 | Triggers: []commercetools.ExtensionTrigger{ 26 | { 27 | ResourceTypeID: "product", 28 | Actions: []commercetools.ExtensionAction{"Create"}, 29 | }, 30 | }, 31 | } 32 | 33 | _, err := client.ExtensionCreate(context.TODO(), draft) 34 | assert.Nil(t, err) 35 | } 36 | 37 | func TestExtensionUpdate(t *testing.T) { 38 | output := testutil.RequestData{} 39 | 40 | client, server := testutil.MockClient(t, testutil.Fixture("extension.azure.json"), &output, nil) 41 | defer server.Close() 42 | 43 | input := &commercetools.ExtensionUpdateWithIDInput{ 44 | ID: "foobar", 45 | Version: 2, 46 | Actions: []commercetools.ExtensionUpdateAction{ 47 | commercetools.ExtensionChangeDestinationAction{ 48 | Destination: commercetools.ExtensionAWSLambdaDestination{ 49 | Arn: "arn:aws:lambda:::function:", 50 | AccessKey: "qwer", 51 | AccessSecret: "secret", 52 | }, 53 | }, 54 | }, 55 | } 56 | 57 | fmt.Println(output) 58 | 59 | _, err := client.ExtensionUpdateWithID(context.TODO(), input) 60 | assert.Nil(t, err) 61 | 62 | expectedBody := `{ 63 | "version": 2, 64 | "actions": [ 65 | { 66 | "action": "changeDestination", 67 | "destination": { 68 | "type": "AWSLambda", 69 | "arn": "arn:aws:lambda:::function:", 70 | "accessKey": "qwer", 71 | "accessSecret": "secret" 72 | } 73 | } 74 | ] 75 | }` 76 | assert.JSONEq(t, expectedBody, output.JSON) 77 | } 78 | 79 | func TestExtensionDeleteByID(t *testing.T) { 80 | client, server := testutil.MockClient(t, testutil.Fixture("extension.azure.json"), nil, nil) 81 | defer server.Close() 82 | 83 | _, err := client.ExtensionDeleteWithID(context.TODO(), "1234", 2) 84 | assert.Nil(t, err) 85 | } 86 | 87 | func TestExtensionDeleteByKey(t *testing.T) { 88 | client, server := testutil.MockClient(t, testutil.Fixture("extension.azure.json"), nil, nil) 89 | defer server.Close() 90 | 91 | _, err := client.ExtensionDeleteWithKey(context.TODO(), "1234", 2) 92 | assert.Nil(t, err) 93 | } 94 | 95 | func TestExtensionQuery(t *testing.T) { 96 | output := testutil.RequestData{} 97 | client, server := testutil.MockClient(t, "{}", &output, nil) 98 | defer server.Close() 99 | 100 | queryInput := commercetools.QueryInput{ 101 | Limit: 500, 102 | } 103 | _, err := client.ExtensionQuery(context.TODO(), &queryInput) 104 | assert.Nil(t, err) 105 | 106 | assert.Equal(t, url.Values{"limit": []string{"500"}}, output.URL.Query()) 107 | } 108 | -------------------------------------------------------------------------------- /commercetools/service_inventory_entry.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // InventoryEntryCreate creates a new instance of type InventoryEntry 13 | func (client *Client) InventoryEntryCreate(ctx context.Context, draft *InventoryEntryDraft, opts ...RequestOption) (result *InventoryEntry, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "inventory" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // InventoryEntryQuery allows querying for type InventoryEntry 28 | func (client *Client) InventoryEntryQuery(ctx context.Context, input *QueryInput) (result *InventoryPagedQueryResponse, err error) { 29 | endpoint := "inventory" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // InventoryEntryDeleteWithID for type InventoryEntry 38 | func (client *Client) InventoryEntryDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *InventoryEntry, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("inventory/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // InventoryEntryGetWithID for type InventoryEntry 54 | func (client *Client) InventoryEntryGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *InventoryEntry, err error) { 55 | params := url.Values{} 56 | for _, opt := range opts { 57 | opt(¶ms) 58 | } 59 | endpoint := fmt.Sprintf("inventory/%s", id) 60 | err = client.get(ctx, endpoint, params, &result) 61 | if err != nil { 62 | return nil, err 63 | } 64 | return result, nil 65 | } 66 | 67 | // InventoryEntryUpdateWithIDInput is input for function InventoryEntryUpdateWithID 68 | type InventoryEntryUpdateWithIDInput struct { 69 | ID string 70 | Version int 71 | Actions []InventoryEntryUpdateAction 72 | } 73 | 74 | func (input *InventoryEntryUpdateWithIDInput) Validate() error { 75 | if input.ID == "" { 76 | return fmt.Errorf("no valid value for ID given") 77 | } 78 | if len(input.Actions) == 0 { 79 | return fmt.Errorf("no update actions specified") 80 | } 81 | return nil 82 | } 83 | 84 | // InventoryEntryUpdateWithID for type InventoryEntry 85 | func (client *Client) InventoryEntryUpdateWithID(ctx context.Context, input *InventoryEntryUpdateWithIDInput, opts ...RequestOption) (result *InventoryEntry, err error) { 86 | if err := input.Validate(); err != nil { 87 | return nil, err 88 | } 89 | 90 | params := url.Values{} 91 | for _, opt := range opts { 92 | opt(¶ms) 93 | } 94 | 95 | endpoint := fmt.Sprintf("inventory/%s", input.ID) 96 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 97 | if err != nil { 98 | return nil, err 99 | } 100 | return result, nil 101 | } 102 | -------------------------------------------------------------------------------- /commercetools/service_channel_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedChannelGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "ac390383-370f-43f8-a534-db1604cb96a8", 16 | "key": "commercetools", 17 | "version": 1, 18 | "roles": [ 19 | "InventorySupply" 20 | ], 21 | "createdAt": "2015-05-28T09:48:35.023Z", 22 | "lastModifiedAt": "2015-05-28T09:48:35.023Z" 23 | } ` 24 | client, server := testutil.MockClient(t, responseData, nil, nil) 25 | defer server.Close() 26 | channel, err := client.ChannelGetWithID(context.TODO(), "dummy-id") 27 | if err != nil { 28 | t.Fatal(err) 29 | } 30 | assert.NotNil(t, channel) 31 | assert.NotNil(t, channel.Version) 32 | assert.NotEmpty(t, channel.LastModifiedAt) 33 | assert.NotEmpty(t, channel.Key) 34 | assert.NotEmpty(t, channel.ID) 35 | assert.NotEmpty(t, channel.CreatedAt) 36 | 37 | } 38 | 39 | func TestGeneratedChannelDeleteWithID(t *testing.T) { 40 | responseData := ` { 41 | "id": "ac390383-370f-43f8-a534-db1604cb96a8", 42 | "key": "commercetools", 43 | "version": 1, 44 | "roles": [ 45 | "InventorySupply" 46 | ], 47 | "createdAt": "2015-05-28T09:48:35.023Z", 48 | "lastModifiedAt": "2015-05-28T09:48:35.023Z" 49 | } ` 50 | client, server := testutil.MockClient(t, responseData, nil, nil) 51 | defer server.Close() 52 | channel, err := client.ChannelDeleteWithID(context.TODO(), "dummy-id", 1) 53 | if err != nil { 54 | t.Fatal(err) 55 | } 56 | assert.NotNil(t, channel) 57 | assert.NotNil(t, channel.Version) 58 | assert.NotEmpty(t, channel.LastModifiedAt) 59 | assert.NotEmpty(t, channel.Key) 60 | assert.NotEmpty(t, channel.ID) 61 | assert.NotEmpty(t, channel.CreatedAt) 62 | 63 | } 64 | 65 | func TestGeneratedChannelQuery(t *testing.T) { 66 | responseData := ` { 67 | "limit": 20, 68 | "offset": 0, 69 | "count": 2, 70 | "total": 2, 71 | "results": [ 72 | { 73 | "id": "ac390383-370f-43f8-a534-db1604cb96a8", 74 | "key": "channel1", 75 | "version": 1, 76 | "roles": [ 77 | "InventorySupply" 78 | ], 79 | "createdAt": "2015-05-28T09:48:35.023Z", 80 | "lastModifiedAt": "2015-05-28T09:48:35.023Z" 81 | }, 82 | { 83 | "id": "51323ad2-89f2-4233-b9be-f15c049769c8", 84 | "key": "channel2", 85 | "version": 2, 86 | "roles": [ 87 | "InventorySupply" 88 | ], 89 | "createdAt": "2017-01-10T06:51:08.866Z", 90 | "lastModifiedAt": "2017-01-10T06:51:08.924Z" 91 | } 92 | ] 93 | } ` 94 | client, server := testutil.MockClient(t, responseData, nil, nil) 95 | defer server.Close() 96 | input := commercetools.QueryInput{} 97 | queryResult, err := client.ChannelQuery(context.TODO(), &input) 98 | if err != nil { 99 | t.Fatal(err) 100 | } 101 | assert.NotNil(t, queryResult) 102 | assert.NotNil(t, queryResult.Total) 103 | assert.NotNil(t, queryResult.Offset) 104 | assert.NotNil(t, queryResult.Limit) 105 | assert.NotNil(t, queryResult.Count) 106 | 107 | } 108 | -------------------------------------------------------------------------------- /commercetools/service_discount_code.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // DiscountCodeCreate creates a new instance of type DiscountCode 13 | func (client *Client) DiscountCodeCreate(ctx context.Context, draft *DiscountCodeDraft, opts ...RequestOption) (result *DiscountCode, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "discount-codes" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // DiscountCodeQuery allows querying for type DiscountCode 28 | func (client *Client) DiscountCodeQuery(ctx context.Context, input *QueryInput) (result *DiscountCodePagedQueryResponse, err error) { 29 | endpoint := "discount-codes" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // DiscountCodeDeleteWithID for type DiscountCode 38 | func (client *Client) DiscountCodeDeleteWithID(ctx context.Context, id string, version int, dataErasure bool, opts ...RequestOption) (result *DiscountCode, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | params.Set("dataErasure", strconv.FormatBool(dataErasure)) 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("discount-codes/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // DiscountCodeGetWithID for type DiscountCode 54 | func (client *Client) DiscountCodeGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *DiscountCode, err error) { 55 | params := url.Values{} 56 | for _, opt := range opts { 57 | opt(¶ms) 58 | } 59 | endpoint := fmt.Sprintf("discount-codes/%s", id) 60 | err = client.get(ctx, endpoint, params, &result) 61 | if err != nil { 62 | return nil, err 63 | } 64 | return result, nil 65 | } 66 | 67 | // DiscountCodeUpdateWithIDInput is input for function DiscountCodeUpdateWithID 68 | type DiscountCodeUpdateWithIDInput struct { 69 | ID string 70 | Version int 71 | Actions []DiscountCodeUpdateAction 72 | } 73 | 74 | func (input *DiscountCodeUpdateWithIDInput) Validate() error { 75 | if input.ID == "" { 76 | return fmt.Errorf("no valid value for ID given") 77 | } 78 | if len(input.Actions) == 0 { 79 | return fmt.Errorf("no update actions specified") 80 | } 81 | return nil 82 | } 83 | 84 | // DiscountCodeUpdateWithID for type DiscountCode 85 | func (client *Client) DiscountCodeUpdateWithID(ctx context.Context, input *DiscountCodeUpdateWithIDInput, opts ...RequestOption) (result *DiscountCode, err error) { 86 | if err := input.Validate(); err != nil { 87 | return nil, err 88 | } 89 | 90 | params := url.Values{} 91 | for _, opt := range opts { 92 | opt(¶ms) 93 | } 94 | 95 | endpoint := fmt.Sprintf("discount-codes/%s", input.ID) 96 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 97 | if err != nil { 98 | return nil, err 99 | } 100 | return result, nil 101 | } 102 | -------------------------------------------------------------------------------- /code-generate/parse_types.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | 6 | yaml "gopkg.in/yaml.v2" 7 | ) 8 | 9 | func createRamlType(name string, properties yaml.MapSlice) RamlType { 10 | 11 | typeName := getPropertyString(properties, "type") 12 | 13 | object := RamlType{ 14 | Name: name, 15 | TypeName: typeName, 16 | CodeName: CreateCodeName(name), 17 | InterfaceName: CreateCodeName(name), 18 | Discriminator: getPropertyString(properties, "discriminator"), 19 | DiscriminatorValue: getPropertyString(properties, "discriminatorValue"), 20 | Package: getPropertyString(properties, "(package)"), 21 | } 22 | if object.Package == "" { 23 | object.Package = "Base" 24 | } 25 | 26 | if value := getPropertyValue(properties, "enum"); value != nil { 27 | for _, item := range value.([]interface{}) { 28 | object.EnumValues = append(object.EnumValues, item.(string)) 29 | } 30 | } 31 | 32 | if getPropertyValue(properties, "(asMap)") != nil { 33 | object.asMap = true 34 | } 35 | 36 | typeProperties := getPropertyValue(properties, "properties") 37 | 38 | if typeProperties != nil { 39 | for _, mapItem := range typeProperties.(yaml.MapSlice) { 40 | attribute := createRamlTypeAttribute(mapItem.Key.(string), mapItem.Value) 41 | object.Attributes = append(object.Attributes, attribute) 42 | 43 | } 44 | 45 | // If the raml type has one attribute with a wildcard name (//) then 46 | // turn it into a map keeping the type 47 | if len(object.Attributes) == 1 && object.Attributes[0].Name == "//" { 48 | object.asMap = true 49 | } 50 | } 51 | return object 52 | } 53 | 54 | func createRamlTypeAttribute(name string, properties interface{}) RamlTypeAttribute { 55 | 56 | optional := false 57 | if strings.HasSuffix(name, "?") { 58 | name = name[:len(name)-1] 59 | optional = true 60 | } 61 | 62 | typeName := "" 63 | if value, isOk := properties.(yaml.MapSlice); isOk { 64 | typeName = getPropertyString(value, "type") 65 | } else { 66 | typeName = properties.(string) 67 | } 68 | 69 | many := false 70 | if strings.HasSuffix(typeName, "[]") { 71 | typeName = typeName[:len(typeName)-2] 72 | many = true 73 | } 74 | 75 | var itemsObject *RamlType 76 | if strings.HasPrefix(name, "/") { 77 | placeholder := getPropertyValue(properties.(yaml.MapSlice), "(placeholderParam)") 78 | if placeholder != nil { 79 | name = getPropertyString(properties.(yaml.MapSlice), "(placeholderParam)", "paramName") 80 | itemsObject = &RamlType{ 81 | Name: getPropertyString(properties.(yaml.MapSlice), "(placeholderParam)", "placeholder"), 82 | TypeName: typeName, 83 | } 84 | } 85 | } 86 | 87 | codeName := CreateCodeName(name) 88 | if codeName == "Error" { 89 | codeName = "ErrorMessage" 90 | } 91 | 92 | object := RamlTypeAttribute{ 93 | Name: name, 94 | TypeName: typeName, 95 | CodeName: codeName, 96 | Optional: optional, 97 | Many: many, 98 | ItemsObject: itemsObject, 99 | } 100 | 101 | if props, isOk := properties.(yaml.MapSlice); isOk { 102 | object.Items = getPropertyString(props, "items") 103 | object.Format = getPropertyString(props, "format") 104 | object.Minimum = getPropertyInt(props, "minimum") 105 | object.Maximum = getPropertyInt(props, "maximum") 106 | } 107 | return object 108 | } 109 | -------------------------------------------------------------------------------- /commercetools/service_inventory_entry_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedInventoryEntryGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "aea4caed-accf-4667-adfe-be08ba6fdf91", 16 | "version": 1, 17 | "sku": "sku_GIRLS_HARTBREAK_CREW_variant1_1421832124541", 18 | "quantityOnStock": 4, 19 | "availableQuantity": 4, 20 | "createdAt": "2015-03-11T13:36:20.720Z", 21 | "lastModifiedAt": "2015-03-11T13:36:20.720Z" 22 | } ` 23 | client, server := testutil.MockClient(t, responseData, nil, nil) 24 | defer server.Close() 25 | inventory_entry, err := client.InventoryEntryGetWithID(context.TODO(), "dummy-id") 26 | if err != nil { 27 | t.Fatal(err) 28 | } 29 | assert.NotNil(t, inventory_entry) 30 | assert.NotNil(t, inventory_entry.Version) 31 | assert.NotEmpty(t, inventory_entry.SKU) 32 | assert.NotNil(t, inventory_entry.QuantityOnStock) 33 | assert.NotEmpty(t, inventory_entry.LastModifiedAt) 34 | assert.NotEmpty(t, inventory_entry.ID) 35 | assert.NotEmpty(t, inventory_entry.CreatedAt) 36 | assert.NotNil(t, inventory_entry.AvailableQuantity) 37 | 38 | } 39 | 40 | func TestGeneratedInventoryEntryDeleteWithID(t *testing.T) { 41 | responseData := ` { 42 | "id": "aea4caed-accf-4667-adfe-be08ba6fdf91", 43 | "version": 1, 44 | "sku": "sku_GIRLS_HARTBREAK_CREW_variant1_1421832124541", 45 | "quantityOnStock": 4, 46 | "availableQuantity": 4, 47 | "createdAt": "2015-03-11T13:36:20.720Z", 48 | "lastModifiedAt": "2015-03-11T13:36:20.720Z" 49 | } ` 50 | client, server := testutil.MockClient(t, responseData, nil, nil) 51 | defer server.Close() 52 | inventory_entry, err := client.InventoryEntryDeleteWithID(context.TODO(), "dummy-id", 1) 53 | if err != nil { 54 | t.Fatal(err) 55 | } 56 | assert.NotNil(t, inventory_entry) 57 | assert.NotNil(t, inventory_entry.Version) 58 | assert.NotEmpty(t, inventory_entry.SKU) 59 | assert.NotNil(t, inventory_entry.QuantityOnStock) 60 | assert.NotEmpty(t, inventory_entry.LastModifiedAt) 61 | assert.NotEmpty(t, inventory_entry.ID) 62 | assert.NotEmpty(t, inventory_entry.CreatedAt) 63 | assert.NotNil(t, inventory_entry.AvailableQuantity) 64 | 65 | } 66 | 67 | func TestGeneratedInventoryEntryQuery(t *testing.T) { 68 | responseData := ` { 69 | "limit": 20, 70 | "offset": 0, 71 | "count": 1, 72 | "total": 1, 73 | "results": [ 74 | { 75 | "id": "aea4caed-accf-4667-adfe-be08ba6fdf91", 76 | "version": 1, 77 | "sku": "sku_GIRLS_HARTBREAK_CREW_variant1_1421832124541", 78 | "quantityOnStock": 4, 79 | "availableQuantity": 4, 80 | "createdAt": "2015-03-11T13:36:20.720Z", 81 | "lastModifiedAt": "2015-03-11T13:36:20.720Z" 82 | } 83 | ] 84 | } ` 85 | client, server := testutil.MockClient(t, responseData, nil, nil) 86 | defer server.Close() 87 | input := commercetools.QueryInput{} 88 | queryResult, err := client.InventoryEntryQuery(context.TODO(), &input) 89 | if err != nil { 90 | t.Fatal(err) 91 | } 92 | assert.NotNil(t, queryResult) 93 | assert.NotNil(t, queryResult.Total) 94 | assert.NotNil(t, queryResult.Offset) 95 | assert.NotNil(t, queryResult.Limit) 96 | assert.NotNil(t, queryResult.Count) 97 | 98 | } 99 | -------------------------------------------------------------------------------- /commercetools/service_extension_types_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "encoding/json" 5 | "testing" 6 | 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/stretchr/testify/assert" 9 | ) 10 | 11 | func TestExtensionMarshall_basicauth(t *testing.T) { 12 | obj := commercetools.Extension{ 13 | Key: "my-key", 14 | Destination: commercetools.ExtensionHTTPDestination{ 15 | URL: "http://example.com", 16 | Authentication: commercetools.ExtensionAuthorizationHeaderAuthentication{ 17 | HeaderValue: "Basic 12345", 18 | }, 19 | }, 20 | Triggers: []commercetools.ExtensionTrigger{ 21 | { 22 | ResourceTypeID: "product", 23 | Actions: []commercetools.ExtensionAction{"Create"}, 24 | }, 25 | }, 26 | } 27 | 28 | result, err := json.Marshal(obj) 29 | assert.Nil(t, err) 30 | assert.JSONEq(t, `{ 31 | "id":"", 32 | "version":0, 33 | "key":"my-key", 34 | "destination":{ 35 | "type":"HTTP", 36 | "url":"http://example.com", 37 | "authentication":{ 38 | "type":"AuthorizationHeader", 39 | "headerValue":"Basic 12345" 40 | } 41 | }, 42 | "triggers":[ 43 | {"resourceTypeId":"product","actions":["Create"]} 44 | ], 45 | "createdAt":"0001-01-01T00:00:00Z", 46 | "lastModifiedAt":"0001-01-01T00:00:00Z"}`, string(result)) 47 | } 48 | 49 | func TestExtensionMarshall_azurekey(t *testing.T) { 50 | obj := commercetools.Extension{ 51 | Key: "my-key", 52 | Destination: commercetools.ExtensionHTTPDestination{ 53 | URL: "http://example.com", 54 | Authentication: commercetools.ExtensionAzureFunctionsAuthentication{ 55 | Key: "MyAzureKey000", 56 | }, 57 | }, 58 | Triggers: []commercetools.ExtensionTrigger{ 59 | { 60 | ResourceTypeID: "product", 61 | Actions: []commercetools.ExtensionAction{"Create"}, 62 | }, 63 | }, 64 | } 65 | 66 | result, err := json.Marshal(obj) 67 | assert.Nil(t, err) 68 | assert.JSONEq(t, `{ 69 | "id":"", 70 | "version":0, 71 | "key":"my-key", 72 | "destination":{ 73 | "type":"HTTP", 74 | "url":"http://example.com", 75 | "authentication":{ 76 | "type":"AzureFunctions", 77 | "key":"MyAzureKey000" 78 | } 79 | }, 80 | "triggers":[ 81 | {"resourceTypeId":"product","actions":["Create"]} 82 | ], 83 | "createdAt":"0001-01-01T00:00:00Z", 84 | "lastModifiedAt":"0001-01-01T00:00:00Z"}`, string(result)) 85 | } 86 | 87 | func TestExtensionMarshall_awslambda(t *testing.T) { 88 | obj := commercetools.Extension{ 89 | Key: "my-key", 90 | Destination: commercetools.ExtensionAWSLambdaDestination{ 91 | Arn: "arn:some:arn", 92 | AccessKey: "12331232131", 93 | AccessSecret: "somesecret", 94 | }, 95 | Triggers: []commercetools.ExtensionTrigger{ 96 | { 97 | ResourceTypeID: "product", 98 | Actions: []commercetools.ExtensionAction{"Create"}, 99 | }, 100 | }, 101 | } 102 | 103 | result, err := json.Marshal(obj) 104 | assert.Nil(t, err) 105 | assert.JSONEq(t, `{ 106 | "id":"", 107 | "version":0, 108 | "key":"my-key", 109 | "destination":{ 110 | "type":"AWSLambda", 111 | "arn": "arn:some:arn", 112 | "accessKey": "12331232131", 113 | "accessSecret": "somesecret" 114 | }, 115 | "triggers":[ 116 | {"resourceTypeId":"product","actions":["Create"]} 117 | ], 118 | "createdAt":"0001-01-01T00:00:00Z", 119 | "lastModifiedAt":"0001-01-01T00:00:00Z"}`, string(result)) 120 | } 121 | -------------------------------------------------------------------------------- /commercetools/service_cart_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/url" 7 | "testing" 8 | 9 | "github.com/labd/commercetools-go-sdk/commercetools" 10 | "github.com/stretchr/testify/assert" 11 | 12 | "github.com/labd/commercetools-go-sdk/testutil" 13 | ) 14 | 15 | func TestCartCreate(t *testing.T) { 16 | output := testutil.RequestData{} 17 | 18 | client, server := testutil.MockClient(t, testutil.Fixture("cart.json"), &output, nil) 19 | defer server.Close() 20 | 21 | input := &commercetools.CartDraft{ 22 | Currency: "EUR", 23 | ShippingAddress: &commercetools.Address{ 24 | Country: "DE", 25 | }, 26 | } 27 | 28 | cart, err := client.CartCreate(context.TODO(), input) 29 | fmt.Printf("%#v", cart) 30 | assert.Nil(t, err) 31 | 32 | assert.Equal(t, commercetools.CountryCode("DE"), cart.ShippingAddress.Country) 33 | } 34 | 35 | func TestCartUpdate(t *testing.T) { 36 | testCases := []struct { 37 | desc string 38 | input *commercetools.CartUpdateWithIDInput 39 | requestBody string 40 | }{ 41 | { 42 | desc: "Set locale", 43 | input: &commercetools.CartUpdateWithIDInput{ 44 | ID: "1234", 45 | Version: 2, 46 | Actions: []commercetools.CartUpdateAction{ 47 | &commercetools.CartSetLocaleAction{ 48 | Locale: "DE", 49 | }, 50 | }, 51 | }, 52 | requestBody: `{ 53 | "version": 2, 54 | "actions": [ 55 | { 56 | "action": "setLocale", 57 | "locale": "DE" 58 | } 59 | ] 60 | }`, 61 | }, 62 | } 63 | 64 | for _, tC := range testCases { 65 | t.Run(tC.desc, func(t *testing.T) { 66 | output := testutil.RequestData{} 67 | 68 | client, server := testutil.MockClient(t, "{}", &output, nil) 69 | defer server.Close() 70 | 71 | _, err := client.CartUpdateWithID(context.TODO(), tC.input) 72 | assert.Nil(t, err) 73 | assert.Equal(t, "/unittest/carts/1234", output.URL.Path) 74 | assert.JSONEq(t, tC.requestBody, output.JSON) 75 | }) 76 | } 77 | } 78 | 79 | func TestCartDelete(t *testing.T) { 80 | output := testutil.RequestData{} 81 | client, server := testutil.MockClient(t, "{}", &output, nil) 82 | defer server.Close() 83 | 84 | _, err := client.CartDeleteWithID(context.TODO(), "debd77c9-ef14-4595-8614-5d123429f9e1", 2, true) 85 | assert.Nil(t, err) 86 | 87 | params := url.Values{} 88 | params.Add("version", "2") 89 | params.Add("dataErasure", "true") 90 | assert.Equal(t, params, output.URL.Query()) 91 | assert.Equal(t, "/unittest/carts/debd77c9-ef14-4595-8614-5d123429f9e1", output.URL.Path) 92 | } 93 | 94 | func TestCartGetByID(t *testing.T) { 95 | client, server := testutil.MockClient(t, testutil.Fixture("cart.json"), nil, nil) 96 | defer server.Close() 97 | 98 | cart, err := client.CartGetWithID(context.TODO(), "debd77c9-ef14-4595-8614-5d123429f9e1") 99 | 100 | assert.Nil(t, err) 101 | assert.Equal(t, "debd77c9-ef14-4595-8614-5d123429f9e1", cart.ID) 102 | } 103 | 104 | func TestCartQuery(t *testing.T) { 105 | output := testutil.RequestData{} 106 | client, server := testutil.MockClient(t, "{}", &output, nil) 107 | defer server.Close() 108 | 109 | queryInput := commercetools.QueryInput{ 110 | Limit: 500, 111 | } 112 | _, err := client.CartQuery(context.TODO(), &queryInput) 113 | 114 | assert.Nil(t, err) 115 | assert.Equal(t, url.Values{"limit": []string{"500"}}, output.URL.Query()) 116 | } 117 | -------------------------------------------------------------------------------- /commercetools/service_product_factory_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/labd/commercetools-go-sdk/commercetools" 7 | ) 8 | 9 | func createExampleProduct() *commercetools.Product { 10 | return &commercetools.Product{ 11 | ID: "e7ba4c75-b1bb-483d-94d8-2c4a10f78472", 12 | Version: 2, 13 | CreatedAt: time.Date(1970, 1, 1, 0, 0, 0, 1000000, time.UTC), 14 | LastModifiedAt: time.Date(1970, 1, 1, 0, 0, 0, 1000000, time.UTC), 15 | MasterData: &commercetools.ProductCatalogData{ 16 | Current: &commercetools.ProductData{ 17 | Name: &commercetools.LocalizedString{ 18 | "en": "MB PREMIUM TECH T", 19 | }, 20 | Categories: []commercetools.CategoryReference{ 21 | { 22 | ID: "cf6d790a-f027-4f46-9a2b-4bc9a31066fb", 23 | }, 24 | }, 25 | Description: &commercetools.LocalizedString{ 26 | "en": "Sample description", 27 | }, 28 | Slug: &commercetools.LocalizedString{ 29 | "en": "mb-premium-tech-t1369226795424", 30 | }, 31 | MasterVariant: &commercetools.ProductVariant{ 32 | ID: 1, 33 | SKU: "sku_MB_PREMIUM_TECH_T_variant1_1369226795424", 34 | Attributes: []commercetools.Attribute{}, 35 | Images: []commercetools.Image{ 36 | { 37 | Dimensions: &commercetools.ImageDimensions{ 38 | H: 1400, 39 | W: 1400, 40 | }, 41 | URL: "https://sphere.io/cli/data/253245821_1.jpg", 42 | }, 43 | }, 44 | Prices: []commercetools.Price{ 45 | { 46 | ID: "753472a3-ddff-4e0f-a93b-2eb29c90ba54", 47 | Value: commercetools.CentPrecisionMoney{ 48 | FractionDigits: 2, 49 | CentAmount: 10000, 50 | CurrencyCode: "EUR", 51 | }, 52 | }, 53 | }, 54 | }, 55 | Variants: []commercetools.ProductVariant{}, 56 | }, 57 | // HasStagedChanged: false, 58 | Published: true, 59 | Staged: &commercetools.ProductData{ 60 | Name: &commercetools.LocalizedString{ 61 | "en": "MB PREMIUM TECH T", 62 | }, 63 | Categories: []commercetools.CategoryReference{ 64 | { 65 | ID: "cf6d790a-f027-4f46-9a2b-4bc9a31066fb", 66 | }, 67 | }, 68 | Description: &commercetools.LocalizedString{ 69 | "en": "Sample description", 70 | }, 71 | Slug: &commercetools.LocalizedString{ 72 | "en": "mb-premium-tech-t1369226795424", 73 | }, 74 | MasterVariant: &commercetools.ProductVariant{ 75 | ID: 1, 76 | SKU: "sku_MB_PREMIUM_TECH_T_variant1_1369226795424", 77 | Attributes: []commercetools.Attribute{}, 78 | Images: []commercetools.Image{ 79 | { 80 | Dimensions: &commercetools.ImageDimensions{ 81 | H: 1400, 82 | W: 1400, 83 | }, 84 | URL: "https://sphere.io/cli/data/253245821_1.jpg", 85 | }, 86 | }, 87 | Prices: []commercetools.Price{ 88 | { 89 | ID: "753472a3-ddff-4e0f-a93b-2eb29c90ba54", 90 | Value: commercetools.CentPrecisionMoney{ 91 | FractionDigits: 2, 92 | CentAmount: 10000, 93 | CurrencyCode: "EUR", 94 | }, 95 | }, 96 | }, 97 | }, 98 | Variants: []commercetools.ProductVariant{}, 99 | }, 100 | }, 101 | ProductType: &commercetools.ProductTypeReference{ 102 | ID: "24f510c3-f334-4099-94e2-d6224a8eb919", 103 | }, 104 | TaxCategory: &commercetools.TaxCategoryReference{ 105 | ID: "f1e10e3a-45eb-49d8-ad0b-fdf984202f59", 106 | }, 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /code-generate/generate_service_update.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/dave/jennifer/jen" 7 | ) 8 | 9 | // Generate the `Update` function 10 | func generateServiceUpdate(method ServiceMethod, objects map[string]RamlType) (code *jen.Statement) { 11 | updateStructID := fmt.Sprintf("%sInput", method.Name) 12 | updateObjectType := fmt.Sprintf("%sUpdateAction", method.ReturnType) 13 | 14 | // Generate the `type WithInput struct {}` 15 | identifier := CreateCodeName(method.Parameters[len(method.Parameters)-1]) 16 | c := jen.Commentf("%s is input for function %s", updateStructID, method.Name).Line() 17 | c.Type().Id(updateStructID).Struct( 18 | jen.Id(identifier).String(), 19 | jen.Id("Version").Int(), 20 | jen.Id("Actions").Index().Id(updateObjectType), 21 | ).Line() 22 | 23 | c.Func().Params(jen.Id("input").Op("*").Id(updateStructID)).Id("Validate").Params().Parens(jen.Id("error")).Block( 24 | 25 | // Validate if input identifier is empty 26 | jen.If(jen.Id("input").Op(".").Id(identifier).Op("==").Lit("")).Block( 27 | jen.Return( 28 | jen.Qual("fmt", "Errorf").Call( 29 | jen.Lit(fmt.Sprintf("no valid value for %s given", identifier)), 30 | ), 31 | ), 32 | ), 33 | 34 | // Validate if update actions are empty 35 | jen.If(jen.Id("len").Call(jen.Id("input").Op(".").Id("Actions")).Op("==").Lit(0)).Block( 36 | jen.Return( 37 | jen.Qual("fmt", "Errorf").Call( 38 | jen.Lit("no update actions specified"), 39 | ), 40 | ), 41 | ), 42 | 43 | jen.Return(jen.Nil()), 44 | ).Line() 45 | 46 | extraParams := generateServiceArgumentCode(method) 47 | methodParamsList := []jen.Code{ 48 | jen.Id("ctx").Qual("context", "Context"), 49 | } 50 | methodParamsList = append(methodParamsList, extraParams[:len(extraParams)-1]...) 51 | methodParamsList = append(methodParamsList, 52 | jen.Id("input").Op("*").Id(updateStructID), 53 | jen.Id("opts").Op("...").Id("RequestOption"), 54 | ) 55 | clientMethod := "update" 56 | 57 | structReceiver := jen.Id("client").Op("*").Id("Client") 58 | description := fmt.Sprintf("for type %s", method.ReturnType) 59 | // if httpMethod.Description != "" { 60 | // description = httpMethod.Description 61 | // } 62 | returnObject := objects[method.ReturnType] 63 | returnParams := createServiceReturnList(method, returnObject) 64 | 65 | c.Commentf("%s %s", method.Name, description).Line() 66 | c.Func().Params(structReceiver).Id(method.Name).Params(jen.List(methodParamsList...)).Parens(returnParams).Block( 67 | // if err := input.Validate(); err != nil { 68 | // return nil, err 69 | // } 70 | jen.If( 71 | jen.Err().Op(":=").Id("input").Op(".").Id("Validate").Call(), 72 | jen.Err().Op("!=").Nil(), 73 | ).Block( 74 | jen.Return(jen.Nil(), jen.Err()), 75 | ).Line(), 76 | 77 | // params := url.Values{} 78 | // for _, opt := range opts { 79 | // opt(¶ms) 80 | // } 81 | jen.Id("params").Op(":=").Qual("net/url", "Values").Block(), 82 | jen.For(jen.List(jen.Id("_"), jen.Id("opt")).Op(":=").Range().Id("opts")).Block( 83 | jen.Id("opt").Call(jen.Op("&").Id("params")), 84 | ).Line(), 85 | 86 | jen.Id("endpoint").Op(":=").Add(generateServicePathCode(method)), 87 | jen.Id("err").Op("=").Id("client").Op(".").Id(clientMethod).Call( 88 | jen.Id("ctx"), 89 | jen.Id("endpoint"), 90 | jen.Id("params"), 91 | jen.Id("input").Op(".").Id("Version"), 92 | jen.Id("input").Op(".").Id("Actions"), 93 | jen.Op("&").Id("result"), 94 | ), 95 | jen.If(jen.Err().Op("!=").Nil()).Block( 96 | jen.Return(jen.Nil(), jen.Err()), 97 | ), 98 | jen.Return(jen.Id("result"), jen.Nil()), 99 | ).Line() 100 | 101 | return c 102 | } 103 | -------------------------------------------------------------------------------- /code-generate/generate_service_action.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | 8 | "github.com/dave/jennifer/jen" 9 | ) 10 | 11 | // Generate the `Action` function 12 | func generateServiceAction(method ServiceMethod, objects map[string]RamlType) (code *jen.Statement) { 13 | methodParamList := []jen.Code{ 14 | jen.Id("ctx").Qual("context", "Context"), 15 | } 16 | extraParams := generateServiceArgumentCode(method) 17 | methodParamList = append(methodParamList, extraParams...) 18 | if method.InputType != "" { 19 | methodParamList = append(methodParamList, jen.Id("value").Op("*").Id(method.InputType)) 20 | } 21 | methodParamList = append(methodParamList, jen.Id("opts").Op("...").Id("RequestOption")) 22 | 23 | var clientMethod string 24 | switch method.HTTPMethod { 25 | case "post": 26 | clientMethod = "create" 27 | case "get": 28 | clientMethod = "get" 29 | } 30 | 31 | structReceiver := jen.Id("client").Op("*").Id("Client") 32 | description := fmt.Sprintf("for type %s", method.InputType) 33 | if method.Description != "" { 34 | description = method.Description 35 | } 36 | 37 | if method.ReturnType == "" { 38 | log.Fatalf("Empty return type for %s", method.Name) 39 | } 40 | 41 | returnObject := objects[method.ReturnType] 42 | returnParams := createServiceReturnList(method, returnObject) 43 | 44 | // Generate the `type Input struct {}` 45 | c := jen.Empty() 46 | if len(method.QueryParameters) > 0 { 47 | c.Commentf("%s is input for function %s", method.InputType, method.Name).Line() 48 | c.Type().Id(method.InputType).StructFunc(func(d *jen.Group) { 49 | for _, param := range method.QueryParameters { 50 | 51 | line := jen.Empty() 52 | 53 | line.Id(param.CodeName) 54 | typeCode := getNativeTypeCode(param) 55 | 56 | if param.ItemsObject != nil { 57 | line.Map(jen.String()).Add(typeCode) 58 | } else if param.Many { 59 | line.Index().Add(typeCode) 60 | } else { 61 | line.Add(typeCode) 62 | } 63 | 64 | // Generate the url tag 65 | urlTags := []string{param.Name} 66 | if param.Optional || param.TypeName == "boolean" { 67 | urlTags = append(urlTags, "omitempty") 68 | } 69 | tagVal := map[string]string{"url": strings.Join(urlTags, ",")} 70 | line.Tag(tagVal) 71 | 72 | d.Add(line) 73 | } 74 | }).Line() 75 | 76 | } 77 | 78 | c.Commentf("%s %s", method.Name, description).Line() 79 | c.Func().Params(structReceiver).Id(method.Name).Params(jen.List(methodParamList...)).Parens(returnParams).BlockFunc(func(b *jen.Group) { 80 | 81 | // params := url.Values{} | SerializeQueryParams(value) 82 | // for _, opt := range opts { 83 | // opt(¶ms) 84 | // } 85 | if len(method.QueryParameters) > 0 { 86 | b.Id("params").Op(":=").Id("serializeQueryParams").Call(jen.Id("value")) 87 | } else { 88 | b.Id("params").Op(":=").Qual("net/url", "Values").Block() 89 | } 90 | 91 | b.For(jen.List(jen.Id("_"), jen.Id("opt")).Op(":=").Range().Id("opts")).Block( 92 | jen.Id("opt").Call(jen.Op("&").Id("params")), 93 | ).Line() 94 | 95 | b.Id("endpoint").Op(":=").Add(generateServicePathCode(method)) 96 | 97 | b.Id("err").Op("=").Id("client").Op(".").Id(clientMethod).CallFunc(func(g *jen.Group) { 98 | g.Id("ctx") 99 | g.Id("endpoint") 100 | g.Id("params") 101 | 102 | if method.HTTPMethod == "post" { 103 | if method.InputType != "" { 104 | g.Id("value") 105 | } else { 106 | g.Nil() 107 | } 108 | } 109 | 110 | g.Op("&").Id("result") 111 | }) 112 | b.If(jen.Err().Op("!=").Nil()).Block( 113 | jen.Return(jen.Nil(), jen.Err()), 114 | ) 115 | b.Return(jen.Id("result"), jen.Nil()) 116 | }).Line() 117 | 118 | return c 119 | } 120 | -------------------------------------------------------------------------------- /commercetools/service_product_test.go: -------------------------------------------------------------------------------- 1 | package commercetools_test 2 | 3 | import ( 4 | "context" 5 | "net/url" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | 10 | "github.com/labd/commercetools-go-sdk/commercetools" 11 | "github.com/labd/commercetools-go-sdk/testutil" 12 | ) 13 | 14 | func TestCreateProductNew(t *testing.T) { 15 | client, server := testutil.MockClient(t, testutil.Fixture("product.example.json"), nil, nil) 16 | defer server.Close() 17 | 18 | draft := &commercetools.ProductDraft{ 19 | Key: "product-test", 20 | Name: &commercetools.LocalizedString{ 21 | "nl": "Een product", 22 | "en": "Some product", 23 | }, 24 | ProductType: &commercetools.ProductTypeResourceIdentifier{ 25 | ID: "8750e1fd-f431-481f-9296-967b1e56bf49", 26 | }, 27 | Slug: &commercetools.LocalizedString{ 28 | "nl": "een-product", 29 | "en": "some-product", 30 | }, 31 | } 32 | product, err := client.ProductCreate(context.TODO(), draft) 33 | assert.Nil(t, err) 34 | assert.Equal(t, 2, product.Version) 35 | assert.Equal(t, "Sample description", (*product.MasterData.Current.Description)["en"]) 36 | } 37 | 38 | func TestGetProductByID(t *testing.T) { 39 | client, server := testutil.MockClient(t, testutil.Fixture("product.example.json"), nil, nil) 40 | defer server.Close() 41 | 42 | product, err := client.ProductGetWithID(context.TODO(), "foo-bar") 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | 47 | expected := createExampleProduct() 48 | assert.Equal(t, expected, product) 49 | assert.Equal(t, product, expected) 50 | } 51 | 52 | func TestProductUpdate(t *testing.T) { 53 | client, server := testutil.MockClient(t, testutil.Fixture("product.example.json"), nil, nil) 54 | defer server.Close() 55 | 56 | product, err := client.ProductUpdateWithID(context.TODO(), &commercetools.ProductUpdateWithIDInput{ 57 | ID: "1", 58 | Version: 2, 59 | /* 60 | TODO: trait priceSelecting should add this... 61 | PriceSelection: commercetools.ProductPriceSelection{ 62 | Currency: "EUR", 63 | }, 64 | */ 65 | Actions: []commercetools.ProductUpdateAction{ 66 | commercetools.ProductAddPriceAction{ 67 | VariantID: 1, 68 | Price: &commercetools.PriceDraft{Value: &commercetools.Money{CentAmount: 1000}}, 69 | }, 70 | }, 71 | }) 72 | 73 | if err != nil { 74 | t.Fatal(err) 75 | } 76 | 77 | assert.Equal(t, 2, product.Version) 78 | assert.Equal(t, "Sample description", (*product.MasterData.Current.Description)["en"]) 79 | } 80 | 81 | func TestProductDeleteByID(t *testing.T) { 82 | client, server := testutil.MockClient(t, testutil.Fixture("product.example.json"), nil, nil) 83 | defer server.Close() 84 | 85 | product, err := client.ProductDeleteWithID(context.TODO(), "foobar", 2) 86 | if err != nil { 87 | t.Fatal(err) 88 | } 89 | 90 | expected := createExampleProduct() 91 | assert.Equal(t, expected, product) 92 | } 93 | 94 | func TestProductDeleteByKey(t *testing.T) { 95 | client, server := testutil.MockClient(t, testutil.Fixture("product.example.json"), nil, nil) 96 | defer server.Close() 97 | 98 | product, err := client.ProductDeleteWithKey(context.TODO(), "foobar", 2) 99 | if err != nil { 100 | t.Fatal(err) 101 | } 102 | 103 | expected := createExampleProduct() 104 | assert.Equal(t, expected, product) 105 | } 106 | 107 | func TestProductQuery(t *testing.T) { 108 | output := testutil.RequestData{} 109 | client, server := testutil.MockClient(t, "{}", &output, nil) 110 | defer server.Close() 111 | 112 | queryInput := commercetools.QueryInput{ 113 | Limit: 500, 114 | } 115 | _, err := client.ProductQuery(context.TODO(), &queryInput) 116 | assert.Nil(t, err) 117 | 118 | assert.Equal(t, url.Values{"limit": []string{"500"}}, output.URL.Query()) 119 | } 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # commercetools-go-sdk 2 | 3 | [![Build Status](https://github.com/labd/commercetools-go-sdk/workflows/Go%20Tests/badge.svg)](https://github.com/labd/commercetools-go-sdk/workflows/) 4 | [![codecov](https://codecov.io/gh/LabD/commercetools-go-sdk/branch/master/graph/badge.svg)](https://codecov.io/gh/LabD/commercetools-go-sdk) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/labd/commercetools-go-sdk)](https://goreportcard.com/report/github.com/labd/commercetools-go-sdk) 6 | [![GoDoc](https://godoc.org/github.com/labd/commercetools-go-sdk?status.svg)](https://godoc.org/github.com/labd/commercetools-go-sdk) 7 | 8 | The Commercetools Go SDK is automatically generated based on the official [API specifications](https://github.com/commercetools/commercetools-api-reference) 9 | of Commercetools. It should therefore be nearly feature complete. 10 | 11 | The SDK was initially created for enabling the creation of the 12 | [Terraform Provider for Commercetools](https://github.com/labd/terraform-provider-commercetools) 13 | That provider enables you to use infrastructure-as-code principles with Commercetools. 14 | 15 | 16 | ## Using the SDK 17 | 18 | 19 | ```go 20 | package main 21 | 22 | import ( 23 | "context" 24 | "fmt" 25 | "log" 26 | "math/rand" 27 | "time" 28 | 29 | "github.com/labd/commercetools-go-sdk/commercetools" 30 | ) 31 | 32 | func main() { 33 | 34 | // Create the new client. When an empty value is passed it will use the CTP_* 35 | // environment variables to get the value. The HTTPClient arg is optional, 36 | // and when empty will automatically be created using the env values. 37 | client, err := commercetools.NewClient(&commercetools.ClientConfig{ 38 | ProjectKey: "", 39 | Endpoints: commercetools.NewClientEndpoints("europe-west1", "gcp"), 40 | Credentials: &commercetools.ClientCredentials{ 41 | ClientID: "", 42 | ClientSecret: "", 43 | Scopes: []string{""}, 44 | }, 45 | }) 46 | 47 | ctx := context.Background() 48 | 49 | // Get or Createa product type 50 | productTypeDraft := commercetools.ProductTypeDraft{ 51 | Name: "a-product-type", 52 | Key: "a-product-type", 53 | } 54 | 55 | productType, err := client.ProductTypeGetWithKey(ctx, productTypeDraft.Key) 56 | if productType == nil { 57 | productType, err = client.ProductTypeCreate(ctx, &productTypeDraft) 58 | if err != nil { 59 | log.Println(err) 60 | } 61 | } 62 | 63 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 64 | randomID := r.Int() 65 | productDraft := &commercetools.ProductDraft{ 66 | Key: fmt.Sprintf("test-product-%d", randomID), 67 | Name: &commercetools.LocalizedString{ 68 | "nl": "Een test product", 69 | "en": "A test product", 70 | }, 71 | ProductType: &commercetools.ProductTypeResourceIdentifier{ 72 | ID: productType.ID, 73 | }, 74 | Slug: &commercetools.LocalizedString{ 75 | "nl": fmt.Sprintf("een-test-product-%d", randomID), 76 | "en": fmt.Sprintf("a-test-product-%d", randomID), 77 | }, 78 | } 79 | 80 | // The last argument is optional for reference expansion 81 | product, err := client.ProductCreate( 82 | ctx, productDraft, commercetools.WithReferenceExpansion("taxCategory")) 83 | if err != nil { 84 | log.Fatal(err) 85 | } 86 | 87 | log.Print(product) 88 | } 89 | ``` 90 | 91 | ## Generating code 92 | 93 | To generate code do the following steps: 94 | - `pip install pyyaml` 95 | - install yq (f.e. `brew install yq` on macOS) 96 | - `git clone https://github.com/commercetools/commercetools-api-reference.git` in the folder on the same level as the commercetools-go-sdk folder 97 | - `make generate` 98 | 99 | 100 | ### TODO for code generating the services: 101 | - CustomObject service implementation 102 | - Implement all traits (f.e. priceSelecting) 103 | -------------------------------------------------------------------------------- /code-generate/generate_service_main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "sort" 6 | 7 | "github.com/dave/jennifer/jen" 8 | ) 9 | 10 | type ResourceMethods struct { 11 | Name string 12 | ServiceDomain ServiceDomain 13 | Get []ServiceMethod 14 | Query []ServiceMethod 15 | Create []ServiceMethod 16 | Update []ServiceMethod 17 | Delete []ServiceMethod 18 | Actions []ServiceMethod 19 | } 20 | 21 | func groupByResourceMethods(methods []ServiceMethod) ResourceMethods { 22 | result := ResourceMethods{} 23 | 24 | sort.Slice(methods, func(i, j int) bool { 25 | return methods[i].Name < methods[j].Name 26 | }) 27 | 28 | for _, method := range methods { 29 | switch method.Type { 30 | case "create": 31 | result.Create = append(result.Create, method) 32 | case "update": 33 | result.Update = append(result.Update, method) 34 | case "query": 35 | result.Query = append(result.Query, method) 36 | case "delete": 37 | result.Delete = append(result.Delete, method) 38 | case "get": 39 | result.Get = append(result.Get, method) 40 | case "action": 41 | result.Actions = append(result.Actions, method) 42 | default: 43 | log.Fatalf("Unknown method type for %s::%s: '%s'\n", method.Context, method.Name, method.Type) 44 | } 45 | } 46 | return result 47 | } 48 | 49 | // Entry point to generate services 50 | func generateServices(objects []RamlType, resources []ServiceDomain) { 51 | typeMapping := map[string]string{} 52 | 53 | for _, item := range objects { 54 | typeMapping[item.Name] = item.CodeName 55 | } 56 | objectsMap := map[string]RamlType{} 57 | for _, item := range objects { 58 | objectsMap[item.Name] = item 59 | } 60 | 61 | for _, resourceService := range resources { 62 | 63 | if len(resourceService.methods) < 1 { 64 | log.Printf("! No methods found for domain %s\n", resourceService.ContextName) 65 | continue 66 | } 67 | 68 | filename := generateFilename(resourceService.Package, "") 69 | log.Printf("Writing commercetools/%s\n", filename) 70 | 71 | f := jen.NewFile("commercetools") 72 | f.HeaderComment("Automatically generated, do not edit") 73 | 74 | contextNames, resourceMethods := orderServiceMethods(&resourceService, objectsMap) 75 | for _, contextName := range contextNames { 76 | value := resourceMethods[contextName] 77 | 78 | for _, method := range value.Create { 79 | code := generateServiceCreate(method, objectsMap) 80 | f.Add(code) 81 | } 82 | 83 | for _, method := range value.Query { 84 | queryCode := generateServiceQuery(method, objectsMap) 85 | f.Add(queryCode) 86 | } 87 | 88 | for _, method := range value.Delete { 89 | code := generateServiceDelete(method, objectsMap) 90 | f.Add(code) 91 | } 92 | 93 | for _, method := range value.Get { 94 | code := generateServiceGet(method, objectsMap) 95 | f.Add(code) 96 | } 97 | 98 | for _, method := range value.Update { 99 | code := generateServiceUpdate(method, objectsMap) 100 | f.Add(code) 101 | } 102 | 103 | for _, method := range value.Actions { 104 | code := generateServiceAction(method, objectsMap) 105 | f.Add(code) 106 | } 107 | } 108 | 109 | err := f.Save("commercetools/service_" + filename) 110 | if err != nil { 111 | panic(err) 112 | } 113 | } 114 | } 115 | 116 | func orderServiceMethods(sd *ServiceDomain, objects map[string]RamlType) ([]string, map[string]ResourceMethods) { 117 | groupedMethods := map[string][]ServiceMethod{} 118 | for _, item := range sd.methods { 119 | item.Domain = *sd 120 | item.UpdateTypeNames(objects) 121 | groupedMethods[item.Context] = append(groupedMethods[item.Context], item) 122 | } 123 | 124 | groupedResourceMethods := map[string]ResourceMethods{} 125 | contextNames := []string{} 126 | 127 | for key, value := range groupedMethods { 128 | groupedResourceMethods[key] = groupByResourceMethods(value) 129 | contextNames = append(contextNames, key) 130 | } 131 | sort.Strings(contextNames) 132 | 133 | return contextNames, groupedResourceMethods 134 | } 135 | -------------------------------------------------------------------------------- /commercetools/service_discount_code_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedDiscountCodeGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "3b3327a4-06c2-4129-8d87-83d5ce53e038", 16 | "version": 2, 17 | "code": "SAVE10", 18 | "name": { 19 | "en": "Save10" 20 | }, 21 | "cartDiscounts": [ 22 | { 23 | "typeId": "cart-discount", 24 | "id": "fdbaf4ea-fbc9-4fea-bac4-1d7e6c1995b3" 25 | } 26 | ], 27 | "isActive": true, 28 | "cartPredicate": "1=1", 29 | "references": [], 30 | "groups": [], 31 | "createdAt": "2015-09-15T09:02:29.323Z", 32 | "lastModifiedAt": "2015-09-15T09:04:06.910Z" 33 | } ` 34 | client, server := testutil.MockClient(t, responseData, nil, nil) 35 | defer server.Close() 36 | discount_code, err := client.DiscountCodeGetWithID(context.TODO(), "dummy-id") 37 | if err != nil { 38 | t.Fatal(err) 39 | } 40 | assert.NotNil(t, discount_code) 41 | assert.NotNil(t, discount_code.Version) 42 | assert.NotEmpty(t, discount_code.LastModifiedAt) 43 | assert.True(t, discount_code.IsActive) 44 | assert.NotEmpty(t, discount_code.ID) 45 | assert.NotEmpty(t, discount_code.CreatedAt) 46 | assert.NotEmpty(t, discount_code.Code) 47 | assert.NotEmpty(t, discount_code.CartPredicate) 48 | 49 | } 50 | 51 | func TestGeneratedDiscountCodeDeleteWithID(t *testing.T) { 52 | responseData := ` { 53 | "id": "3b3327a4-06c2-4129-8d87-83d5ce53e038", 54 | "version": 2, 55 | "code": "SAVE10", 56 | "name": { 57 | "en": "Save10" 58 | }, 59 | "cartDiscounts": [ 60 | { 61 | "typeId": "cart-discount", 62 | "id": "fdbaf4ea-fbc9-4fea-bac4-1d7e6c1995b3" 63 | } 64 | ], 65 | "isActive": true, 66 | "cartPredicate": "1=1", 67 | "references": [], 68 | "groups": [], 69 | "createdAt": "2015-09-15T09:02:29.323Z", 70 | "lastModifiedAt": "2015-09-15T09:04:06.910Z" 71 | } ` 72 | client, server := testutil.MockClient(t, responseData, nil, nil) 73 | defer server.Close() 74 | discount_code, err := client.DiscountCodeDeleteWithID(context.TODO(), "dummy-id", 1, true) 75 | if err != nil { 76 | t.Fatal(err) 77 | } 78 | assert.NotNil(t, discount_code) 79 | assert.NotNil(t, discount_code.Version) 80 | assert.NotEmpty(t, discount_code.LastModifiedAt) 81 | assert.True(t, discount_code.IsActive) 82 | assert.NotEmpty(t, discount_code.ID) 83 | assert.NotEmpty(t, discount_code.CreatedAt) 84 | assert.NotEmpty(t, discount_code.Code) 85 | assert.NotEmpty(t, discount_code.CartPredicate) 86 | 87 | } 88 | 89 | func TestGeneratedDiscountCodeQuery(t *testing.T) { 90 | responseData := ` { 91 | "limit": 20, 92 | "offset": 0, 93 | "count": 1, 94 | "total": 1, 95 | "results": [ 96 | { 97 | "id": "3b3327a4-06c2-4129-8d87-83d5ce53e038", 98 | "version": 2, 99 | "code": "SAVE10", 100 | "name": { 101 | "en": "Save10" 102 | }, 103 | "cartDiscounts": [ 104 | { 105 | "typeId": "cart-discount", 106 | "id": "fdbaf4ea-fbc9-4fea-bac4-1d7e6c1995b3" 107 | } 108 | ], 109 | "isActive": true, 110 | "cartPredicate": "1=1", 111 | "references": [], 112 | "groups": [], 113 | "attributeTypes": {}, 114 | "cartFieldTypes": {}, 115 | "lineItemFieldTypes": {}, 116 | "customLineItemFieldTypes": {}, 117 | "createdAt": "2015-09-15T09:02:29.323Z", 118 | "lastModifiedAt": "2015-09-15T09:04:06.910Z" 119 | } 120 | ] 121 | } ` 122 | client, server := testutil.MockClient(t, responseData, nil, nil) 123 | defer server.Close() 124 | input := commercetools.QueryInput{} 125 | queryResult, err := client.DiscountCodeQuery(context.TODO(), &input) 126 | if err != nil { 127 | t.Fatal(err) 128 | } 129 | assert.NotNil(t, queryResult) 130 | assert.NotNil(t, queryResult.Total) 131 | assert.NotNil(t, queryResult.Offset) 132 | assert.NotNil(t, queryResult.Limit) 133 | assert.NotNil(t, queryResult.Count) 134 | 135 | } 136 | -------------------------------------------------------------------------------- /commercetools/service_message_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedMessageGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "174adf2f-783f-4ce5-a2d5-ee7d3ee7caf4", 16 | "version": 1, 17 | "sequenceNumber": 1, 18 | "resource": { 19 | "typeId": "category", 20 | "id": "45251684-d693-409d-9864-f93f486adb95" 21 | }, 22 | "resourceVersion": 1, 23 | "type": "CategoryCreated", 24 | "category": { 25 | "id": "45251684-d693-409d-9864-f93f486adb95", 26 | "version": 1, 27 | "name": { 28 | "en": "myCategory" 29 | }, 30 | "slug": { 31 | "en": "my-category" 32 | }, 33 | "ancestors": [], 34 | "orderHint": "0.000014556311799451762128695", 35 | "createdAt": "2016-02-16T13:59:39.945Z", 36 | "lastModifiedAt": "2016-02-16T13:59:39.945Z", 37 | "assets": [], 38 | "lastMessageSequenceNumber": 1 39 | }, 40 | "createdAt": "2016-02-16T13:59:39.945Z", 41 | "lastModifiedAt": "2016-02-16T13:59:39.945Z" 42 | } ` 43 | client, server := testutil.MockClient(t, responseData, nil, nil) 44 | defer server.Close() 45 | message, err := client.MessageGetWithID(context.TODO(), "dummy-id") 46 | if err != nil { 47 | t.Fatal(err) 48 | } 49 | assert.NotNil(t, message) 50 | 51 | } 52 | 53 | func TestGeneratedMessageQuery(t *testing.T) { 54 | responseData := ` { 55 | "limit": 20, 56 | "offset": 0, 57 | "count": 2, 58 | "total": 2, 59 | "results": [ 60 | { 61 | "id": "7d165eba-6032-4614-8e6a-fb78d2a02139", 62 | "version": 1, 63 | "sequenceNumber": 1, 64 | "resource": { 65 | "typeId": "category", 66 | "id": "c979f0f7-2e6a-4e8b-92eb-59e6e840e797" 67 | }, 68 | "resourceVersion": 1, 69 | "type": "CategoryCreated", 70 | "category": { 71 | "id": "c979f0f7-2e6a-4e8b-92eb-59e6e840e797", 72 | "version": 1, 73 | "name": { 74 | "en": "test-Category" 75 | }, 76 | "slug": { 77 | "en": "test-category" 78 | }, 79 | "ancestors": [], 80 | "orderHint": "0.00001455631179379695951525", 81 | "createdAt": "2016-02-16T13:59:39.379Z", 82 | "lastModifiedAt": "2016-02-16T13:59:39.379Z", 83 | "assets": [], 84 | "lastMessageSequenceNumber": 1 85 | }, 86 | "createdAt": "2016-02-16T13:59:39.379Z", 87 | "lastModifiedAt": "2016-02-16T13:59:39.379Z" 88 | }, 89 | { 90 | "id": "174adf2f-783f-4ce5-a2d5-ee7d3ee7caf4", 91 | "version": 1, 92 | "sequenceNumber": 1, 93 | "resource": { 94 | "typeId": "category", 95 | "id": "45251684-d693-409d-9864-f93f486adb95" 96 | }, 97 | "resourceVersion": 1, 98 | "type": "CategoryCreated", 99 | "category": { 100 | "id": "45251684-d693-409d-9864-f93f486adb95", 101 | "version": 1, 102 | "name": { 103 | "en": "myCategory" 104 | }, 105 | "slug": { 106 | "en": "my-category" 107 | }, 108 | "ancestors": [], 109 | "orderHint": "0.000014556311799451762128695", 110 | "createdAt": "2016-02-16T13:59:39.945Z", 111 | "lastModifiedAt": "2016-02-16T13:59:39.945Z", 112 | "assets": [], 113 | "lastMessageSequenceNumber": 1 114 | }, 115 | "createdAt": "2016-02-16T13:59:39.945Z", 116 | "lastModifiedAt": "2016-02-16T13:59:39.945Z" 117 | } 118 | ] 119 | } ` 120 | client, server := testutil.MockClient(t, responseData, nil, nil) 121 | defer server.Close() 122 | input := commercetools.QueryInput{} 123 | queryResult, err := client.MessageQuery(context.TODO(), &input) 124 | if err != nil { 125 | t.Fatal(err) 126 | } 127 | assert.NotNil(t, queryResult) 128 | assert.NotNil(t, queryResult.Total) 129 | assert.NotNil(t, queryResult.Offset) 130 | assert.NotNil(t, queryResult.Limit) 131 | assert.NotNil(t, queryResult.Count) 132 | 133 | } 134 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 0.3.0 (2021-04-12) 2 | ================== 3 | - Upgrade services and types from commercetools-api-reference [#59](https://github.com/labd/commercetools-go-sdk/pull/59) 4 | - Add validation for structs for Update calls 5 | - Enable custom objects endpoint after raml update 6 | - *Backwards incompatible:* DateOfBirth fields now take a `*Date` instead of a `Date` value 7 | 8 | ## Breaking changes 9 | 10 | ### Removed 11 | - ExtensionNoResponseError.ErrorByExtension 12 | - ExtensionNoResponseError.ExtensionExtraInfo 13 | - ExtensionNoResponseError.LocalizedMessage 14 | - PagedQueryResponse.Facets 15 | - TaxedPriceDraft.UnmarshalJSON() 16 | 17 | ## Renamed 18 | - StoresAddDistributionChannelsAction renamed to StoreAddDistributionChannelAction 19 | - StoresAddSupplyChannelsAction renamed to StoreAddSupplyChannelAction 20 | - StoresRemoveDistributionChannelsAction renamed to StoreRemoveDistributionChannelAction 21 | - StoresRemoveSupplyChannelsAction renamed to StoreRemoveSupplyChannelAction 22 | - StoresSetDistributionChannelsAction renamed to StoreSetDistributionChannelsAction 23 | - StoresSetSupplyChannelsAction renamed to StoreSetSupplyChannelsAction 24 | 25 | ### Changes 26 | 27 | | struct | old type | new type 28 | |--------------------------------------------------------|-------------------|------------------------ 29 | | CartDiscount.Value | CartDiscountValue | CartDiscountValueDraft 30 | | CartDiscountValueGiftLineItemDraft.DistributionChannel | *ChannelReference | *ChannelResourceIdentifier 31 | | CartDiscountValueGiftLineItemDraft.Product | *ProductReference | *ProductResourceIdentifier 32 | | CartDiscountValueGiftLineItemDraft.SupplyChannel | *ChannelReference | *ChannelResourceIdentifier 33 | | CartSetShippingMethodAction.Custom | *CustomFields | *CustomFieldsDraft 34 | | CustomerSignInResult.Cart | interface{} | *Cart 35 | | DeliveryAddedMessage.RemovedImageUrls | []interface{} | []string 36 | | DeliveryItem.Quantity | float64 | int 37 | | FacetResultRange.Total | int | float64 38 | | MyCartAddLineItemAction.Quantity | float64 | int 39 | | MyCartChangeLineItemQuantityAction.Quantity | float64 | int 40 | | MyCartRemoveLineItemAction.Quantity | float64 | int 41 | | ProductPublishedMessagePayload.RemovedImageUrls | []interface{} | []string 42 | | TaxedPriceDraft.TotalNet | TypedMoneyDraft | *Money 43 | | TaxedPriceDraft.TotalGross | TypedMoneyDraft | *Money 44 | | ShippingMethodDraft.LocalizedDescription | string | *LocalizedDescription 45 | 46 | 0.2.0 (2020-07-20) 47 | ================== 48 | - *Backwards incompatible:* Add context parameter to all method calls. (#51) 49 | - Add a more simple Client factory as commercetools.NewClient() (#50) 50 | - Add support for reference expansion by passing a function option as last 51 | parameter. For example: 52 | client.ProductCreate( 53 | ctx, draft, commercetools.WithReferenceExpansion("productType)) 54 | See #53 for more information 55 | - Add a GraphQL interface to the client (See #49) 56 | - Improve handling of OAuth2 authentication errors (#48) 57 | 58 | 59 | 0.1.0 (2020-07-07) 60 | ================== 61 | First versioned release. Although this library has been in development for 62 | nearly 2 years (first commit 2018-06-18) it never was properly tagged since we 63 | only used it for our commercetools provider. 64 | 65 | The codebase is currently fairly stable so this is a good moment to actually 66 | create a tag and start properly updating the changelog. 67 | 68 | Note that although all the types (structs) should be up-to-date (autogenerated) 69 | some services might not be implemented yet. 70 | 71 | For now at least the following services are implemented: 72 | - API clients 73 | - Carts 74 | - Cart discounts 75 | - Categories 76 | - Channels 77 | - Custom objects 78 | - Customers 79 | - Customer groups 80 | - Discount codes 81 | - Extensions 82 | - Inventory 83 | - Messages 84 | - Orders 85 | - Payments 86 | - Products 87 | - Product discounts 88 | - Product types 89 | - Project 90 | - Reviews 91 | - Shipping methods 92 | - Shopping lists 93 | - State machines 94 | - Stores 95 | - Subscriptions 96 | - Tax categories 97 | - Zones 98 | -------------------------------------------------------------------------------- /commercetools/service_customer_group_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedCustomerGroupGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "aef9cf41-94ad-4794-8122-62d308900430", 16 | "version": 2, 17 | "name": "Webshop user", 18 | "createdAt": "2017-01-10T06:51:25.896Z", 19 | "lastModifiedAt": "2017-01-10T06:51:25.946Z" 20 | } ` 21 | client, server := testutil.MockClient(t, responseData, nil, nil) 22 | defer server.Close() 23 | customer_group, err := client.CustomerGroupGetWithID(context.TODO(), "dummy-id") 24 | if err != nil { 25 | t.Fatal(err) 26 | } 27 | assert.NotNil(t, customer_group) 28 | assert.NotNil(t, customer_group.Version) 29 | assert.NotEmpty(t, customer_group.Name) 30 | assert.NotEmpty(t, customer_group.LastModifiedAt) 31 | assert.NotEmpty(t, customer_group.ID) 32 | assert.NotEmpty(t, customer_group.CreatedAt) 33 | 34 | } 35 | 36 | func TestGeneratedCustomerGroupGetWithKey(t *testing.T) { 37 | responseData := ` { 38 | "id": "aef9cf41-94ad-4794-8122-62d308900430", 39 | "version": 2, 40 | "name": "Webshop user", 41 | "createdAt": "2017-01-10T06:51:25.896Z", 42 | "lastModifiedAt": "2017-01-10T06:51:25.946Z" 43 | } ` 44 | client, server := testutil.MockClient(t, responseData, nil, nil) 45 | defer server.Close() 46 | customer_group, err := client.CustomerGroupGetWithKey(context.TODO(), "dummy-id") 47 | if err != nil { 48 | t.Fatal(err) 49 | } 50 | assert.NotNil(t, customer_group) 51 | assert.NotNil(t, customer_group.Version) 52 | assert.NotEmpty(t, customer_group.Name) 53 | assert.NotEmpty(t, customer_group.LastModifiedAt) 54 | assert.NotEmpty(t, customer_group.ID) 55 | assert.NotEmpty(t, customer_group.CreatedAt) 56 | 57 | } 58 | 59 | func TestGeneratedCustomerGroupDeleteWithID(t *testing.T) { 60 | responseData := ` { 61 | "id": "aef9cf41-94ad-4794-8122-62d308900430", 62 | "version": 2, 63 | "name": "Webshop user", 64 | "createdAt": "2017-01-10T06:51:25.896Z", 65 | "lastModifiedAt": "2017-01-10T06:51:25.946Z" 66 | } ` 67 | client, server := testutil.MockClient(t, responseData, nil, nil) 68 | defer server.Close() 69 | customer_group, err := client.CustomerGroupDeleteWithID(context.TODO(), "dummy-id", 1) 70 | if err != nil { 71 | t.Fatal(err) 72 | } 73 | assert.NotNil(t, customer_group) 74 | assert.NotNil(t, customer_group.Version) 75 | assert.NotEmpty(t, customer_group.Name) 76 | assert.NotEmpty(t, customer_group.LastModifiedAt) 77 | assert.NotEmpty(t, customer_group.ID) 78 | assert.NotEmpty(t, customer_group.CreatedAt) 79 | 80 | } 81 | 82 | func TestGeneratedCustomerGroupDeleteWithKey(t *testing.T) { 83 | responseData := ` { 84 | "id": "aef9cf41-94ad-4794-8122-62d308900430", 85 | "version": 2, 86 | "name": "Webshop user", 87 | "createdAt": "2017-01-10T06:51:25.896Z", 88 | "lastModifiedAt": "2017-01-10T06:51:25.946Z" 89 | } ` 90 | client, server := testutil.MockClient(t, responseData, nil, nil) 91 | defer server.Close() 92 | customer_group, err := client.CustomerGroupDeleteWithKey(context.TODO(), "dummy-id", 1) 93 | if err != nil { 94 | t.Fatal(err) 95 | } 96 | assert.NotNil(t, customer_group) 97 | assert.NotNil(t, customer_group.Version) 98 | assert.NotEmpty(t, customer_group.Name) 99 | assert.NotEmpty(t, customer_group.LastModifiedAt) 100 | assert.NotEmpty(t, customer_group.ID) 101 | assert.NotEmpty(t, customer_group.CreatedAt) 102 | 103 | } 104 | 105 | func TestGeneratedCustomerGroupQuery(t *testing.T) { 106 | responseData := ` { 107 | "limit": 20, 108 | "offset": 0, 109 | "count": 1, 110 | "total": 1, 111 | "results": [ 112 | { 113 | "id": "aef9cf41-94ad-4794-8122-62d308900430", 114 | "version": 2, 115 | "name": "Webshop user", 116 | "createdAt": "2017-01-10T06:51:25.896Z", 117 | "lastModifiedAt": "2017-01-10T06:51:25.946Z" 118 | } 119 | ] 120 | } ` 121 | client, server := testutil.MockClient(t, responseData, nil, nil) 122 | defer server.Close() 123 | input := commercetools.QueryInput{} 124 | queryResult, err := client.CustomerGroupQuery(context.TODO(), &input) 125 | if err != nil { 126 | t.Fatal(err) 127 | } 128 | assert.NotNil(t, queryResult) 129 | assert.NotNil(t, queryResult.Total) 130 | assert.NotNil(t, queryResult.Offset) 131 | assert.NotNil(t, queryResult.Limit) 132 | assert.NotNil(t, queryResult.Count) 133 | 134 | } 135 | -------------------------------------------------------------------------------- /commercetools/service_type.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // TypeCreate creates a new instance of type Type 13 | func (client *Client) TypeCreate(ctx context.Context, draft *TypeDraft, opts ...RequestOption) (result *Type, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "types" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // TypeQuery allows querying for type Type 28 | func (client *Client) TypeQuery(ctx context.Context, input *QueryInput) (result *TypePagedQueryResponse, err error) { 29 | endpoint := "types" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // TypeDeleteWithID for type Type 38 | func (client *Client) TypeDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *Type, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("types/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // TypeDeleteWithKey for type Type 54 | func (client *Client) TypeDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *Type, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("types/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // TypeGetWithID for type Type 70 | func (client *Client) TypeGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Type, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("types/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // TypeGetWithKey for type Type 84 | func (client *Client) TypeGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Type, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("types/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // TypeUpdateWithIDInput is input for function TypeUpdateWithID 98 | type TypeUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []TypeUpdateAction 102 | } 103 | 104 | func (input *TypeUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // TypeUpdateWithID for type Type 115 | func (client *Client) TypeUpdateWithID(ctx context.Context, input *TypeUpdateWithIDInput, opts ...RequestOption) (result *Type, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("types/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // TypeUpdateWithKeyInput is input for function TypeUpdateWithKey 134 | type TypeUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []TypeUpdateAction 138 | } 139 | 140 | func (input *TypeUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // TypeUpdateWithKey for type Type 151 | func (client *Client) TypeUpdateWithKey(ctx context.Context, input *TypeUpdateWithKeyInput, opts ...RequestOption) (result *Type, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("types/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_zone.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // ZoneCreate creates a new instance of type Zone 13 | func (client *Client) ZoneCreate(ctx context.Context, draft *ZoneDraft, opts ...RequestOption) (result *Zone, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "zones" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // ZoneQuery allows querying for type Zone 28 | func (client *Client) ZoneQuery(ctx context.Context, input *QueryInput) (result *ZonePagedQueryResponse, err error) { 29 | endpoint := "zones" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // ZoneDeleteWithID for type Zone 38 | func (client *Client) ZoneDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *Zone, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("zones/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // ZoneDeleteWithKey for type Zone 54 | func (client *Client) ZoneDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *Zone, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("zones/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // ZoneGetWithID for type Zone 70 | func (client *Client) ZoneGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Zone, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("zones/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // ZoneGetWithKey for type Zone 84 | func (client *Client) ZoneGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Zone, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("zones/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // ZoneUpdateWithIDInput is input for function ZoneUpdateWithID 98 | type ZoneUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []ZoneUpdateAction 102 | } 103 | 104 | func (input *ZoneUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // ZoneUpdateWithID for type Zone 115 | func (client *Client) ZoneUpdateWithID(ctx context.Context, input *ZoneUpdateWithIDInput, opts ...RequestOption) (result *Zone, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("zones/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // ZoneUpdateWithKeyInput is input for function ZoneUpdateWithKey 134 | type ZoneUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []ZoneUpdateAction 138 | } 139 | 140 | func (input *ZoneUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // ZoneUpdateWithKey for type Zone 151 | func (client *Client) ZoneUpdateWithKey(ctx context.Context, input *ZoneUpdateWithKeyInput, opts ...RequestOption) (result *Zone, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("zones/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_state.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // StateCreate creates a new instance of type State 13 | func (client *Client) StateCreate(ctx context.Context, draft *StateDraft, opts ...RequestOption) (result *State, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "states" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // StateQuery allows querying for type State 28 | func (client *Client) StateQuery(ctx context.Context, input *QueryInput) (result *StatePagedQueryResponse, err error) { 29 | endpoint := "states" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // StateDeleteWithID for type State 38 | func (client *Client) StateDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *State, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("states/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // StateDeleteWithKey for type State 54 | func (client *Client) StateDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *State, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("states/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // StateGetWithID for type State 70 | func (client *Client) StateGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *State, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("states/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // StateGetWithKey for type State 84 | func (client *Client) StateGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *State, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("states/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // StateUpdateWithIDInput is input for function StateUpdateWithID 98 | type StateUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []StateUpdateAction 102 | } 103 | 104 | func (input *StateUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // StateUpdateWithID for type State 115 | func (client *Client) StateUpdateWithID(ctx context.Context, input *StateUpdateWithIDInput, opts ...RequestOption) (result *State, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("states/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // StateUpdateWithKeyInput is input for function StateUpdateWithKey 134 | type StateUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []StateUpdateAction 138 | } 139 | 140 | func (input *StateUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // StateUpdateWithKey for type State 151 | func (client *Client) StateUpdateWithKey(ctx context.Context, input *StateUpdateWithKeyInput, opts ...RequestOption) (result *State, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("states/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_store.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // StoreCreate creates a new instance of type Store 13 | func (client *Client) StoreCreate(ctx context.Context, draft *StoreDraft, opts ...RequestOption) (result *Store, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "stores" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // StoreQuery allows querying for type Store 28 | func (client *Client) StoreQuery(ctx context.Context, input *QueryInput) (result *StorePagedQueryResponse, err error) { 29 | endpoint := "stores" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // StoreDeleteWithID for type Store 38 | func (client *Client) StoreDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *Store, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("stores/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // StoreDeleteWithKey for type Store 54 | func (client *Client) StoreDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *Store, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("stores/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // StoreGetWithID for type Store 70 | func (client *Client) StoreGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Store, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("stores/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // StoreGetWithKey for type Store 84 | func (client *Client) StoreGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Store, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("stores/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // StoreUpdateWithIDInput is input for function StoreUpdateWithID 98 | type StoreUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []StoreUpdateAction 102 | } 103 | 104 | func (input *StoreUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // StoreUpdateWithID for type Store 115 | func (client *Client) StoreUpdateWithID(ctx context.Context, input *StoreUpdateWithIDInput, opts ...RequestOption) (result *Store, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("stores/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // StoreUpdateWithKeyInput is input for function StoreUpdateWithKey 134 | type StoreUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []StoreUpdateAction 138 | } 139 | 140 | func (input *StoreUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // StoreUpdateWithKey for type Store 151 | func (client *Client) StoreUpdateWithKey(ctx context.Context, input *StoreUpdateWithKeyInput, opts ...RequestOption) (result *Store, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("stores/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_shopping_list_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedShoppingListGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "9693f04b-5aec-467f-baa1-fc74da7d0c3d", 16 | "version": 1, 17 | "name": { 18 | "en": "test" 19 | }, 20 | "key": "test", 21 | "lineItems": [], 22 | "textLineItems": [], 23 | "createdAt": "2017-03-30T11:49:40.904Z", 24 | "lastModifiedAt": "2017-03-30T11:49:40.904Z" 25 | } ` 26 | client, server := testutil.MockClient(t, responseData, nil, nil) 27 | defer server.Close() 28 | shopping_list, err := client.ShoppingListGetWithID(context.TODO(), "dummy-id") 29 | if err != nil { 30 | t.Fatal(err) 31 | } 32 | assert.NotNil(t, shopping_list) 33 | assert.NotNil(t, shopping_list.Version) 34 | assert.NotEmpty(t, shopping_list.LastModifiedAt) 35 | assert.NotEmpty(t, shopping_list.Key) 36 | assert.NotEmpty(t, shopping_list.ID) 37 | assert.NotEmpty(t, shopping_list.CreatedAt) 38 | 39 | } 40 | 41 | func TestGeneratedShoppingListGetWithKey(t *testing.T) { 42 | responseData := ` { 43 | "id": "9693f04b-5aec-467f-baa1-fc74da7d0c3d", 44 | "version": 1, 45 | "name": { 46 | "en": "test" 47 | }, 48 | "key": "test", 49 | "lineItems": [], 50 | "textLineItems": [], 51 | "createdAt": "2017-03-30T11:49:40.904Z", 52 | "lastModifiedAt": "2017-03-30T11:49:40.904Z" 53 | } ` 54 | client, server := testutil.MockClient(t, responseData, nil, nil) 55 | defer server.Close() 56 | shopping_list, err := client.ShoppingListGetWithKey(context.TODO(), "dummy-id") 57 | if err != nil { 58 | t.Fatal(err) 59 | } 60 | assert.NotNil(t, shopping_list) 61 | assert.NotNil(t, shopping_list.Version) 62 | assert.NotEmpty(t, shopping_list.LastModifiedAt) 63 | assert.NotEmpty(t, shopping_list.Key) 64 | assert.NotEmpty(t, shopping_list.ID) 65 | assert.NotEmpty(t, shopping_list.CreatedAt) 66 | 67 | } 68 | 69 | func TestGeneratedShoppingListDeleteWithID(t *testing.T) { 70 | responseData := ` { 71 | "id": "9693f04b-5aec-467f-baa1-fc74da7d0c3d", 72 | "version": 1, 73 | "name": { 74 | "en": "test" 75 | }, 76 | "key": "test", 77 | "lineItems": [], 78 | "textLineItems": [], 79 | "createdAt": "2017-03-30T11:49:40.904Z", 80 | "lastModifiedAt": "2017-03-30T11:49:40.904Z" 81 | } ` 82 | client, server := testutil.MockClient(t, responseData, nil, nil) 83 | defer server.Close() 84 | shopping_list, err := client.ShoppingListDeleteWithID(context.TODO(), "dummy-id", 1, true) 85 | if err != nil { 86 | t.Fatal(err) 87 | } 88 | assert.NotNil(t, shopping_list) 89 | assert.NotNil(t, shopping_list.Version) 90 | assert.NotEmpty(t, shopping_list.LastModifiedAt) 91 | assert.NotEmpty(t, shopping_list.Key) 92 | assert.NotEmpty(t, shopping_list.ID) 93 | assert.NotEmpty(t, shopping_list.CreatedAt) 94 | 95 | } 96 | 97 | func TestGeneratedShoppingListDeleteWithKey(t *testing.T) { 98 | responseData := ` { 99 | "id": "9693f04b-5aec-467f-baa1-fc74da7d0c3d", 100 | "version": 1, 101 | "name": { 102 | "en": "test" 103 | }, 104 | "key": "test", 105 | "lineItems": [], 106 | "textLineItems": [], 107 | "createdAt": "2017-03-30T11:49:40.904Z", 108 | "lastModifiedAt": "2017-03-30T11:49:40.904Z" 109 | } ` 110 | client, server := testutil.MockClient(t, responseData, nil, nil) 111 | defer server.Close() 112 | shopping_list, err := client.ShoppingListDeleteWithKey(context.TODO(), "dummy-id", 1, true) 113 | if err != nil { 114 | t.Fatal(err) 115 | } 116 | assert.NotNil(t, shopping_list) 117 | assert.NotNil(t, shopping_list.Version) 118 | assert.NotEmpty(t, shopping_list.LastModifiedAt) 119 | assert.NotEmpty(t, shopping_list.Key) 120 | assert.NotEmpty(t, shopping_list.ID) 121 | assert.NotEmpty(t, shopping_list.CreatedAt) 122 | 123 | } 124 | 125 | func TestGeneratedShoppingListQuery(t *testing.T) { 126 | responseData := ` { 127 | "limit": 20, 128 | "offset": 0, 129 | "count": 1, 130 | "total": 1, 131 | "results": [ 132 | { 133 | "id": "9693f04b-5aec-467f-baa1-fc74da7d0c3d", 134 | "version": 1, 135 | "name": { 136 | "en": "test" 137 | }, 138 | "key": "test", 139 | "lineItems": [], 140 | "textLineItems": [], 141 | "createdAt": "2017-03-30T11:49:40.904Z", 142 | "lastModifiedAt": "2017-03-30T11:49:40.904Z" 143 | } 144 | ] 145 | } ` 146 | client, server := testutil.MockClient(t, responseData, nil, nil) 147 | defer server.Close() 148 | input := commercetools.QueryInput{} 149 | queryResult, err := client.ShoppingListQuery(context.TODO(), &input) 150 | if err != nil { 151 | t.Fatal(err) 152 | } 153 | assert.NotNil(t, queryResult) 154 | assert.NotNil(t, queryResult.Total) 155 | assert.NotNil(t, queryResult.Offset) 156 | assert.NotNil(t, queryResult.Limit) 157 | assert.NotNil(t, queryResult.Count) 158 | 159 | } 160 | -------------------------------------------------------------------------------- /commercetools/service_store_generated_test.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools_test 4 | 5 | import ( 6 | "context" 7 | "github.com/labd/commercetools-go-sdk/commercetools" 8 | "github.com/labd/commercetools-go-sdk/testutil" 9 | "github.com/stretchr/testify/assert" 10 | "testing" 11 | ) 12 | 13 | func TestGeneratedStoreGetWithID(t *testing.T) { 14 | responseData := ` { 15 | "id": "c2f93299-c967-44af-8c2a-d2220bf39eb2", 16 | "version": 1, 17 | "key": "random-key-12314", 18 | "name": { 19 | "en": "big store" 20 | }, 21 | "createdAt": "1971-01-01T00:00:00.001Z", 22 | "lastModifiedAt": "1972-01-01T00:00:00.001Z", 23 | "distributionChannels": [] 24 | } ` 25 | client, server := testutil.MockClient(t, responseData, nil, nil) 26 | defer server.Close() 27 | store, err := client.StoreGetWithID(context.TODO(), "dummy-id") 28 | if err != nil { 29 | t.Fatal(err) 30 | } 31 | assert.NotNil(t, store) 32 | assert.NotNil(t, store.Version) 33 | assert.NotEmpty(t, store.LastModifiedAt) 34 | assert.NotEmpty(t, store.Key) 35 | assert.NotEmpty(t, store.ID) 36 | assert.NotEmpty(t, store.CreatedAt) 37 | 38 | } 39 | 40 | func TestGeneratedStoreGetWithKey(t *testing.T) { 41 | responseData := ` { 42 | "id": "c2f93299-c967-44af-8c2a-d2220bf39eb2", 43 | "version": 1, 44 | "key": "random-key-12314", 45 | "name": { 46 | "en": "big store" 47 | }, 48 | "createdAt": "1971-01-01T00:00:00.001Z", 49 | "lastModifiedAt": "1972-01-01T00:00:00.001Z", 50 | "distributionChannels": [] 51 | } ` 52 | client, server := testutil.MockClient(t, responseData, nil, nil) 53 | defer server.Close() 54 | store, err := client.StoreGetWithKey(context.TODO(), "dummy-id") 55 | if err != nil { 56 | t.Fatal(err) 57 | } 58 | assert.NotNil(t, store) 59 | assert.NotNil(t, store.Version) 60 | assert.NotEmpty(t, store.LastModifiedAt) 61 | assert.NotEmpty(t, store.Key) 62 | assert.NotEmpty(t, store.ID) 63 | assert.NotEmpty(t, store.CreatedAt) 64 | 65 | } 66 | 67 | func TestGeneratedStoreDeleteWithID(t *testing.T) { 68 | responseData := ` { 69 | "id": "c2f93299-c967-44af-8c2a-d2220bf39eb2", 70 | "version": 1, 71 | "key": "random-key-12314", 72 | "name": { 73 | "en": "big store" 74 | }, 75 | "createdAt": "1971-01-01T00:00:00.001Z", 76 | "lastModifiedAt": "1972-01-01T00:00:00.001Z", 77 | "distributionChannels": [] 78 | } ` 79 | client, server := testutil.MockClient(t, responseData, nil, nil) 80 | defer server.Close() 81 | store, err := client.StoreDeleteWithID(context.TODO(), "dummy-id", 1) 82 | if err != nil { 83 | t.Fatal(err) 84 | } 85 | assert.NotNil(t, store) 86 | assert.NotNil(t, store.Version) 87 | assert.NotEmpty(t, store.LastModifiedAt) 88 | assert.NotEmpty(t, store.Key) 89 | assert.NotEmpty(t, store.ID) 90 | assert.NotEmpty(t, store.CreatedAt) 91 | 92 | } 93 | 94 | func TestGeneratedStoreDeleteWithKey(t *testing.T) { 95 | responseData := ` { 96 | "id": "c2f93299-c967-44af-8c2a-d2220bf39eb2", 97 | "version": 1, 98 | "key": "random-key-12314", 99 | "name": { 100 | "en": "big store" 101 | }, 102 | "createdAt": "1971-01-01T00:00:00.001Z", 103 | "lastModifiedAt": "1972-01-01T00:00:00.001Z", 104 | "distributionChannels": [] 105 | } ` 106 | client, server := testutil.MockClient(t, responseData, nil, nil) 107 | defer server.Close() 108 | store, err := client.StoreDeleteWithKey(context.TODO(), "dummy-id", 1) 109 | if err != nil { 110 | t.Fatal(err) 111 | } 112 | assert.NotNil(t, store) 113 | assert.NotNil(t, store.Version) 114 | assert.NotEmpty(t, store.LastModifiedAt) 115 | assert.NotEmpty(t, store.Key) 116 | assert.NotEmpty(t, store.ID) 117 | assert.NotEmpty(t, store.CreatedAt) 118 | 119 | } 120 | 121 | func TestGeneratedStoreQuery(t *testing.T) { 122 | responseData := ` { 123 | "limit": 20, 124 | "offset": 0, 125 | "count": 2, 126 | "total": 2, 127 | "results": [ 128 | { 129 | "id": "c2f93299-c967-44af-8c2a-d2220bf39eb2", 130 | "version": 1, 131 | "key": "random-key-12314", 132 | "name": { 133 | "en": "big store" 134 | }, 135 | "createdAt": "1971-01-01T00:00:00.001Z", 136 | "lastModifiedAt": "1972-01-01T00:00:00.001Z", 137 | "distributionChannels": [] 138 | }, 139 | { 140 | "id": "c2f93209-c967-44af-8c2a-d2220bf39eb2", 141 | "version": 1, 142 | "key": "random-key-1234314", 143 | "name": { 144 | "en": "second store" 145 | }, 146 | "createdAt": "1973-01-01T00:00:00.001Z", 147 | "lastModifiedAt": "1973-01-01T00:00:00.001Z", 148 | "distributionChannels": [] 149 | } 150 | ] 151 | } ` 152 | client, server := testutil.MockClient(t, responseData, nil, nil) 153 | defer server.Close() 154 | input := commercetools.QueryInput{} 155 | queryResult, err := client.StoreQuery(context.TODO(), &input) 156 | if err != nil { 157 | t.Fatal(err) 158 | } 159 | assert.NotNil(t, queryResult) 160 | assert.NotNil(t, queryResult.Total) 161 | assert.NotNil(t, queryResult.Offset) 162 | assert.NotNil(t, queryResult.Limit) 163 | assert.NotNil(t, queryResult.Count) 164 | 165 | } 166 | -------------------------------------------------------------------------------- /commercetools/service_category.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // CategoryCreate creates a new instance of type Category 13 | func (client *Client) CategoryCreate(ctx context.Context, draft *CategoryDraft, opts ...RequestOption) (result *Category, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "categories" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // CategoryQuery allows querying for type Category 28 | func (client *Client) CategoryQuery(ctx context.Context, input *QueryInput) (result *CategoryPagedQueryResponse, err error) { 29 | endpoint := "categories" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // CategoryDeleteWithID for type Category 38 | func (client *Client) CategoryDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *Category, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("categories/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // CategoryDeleteWithKey for type Category 54 | func (client *Client) CategoryDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *Category, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("categories/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // CategoryGetWithID for type Category 70 | func (client *Client) CategoryGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Category, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("categories/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // CategoryGetWithKey for type Category 84 | func (client *Client) CategoryGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Category, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("categories/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // CategoryUpdateWithIDInput is input for function CategoryUpdateWithID 98 | type CategoryUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []CategoryUpdateAction 102 | } 103 | 104 | func (input *CategoryUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // CategoryUpdateWithID for type Category 115 | func (client *Client) CategoryUpdateWithID(ctx context.Context, input *CategoryUpdateWithIDInput, opts ...RequestOption) (result *Category, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("categories/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // CategoryUpdateWithKeyInput is input for function CategoryUpdateWithKey 134 | type CategoryUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []CategoryUpdateAction 138 | } 139 | 140 | func (input *CategoryUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // CategoryUpdateWithKey for type Category 151 | func (client *Client) CategoryUpdateWithKey(ctx context.Context, input *CategoryUpdateWithKeyInput, opts ...RequestOption) (result *Category, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("categories/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_review.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // ReviewCreate creates a new instance of type Review 13 | func (client *Client) ReviewCreate(ctx context.Context, draft *ReviewDraft, opts ...RequestOption) (result *Review, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "reviews" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // ReviewQuery allows querying for type Review 28 | func (client *Client) ReviewQuery(ctx context.Context, input *QueryInput) (result *ReviewPagedQueryResponse, err error) { 29 | endpoint := "reviews" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // ReviewDeleteWithID for type Review 38 | func (client *Client) ReviewDeleteWithID(ctx context.Context, id string, version int, dataErasure bool, opts ...RequestOption) (result *Review, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | params.Set("dataErasure", strconv.FormatBool(dataErasure)) 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("reviews/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // ReviewDeleteWithKey for type Review 54 | func (client *Client) ReviewDeleteWithKey(ctx context.Context, key string, version int, dataErasure bool, opts ...RequestOption) (result *Review, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | params.Set("dataErasure", strconv.FormatBool(dataErasure)) 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("reviews/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // ReviewGetWithID for type Review 70 | func (client *Client) ReviewGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Review, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("reviews/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // ReviewGetWithKey for type Review 84 | func (client *Client) ReviewGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Review, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("reviews/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // ReviewUpdateWithIDInput is input for function ReviewUpdateWithID 98 | type ReviewUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []ReviewUpdateAction 102 | } 103 | 104 | func (input *ReviewUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // ReviewUpdateWithID for type Review 115 | func (client *Client) ReviewUpdateWithID(ctx context.Context, input *ReviewUpdateWithIDInput, opts ...RequestOption) (result *Review, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("reviews/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // ReviewUpdateWithKeyInput is input for function ReviewUpdateWithKey 134 | type ReviewUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []ReviewUpdateAction 138 | } 139 | 140 | func (input *ReviewUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // ReviewUpdateWithKey for type Review 151 | func (client *Client) ReviewUpdateWithKey(ctx context.Context, input *ReviewUpdateWithKeyInput, opts ...RequestOption) (result *Review, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("reviews/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_payment.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // PaymentCreate creates a new instance of type Payment 13 | func (client *Client) PaymentCreate(ctx context.Context, draft *PaymentDraft, opts ...RequestOption) (result *Payment, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "payments" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // PaymentQuery allows querying for type Payment 28 | func (client *Client) PaymentQuery(ctx context.Context, input *QueryInput) (result *PaymentPagedQueryResponse, err error) { 29 | endpoint := "payments" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // PaymentDeleteWithID for type Payment 38 | func (client *Client) PaymentDeleteWithID(ctx context.Context, id string, version int, dataErasure bool, opts ...RequestOption) (result *Payment, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | params.Set("dataErasure", strconv.FormatBool(dataErasure)) 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("payments/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // PaymentDeleteWithKey for type Payment 54 | func (client *Client) PaymentDeleteWithKey(ctx context.Context, key string, version int, dataErasure bool, opts ...RequestOption) (result *Payment, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | params.Set("dataErasure", strconv.FormatBool(dataErasure)) 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("payments/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // PaymentGetWithID for type Payment 70 | func (client *Client) PaymentGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Payment, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("payments/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // PaymentGetWithKey for type Payment 84 | func (client *Client) PaymentGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Payment, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("payments/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // PaymentUpdateWithIDInput is input for function PaymentUpdateWithID 98 | type PaymentUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []PaymentUpdateAction 102 | } 103 | 104 | func (input *PaymentUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // PaymentUpdateWithID for type Payment 115 | func (client *Client) PaymentUpdateWithID(ctx context.Context, input *PaymentUpdateWithIDInput, opts ...RequestOption) (result *Payment, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("payments/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // PaymentUpdateWithKeyInput is input for function PaymentUpdateWithKey 134 | type PaymentUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []PaymentUpdateAction 138 | } 139 | 140 | func (input *PaymentUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // PaymentUpdateWithKey for type Payment 151 | func (client *Client) PaymentUpdateWithKey(ctx context.Context, input *PaymentUpdateWithKeyInput, opts ...RequestOption) (result *Payment, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("payments/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_extension.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // ExtensionCreate creates a new instance of type Extension 13 | func (client *Client) ExtensionCreate(ctx context.Context, draft *ExtensionDraft, opts ...RequestOption) (result *Extension, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "extensions" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // ExtensionQuery allows querying for type Extension 28 | func (client *Client) ExtensionQuery(ctx context.Context, input *QueryInput) (result *ExtensionPagedQueryResponse, err error) { 29 | endpoint := "extensions" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // ExtensionDeleteWithID for type Extension 38 | func (client *Client) ExtensionDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *Extension, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("extensions/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // ExtensionDeleteWithKey for type Extension 54 | func (client *Client) ExtensionDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *Extension, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("extensions/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // ExtensionGetWithID Retrieves the representation of an extension by its id. 70 | func (client *Client) ExtensionGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *Extension, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("extensions/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // ExtensionGetWithKey Retrieves the representation of an extension by its key. 84 | func (client *Client) ExtensionGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *Extension, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("extensions/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // ExtensionUpdateWithIDInput is input for function ExtensionUpdateWithID 98 | type ExtensionUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []ExtensionUpdateAction 102 | } 103 | 104 | func (input *ExtensionUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // ExtensionUpdateWithID for type Extension 115 | func (client *Client) ExtensionUpdateWithID(ctx context.Context, input *ExtensionUpdateWithIDInput, opts ...RequestOption) (result *Extension, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("extensions/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // ExtensionUpdateWithKeyInput is input for function ExtensionUpdateWithKey 134 | type ExtensionUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []ExtensionUpdateAction 138 | } 139 | 140 | func (input *ExtensionUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // ExtensionUpdateWithKey for type Extension 151 | func (client *Client) ExtensionUpdateWithKey(ctx context.Context, input *ExtensionUpdateWithKeyInput, opts ...RequestOption) (result *Extension, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("extensions/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | -------------------------------------------------------------------------------- /commercetools/service_product_type.go: -------------------------------------------------------------------------------- 1 | // Automatically generated, do not edit 2 | 3 | package commercetools 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | ) 11 | 12 | // ProductTypeCreate creates a new instance of type ProductType 13 | func (client *Client) ProductTypeCreate(ctx context.Context, draft *ProductTypeDraft, opts ...RequestOption) (result *ProductType, err error) { 14 | params := url.Values{} 15 | for _, opt := range opts { 16 | opt(¶ms) 17 | } 18 | 19 | endpoint := "product-types" 20 | err = client.create(ctx, endpoint, params, draft, &result) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return result, nil 25 | } 26 | 27 | // ProductTypeQuery allows querying for type ProductType 28 | func (client *Client) ProductTypeQuery(ctx context.Context, input *QueryInput) (result *ProductTypePagedQueryResponse, err error) { 29 | endpoint := "product-types" 30 | err = client.query(ctx, endpoint, input.toParams(), &result) 31 | if err != nil { 32 | return nil, err 33 | } 34 | return result, nil 35 | } 36 | 37 | // ProductTypeDeleteWithID for type ProductType 38 | func (client *Client) ProductTypeDeleteWithID(ctx context.Context, id string, version int, opts ...RequestOption) (result *ProductType, err error) { 39 | params := url.Values{} 40 | params.Set("version", strconv.Itoa(version)) 41 | 42 | for _, opt := range opts { 43 | opt(¶ms) 44 | } 45 | endpoint := fmt.Sprintf("product-types/%s", id) 46 | err = client.delete(ctx, endpoint, params, &result) 47 | if err != nil { 48 | return nil, err 49 | } 50 | return result, nil 51 | } 52 | 53 | // ProductTypeDeleteWithKey for type ProductType 54 | func (client *Client) ProductTypeDeleteWithKey(ctx context.Context, key string, version int, opts ...RequestOption) (result *ProductType, err error) { 55 | params := url.Values{} 56 | params.Set("version", strconv.Itoa(version)) 57 | 58 | for _, opt := range opts { 59 | opt(¶ms) 60 | } 61 | endpoint := fmt.Sprintf("product-types/key=%s", key) 62 | err = client.delete(ctx, endpoint, params, &result) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return result, nil 67 | } 68 | 69 | // ProductTypeGetWithID for type ProductType 70 | func (client *Client) ProductTypeGetWithID(ctx context.Context, id string, opts ...RequestOption) (result *ProductType, err error) { 71 | params := url.Values{} 72 | for _, opt := range opts { 73 | opt(¶ms) 74 | } 75 | endpoint := fmt.Sprintf("product-types/%s", id) 76 | err = client.get(ctx, endpoint, params, &result) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return result, nil 81 | } 82 | 83 | // ProductTypeGetWithKey for type ProductType 84 | func (client *Client) ProductTypeGetWithKey(ctx context.Context, key string, opts ...RequestOption) (result *ProductType, err error) { 85 | params := url.Values{} 86 | for _, opt := range opts { 87 | opt(¶ms) 88 | } 89 | endpoint := fmt.Sprintf("product-types/key=%s", key) 90 | err = client.get(ctx, endpoint, params, &result) 91 | if err != nil { 92 | return nil, err 93 | } 94 | return result, nil 95 | } 96 | 97 | // ProductTypeUpdateWithIDInput is input for function ProductTypeUpdateWithID 98 | type ProductTypeUpdateWithIDInput struct { 99 | ID string 100 | Version int 101 | Actions []ProductTypeUpdateAction 102 | } 103 | 104 | func (input *ProductTypeUpdateWithIDInput) Validate() error { 105 | if input.ID == "" { 106 | return fmt.Errorf("no valid value for ID given") 107 | } 108 | if len(input.Actions) == 0 { 109 | return fmt.Errorf("no update actions specified") 110 | } 111 | return nil 112 | } 113 | 114 | // ProductTypeUpdateWithID for type ProductType 115 | func (client *Client) ProductTypeUpdateWithID(ctx context.Context, input *ProductTypeUpdateWithIDInput, opts ...RequestOption) (result *ProductType, err error) { 116 | if err := input.Validate(); err != nil { 117 | return nil, err 118 | } 119 | 120 | params := url.Values{} 121 | for _, opt := range opts { 122 | opt(¶ms) 123 | } 124 | 125 | endpoint := fmt.Sprintf("product-types/%s", input.ID) 126 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 127 | if err != nil { 128 | return nil, err 129 | } 130 | return result, nil 131 | } 132 | 133 | // ProductTypeUpdateWithKeyInput is input for function ProductTypeUpdateWithKey 134 | type ProductTypeUpdateWithKeyInput struct { 135 | Key string 136 | Version int 137 | Actions []ProductTypeUpdateAction 138 | } 139 | 140 | func (input *ProductTypeUpdateWithKeyInput) Validate() error { 141 | if input.Key == "" { 142 | return fmt.Errorf("no valid value for Key given") 143 | } 144 | if len(input.Actions) == 0 { 145 | return fmt.Errorf("no update actions specified") 146 | } 147 | return nil 148 | } 149 | 150 | // ProductTypeUpdateWithKey for type ProductType 151 | func (client *Client) ProductTypeUpdateWithKey(ctx context.Context, input *ProductTypeUpdateWithKeyInput, opts ...RequestOption) (result *ProductType, err error) { 152 | if err := input.Validate(); err != nil { 153 | return nil, err 154 | } 155 | 156 | params := url.Values{} 157 | for _, opt := range opts { 158 | opt(¶ms) 159 | } 160 | 161 | endpoint := fmt.Sprintf("product-types/key=%s", input.Key) 162 | err = client.update(ctx, endpoint, params, input.Version, input.Actions, &result) 163 | if err != nil { 164 | return nil, err 165 | } 166 | return result, nil 167 | } 168 | --------------------------------------------------------------------------------