axios#AxiosTransformer TypeScript Examples

The following examples show how to use axios#AxiosTransformer. 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: ContentDeliveryAPI.ts    From foundation-lib-spa-core with Apache License 2.0 5 votes vote down vote up
public async invoke<TypeOut extends unknown = any, TypeIn extends unknown = any>(content: ContentReference, method: string, verb?: Method, data?: TypeIn, requestTransformer?: AxiosTransformer): Promise<ActionResponse<TypeOut | NetworkErrorData, IContent>>
    {
        if (!this._config.EnableExtensions) return Promise.reject('Extensions must be enabled to use the invoke method');

        // Base configuration
        const apiId = ContentLinkService.createApiId(content, !this.InEditMode, this.InEditMode);
        const url = new URL(this.MethodService + apiId + '/' + method, this.BaseURL);

        // Default JSON Transformer for request data
        const defaultTransformer : AxiosTransformer = (reqData, reqHeaders) => {
            if (reqData) {
                reqHeaders['Content-Type'] = 'application/json';
                return JSON.stringify(reqData);
            }
            return reqData;
        }

        // Axios request config
        const options : Partial<AxiosRequestConfig> = {
            method: verb,
            data,

            transformRequest: requestTransformer || defaultTransformer
        }

        const createActionErrorResponse = (error : NetworkErrorData) : ActionResponse<NetworkErrorData, NetworkErrorData> => {
            const actionResponse : ActionResponse<NetworkErrorData, NetworkErrorData> = {
                actionName: method,
                contentLink: error.contentLink,
                currentContent: error,
                responseType: ResponseType.ActionResult,
                data: error,
                language: this.Language,
                name: typeof(error.name) === "string" ? error.name : error.name.value,
                url: error.contentLink.url
            }
            return actionResponse;
        }

        // Run the actual request
        return this.doRequest<ActionResponse<TypeOut | NetworkErrorData, IContent>>(url, options)
                .then(r => isNetworkError(r) ? createActionErrorResponse(r) : r)
                .catch((e : Error) => {
                    const errorResponse = this.createNetworkErrorResponse(e);
                    return createActionErrorResponse(errorResponse);
                });
    }
Example #2
Source File: ContentDeliveryAPI.d.ts    From foundation-lib-spa-core with Apache License 2.0 5 votes vote down vote up
invoke<TypeOut extends unknown = any, TypeIn extends unknown = any>(content: ContentReference, method: string, verb?: Method, data?: TypeIn, requestTransformer?: AxiosTransformer): Promise<ActionResponse<TypeOut | NetworkErrorData, IContent>>;
Example #3
Source File: BackendApiClient.ts    From jitsu with MIT License 5 votes vote down vote up
private exec(
    method: Method,
    transform: AxiosTransformer,
    url: string,
    payload: unknown,
    options: ApiRequestOptions = { version: 1 }
  ): Promise<any> {
    const opts = { ...DEFAULT_OPTIONS, ...(options ?? {}) }
    const baseUrl = opts.proxy ? this.proxyUrl : this.baseUrl
    const baseUrlWithApiVersion = concatenateURLs(baseUrl, `/v${opts.version}/`)
    let fullUrl = concatenateURLs(baseUrlWithApiVersion, url)
    if (opts.urlParams) {
      fullUrl +=
        "?" +
        Object.entries(opts.urlParams)
          .filter(([, val]) => val !== undefined)
          .map(([key, val]) => `${key}=${encodeURIComponent(val + "")}`)
          .join("&")
    }

    const request: AxiosRequestConfig = {
      method: method,
      url: fullUrl,
      transformResponse: transform,
    }

    if (!opts.noauth) {
      request.headers = {
        "X-Client-Auth": this.apiAccessAccessor().accessToken,
      }
    }

    if (payload !== undefined) {
      if (method.toLowerCase() === "get") {
        throw new Error(`System UI Error: GET ${fullUrl} can't have a body`)
      }
      request.data = payload
    }
    return new Promise<any>((resolve, reject) => {
      axios(request)
        .then((response: AxiosResponse<any>) => {
          if (response.status == 200 || response.status == 201) {
            resolve(response.data)
          } else if (response.status == 204) {
            resolve({})
          } else {
            let error = new APIError(response, request)
            this.handleApiError(request, response)
            reject(error)
          }
        })
        .catch(error => {
          if (error.response) {
            this.handleApiError(request, error.response)
            reject(new APIError(error.response, request))
          } else {
            let baseMessage = "Request at " + fullUrl + " failed"
            if (error.message) {
              baseMessage += " with " + error.message
            }
            this.analyticsService.onFailedAPI({
              method: request.method,
              url: request.url,
              requestPayload: request.data,
              responseStatus: -1,
              errorMessage: baseMessage,
            })
            reject(error)
            reject(new Error(baseMessage))
          }
        })
    })
  }