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

@culturehq/client

v14.1.1

Published

A JavaScript client that wraps the CultureHQ API

Downloads

132

Readme

@culturehq/client

Build Status Package Version

A JavaScript client that wraps the CultureHQ API.

Getting started

Install the package into your application using npm (npm install @culturehq/client --save) or yarn (yarn add @culturehq/client). Then import the package into your node application like:

import { makeGet } from "@culturehq/client";

API calls

Every API call function returns a Promise. You can call them with normal Promise semantics, as in below:

const getProfile = () => {
  makeGet("/profile")
    .then(response => {
      console.log(response);
    })
    .catch(error => {
      console.error(error);
    });
};

or you can use async/await syntax, as in below:

const getProfile = async () => {
  try {
    const response = await makeGet("/profile");
    console.log(response);
  } catch (error) {
    console.error(error);
  }
};

Sign-in state

Signed in state is handled through the client using the signIn and signOut functions. These effectively act as normal API calls but with the additional functionality of setting or clearing localStorage with the returned API token.

You can also manually set the API token by using the setToken named export. This is especially useful if the token is fixed in some context (as in most integrations).

Upload signing

To support faster uploading, we allow images to be uploaded directly to S3, and then just send along the signed URL to the API for fetching. This allows API servers to continue processing requests instead of waiting for the upload to complete.

To use this mechanism, call this function with a file object and it will return a Promise that resolves to the URL of the file that was uploaded, as in the following example:

import { signUpload } from "@culturehq/client";

signUpload(document.querySelector("#file").files[0]).then(url => {
  console.log(url);
});

Pagination

Almost every one of the index endpoints is paginated, and will return pagination metadata along with the actual data of the call. The pagination object will look like:

const pagination = { currentPage, totalPages, totalCount };

You can handle this pagination manually, e.g., links on the bottom of the page. You can also use the client's built-in automatic pagination capabilities by using the makePaginatedGet named export, as in the following example:

import { makePaginatedGet } from "@culturehq/client";

const { events } = await makePaginatedGet("events", "/events");

This will return the pagination information as normal, but the events will be concatenated together.

WebSocket connections

There are a few functions on the client that will establish a WebSocket connection and call a callback function when data is received. For these functions, in order to avoid leaking memory, it's important to ensure that when you're done with the subscription (for instance when the component containing it is unmounted) that you call unsubscribe on the subscription object. An example with React of using these functions is below:

import { onNotificationReceived } from "@culturehq/client";

class MyComponent {
  state = { lastNotification: null };

  componentDidMount() {
    this.subscription = onNotificationReceived(notification => {
      this.setState({ lastNotification: notification });
    });
  }

  componentWillUnmount() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }

  render() {
    const { lastNotification } = this.state;

    return <span>{lastNotification}<span>;
  }
}

The list of all of these class of functions can be found in src/cable.js.

Skipping preflight checks

You can avoid all of the CORS preflight checks if the domains of both the request and response match. You can accomplish this only if you're on a subdomain and the server that you're trying to hit is on another subdomain of the same parent domain.

The way it works is by changing the document.domain value to be the common parent domain of both the request and the response. The request can just be changed by setting document.domain in the main window (this is allowed by browsers because you're always allowed to set it to a suffix of the current domain).

The response domain can be changed by embedding an iframe into the page that contains a specially crafted page from the response server. The iframe contains a small HTML page with a script tag that changes the document.domain value to match the requesting server. You can then pull the fetch function from the child window into the parent and use that to hit the server.

If using this code in production on a culturehq subdomain, we can embed an iframe using the API's /proxyendpoint which contains the code to change thedocument.domainvalue toculturehq.com. We can then do the same in this window and pull thefetchfunction from the child window. This logic is encapsulated in theskipPreflightChecks` and can be used like so:

import { skipPreflightChecks } from "@culturehq/client";

skipPreflightChecks();

Development

First, install the dependencies with yarn. Run yarn test to run the tests with jest. Run yarn lint to run linting with eslint.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/CultureHQ/client.

License

The code is available as open source under the terms of the MIT License.