Skip to content

Commit

Permalink
garden: cleanup readme, better naming
Browse files Browse the repository at this point in the history
  • Loading branch information
duncangrubbs committed May 1, 2024
1 parent 6d729de commit 83e5747
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 25 deletions.
33 changes: 17 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,26 @@ Ozzzy is a interface for interacting with HTTP APIs from Javascript clients. It

### REST Methods

Ozzzy is similar to [axios](https://axios-http.com/docs/intro) in that is provides a core set of functions for making HTTP requests. You start by constructing an `Api` for a specific backend service that your client needs to interact with. For example
Ozzzy is similar to [axios](https://axios-http.com/docs/intro) in that is provides a core set of functions for making HTTP requests. You start by constructing an `HttpApi` for a specific backend service that your client needs to interact with. For example

```typescript
import { Api } from 'ozzzy'
import { HttpApi } from 'ozzzy'

const userService = new Api('/api/v1/users')
const userService = new HttpApi('/api/v1/users')
```

All the arguments to the constructor are optional, but you can provide a base URL if HTTP requests made with this service have one in common. You can also optionally pass a AuthProvider implementation, a set of shared headers, and a set of middleware functions.

This service now has a similar API to axios. For example to make a `GET` request

```typescript
import { handleErrors } from 'ozzzy'

try {
const userResponse = await userService.get<ResponseType>('/region/europe')
const userResponse = await userService.get<ResponseType>(
'/region/europe',
handleErrors,
)
} catch (error) {
console.error(error)
}
Expand All @@ -40,23 +45,19 @@ try {
Under the hood this builds the request headers and options, sends the fetch request, applies all of your middleware functions to the response and returns you the final result. Ozzzy supports `GET`, `PUT`, `POST`, and `DELETE`. For REST requests that support a body payload, you can pass any JSON serializable object as part of the request. For example

```typescript
try {
const newUser = await userService.post<User>('/users/new', { name: 'Jane' })
} catch (error) {
console.error(error)
}
const newUser = await userService.post<User>('/users/new', { name: 'Jane' })
```

### Auth

To send an authorization HTTP header, you could simply build the header adn pass it to the `Api` constructor. That being said, it's recommended to either use the `OzzzyAuth` provider, or write your own provider that implements the `AuthProvider` interface. This way, different instances of `Api` can share the same `AuthProvider` instance. If you use `OzzzyAuth`, it supports a few basic auth schemes out of the box like `Bearer` and `Basic`. To use an `AuthProvider` instance, pass it to the constructor like so
To send an authorization HTTP header, you could simply build the header and pass it to the `HttpApi` constructor. That being said, it's recommended to either use the `OzzzyAuth` provider, or write your own provider that implements the `AuthProvider` interface. This way, different instances of `Api` can share the same `AuthProvider` instance. If you use `OzzzyAuth`, it supports a few basic auth schemes out of the box like `Bearer` and `Basic`. To use an `AuthProvider` instance, pass it to the constructor like so

```typescript
import { OzzzyAuth } from 'ozzzy'
import { HttpApi, OzzzyAuth, AuthTypes } from 'ozzzy'

const auth = new OzzzyAuth(AuthTypes.Bearer, userToken, 'Authorization')

const service = new Api('/api/v1', auth)
const service = new HttpApi('/api/v1', auth)
```

This code configures the service to send the provided token in the `Authorization` header. The `AuthType` determines the format of this header. In this case the header would look like
Expand All @@ -70,15 +71,15 @@ Authorization: Bearer YOUR_TOKEN
At the core of Ozzzy is the concept of middleware. This can be applied at the service level or the request level. Middleware intercepts the `Response` object, does something to it, and then passes it to the next middleware. It is important to keep in mind that order matters.

```typescript
const middlewareOne = (data) => {
const middlewareOne = async (data) => {
// do something to the response data
// of all requests made with this service
return data
}

const myService = new Api('/api/v1', undefined, [], middlewareOne)
const myService = new HttpApi('/api/v1', undefined, [], middlewareOne)

const middlewareTwo = (data) => {
const middlewareTwo = async (data) => {
// do something to the response data that is
// specific to this request
return data
Expand All @@ -98,7 +99,7 @@ fetch('https://some-url', headers, ...options)
// finally return the response
```

With Ozzzy, you can write a middleware function once, and then apply it at the service level or request level. Out of convenience, ozzzy comes with a few middlewares out of the box. Of course it is your choice if you want to apply these middlewares, but they are already written so that you do not have write them yourself. These include a middleware to parse the response as JSON, a basic logger, and a middleware to check the status code of the response and reject the promise if the `Response.ok` field is `false`.
With Ozzzy, you can write a middleware function once, and then apply it at the service level or request level. Out of convenience, Ozzzy comes with a few middlewares out of the box. Of course it is your choice if you want to apply these middlewares, but they are already written so that you do not have write them yourself. These include a middleware to parse the response as JSON, a basic logger, and a middleware to check the status code of the response and reject the promise if the `Response.ok` field is `false`.

## Testing Locally

Expand Down
10 changes: 5 additions & 5 deletions src/examples/basic.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
Api,
HttpApi,
hydrateDates,
checkStatus,
handleErrors,
toJson,
logger,
loggerUtil,
Expand All @@ -16,7 +16,7 @@ type ApiResponse = {
completed: boolean
}

const api = new Api(
const api = new HttpApi(
baseUrl,
undefined,
[],
Expand All @@ -25,7 +25,7 @@ const api = new Api(
You can apply your middleware here.
*/
logger,
checkStatus,
handleErrors,
)

/**
Expand Down Expand Up @@ -59,7 +59,7 @@ async function run() {

loggerUtil.debug('request 2')
try {
await api.get(api.buildUrl('/todos/sadfsf'), sampleMiddleware)
await api.get(api.buildUrl('/todos/sadfsf'))
} catch (error) {
console.error(error)
}
Expand Down
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
hydrateDates,
checkStatus,
handleErrors,
logger,
toJson,
} from './middleware/index.js'
Expand All @@ -12,13 +12,13 @@ import { RestMethods } from './shared-types/rest-methods.enum.js'
import { logger as loggerUtil } from './utils/logger.js'

export {
HttpApi as Api,
HttpApi,
Auth,
RestMethods,
type Middleware,
AuthTypes,
hydrateDates,
checkStatus,
handleErrors,
logger,
toJson,
loggerUtil,
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { hydrateDates } from './dates.middleware.js'
export { handleErrors as checkStatus } from './error-handler.middleware.js'
export { handleErrors } from './error-handler.middleware.js'
export { logger } from './logger.middleware.js'
export { toJson } from './json.middleware.js'

0 comments on commit 83e5747

Please sign in to comment.