got#RequestError TypeScript Examples

The following examples show how to use got#RequestError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: viera.ts    From homebridge-vieramatic with Apache License 2.0 5 votes vote down vote up
#post = async <T>(
    requestType: RequestType,
    realAction: string,
    realParameters = 'None',
    closure: (arg: string) => Outcome<T> = (x) => x as unknown as Outcome<T>
  ): Promise<Outcome<T>> => {
    let [action, parameters]: string[] = []
    let payload: Outcome<T>, reset: Outcome<void>
    const [sessionGone, isCommand] = ['No such session', requestType === 'command']
    const [urL, urn] = isCommand
      ? [VieraTV.NRC, VieraTV.RemoteURN]
      : [VieraTV.DMR, VieraTV.RenderingURN]

    const doIt = async (): Promise<Outcome<T>> => {
      if (this.specs.requiresEncryption && isCommand && !VieraTV.plainText.includes(realAction)) {
        const outcome = await this.#renderEncryptedRequest(realAction, urn, realParameters)

        if (Ok(outcome)) [action, parameters] = outcome.value
        else return outcome
      } else [action, parameters] = [realAction, realParameters]

      return (await this.#client(urL, this.#renderRequest(action, urn, parameters))
        .then((r) => {
          const replacer = (_match: string, _offset: string, content: string): string =>
            this.#decryptPayload(content, this.#session.key, this.#session.iv)
          const value = r.body.replace(/(<X_EncResult>)(.*)(<\/X_EncResult>)/g, replacer)

          return { value }
        })
        .catch((error: RequestError) =>
          error.response?.statusCode === 500 && error.response.statusMessage?.includes(sessionGone)
            ? { error: Error(sessionGone) }
            : { error }
        )) as Outcome<T>
    }

    if (Abnormal((payload = await doIt())))
      if (payload.error.message === sessionGone) {
        this.log.warn('Session mismatch found; The session counter was reset in order to move on.')
        if (Abnormal((reset = await this.#requestSessionId()))) return reset
        if (Abnormal((payload = await doIt()))) return payload
      } else return payload

    return closure(payload.value as unknown as string)
  }