Skip to content

Add usage examples for middleware to README #14

@ondrejsevcik

Description

@ondrejsevcik

Add practical usage examples to the README demonstrating how to use the library with various middleware patterns. The following examples should be included:


Use case: Console logging / error reporting tool

const logToConsole: MiddlewareFn = (next) => (request) => {
    console.log("Request", request);

    return next(request).then(async (response) => {
        console.log("Response", response);
        return response;
    });
};

Use case: Add authentication token to requests

const addCustomHeader = (next: RequestFetchLike) => (request: Request) => {
	const token = getToken();
	request.headers.set('authentication', `Bearer ${token}`);
  return next(request);
}

Use case: Throw error on 4xx or 5xx response

const errorOnNotOkResponse = (next: RequestFetchLike) => (request: Request) => {
  return next(request).then(async response => {
    if (!response.ok) {
      throw new Error(`Response status ${response.status}`);
    }
    return response;
  });
}

Use case: Refresh token on 401 Unauthorized response

const refreshTokenOnUnauthorizedResponse = (next: FetchLike) => (request: Request) => {
	let hasRetried = false

	return next(request).then(async (response) => {
		if (response.status === 401 && !hasRetried) {
			hasRetried = true

			await refreshToken();
			// Replay the request one more time
			return next(request)
		}
		return response
	})

Use case: Retry with delay on first fail

const retry = (timeout: number) => (next: Next) => (request: Request) => {
  const checkIfFail = async request => !request.ok ? throw new Error('retry') : request
  let retried = false;
  const retry = async (error) => {
    if (retried) return error;
    retried = true;
    // wait a bit
    await timeout(timeout);
    // Replay the request
    return next(request);
  } 
  return next(request).then(checkIfFail).catch(retry);
}

These examples will help users understand how to leverage middleware for common use cases such as logging, authentication, error handling, token refresh, and retries.

Metadata

Metadata

Assignees

Labels

documentationImprovements or additions to documentation

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions