Skip to content

Commit

Permalink
Feat: Add support for custom APIs @W-15585881@ (#402)
Browse files Browse the repository at this point in the history
* add custom API helper

* add unit tests

* lint

* update docs

* update README

* move custom api param type from core to commerce-sdk

* update unit test

* update unit tests and add flag for transforming request body

* update property name

* update README example with enableTransformBody example

* update example in README

* revert template changes

* update customApiParameters type

* consume new commerce-sdk-core
  • Loading branch information
joeluong-sfcc committed May 10, 2024
1 parent bece071 commit 12f9bd2
Show file tree
Hide file tree
Showing 9 changed files with 572 additions and 10 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ only use JavaScript, or if you use TypeScript but only import the client classes
then your usage **will not change**. You will likely only need to make changes if
you import the type definitions directly.

## v2.16.0-dev

#### Enchancements

- Add helper function `customApiHelper.callCustomEndpoint` to call [Custom APIs](https://developer.salesforce.com/docs/commerce/commerce-api/guide/custom-apis.html) - [#402](https://github.com/SalesforceCommerceCloud/commerce-sdk/pull/402)

## v2.15.0

#### API Changes
Expand Down
85 changes: 85 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,91 @@ const searchResults = await searchClient.productSearch({

Invalid query parameters that are not a part of the API and do not follow the `c_` custom query parameter convention will be filtered from the request and a warning will be displayed.

### Custom APIs

The SDK supports calling [custom APIs](https://developer.salesforce.com/docs/commerce/commerce-api/guide/custom-apis.html) with a helper function, `customApiHelper.callCustomEndpoint()`.

Example usage:

```javascript
import * as CommerceSdk from "commerce-sdk";
const { helpers } = CommerceSdk;

// client configuration parameters
const clientConfigExample = {
parameters: {
clientId: '<your-client-id>',
organizationId: '<your-org-id>',
shortCode: '<your-short-code>',
siteId: '<your-site-id>',
},
// If not provided, it'll use the default production URI:
// 'https://{shortCode}.api.commercecloud.salesforce.com/custom/{apiName}/{apiVersion}'
// path parameters should be wrapped in curly braces like the default production URI
baseUri: '<your-base-uri>'
};

const access_token = '<INSERT_ACCESS_TOKEN_HERE>'

// Required params: apiName, endpointPath, shortCode, organizaitonId
// Required path params can be passed into:
// options.customApiPathParameters or clientConfig.parameters
// customApiPathParameters will take priority for duplicate values
const customApiArgs = {
apiName: 'loyalty-info',
apiVersion: 'v1', // defaults to v1 if not provided
endpointPath: 'customers'
}

const getResponse = await helpers.callCustomEndpoint({
options: {
// http operation is defaulted to 'GET' if not provided
method: 'GET',
parameters: {
queryParameter: 'queryParameter1',
},
headers: {
// Content-Type is defaulted to application/json if not provided
'Content-type': 'application/json',
authorization: `Bearer ${access_token}`
},
customApiPathParameters: customApiArgs,
},
clientConfig: clientConfigExample,
// Flag to retrieve raw response or data from helper function
rawResponse: false
})

const postResponse = await customApiHelper.callCustomEndpoint({
options: {
method: 'POST',
headers: {
authorization: `Bearer ${access_token}`
},
customApiPathParameters: {
apiVersion: 'v1',
endpointPath: 'greeting',
apiName: 'e2e-tests',
},
// When this flag is set to true, the request body will be automatically
// formatted in the expected format set by the 'Content-type' headers
// 'application/json' or 'application/x-www-form-urlencoded'
enableTransformBody: true,

// object can be passed since we have enableTransformBody set to true
body: { data: 'data' }
// if enableTransformBody is not set to true,
// we have to ensure the request body is correctly formatted
// body: JSON.stringify({ data: 'data' })
},
clientConfig: clientConfigExample,
rawResponse: false
})

console.log('get response: ', getResponse)
console.log('post response: ', postResponse)
```

## Caching

The SDK currently supports two types of caches - In-memory and Redis. Both the implementations respect [standard cache headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). To use another type of cache, write your own implementation of the [CacheManager](https://github.com/SalesforceCommerceCloud/commerce-sdk-core/tree/main/src/base/cacheManager.ts). See the [default cache manager](https://github.com/SalesforceCommerceCloud/commerce-sdk-core/tree/main/src/base/cacheManagerKeyv.ts) to design your implementation.
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
]
},
"dependencies": {
"@commerce-apps/core": "^1.6.1",
"@commerce-apps/core": "^1.7.0",
"nanoid": "^3.3.4",
"retry": "^0.13.1",
"tslib": "^2.4.1"
Expand Down
7 changes: 6 additions & 1 deletion src/static/helperTemplates/index.ts.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,10 @@
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { getShopperToken } from "./shopperCustomer"
import { callCustomEndpoint } from "./customApi";
export const helpers = {
callCustomEndpoint,
getShopperToken
}
export * as slasHelpers from "./slas";
export * as helpers from "./shopperCustomer";
8 changes: 8 additions & 0 deletions src/static/helpers/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
export const CUSTOM_API_DEFAULT_BASE_URI =
"https://{shortCode}.api.commercecloud.salesforce.com/custom/{apiName}/{apiVersion}";
Loading

0 comments on commit 12f9bd2

Please sign in to comment.