CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-reqwest

A wrapper for asynchronous HTTP requests supporting XMLHttpRequest, JSONP, CORS, and CommonJS Promises

Pending
Overview
Eval results
Files

jquery-compat.mddocs/

jQuery Compatibility

Configuration utilities and jQuery/Zepto compatibility layer for seamless migration from other AJAX libraries. Provides global defaults configuration and option remapping to handle differences between reqwest and jQuery/Zepto APIs.

Capabilities

Ajax Setup

Sets global default options that will be applied to all subsequent requests.

/**
 * Sets global default options for all requests
 * @param {Object} options - Global configuration options
 */
reqwest.ajaxSetup(options);

interface GlobalOptions {
  dataFilter?: Function; // Global response filtering function
  // Any other reqwest option can be set as global default
}

Usage Examples:

// Set global data filter
reqwest.ajaxSetup({
  dataFilter: function(data, type) {
    // Remove security prefix from all JSON responses
    if (type === 'json' && typeof data === 'string') {
      return data.replace(/^\)\]\}',?\n/, '');
    }
    return data;
  }
});

// Set global headers
reqwest.ajaxSetup({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Authorization': 'Bearer ' + getAuthToken()
  }
});

// Set global timeout
reqwest.ajaxSetup({
  timeout: 30000, // 30 seconds for all requests
  error: function(xhr, type, error) {
    if (type === 'timeout') {
      console.log('Request timed out - check your connection');
    }
  }
});

// Multiple configurations
reqwest.ajaxSetup({
  contentType: 'application/json',
  processData: false,
  dataFilter: function(data, type) {
    // Log all responses for debugging
    console.log('Response received:', type, data);
    return data;
  },
  before: function(xhr) {
    // Add timestamp to all requests
    xhr.setRequestHeader('X-Request-Time', new Date().toISOString());
  }
});

Compatibility Mode

jQuery/Zepto compatibility layer that remaps option names to handle API differences.

/**
 * jQuery/Zepto compatibility layer
 * @param {Object} options - jQuery-style options object
 * @param {Function} callback - Optional success callback
 * @returns {Object} Request object with promise-like interface
 */
reqwest.compat(options, callback);

Option Remapping:

  • type (jQuery) → method (reqwest)
  • dataType (jQuery) → type (reqwest)
  • jsonp (jQuery) → jsonpCallback (reqwest)
  • jsonpCallback (jQuery) → jsonpCallbackName (reqwest)

Usage Examples:

// jQuery-style options
reqwest.compat({
  url: '/api/data',
  type: 'POST',           // Mapped to method: 'POST'
  dataType: 'json',       // Mapped to type: 'json'
  data: { name: 'John' },
  success: function(data) {
    console.log('Success:', data);
  },
  error: function(xhr, status, error) {
    console.log('Error:', error);
  }
});

// JSONP with jQuery-style options
reqwest.compat({
  url: 'https://api.example.com/data',
  dataType: 'jsonp',                    // Mapped to type: 'jsonp'
  jsonp: 'callback',                    // Mapped to jsonpCallback: 'callback'
  jsonpCallback: 'handleResponse',      // Mapped to jsonpCallbackName: 'handleResponse'
  success: function(data) {
    console.log('JSONP data:', data);
  }
});

// Mixed jQuery and reqwest options
reqwest.compat({
  url: '/api/upload',
  type: 'POST',           // jQuery style
  processData: false,     // reqwest style
  contentType: false,     // jQuery style
  data: formData,
  success: function(response) {
    console.log('Upload complete:', response);
  }
});

Get Callback Prefix

Utility function that returns the current JSONP callback prefix used by reqwest.

/**
 * Returns the callback prefix used for JSONP requests
 * @returns {string} Current callback prefix (format: 'reqwest_' + timestamp)
 */
reqwest.getcallbackPrefix();

Usage Examples:

// Get current callback prefix
const prefix = reqwest.getcallbackPrefix();
console.log('JSONP callback prefix:', prefix);
// Output: "reqwest_1698765432123"

// Use in custom JSONP handling
const customCallback = prefix + '_custom_' + Math.random();
reqwest({
  url: 'https://api.example.com/jsonp?callback=' + customCallback,
  type: 'jsonp',
  jsonpCallbackName: customCallback,
  success: function(data) {
    console.log('Custom JSONP callback executed:', data);
  }
});

Migration from jQuery

Direct Replacement

// jQuery AJAX
$.ajax({
  url: '/api/users',
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    console.log('Users loaded:', data);
  },
  error: function(xhr, status, error) {
    console.log('Failed to load users');
  }
});

// Reqwest equivalent using compat
reqwest.compat({
  url: '/api/users',
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    console.log('Users loaded:', data);
  },
  error: function(xhr, type, error) {
    console.log('Failed to load users');
  }
});

Global Setup Migration

// jQuery global setup
$.ajaxSetup({
  timeout: 10000,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-API-Key', 'your-api-key');
  },
  error: function(xhr, status, error) {
    console.log('Global error handler:', error);
  }
});

// Reqwest equivalent
reqwest.ajaxSetup({
  timeout: 10000,
  before: function(xhr) {
    xhr.setRequestHeader('X-API-Key', 'your-api-key');
  },
  error: function(xhr, type, error) {
    console.log('Global error handler:', error);
  }
});

Promise Style Migration

// jQuery with promises
$.ajax({
  url: '/api/data',
  type: 'POST',
  data: { key: 'value' }
})
.done(function(data) {
  console.log('Success:', data);
})
.fail(function(xhr, status, error) {
  console.log('Error:', error);
})
.always(function() {
  console.log('Complete');
});

// Reqwest equivalent (no compat needed for promises)  
reqwest({
  url: '/api/data',
  method: 'POST',
  data: { key: 'value' }
})
.then(function(data) {
  console.log('Success:', data);
})
.fail(function(xhr, type, error) {
  console.log('Error:', error);
})
.always(function() {
  console.log('Complete');
});

Ender Framework Integration

When reqwest is used with Ender, additional jQuery-style methods become available:

Ender Ajax Methods

// Available when reqwest is used with Ender
$.ajax(options);                    // Alias for reqwest
$.ajax.compat(options);             // Alias for reqwest.compat
$.ajaxSetup(options);              // Alias for reqwest.ajaxSetup

Ender Setup for jQuery Compatibility

// Make compat mode the default in Ender
$.ajax.compat && $.ender({ ajax: $.ajax.compat });

// Now all $.ajax calls use jQuery-compatible options
$.ajax({
  url: '/api/data',
  type: 'POST',        // Will be mapped to method
  dataType: 'json',    // Will be mapped to type
  success: function(data) {
    console.log('Data:', data);
  }
});

Advanced Configuration Patterns

Environment-Specific Setup

// Development environment
if (NODE_ENV === 'development') {
  reqwest.ajaxSetup({
    timeout: 60000, // Longer timeout for debugging
    dataFilter: function(data, type) {
      console.log('API Response:', type, data);
      return data;
    },
    error: function(xhr, type, error) {
      console.error('DEV ERROR:', {xhr, type, error});
    }
  });
}

// Production environment
if (NODE_ENV === 'production') {
  reqwest.ajaxSetup({
    timeout: 15000,
    error: function(xhr, type, error) {
      // Send errors to monitoring service
      analytics.track('api_error', {
        url: xhr.responseURL,
        status: xhr.status,
        error: error
      });
    }
  });
}

Authentication Integration

// Set up automatic authentication
function setupAuthenticatedRequests() {
  reqwest.ajaxSetup({
    before: function(xhr) {
      const token = localStorage.getItem('authToken');
      if (token) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
      }
    },
    error: function(xhr, type, error) {
      // Handle authentication errors globally
      if (xhr.status === 401) {
        localStorage.removeItem('authToken');
        window.location.href = '/login';
      }
    }
  });
}

// Initialize authentication setup
setupAuthenticatedRequests();

// All subsequent requests will include auth headers
reqwest({ url: '/api/protected-data' })
  .then(function(data) {
    console.log('Protected data:', data);
  });

API Response Normalization

// Normalize different API response formats
reqwest.ajaxSetup({
  dataFilter: function(data, type) {
    if (type === 'json' && data) {
      // Handle wrapped responses
      if (data.status && data.data) {
        return data.data;
      }
      
      // Handle paginated responses
      if (data.results && Array.isArray(data.results)) {
        data.items = data.results; // Normalize property name
        return data;
      }
      
      // Handle error responses
      if (data.error) {
        throw new Error(data.error.message || 'API Error');
      }
    }
    
    return data;
  }
});

// All JSON responses are now normalized
reqwest({ url: '/api/users', type: 'json' })
  .then(function(users) {
    // users is already unwrapped from {status: 'ok', data: users}
    console.log('Normalized users:', users);
  });

Install with Tessl CLI

npx tessl i tessl/npm-reqwest

docs

core-requests.md

index.md

jquery-compat.md

promise-interface.md

utilities.md

tile.json