npm package: @orbis-systems/accounts-ts-sdk
Description: AMT SDK is designed to help clients consume Account Management API with ease. AMT SDK takes care of all the heavy lifting and provides out of the box ready to use object.
Author: Teddy Radenkov
Latest version: 1.1.42

# Account Management Typescript SDK - (AMT)

AMT SDK is designed to help clients consume Account Management API with ease. AMT SDK takes care of all the heavy lifting and provides out of the box ready to use object.

#### Example of a use case
```typescript
//APIConfigure.ts
import configureSDK from '@orbis-systems/accounts-ts-sdk';

const SDK = SDKClient({
   environment: 'development'
});

export default SDK;
```

```typescript
//App.ts
import SDK from '../api/APIConfigure';

class App extends React.Component<IProps> {
    state: {
        applications: [],
    }
    
    public async componentDidMount(): Promise<void> {
        const user = SDK.rest.client.login('username', 'password', ['user.role']);
        SDK.rest.client.autoRenewToken();`_**~~``~~**_`
        const res = SDK.rest.applications.list();
        if(res.success){
            this.setState({
                applications: res.data.applications,
            });
        }else{
            res.error // handle error
        }           
    }   

    public render(): JSX.Element {
        return (
            <>
                {
                    this.state.applications.map(application => {
                        return (
                            //Render what's needed
                        );
                    })  
                }   
            </>
        )
    };
}
```

## Configuration

```typescript
interface IConfig {
  tokenExpired?: Function
  onUnauthorized?: Function
  onEndpointError?: Function
  environment: 'production' | 'sandbox'
  storage?: 'local' | 'session'
}
```

AMT SDK must be configured before use. It provides a configure function that takes a configuration object with options.
+ `tokenExpired?: Function` `optional`
    + Called when the token could not be renewed.
    
+ `onUnauthorized?: Function` `optional`
    + Called when an endpoint returned 401 Unauthorized.
    
+ `onEndpointError?: Function` `optional`
    + Called on any endpoint error that has occurred and provides error.
    
+ `environment: 'production' | 'sandbox'` `required`
    + Sets environment to which AMT needs to connect to.
    
+ `storage?: local' | 'session` `default: session` `optional`
    + Called when the token could not be renewed.

#### Example
```typescript
import configureSDK from './index';

const SDK = configureSDK({
    environment: 'production', 
    onEndpointError: (err): void => {
        store.dispatch({
            type: actionTypes.API_ERROR,
            payload: err
        });
    },
    onUnauthorized: (): void => {
        store.dispatch({
            type: actionTypes.AUTH_UNAUTHORIZED,
        })
    },
    tokenExpired: (): void => {
        localStorage.clear();
        store.dispatch({
            type: actionTypes.AUTH_LOGOUT,
        });
    },
    storage: 'local'
});
```

## Authentication
AMT SDK provides a `client` object that is used to authenticate with Accounts Management API. On a successful authentication AMT SDK stores the token provided into session storage for later use. All endpoints that are protected must be used after the client has authenticated, otherwise the `onUnauthorized` function with be called. `client` object has three methods.
+ `login(email: string, password: string, includes?: Array<string>)`

  ```typescript
  //Includes (`['user.role']`) is not required but if needed, please refer to Accounts Management API for available includes
  const user = await SDK.rest.client.login('email', 'password', ['user.role']);
  ```
+ `logout()`

  ```typescript
  await SDK.rest.client.logout();
  ```
+ `autoRenewToken(): boolean`

  ```typescript
  //Called at root of application in order to start auto token renewal counter, otherwise tokenExpired() will be called when the token has expired
  const success = SDK.rest.client.autoRenewToken();
  ```
  
## Endpoints
+ For authentication endpoints please refer to authentication section. 
+ For any other endpoints please refer to Accounts Management API https://orbis.dev/api/set/7/account-management-and-onboarding

#### Endpoint structure
Besides authentication all endpoints have the same structure.

##### Accesss 
To call an endpoint you must use the `SDK.rest` object and then add the endpoint name.
+ `/` becomes a `.`
+ `-` is removed and word is camel cased
```typescript
//POST {{domain}}/api/applications/get-application-types
SDK.rest.applications.getApplicationTypes();

//POST {{domain}}/api/applications/submit
SDK.rest.applications.submit();
```

##### Parameters `endpoint(data?: object, config?: IRequestConfig ) => Promise<any>`
+ `data` `optional` is anything that is required by Accounts Management API
```typescript
{
    with: [''], //Anything that your client needs
    user_id: 1 //Or anything else required for given endpoint
}
```
+ `config` `optional` can be used to override defaults
```typescript
{
    method?: string; //Default: 'POST'
    urlQuery?: string | Array<string>; //Default: ''
    params?: object; //Default {}
    headers?: object; //Default { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }
}
```
##### Return
```typescript
interface Response {
    data: any,
    status: number | null,
    success: boolean,
    messages: { [key: string]: Array<string> },
    error: {} | null
}
```