# @byu-oit-sdk/client

An OAuth 2.0-compliant library, effectively replacing [byu-wso2-request](https://github.com/byu-oit/byu-wso2-request).

**Requirements**:

- Node.js 18+
  - or Node.js 10+ with fetch and crypto polyfills
- npm v9+

### Features

- Isomorphic (work in Node.js and the browser)
- Automatically fetches and refreshes access tokens
- Automatic retries for 401 responses with a 100ms delay
- Automatically add headers to help identify the request
    - `byu-oit-sdk-request` supplies the attempt number and maximum number of requests
    - `byu-oit-sdk-invocation-id` supplies a unique identifier to track requests

## Client

Initializing the client is simple. The Client can be configured with some options to override the default behavior if desired. Many of the configurations can be supplied via environment variables.

```typescript
const client = new Client({ /* options here */ })
```
Here are a list of supported options:

| Option      | Type                                                                                                         | Default Value                                                                                                                             | Purpose                                                                                                                                           |
|-------------|--------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------|
| logger      | `Logger`, from pino                                                                                          | [`ByuLogger()`](https://www.npmjs.com/package/@byu-oit/logger)                                                                            | *(Optional)* Logging information from client functionality                                                                                        |
| credentials | [`CredentialProvider`](https://byu-oit-sdk.github.io/javascript/modules/Credential_Provider.html) (or false) | [`ChainedCredentialProvider()`](https://byu-oit-sdk.github.io/javascript/modules/Credential_Provider.html#md:chained-credential-provider) | *(Optional)* The credential provider used resolving access tokens                                                                                 |
| retry       | [`RetryMiddlewareConfiguration`](https://byu-oit-sdk.github.io/javascript/modules/Middleware_Retry.html)     | `{ strategy: new RetryStrategy() }`                                                                                                       | *(Optional)* Configures the retry middleware. The default configuration will attempt one retry when the response contains a 401 HTTP status code. |

> [!IMPORTANT]
> The default credential provider is
> the [Chained Credentials provider](https://byu-oit-sdk.github.io/javascript/modules/Credential_Provider.html) which
> searches the environment for variables with the prefix `BYU_OIT_` and guesses which type of provider it should
> instatiate based on what it can find. If a specific credential provider is needed, it should be configured and
> passed into the Client constructor.

The default retry strategy retries once on 401 HTTP response codes after a 100-millisecond delay. The token middleware
will try to get a new token before the request is sent. Any middleware added after the retry middleware will also be
invoked prior to each request retry.

> [!TIP]
> Disable automatic authentication and retries by setting the credentials option to false.
> ```typescript
> const client = new Client({credentials: false})
> ```

> [!TIP]
> You can specify a custom credential provider prefix. Otherwise, it defaults to looking for environment variables
> with the prefix "BYU_OIT_".
> ```typescript
> const client = new Client({credentials: ClientCredentialsProvider.fromEnv('OAUTH_')})
> ```

## FetchCommand

The `FetchCommand` class is a utility for passing options directly to the `fetch` function. To instantiate a
`fetch` command, use the same options as the [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).

```ts
import { Client, FetchCommand } from '@byu-oit-sdk/client'

/** Instantiate the client with environment variables */
const client = new Client()

/** The issuer must be downloaded from the discovery endpoint */
const issuer = await client.issuer()
const uri = new URL('echo/v1/echo/test', issuer) // i.e. https://api.byu.edu/echo/v1/echo/test
const command = new FetchCommand(uri/**, Addtional fetch options */)

/** Send the command */
const response = await client.send(command)
```

You may also invoke the equivalent `fetch` method on the client to accomplish the same result.

```ts
import { Client, Command } from '@byu-oit-sdk/client'

/** Instantiate the client with environment variables */
const client = new Client()

/** The issuer must be downloaded from the discovery endpoint */
const issuer = await client.issuer()
const uri = new URL('echo/v1/echo/test', issuer) // i.e. https://api.byu.edu/echo/v1/echo/test

/** invoke the fetch method */
const response = await client.fetch(uri)
```

# Contributing

The main components underlying the BYU SDK are clients, commands, and middleware. Understanding each is crucial for
troubleshooting problems, creating new SDKs, or extending an existing SDK.

## Client

Simply put, the client is the actuator of a request. Every client has a `send` function which serializes requests and
deserializes responses. A client represents a set of commonly grouped endpoints. These endpoints usually share the same
base path or are hosted by the same web server.

For a usage example, [see above](#usage).

## Command

Commands represent a single HTTP request. The input of a command is an object that should include all the necessary
parameters that a user might want to specify to customize the HTTP response. The output of a command is a deserialized
representation of the raw HTTP response, usually taking the form of a class instance or an object whose shape is
well-defined. When a non-2xx response code is received, an error is thrown. Response errors should extend the [built-in
HttpResponseError](#httpresponseerror).

Using commands abstracts the complexity of formatting HTTP requests, and validating responses away from developers.

## Middleware

The Middleware facilitates the stages of the middleware stack. To learn more about the middleware stack, read
[Introducing Middleware Stack in Modular AWS SDK for JavaScript](https://aws.amazon.com/blogs/developer/middleware-stack-modular-aws-sdk-js/).

[Middleware](https://byu-oit-sdk.github.io/javascript/modules/Middleware_Stack.html) can be placed on the middleware stack on a command or client. If placed on the command's
middleware stack, only that command will run the middleware. When placed on the client, all commands using that client
instance will run the middleware.

## Creating Clients

Maintaining a client helps consumers implement HTTP requests to your web service without needing to know how to format
the request, handle pagination, or gracefully respond to intermittent service outages.

New clients may be added under the `/clients` directory. Clients should extend this package by adding serializer and
deserializer middleware to their commands. A client must extend and export a Client class and every Command class that
the client supports. The client *SHOULD* make those commands available as methods on the client. There are several good
examples of this in the `/clients` directory that you may use for reference.

> [!TIP]
> You do not have to create a stand-alone client to use this package or write commands as long as your web service supports
> authentication as defined in the OAuth 2.0 and OpenID Connect specifications. Instead, import the client,
> write your own commands within you project and pass them into the send function!
>
> (...but sharing is caring! So, consider publishing commands for the web services you expose)

### Client Nomenclature & Versioning

Clients should follow the naming scheme `@byu-oit-sdk/client-*`. For example, a client for the Workday APIs could be named
`@byu-oit-sdk/client-workday`. Clients outside the byu-oit-sdk organization should still follow the naming schema with a
different namespace. The class should follow the naming schema `[ApiName]Client` (e.g. `WorkdayClient`).

Commands should also follow the same naming schema `[CommandName]Command` but the method name on the client class should
follow the camelcase convention of `[commandName]` (e.g. `getPerson`).

API versioning strategies vary widely. Regardless, supplying an SDK helps developers consider version management, and may help
alleviate growing pains as APIs evolve. Whatever strategy you choose, make sure to thoroughly document which versions of your
SDK work with the endpoints in your web service.

### HttpResponseError

Any HTTP Error should be thrown by the client. It is not acceptable to return the error because the `Input` and `Output`
types are deserialized and simplified forms of the fetch `Request` and `Response`. It saves the developer the hassle of
serializing, parsing, and type checking/narrowing when we only return one type and throw non-2xx responses.

#### Exceptional Error Cases

Sometimes, it may be completely acceptable to receive a `404` response in a particular application. In that case, the
client should define a `NotFoundError` which the consuming developer may choose to handle by returning null. In this
case the function return type would be `Output | null` as shown in the example below.

```typescript
import { UpdateExampleCommand, UpdateExampleOutput } from '@byu-oit-sdk/client-example'
async function setFooToBar (): UpdateExampleOutput | null {
  const command = new UpdateExampleCommand({ foo: 'bar' })
  return client.send(command).catch(e => {
    if (e instanceof NotFoundError) return null
    throw e // or handle other errors
  })
}
```

Alternatively, you could use the functional style.

```typescript
import { UpdateExampleOutput } from '@byu-oit-sdk/client-example'
async function setFooToBar (): UpdateExampleOutput | null {
  return client.updateExampleCommand({ foo: 'bar' }).catch(e => {
    if (e instanceof NotFoundError) return null
    throw e // or handle other errors
  })
}
```
