npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mzbg/sdk-core

v0.1.1

Published

Configuration driven core functionality to build the client side SDK / API layer

Downloads

133

Readme

SDK Core

SDK Core provides configuration based SDK generation. Its a flexible and feature-rich API SDK backbone that provides a simple interface for making HTTP requests with built-in support for retry logic, polling, and subscription capabilities.

Installation

npm i sdk-core

Basic Usage

import { api } from 'sdk-core';

// Initialize the API
api.init({
  axiosConfig: {
    baseURL: 'https://api.example.com',
    headers: {
      'Content-Type': 'application/json'
    }
  },
  endpoints: [
    // Your endpoint configurations
  ]
});

// Make a request
const userDetails = await api.user.get({
  params: {
    userId: loginResponse.data.id,
  },
});

Making Direct Calls

You can also make direct API calls by passing an object with url and other configs:

// GET request
const response = await api.get({
  url: '/users/123',
  params: {
    fields: 'name,email'
  }
});

// POST request
const newUser = await api.post({
  url: '/users',
  data: {
    name: 'John Doe',
    email: '[email protected]'
  }
});

// PUT request
const updatedUser = await api.put({
  url: '/users/123',
  data: {
    name: 'John Updated'
  }
});

// DELETE request
await api.delete({
  url: '/users/123'
});

Features

1. Request Interceptors

You can intercept requests and responses:

// Request interceptor
api.interceptRequest(
  (config) => {
    // Modify request config
    return config;
  },
  (error) => {
    // Handle request error
    return Promise.reject(error);
  }
);

// Response interceptor
api.interceptResponse(
  (response) => {
    // Handle response
    return response;
  },
  (error) => {
    // Handle response error
    return Promise.reject(error);
  }
);

2. Polling and Subscriptions

The SDK supports automatic polling and subscription to endpoints:

subscribe method accepts 3 arguments:

  • (Required) Endpoint method
  • (Required) Callback function (to be called when data is received / error occurs)
  • (Optional) Request configuration provider (to be called before each request)
// Subscribe to an endpoint
const callback = (data) => {
  console.log('Received updated data:', data);
};
const requestConfigProvider = () => {
  const requestConfig = {
    params: {
      id: 1
    }
  };

  return requestConfig;
}
api.subscribe(api.users.get, callback, requestConfigProvider);

// Unsubscribe from an endpoint
api.unsubscribe(api.users.get, callback);

3. Api response caching

SDK Core provides built-in caching capabilities:

// Configure cache settings
api.init({
  cache: {
    enabled: true,
    ttl: 60000, // Cache TTL in milliseconds
    storageType: 'memory', // 'memory' or 'localStorage'
    maxSize: 100 // Maximum number of cached items
  }
});

// Make a cached request
const cachedData = await api.users.get({
  cache: {
    key: 'users-list',
    ttl: 30000, // Override default TTL
    condition: (response) => response.status === 200
  }
});

// Clear specific cache
api.cache.delete('users-list');

// Clear all cache
api.cache.clear();

// Get cache stats
const stats = api.cache.getStats();

You can also implement custom cache adapters:

class CustomCache {
  get(key) { /* ... */ }
  set(key, value, ttl) { /* ... */ }
  delete(key) { /* ... */ }
  clear() { /* ... */ }
  getStats() { /* ... */ }
}

api.init({
  cache: {
    adapter: new CustomCache()
  }
});

4. Configuration driven

Basic Example

This example shows a simple configuration with a single endpoint and method:

api.init({
  endpoints: [
    {
      name: 'users',
      url: '/users',
      methods: [
        {
          method: 'get'
        }
      ]
    }
  ]
});

Nested Endpoints Example

This example demonstrates how to configure nested endpoints, useful for hierarchical APIs:

api.init({
  endpoints: [
    {
      name: 'organization',
      url: '/org',
      methods: [
        {
          method: 'get'
        }
      ],
      endpoints: [
        {
          name: 'teams',
          url: '/teams',
          methods: [
            {
              method: 'get'
            }
          ],
          endpoints: [
            {
              name: 'members',
              url: '/members',
              methods: [
                {
                  method: 'get'
                }
              ]
            }
          ]
        }
      ]
    }
  ]
});

// Can be accessed as:
await api.organization.teams.members.get({
  params: {
    orgId: 123,
    teamId: 456,
    memberId: 789
  }
});

Endpoint Configuration

Each endpoint can be configured with:

  • name: Endpoint identifier
  • url: Endpoint URL
  • methods: Array of method configurations
  • endpoints: Nested endpoints

Method Configuration

Methods can be configured with:

  • method: HTTP method
  • url: Method-specific URL
  • retry: Method-specific retry configuration
  • polling: Polling configuration

Error Handling

The SDK throws errors for:

  • Uninitialized API
  • Invalid parameter types
  • Missing required parameters
  • Invalid endpoint configurations
  • Failed requests

TODO

There are a few features that are planned for future releases:

  • Add support to validate request params and payload using ajv schema
  • Add support for configuring and seding requests to multiple servers
  • Add request chaining support
  • Add request pipeline support
  • Add request dependency resolution
  • Add GraphQL support
  • Implement WebSocket support for real-time updates
  • Implement automatic request batching
  • Add implementation to handle authentication
  • Enable request rate limiting
  • Add response data transformation helpers
  • Add OpenAPI/Swagger schema generation and validation
  • Add caching layer support with offline capability
  • Add request throttling and concurrent request handling
  • Add request mocking support for testing
  • Add logging and analytics capabilities
  • Implement API analytics and performance monitoring
  • Add support for distributed tracing
  • Add CORS handling and configuration
  • Add support for file uploads and progress tracking
  • Implement custom response serializers/deserializers
  • Add support for circuit breaker pattern
  • Implement request prioritization and queuing
  • Add API discovery and documentation generation
  • Add support for response streaming
  • Add response schema validation
  • Add support for middleware and plugin architecture
  • Add support for custom header management

TypeScript Support

The SDK is written in TypeScript and provides full type definitions for all features.

License

This package is licensed under MIT or Apache-2.0 license