Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/token-refresh #339

Merged
merged 5 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/semantic-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ jobs:
CL_SDK_ORGANIZATION: sdk-test-org
CL_SDK_CLIENT_ID: ${{secrets.CL_SDK_CLIENT_ID}}
CL_SDK_CLIENT_SECRET: ${{secrets.CL_SDK_CLIENT_SECRET}}
CL_SDK_ACCESS_TOKEN_EXPIRED: ${{secrets.CL_SDK_ACCESS_TOKEN_EXPIRED}}
run: pnpm test
- name: Release
env:
Expand Down
104 changes: 104 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ A JavaScript Library wrapper that makes it quick and easy to interact with the [
- [Installation](#installation)
- [Authentication](#authentication)
- [Import](#import)
- [Options](#options)
- [SDK usage](#sdk-usage)
- [Overriding credentials](#overriding-credentials)
- [Handling validation errors](#handling-validation-errors)
- [Using interceptors](#using-interceptors)
- [Refreshing access token](#refreshing-access-token)
- [Contributors guide](#contributors-guide)
- [Need help?](#need-help)
- [License](#license)
Expand Down Expand Up @@ -66,6 +69,37 @@ const cl = CommerceLayer({
})
```

### Options

When instantiating a new SDK client you can pass some options to initialize it:

```javascript
{
organization: string // The organization slug
accessToken: string // A valid API access token
timeout?: number // A custom request timout (<= 15 secs [default])
headers?: RequestHeaders // Custom request headers
userAgent?: string // Custom user-agent useful in certaing contexts but often not allowed by browsers
fetch?: Fetch // A specific fetch implementation
refreshToken?: RefreshToken // A function responsible for token refresh
}
```

Same options can be changed after SDK initialization or passed at runtime while executing an API call:

```javascript
const options = { ... }

// Instantiate the client using desired options
const cl = CommerceLayer(options)

// Change configuration after client cteation
cl.config(options)

// Use runtime configuration without persisting settings
cl.customers.list({}, options)
```

## SDK usage

The JavaScript SDK is a wrapper around Commerce Layer API which means you would still be making API requests but with a different syntax. For now, we don't have comprehensive SDK documentation for every single resource our API supports (about 400+ endpoints), hence you will need to rely on our comprehensive [API Reference](https://docs.commercelayer.io/core/v/api-reference) as you go about using this SDK. So for example, if you want to create an order, take a look at the [Order object](https://docs.commercelayer.io/core/v/api-reference/orders/object) or the [Create an order](https://docs.commercelayer.io/core/v/api-reference/orders/create) documentation to see the required attributes and/or relationships. The same goes for every other supported resource.
Expand Down Expand Up @@ -388,6 +422,76 @@ Commerce Layer API returns specific errors (with extra information) on each attr

ℹ️ Check our API reference for more information about the [errors](https://docs.commercelayer.io/developers/handling-errors) returned by the API.

## Using interceptors

You can use interceptors to intercept SDK messages and modify them on the fly before the request is sent to the API or before the response is parsed and returned by the client. You can also access the error object before it is thrown by the SDK.

Interceptors are special functions that are able to handle SDK messages and return a (eventually) modified version of them for use by the client.

```javascript
const requestInterceptor = (request: RequestObj): RequestObj => {
console.log(request)
return request
}

const responseInterceptor = (response: ResponseObj): ResponseObj => {
console.log(response)
return response
}

const errorInterceptor = (error: ErrorObj): ErrorObj => {
console.log(error)
return error
}
```

Here an example of how to use them:

```javascript
// Add the interceptors (only one or all if needed)
cl.addRequestInterceptor(requestInterceptor)
cl.addResponseInterceptor(responseInterceptor, errorInterceptor)

const customers = await cl.customers.list()

// Remove interceptors
// Tt is possible to remove only a specific interceptor: cl.removeInterceptor('request')
cl.removeInterceptors()
```

#### Raw Response Reader

The *RawResponseReader* is a special interceptor that allows to catch the original message coming frome the API before it is parsed and translated in SDK objects.

```javascript
// Add a RawResponseReader capable of capturing also response headers
const rrr = cl.addRawResponseReader({ headers: true })

const customers = await cl.customers.list()

cl.removeRawResponseReader()

console.log(rrr.rawResponse)
console.log(rrr.headers)
```

## Refreshing access token

It is possible that you are using an access token that is about to expire especially if it has been used for many API calls.
In this case you can define a special function that takes care of refreshing the token when a call fails because it has expired.

```javascript
async function myRefreshTokenFunction(espiredToken: string): Promise<string> {
// Get a new access token using for example our js-auth library
return (await getAccessToken()).accessToken
}

cl.config({ refreshToken: myRefreshTokenFunction })

// If needed you can later retrieve the new access token
const newToken = cl.currentAccessToken
```

## Contributors guide

1. Fork [this repository](https://github.com/commercelayer/commercelayer-sdk) (learn how to do this [here](https://help.github.com/articles/fork-a-repo)).
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,16 @@
"@semantic-release/git": "^10.0.1",
"@types/debug": "^4.1.12",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.13",
"@types/node": "^20.14.1",
"dotenv": "^16.4.5",
"eslint": "^8.57.0",
"jest": "^29.7.0",
"json-typescript": "^1.1.2",
"jsonapi-typescript": "^0.1.3",
"lodash.isequal": "^4.5.0",
"semantic-release": "^23.1.1",
"tsup": "^8.0.2",
"tsx": "^4.11.0",
"tsup": "^8.1.0",
"tsx": "^4.11.2",
"typescript": "^5.4.5"
},
"repository": "github:commercelayer/commercelayer-sdk",
Expand Down
Loading