Class

ApiInterface

ApiInterface(config)

This is the parent class for all API interfaces. An API interface is the connection between your React web app and a remote JCU API.

From this class, API interfaces inherit the ability to manage a base url, have transient headers (such as user tokens) automatically added to url requests, and can call convenience functions like getData and postData.

Use this ApiInterface by:

  • Creating a new API interface class that extends this ApiInterface parent class (see example below)
  • Setting static values interfaceName and interfaceVersion in your new class
  • Defining your interface's configuration in your application's config file (see appConfigSchema.js for info about API interface configurations)
  • Importing your new interface into ApiManager and calling addInterface to add it to the library of API interfaces.

Once you've done these steps, your new interface will be available from the ApiManager's getApiInterface, retrievable using the interfaceName and interfaceVersion you gave it.

Example API interface using this parent class

import { deepMerge } from 'grommet/utils'
import { ApiInterface } from '@jcu/spark'

class ExampleInterface extends ApiInterface {
    static interfaceName = 'example-api'  // name of this API interface
    static interfaceVersion = '0.1.0'     // version of this interface implementation

    // Optional defaults for configuration.
    // Items specified here can be overridden from the
    // config file.
    static defaultConfig = {
        dateFormat: "YYYY-MM-DDThh:mm"
    }

    constructor(config) {
        const superConfig = deepMerge(ExampleInterface.defaultConfig, config)
        super(superConfig)
    }

    // API-specific action (fetching Examples)
    // should (almost) always be asynchronous
    async fetchExampleData(options = {}) {
        let exampleData = this.getData('')
        .then( (response) => {
             let info = response.data
             // do data manipulation here, e.g. sorting, filtering...
             return info
        })
        .catch( (e) => {
             console.log('problem getting data: ', e)
             return e
        })

        return exampleData
    }
}
export default ExampleInterface

Mocking API Responses

It's common to mock API data like this:

    // ... inside your getInfo(...) function:
    return delayedResult({
         data: {
             id: userId,
             name: 'Pierce Hawthorne',
             dob: '1944/11/27'
         }
    }, 5)

The above returns a promise (similar to regular API fetches) that resolves after 5 seconds (+- 2.5 seconds)

Future Direction

Potentially, non-RESTful interfaces like GraphQL or streaming connections might require alternative architectures; one option would be that this becomes the base class for RESTful APIs, there is another base class for graph APIs, and a common super parent for those which handles the common concerns like header management.

Constructor

# new ApiInterface(config)

The ApiInterface constructor. Takes a configuration object.

Parameters:
Name Type Description
config Object

API interface configuration details. Schema in appConfigSchema.js

url string

Base URL for the HTTP(S) endpoint

options ApiInterface#options

Additional configuration parameters

View Source interfaces/ApiInterface.ts, line 98

Classes

ApiInterface

Members

string

# abstract static interfaceName

The string identifier for this API interface. You will use this, along with interfaceVersion, to retrieve an interface from the API library in your React app. Use dash-separated, all-lower-case words, e.g. 'eop-schedule', 'web-app-config'

View Source interfaces/ApiInterface.ts, line 411

string

# abstract static interfaceName

The string identifier for this API interface. You will use this, along with interfaceVersion, to retrieve an interface from the API library in your React app. Use dash-separated, all-lower-case words, e.g. 'eop-schedule', 'web-app-config'

View Source interfaces/ApiInterface.ts, line 445

# abstract static interfaceVersion

Version number (in string format) for this edition of this API interface. You will use this, along with interfaceName, to retrieve an interface from the API library in your React app. Use a three-value semver style version e.g. '1.2.3'

View Source interfaces/ApiInterface.ts, line 419

string

# abstract static interfaceVersion

Version number (in string format) for this edition of this API interface. You will use this, along with interfaceName, to retrieve an interface from the API library in your React app. Use a three-value semver style version e.g. '1.2.3'

View Source interfaces/ApiInterface.ts, line 454

Map.<string, string>

# transientHeaders

A Map of transient headers that get attached to axios connections when the interface is retrieved.

Most commonly used for authentication headers, to attach and remove auth tokens during login / logout

View Source interfaces/ApiInterface.ts, line 469

Methods

# addError(errorDescription)

Adds an error to the interfaces error list

Parameters:
Name Type Description
errorDescription String

A description of the error

View Source interfaces/ApiInterface.ts, line 129

# connect()

"Connect" the interface to the configured API endpoint. This does not open an actual network connection, it only creates an Axios connection object that will be used to handle any requests.

View Source interfaces/ApiInterface.ts, line 160

# delayedResult(data, delayopt, fixedDelayopt)

A utility function returning a Promise that will be fulfilled by data after a duration of roughly delay seconds. delay will be 3 seconds if not supplied.

By default the delay will vary randomly between 0.5 * delay and 1.5 * delay (±50%).

If you don't want the delay length to randomly vary, supply true as the third argument, fixedDelay. Use this to mock out returning results asynchonously from your API calls, for example:

async getUserInfo(userId) {
    // mock data for now
    return delayedResult({
         data: {
             id: userId,
             name: 'Pierce Hawthorne',
             dob: '1944/11/27'
         }
    })
}

NOTE: For your benefit, it's best to try and match the response data to the expected response from the API. For most JCU APIs, this usually means including a data key as a wrapper for your data (as the APIs tend to return their answers in a data key, see below).

{
    data: {
        ...
    }
}
Parameters:
Name Type Attributes Default Description
data *

The data you want returned after the delay

delay number <optional>
3

Time (in seconds) to delay returning the response

fixedDelay boolean <optional>
false

Flag to set the delay to fixed instead of +- 50%

View Source interfaces/ApiInterface.ts, line 367

# async delete(path, optionsopt) → {Promise.<AxiosResponse>}

A convenience method that performs a DELETE request to the API endpoint and directly returns the response that carried that data.

Note that unlike some other methods, there is no data argument; if you need to send data with your DELETE call, supply the data structure in options.data.

This uses query in the background.

Parameters:
Name Type Attributes Description
path string

Trailing path for the request

options ApiInterface#options <optional>

// TODO: Future implementation

data * <optional>

JSON data to be sent by the request

View Source interfaces/ApiInterface.ts, line 315

the response to the DELETE call

Promise.<AxiosResponse>

# async getData(path, paramsopt, optionsopt) → {Promise.<AxiosResponse>}

A convenience method that performs a GET request to the API endpoint and directly returns the response that carried that data.

This uses query in the background.

Parameters:
Name Type Attributes Description
path string

Trailing path for the request

params * <optional>

Extra query params for the request

options ApiInterface#options <optional>

// TODO: Future implementation

View Source interfaces/ApiInterface.ts, line 225

the response to the GET call

Promise.<AxiosResponse>
Example
```
    const {data, status} = await getData(url)
    if (status >= 200 && status < 300) { console.log('all good') }
```

# async patchData(path, dataopt, optionsopt) → {Promise.<AxiosResponse>}

A convenience method that performs a PATCH request to the API endpoint and directly returns the server's response.

This uses query in the background.

Parameters:
Name Type Attributes Description
path string

Trailing path for the request

data * <optional>

JSON data to be sent by the request

options ApiInterface#options <optional>

// TODO: Future implementation

View Source interfaces/ApiInterface.ts, line 291

the response to the PATCH call

Promise.<AxiosResponse>

# async postData(path, dataopt, optionsopt) → {Promise.<AxiosResponse>}

A convenience method that performs a POST request to the API endpoint and directly returns the server's response to the POST request.

Parameters:
Name Type Attributes Description
path string

Trailing path for the request

data * <optional>

JSON data to be sent by the request

options ApiInterface#options <optional>

//TODO: Future implementation

View Source interfaces/ApiInterface.ts, line 251

the response to the POST call

Promise.<AxiosResponse>
Example
```
    const {status} = await getData(url, postData)
    if (status >= 200 && status < 300) { console.log('posted') }
```

This uses query in the background.

# async putData(path, dataopt, optionsopt) → {Promise.<AxiosResponse>}

A convenience method that performs a PUT request to the API endpoint and directly returns the server's response to the PUT request.

This uses query in the background.

Parameters:
Name Type Attributes Description
path string

Trailing path for the request

data * <optional>

JSON data to be sent by the request

options ApiInterface#options <optional>

// TODO: Future implementation

View Source interfaces/ApiInterface.ts, line 271

the response to the PUT call

Promise.<AxiosResponse>

# async query(requestConfig) → {Promise}

Make a HTTP request to the configured API endpoint. Uses Axios library.

Parameters:
Name Type Description
requestConfig Request

An Axios config object for the HTTP request

View Source interfaces/ApiInterface.ts, line 174

(A Promise that resolves to) the API response

Promise

# transientHeadersListener(header, value)

Listener function for adding and removing transient headers. Generally you won't need to use this method yourself -- it's used internally by the OIDC context to attach and remove transient headers like OIDC user tokens.

Parameters:
Name Type Description
header *

The header to set or remove

value string

The value of the header

View Source interfaces/ApiInterface.ts, line 144

Type Definitions

Object

# options

This object provides extended functionality to the ApiInterface class methods

Properties:
Name Type Description
headers Object

A JSON key/value set of HTTP headers

View Source interfaces/ApiInterface.ts, line 388

Object

# options

This object provides extended functionality to the ApiInterface class methods

Properties:
Name Type Description
headers Object

A JSON key/value set of HTTP headers

View Source interfaces/ApiInterface.ts, line 428

Object

# status

The current status of the ApiInterface

Properties:
Name Type Description
inflight number

The number of currently in-flight requests

errors array

An array of the errors "raised" by the API interface

View Source interfaces/ApiInterface.ts, line 107

Object

# status

The current status of the ApiInterface

Properties:
Name Type Description
inflight number

The number of currently in-flight requests

errors array

An array of the errors "raised" by the API interface

View Source interfaces/ApiInterface.ts, line 455