1.3.11 • Published 2 months ago

@blockquote-web-components/ajax-provider v1.3.11

Weekly downloads
-
License
MIT
Repository
-
Last release
2 months ago

AJAX Provider Documentation

A class that provides AJAX functionality with event handling capabilities.

Table of Contents

Introduction

The AJAX Provider is a JavaScript class that provides AJAX functionality with event handling capabilities through EventTarget. It uses the AjaxProviderMixin, a mixin that leverages RxJS to manage AJAX requests efficiently.

Installation

To use the AJAX Provider, you need to install it as a package dependency.

npm install @blockquote-web-components/ajax-provider

Demo

Open in StackBlitz

Usage

Creating an Instance

To use the AJAX Provider, first, create an instance of the AjaxProvider class.

import { AjaxProvider } from '@blockquote-web-components/ajax-provider';

// A basic request configuration looks like this:
const ajaxProvider = new AjaxProvider({
  url: 'https://httpbin.org/get',
});
  // Default method
  method: 'GET',

  // Default request Headers.
  headers: {
    Accept: 'application/json, text/plain, *\/*; q=0.01',
    'Content-Type': 'application/json',
  }

Configuring AJAX Requests

You can configure your AJAX request by setting various options on the ajaxProvider instance. Here are some common configuration options:

const ajaxProvider = new AjaxProvider({
  url: 'https://httpbin.org/get',
  path: method.toLowerCase(),
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'rxjs-custom-header': 'Rxjs',
  },
  body: {
    rxjs: `Hi`,
  },
  includeDownloadProgress: true,
  includeUploadProgress: true,
});

Sending AJAX Requests

Once you have configured the AJAX request, you can send it using the generateRequest method. This method returns a promise that resolves with the AJAX response or attaching event listeners to handle various stages of the AJAX request.

const ajaxProvider = new AjaxProvider({
  url: 'https://api.github.com/users',
  queryParams: 'per_page=4',
});

ajaxProvider
  .generateRequest()
  .then(response => {
    console.log('Response:', response.response);
  })
  .catch(error => {
    console.log('Error:', error.message);
  });

Event Handling

The AJAX Provider allows you to handle events related to HTTP requests. You can listen to events such as:

  • 'presend' --> 'progress' --> 'response' --> 'responseend'
  • 'presend' --> 'error' --> 'errorend'

Here's how to set up event listeners:

const ajaxProvider = new AjaxProvider({
  url: 'https://api.github.com/users',
  queryParams: 'per_page=3',
});

ajaxProvider.addEventListener('ajaxpresend', ({ detail }) => {
  console.log('Preparing to send request...', detail);
});

ajaxProvider.addEventListener('ajaxprogress', ({ detail }) => {
  console.log(`Progress: ${detail.loaded} of ${detail.total} bytes`);
});

ajaxProvider.addEventListener('ajaxresponse', ({ detail }) => {
  const { response } = detail;
  console.log('Received response:', response);
});

ajaxProvider.addEventListener('ajaxresponseend', ({ detail }) => {
  console.log('End request:', detail);
});

ajaxProvider.addEventListener('ajaxerror', ({ detail }) => {
  const error = detail;
  console.log('Request error:', error.message);
});

ajaxProvider.addEventListener('ajaxerrorend', ({ detail }) => {
  console.log('End error:', detail);
});

ajaxProvider.generateRequest();

API Reference

Requests can be made by passing the relevant config to AjaxProvider.

Properties

Configuration for the RxJS/ajax creation function.

  • url: The base URL for the AJAX request. (string)
  • body: The request body. (*)
  • async: Whether or not to send the request asynchronously. (boolean)
    • Default value: true
  • method: The HTTP request method (e.g., GET, POST). (string)
    • Default value: GET
  • headers: Custom headers for the request. (Object|undefined)
    • Default value:
      • Accept: 'application/json, text/plain, \/; q=0.01'
      • Content-Type: 'application/json'
  • timeout: The request timeout in milliseconds. (number)
    • Default value: 0
  • user: The user for authentication. (string)
  • password: The password for authentication. (string)
  • withCredentials: Indicates whether to include credentials with the request. (boolean)
    • Default value: false
  • xsrfCookieName: The name of the XSRF cookie. (string)
  • xsrfHeaderName: The name of the XSRF header. (string)
  • responseType: The response type (e.g., 'json', 'text'). (string)
    • Default value: json
  • queryParams: The query parameters to include in the request URL. (Object|undefined)
  • includeDownloadProgress: Indicates whether to include download progress in the response. (boolean)
    • Default value: false
  • includeUploadProgress: Indicates whether to include upload progress in the response. (boolean)
    • Default value: false

Configuration AJAX Provider.

  • path: The path to append to the base URL. (string)
  • dispatchEventContext: The context for dispatching events. (AjaxProvider instance)
  • lastResponse: The last AJAX response object. (Object)
  • lastError: The last error object. (Object)
  • customEventPrefix: A custom event prefix for events related to HTTP requests. (string)
    • Default value: ajax
  • avoidBoundary: Set to true to stop delegating the use of boundaries for multipart requests to the browser. (boolean)
    • Only change this to true if you know what you are doing. Default value: false

Methods

  • generateRequest(): Generates and sends the AJAX request. This method can be used both with promises and by attaching event listeners to handle various stages of the AJAX request.

src/AjaxProvider.js:

class: AjaxProvider

Mixins
NameModulePackage
AjaxProviderMixin/src/AjaxProviderMixin.js
Fields
NamePrivacyTypeDefaultDescriptionInherited From
dispatchEventContextObjectthisThe context for dispatching events.
lastResponseObjectundefinedThe last AJAX response object.
lastErrorObjectundefinedThe last error object.
customEventPrefixstring'ajax'A custom event prefix for events related to HTTP requests.
avoidBoundarybooleanfalseSet to `true` to stop delegating the use of boundaries for multipart requests to the browser. Only change this to `true` if you know what you are doing.
urlstring''The base URL for the AJAX request.AjaxProviderMixin
pathstring''The path to append to the base URL.AjaxProviderMixin
body*undefinedThe request body.AjaxProviderMixin
asyncbooleantrueWhether or not to send the request asynchronously.AjaxProviderMixin
methodstring'GET'The HTTP request method (e.g., GET, POST).AjaxProviderMixin
_headersObject{ Accept: 'application/json, text/plain, */*; q=0.01', 'Content-Type': 'application/json', }The default headers for the request.AjaxProviderMixin
headersObject\|undefinedundefinedCustom headers for the request.AjaxProviderMixin
timeoutnumber0The request timeout in milliseconds.AjaxProviderMixin
userstring''The user for authentication.AjaxProviderMixin
passwordstring''The password for authentication.AjaxProviderMixin
withCredentialsbooleanfalseIndicates whether to include credentials with the request.AjaxProviderMixin
xsrfCookieNamestring''The name of the XSRF cookie.AjaxProviderMixin
xsrfHeaderNamestring''The name of the XSRF header.AjaxProviderMixin
responseTypestring''The response type (e.g., 'json', 'text').AjaxProviderMixin
queryParamsObject\|undefinedundefinedThe query parameters to include in the request URL.AjaxProviderMixin
includeDownloadProgressbooleanfalseIndicates whether to include download progress in the response.AjaxProviderMixin
includeUploadProgressbooleanfalseIndicates whether to include upload progress in the response.AjaxProviderMixin
Methods
NamePrivacyDescriptionParametersReturnInherited From
_assignAjaxProviderConfigAssigns configuration options to the AjaxProvider instance.config: Object
generateRequestGenerates and sends the AJAX request.Promise<any>AjaxProviderMixin
Methods
NamePrivacyDescriptionParametersReturnInherited From
_assignAjaxRxjsConfigprivateAssigns the configuration settings for the AJAX request.ObjectAjaxProviderMixin
_joinUrlDataprivateJoins the base URL and path to create the complete request URL.stringAjaxProviderMixin
_joinHeadersprivateJoins the default headers with custom headers.formDataObjectAjaxProviderMixin
_dispatchEventprivateDispatches a custom event with the specified type and payload.type: string, payload: *AjaxProviderMixin

Exports

KindNameDeclarationModulePackage
jsAjaxProviderAjaxProvidersrc/AjaxProvider.js

Mixin for providing AJAX functionality using RxJS. This mixin can be used to enhance classes with AJAX capabilities.

src/AjaxProviderMixin.js:

mixin: AjaxProviderMixin

Mixins
NameModulePackage
dedupeMixin@open-wc/dedupe-mixin
Parameters
NameTypeDefaultDescription
Base
Fields
NamePrivacyTypeDefaultDescriptionInherited From
urlstring''The base URL for the AJAX request.
pathstring''The path to append to the base URL.
body*undefinedThe request body.
asyncbooleantrueWhether or not to send the request asynchronously.
methodstring'GET'The HTTP request method (e.g., GET, POST).
_headersObject{ Accept: 'application/json, text/plain, */*; q=0.01', 'Content-Type': 'application/json', }The default headers for the request.
headersObject\|undefinedundefinedCustom headers for the request.
timeoutnumber0The request timeout in milliseconds.
userstring''The user for authentication.
passwordstring''The password for authentication.
withCredentialsbooleanfalseIndicates whether to include credentials with the request.
xsrfCookieNamestring''The name of the XSRF cookie.
xsrfHeaderNamestring''The name of the XSRF header.
responseTypestring''The response type (e.g., 'json', 'text').
queryParamsObject\|undefinedundefinedThe query parameters to include in the request URL.
includeDownloadProgressbooleanfalseIndicates whether to include download progress in the response.
includeUploadProgressbooleanfalseIndicates whether to include upload progress in the response.
Methods
NamePrivacyDescriptionParametersReturnInherited From
generateRequestGenerates and sends the AJAX request.Promise<any>
Methods
NamePrivacyDescriptionParametersReturnInherited From
_assignAjaxRxjsConfigprivateAssigns the configuration settings for the AJAX request.Object
_joinUrlDataprivateJoins the base URL and path to create the complete request URL.string
_joinHeadersprivateJoins the default headers with custom headers.formDataObject
_dispatchEventprivateDispatches a custom event with the specified type and payload.type: string, payload: *

Exports

KindNameDeclarationModulePackage
jsAjaxProviderMixinAjaxProviderMixinsrc/AjaxProviderMixin.js

src/index.js:

Exports

KindNameDeclarationModulePackage
jsAjaxProviderAjaxProvider./AjaxProvider.js
jsAjaxProviderMixinAjaxProviderMixin./AjaxProviderMixin.js

src/utils.js:

Variables

NameDescriptionType
isStandardBrowserEnvDetermines if the code is running in a standard browser environment. This function checks for specific conditions that indicate whether the code is running in a standard browser environment, allowing Axios to work in various environments like web workers, React Native, or NativeScript.
isStandardBrowserWebWorkerEnvDetermines if the code is running in a standard browser WebWorker environment. This function checks for specific conditions that indicate whether the code is running in a standard browser WebWorker environment. It takes into account the limitations of the `isStandardBrowserEnv` method when working with WebWorkers.

Functions

NameDescriptionParametersReturn
isFormDataDetermine if a value is a FormDatathing: *boolean
assignIfDefinedUtility function to assign a property to an object if the value is defined.obj: Object, prop: string, value: *

Exports

KindNameDeclarationModulePackage
jsisStandardBrowserEnvisStandardBrowserEnvsrc/utils.js
jsisStandardBrowserWebWorkerEnvisStandardBrowserWebWorkerEnvsrc/utils.js
jsisFormDataisFormDatasrc/utils.js
jsassignIfDefinedassignIfDefinedsrc/utils.js
1.3.10

2 months ago

1.3.11

2 months ago

1.3.9

3 months ago

1.3.7

3 months ago

1.3.6

4 months ago

1.3.5

4 months ago

1.3.4

4 months ago

1.3.8

3 months ago

1.3.3

6 months ago

1.3.2

6 months ago

1.3.1

7 months ago

1.3.0

10 months ago

1.2.0

10 months ago

1.1.5

11 months ago

1.1.4

11 months ago

1.1.3

12 months ago

1.1.1

1 year ago

1.1.2

1 year ago

1.1.0

1 year ago

1.0.0

1 year ago