gavins-cool-api-helper
v0.0.4
Published
Just some helper utilities
Downloads
1
Readme
api-helper
Just some clientside-friendly utilities for using APIs.
Quick start example
/**
* Create the API instance with default origin and headers
*/
const origin = 'https://mydomain.com'
const defaultHeaders = {'x-tracking-id' : 'aaa-bbb-ccc-ddd'}
const api = new API(origin, defaultHeaders)
/**
* Create a custom type and add a formatter to always return it.
*/
type MyResponse = {
status: number
message: string
success: boolean
data: unknown
}
api.formatResponse(async res => {
const json = await res.json()
const data: MyResponse = {
status: res.status,
message: res.ok ? json.message : 'something went wrong',
success: res.ok,
data: json
}
return data
})
/**
* Now we can make typed API requests
*/
const userResponse = await api.GET<MyResponse>('/api/users/1234')
if(userRespnose.success){
handleSuccess(userResponse.data)
}else{
handleFailure(userResponse.data, userResponse.status)
}
Construction
When creating the class you can pass in optional base origin and headers that will be used for every request.
Note that if not provided the base origin will be window.location.origin
.
Default headers always include Accept
and Content-Type
set to application/json
unless overriden.
The default fetcher used is the global fetch
or window.fetch
. If neither of these
are available, one should be provided in the constructor or by using .setFetch()
Example
import { fetch as fetcher} from 'node-fetch'
const origin = 'https://mydomain.com'
const headers = {'x-tracking-id' : 'aaaaa-bbbbb-ccccc-ddddd'}
const api = new API(
origin, // default: window.location.origin
headers, // default: application/json accept & content-type headers
fetcher // default: fetch ?? window.fetch
)
Methods
.setFetch(fetch: FetchFunc): API
Optionally set the fetcher for the instance.
For example if you are using the class in an environment where window.fetch
is
not available
Example
api.setFetch(require('fetch'))
const res = await api
.GET('/api/users/1234)
.setHeaders(headers: ApiHeaders): API
Add / Overwrite the default headers that are used on every request. Useful if you need to add headers after some requests are already made.
Example
const api = new API('https://mydomain.com')
// request some authorisation tokens
const authResponse = await api
.withJson({grant_type: 'authorization_code', client_id, client_secret})
.POST('/api/auth/tokens')
const tokens = await authResponse.json()
// set the token in the header so all subsequent requests will use it automatically
api.setHeaders({authorization: `Bearer ${tokens.access_token}`})
// now we can use endpoints that require auth headers to be used
const userResponse = await api.GET('/api/users/1234')
const userDetails = await userResponse.json()
.formatResponse(callback: ResponseFormatter): void
Optionally configure the shape of the response returned after making a request.
If not used, the returned response is always the fetch Response type.
Example
// ...
type MyResponse = {
response: Response
status: number
message: string
}
api.formatResponse(async res => {
const json = await res.json()
const data: MyResponse = {
response: res,
status: res.status,
message: res.ok ? 'success' : 'failure',
}
})
// ...
.withHeaders(headers: ApiHeaders): API
Sets the headers for this request only.
This is in addition to the default headers.
Example
const response = api
.withHeaders({Authorization: `Bearer ${authToken}`})
.GET('/api/users/1234')
.withParams(params: GetParams): API
Sets the query string parameters for this request.
Example
const response = api
.withParams({include: 'email,firstName,lastName'})
.GET('/api/users/1234')
.withJson(body: JsonBody): API
Sets the json body for this request.
Example
const response = api
.withJson({firstName: 'Alice', lastName: 'Aardvark'})
.POST('/api/users')
.rawBody(body: string): API
Sets a raw body to be used for this request.
Example
const response = api
.withHeaders({'content-type': 'text/html; charset=utf-8'})
.rawBody('<p class="user-bio">This is some content to save! 🤣<p>')
.POST('/api/users/1234/bio')
.<T>DELETE|GET|POST|PUT|PATCH(url: string): Promise<CustomResponse<T>>
Makes the actual request with the given method.
Note that if you provided a type you can type the response!
Example
const res = await api
.withJson({email: '[email protected]', username: 'Big Babs'})
.POST<MyResponse>('/api/users')
if(res.status === 201){
console.log(res.message) // "user created!"
}