Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/is-error-like-response / src / fromGraphqlOrAnyToResponse.ts
Size: Mime:
import { isObj } from 'exotic'
import { GraphQueryLanguageObj, CommonStreamOrchestrationResponse } from './typings'

export const isGraphQueryLanguage = (x: any): x is GraphQueryLanguageObj =>
  isObj(x) && isObj((x as any).data)

export const EMPTY_ERROR_RESPONSE = Object.freeze({
  responseCode: Infinity,
  responseMessage: 'failure @@EMPTY',
})

// { response: state: status }
// { data: cart: response: state: status }
// Object.keys(response).length <= 1 => with gql this is always true
// so it needs to handle that
export function fromGraphqlOrAnyToResponse(x: any): CommonStreamOrchestrationResponse {
  if (isGraphQueryLanguage(x)) {
    if (x.error) {
      console.error('[isErrorLikeResponse] response had .error')
      return EMPTY_ERROR_RESPONSE
    }

    // example:
    // { data: { cart: { } } } => cart
    const found = Object.keys(x.data).pop()

    /**
     * means we have a .data that is empty obj
     */
    if (found === undefined) {
      console.error('[isErrorLikeResponse] obj had .data that was empty')
      return EMPTY_ERROR_RESPONSE
    } else {
      const response = x.data[found]

      if (response === undefined) {
        console.error('[isErrorLikeResponse] obj had .data with the first key that had an invalid value')
        return EMPTY_ERROR_RESPONSE
      } else {
        return response
      }
    }
  } else {
    return x
  }
}