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

dc-api-client

v1.1.1

Published

HTTP API client primary designed for dc-api-core

Downloads

34

Readme

HTTP API client

Primary designed for dc-api-core.

NPM

Basic usage

Import dc-api-client to your project

// Use Node.JS require
const API = require('dc-api-client');
// OR use import for ES6+/TS
import API from 'dc-api-client'

Make request to backend

const res = await API.Controller.action({
    // Any JSON-compatible types are supported.
    // You can also use Blob or File as the value.
});
  • Controller - your controller name
  • action - your action name in controller
  • res - Response object

Response object

| Name | Type | Note | |---------|-----------|-------------------------------------------------------------------------------| | success | Boolean | true if response code is 200 | | code | Number | HTTP response code | | msg | any | If backend returned JSON, it will be parsed, otherwise contains raw response. |

Example

Sending user data to register method in Auth controller.

const API = require('dc-api-client');
const res = await API.Auth.register({
    email: '[email protected]',
    password: '123123'
});
console.log(res);

Example console output:

{
    success: true,
    code: 200,
    msg: {
        status: 'user_registered',
        id: 42
    }
}

Sending request with query string

API.TestController.action(null, { query: 'works' });
// useKebab = false:    GET /TestController/action?query=works
// useKebab = true:     GET /test-controller/action?query=works

Settings

Settings stored in API.settings object.

| Field | Type  | Default | Note | |-------------------|----------|---------------------|-------------------------------------------------------------------| | secure | boolean | true | true - use HTTPS, instead of HTTP | | base | string | location.hostname | Hostname with prefix path | | dev | Function | Read-only | Enables or disables dev mode as setter, returns boolean as getter | | reconnectAttempts | number | 5 | Count of WebSocket reconnection attempts, -1 is ∞ | | reconnectTimeout | number | 2.5 | WebSocket reconnection timeout is seconds | | useKebab | boolean | false | true - automatically transform names to kebab-case | | followRedirects | boolean | true | true - automatically redirect if "Location" header present |

Settings example #1

const API = require('dc-api-client');

// Redundant, because HTTPS enabled by default
API.settings.secure = true;
API.settings.base = 'your-domain.com:8080/api';

Where your-domain.com is your domain or IP address.

Settings example #2

import API from 'dc-api-client';

API.settings.secure = false;
API.settings.base = `${location.hostname}:8080/api`;

Socket controller

WebSockets connection will be initialized when controller used for first time.

WS URI: ws[s]://<settings.base>/socket

API.Socket: {
    // Calling <event> method in Socket controller on back-end
    emit (event: String, ...arguments: any[]);

    // Sets trigger for <event> reply
    on (event: String, listener: (...arguments: any[]) => {});

    // Sets one time trigger for <event> reply
    once (event: String, listener: (...arguments: any[]) => {});

    // Removing trigger for <event>
    off (event: String, listener: (...arguments: any[]) => {});
};

Socket events

API.Socket.on('open', isReconnect => {
    if (isReconnect) console.log('Reconnected!');
    else console.log('Connected for first time');
});

API.Socket.on('reconnect', attempt => {
    // This event will be fired BEFORE reconnection
    if (API.settings.reconnectAttempts == -1) console.log(`[${attempt}/∞] Reconnecting...`);
    else console.log(`[${attempt}/${API.settings.reconnectAttempts}] Reconnecting...`);
});

API.Socket.on('close', (code, reason) => {
    // Reconnection never trigger this event,
    // i.e. on full connection lost
    console.log(`Connection was closed with code ${code}: ${reason || 'No reason provided'}`);
    // e - CloseEvent object (browser event)
});

API.Socket.on('<custom-event-name>', (a, b) => {
    // Handles event emitted from the server
    // For example, with dc-api-core you can use this line to emit your event
    //     this.emit('<custom-event-name>', 7, 5);
    // which will send packet below
    //     ["<custom-event-name>",7,5]
    // and will be handled here by dc-api-client
    console.log('New <custom-event-name> data!', a, b);
});

Advanced features

Multiple API connections

main.js:

import API from 'dc-api-client'
// Registering `ExampleAPI` in `API.instances`, this method also returns created instance
API.registerInstance('ExampleAPI', { base: 'api.example.com', secure: false });

other.js

import API from 'dc-api-client'
const { ExampleAPI } = API.instances;

// http://api.example.com/Controller/action
const res = await ExampleAPI.Controller.action();

// Works with WebSocket connection
// ws://api.example.com/socket
ExampleAPI.Socket.on('test', () => console.log('Test received'));
ExampleAPI.Socket.emit('send-me-test');

POST utility

Sends POST request in browser with form.

API.post(url: String, data: Object, newtab: Boolean = false);

Alternative request sending

API.send(controller: String, action: String, data: any, query: Object): Promise<Response>;

Known issues

dc-api-client doesn't work properly with Rollup

Inject NODE_ENV variable with process object manually or use rollup-plugin-inject-process-env.

Vanilla fallback

You can use pre-bundled version (browser.js ~4 kb) in browser without webpack, parcel, browserify or other bundlers.

Compatibility:

| Internet Explorer | Edge | Firefox | Chrome | Safari | Opera | |:-----------------:|:----:|:-------:|:------:|:------:|:-----:| | Not supported | 12+ | 22+ | 49+ | 10+ | 36+ |