Networking API Reference

This document provides a comprehensive reference to the Networking API, enabling your applications to communicate over networks, fetch data from remote services, and interact with the internet.

Introduction to Network Operations

The Networking API offers a robust set of tools for handling HTTP requests, managing network connectivity status, and performing asynchronous network operations. It's designed to be intuitive and efficient, allowing developers to easily integrate network capabilities into their applications.

Key Features:

Core Classes and Interfaces

NetworkManager

The central class for managing network-related operations and monitoring connectivity status.

Methods:

Method Signature Description
fetch(url: string, options?: FetchOptions): Promise<Response> Initiates an HTTP request to the specified URL. Returns a Promise that resolves with the Response object.
get(url: string, params?: Record<string, any>): Promise<Response> Shorthand for making an HTTP GET request. Appends query parameters if provided.
post(url: string, data?: any, options?: PostOptions): Promise<Response> Shorthand for making an HTTP POST request. Allows specifying request body and content type.
isConnected(): boolean Checks the current network connectivity status.
onConnectivityChange(callback: (isConnected: boolean) => void): void Registers a callback function to be notified when the network connectivity status changes.

RequestOptions Interface

Defines the options that can be passed to the fetch method.

interface RequestOptions {
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
    headers?: Record<string, string>;
    body?: any;
    responseType?: 'json' | 'text' | 'blob';
    timeout?: number; // in milliseconds
    retries?: number;
    retryDelay?: number; // in milliseconds
}
        

Response Interface

Represents a network response.

interface Response {
    status: number;
    statusText: string;
    headers: Record<string, string>;
    data: any; // Parsed response body based on 'responseType'
    json(): Promise<any>;
    text(): Promise<string>;
    blob(): Promise<Blob>;
}
        

Making HTTP Requests

The primary way to interact with remote resources is through the fetch method.

Example: Fetching JSON Data


import { NetworkManager } from '@msdn/networking';

const networkManager = new NetworkManager();

networkManager.fetch('/api/users', {
    method: 'GET',
    headers: {
        'Accept': 'application/json'
    },
    responseType: 'json'
})
.then(response => {
    if (response.status === 200) {
        console.log('Users:', response.data);
    } else {
        console.error('Failed to fetch users:', response.statusText);
    }
})
.catch(error => {
    console.error('Network error:', error);
});
        

Example: Posting Data


import { NetworkManager } from '@msdn/networking';

const networkManager = new NetworkManager();
const newUser = { name: 'Jane Doe', email: 'jane.doe@example.com' };

networkManager.post('/api/users', newUser, {
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(response => {
    if (response.status === 201) {
        console.log('User created:', response.data);
    } else {
        console.error('Failed to create user:', response.statusText);
    }
})
.catch(error => {
    console.error('Network error:', error);
});
        

Handling Network Connectivity

It's crucial to be aware of the application's network connectivity status.

Checking Connectivity


import { NetworkManager } from '@msdn/networking';

const networkManager = new NetworkManager();

if (networkManager.isConnected()) {
    console.log('Device is online.');
    // Proceed with network operations
} else {
    console.log('Device is offline.');
    // Show an offline message or queue operations
}
        

Listening for Changes


import { NetworkManager } from '@msdn/networking';

const networkManager = new NetworkManager();

networkManager.onConnectivityChange(isConnected => {
    if (isConnected) {
        console.log('Network connection restored.');
        // Try to re-sync data or resume operations
    } else {
        console.log('Network connection lost.');
        // Inform the user or pause operations
    }
});
        
Note: The NetworkManager automatically handles basic retry logic for transient network errors if configured via the retries and retryDelay options.
Warning: Always handle potential errors gracefully. Network requests can fail due to various reasons, including server issues, network interruptions, or invalid requests.
Tip: For large data transfers, consider using responseType: 'blob' and streaming the response to manage memory efficiently.

Error Handling

Network operations return Promises, which can be handled using .then() and .catch(). The catch block will receive an error object if the request fails due to network issues, timeouts, or server-side errors (e.g., 5xx status codes might be thrown as exceptions depending on configuration).

Common Error Types:

Best Practices