Cloudly HTTP Request/Response Utility

raw JSON →
0.1.8 verified Thu Apr 23 auth: no javascript

Cloudly HTTP is a TypeScript-first utility library designed to streamline the handling of HTTP requests and responses in JavaScript/TypeScript environments. Currently in its early stages (version 0.1.8), it aims to provide a structured and type-safe approach to building HTTP clients and servers, likely targeting serverless or cloud-native applications given the 'Cloudly' prefix. The library focuses on encapsulating HTTP logic, offering features like configurable client constructors and explicit path management. Its core differentiator lies in its strong TypeScript typing and structured API for managing complex HTTP interactions, rather than being a generic fetch wrapper, which helps prevent common runtime errors and improves code maintainability. It has a relatively rapid release cadence in its minor versions due to being in early development.

error TypeError: Cannot read properties of undefined (reading 'get')
cause Attempting to use `client.get('path')` without correctly initializing the Client constructor with named callbacks after the v0.1.0 breaking change.
fix
Update the Client constructor to use a configuration object: new Client({ request: myRequestHandlerFunction }).
error UnhandledPromiseRejection: Error: Invalid path: 'users' (missing leading slash)
cause The `path` parameter for client methods (e.g., `get`, `post`) is missing the mandatory leading forward slash (`/`) introduced in v0.1.0.
fix
Prefix the path with a forward slash: client.get('/users') instead of client.get('users').
error TS2345: Argument of type 'string' is not assignable to parameter of type 'ClientConfig'.
cause Passing a non-object argument to the `Client` constructor when `ClientConfig` (an object with named callbacks) is expected.
fix
Ensure the Client constructor receives an object that conforms to the ClientConfig interface, e.g., new Client({ request: myRequestCallback }).
breaking The Client constructor no longer accepts positional arguments. Instead, it now requires a single object argument for its configuration, primarily for named callbacks.
fix Refactor `new Client(callback1, callback2)` to `new Client({ request: callback1, response: callback2 })` or similar named properties as defined by the `ClientConfig` interface.
breaking All `path` parameters passed to client methods (e.g., `client.get(path)`) must now be explicitly prefixed with a forward slash (`/`).
fix Ensure all path strings begin with `/`. For example, change `client.get('users')` to `client.get('/users')`.
gotcha As a library in early development (currently v0.1.x), Cloudly HTTP may introduce further breaking changes in minor or patch versions. Developers should pin exact versions or review changelogs diligently.
fix Monitor GitHub repository for updates, read release notes carefully, and consider pinning the exact package version in your `package.json` (e.g., `"cloudly-http": "0.1.8"`).
npm install cloudly-http
yarn add cloudly-http
pnpm add cloudly-http

This quickstart demonstrates how to instantiate the `Client` with a mock request handler, make a GET request, and process the typed response, highlighting the library's structured approach to HTTP interactions.

import { Client, type HttpRequest, type HttpResponse, type ClientConfig } from 'cloudly-http';

interface MyAPIResponse {
  message: string;
  status: string;
}

// Define a mock fetch-like function for demonstration
const mockFetch = async (request: HttpRequest): Promise<HttpResponse> => {
  console.log(`Mock Fetch: ${request.method} ${request.url}`);
  if (request.url === '/api/hello') {
    return {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: 'Hello from Cloudly!', status: 'success' })
    };
  }
  return {
    status: 404,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: 'Not Found', status: 'error' })
  };
};

const clientConfig: ClientConfig = {
  // In a real app, this would be a configured handler, e.g., for node-fetch or browser fetch
  request: async (request: HttpRequest) => {
    // Simulate network delay
    await new Promise(resolve => setTimeout(resolve, 50));
    return mockFetch(request);
  }
};

const apiClient = new Client(clientConfig);

async function fetchData() {
  try {
    const response = await apiClient.get<MyAPIResponse>('/api/hello');
    if (response.status === 200 && response.body) {
      const data = response.body;
      console.log('Received data:', data.message);
    } else {
      console.error('API Error:', response.status, response.body);
    }

    const notFoundResponse = await apiClient.get('/api/unknown');
    console.log('Not Found Response Status:', notFoundResponse.status);

  } catch (error) {
    console.error('Request failed:', error);
  }
}

fetchData();