Skip to content

Type Alias: FetchInterceptorResult<Args>

FetchInterceptorResult<Args> = Interceptor<unknown, Args>

Defined in: packages/fetch/src/types/interceptors.ts:179

Fetch result interceptor to be invoked before returning parsed fetch result.

Result interceptors are executed ONLY when a result is successfully parsed (as ArrayBuffer, Blob, JSON, Text...). Result interceptors WILL NOT be executed if:

  • return type is set to Response by using FetchAs.response in the FetchOptions.as
  • exceptions is thrown even before attempting to parse
  • parse fails

This interceptor can also be used as a transformer by returns a different/modified result.

Type Parameters

Args

Args extends unknown[] = FetchArgsInterceptor

Example

Intercept and transform fetch result

javascript
import fetch from '@superutils/fetch'

// first transform result (user object) and ensure user result alwasy contain a hexadecimal crypto balance
const ensureBalanceHex = (user = {}) => {
  user.crypto ??= {}
  user.crypto.balance ??= '0x0'
  return user
}
// then check convert hexadecimal number to BigInt
const hexToBigInt = user => {
  user.crypto.balance = BigInt(user.crypto.balance)
  return user
}
// then log balance (no transformation)
const logBalance = (result, url) => {
  // only log balance for single user requests
  const shouldLog = result?.hasOwnProperty('crypto') && /^[0-9]+$/.test(
    url?.split('/users/')[1].replace('/', '')
  )
  shouldLog && console.log(
    new Date().toISOString(),
    '[UserBalance] UserID:', result.id,
    result.crypto.balance
  )
}
// now we make the actaul fetch request
const result = await fetch.get('[DUMMYJSON-DOT-COM]/users/1', {
  interceptors: {
    result: [
	     ensureBalanceHex,
	     hexToBigInt,
	     logBalance
	   ]
  }
})
console.log({result})