GithubHelp home page GithubHelp logo

client's Introduction

@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.

client's People

Contributors

kddnewton avatar mergify[bot] avatar dependabot-preview[bot] avatar josuesantamaria avatar dependabot[bot] avatar dependabot-support avatar alexjohnson505 avatar mebling avatar

Watchers

James Cloos avatar Chase Newton avatar

client's Issues

Support environments without localStorage

  • src/state.js needs to change to not automatically read out of local storage
  • should check for localStorage with try { window.localStorage } catch (error) {}, fallback to sessionStorage, else just fall back to in-memory
  • allow persistence to be asynchronous

As a User, I want an options to "Stay Logged In".

CultureHQ.signIn() currently stores the user's auth token. Do we want to add an additional parameter that allows a user to log in, but not to save their session/token? Maybe "Stay Logged In" by default, and specific when to NOT save session.

{
email: ...
password: ...
stayLoggedIn: ....
}

Error on DELETE endpoints

I'm getting an error on a few on the DELETE endpoints. deleteExpense, deleteSurveyItem, etc.

Unexpected end of JSON input

Any ideas?

screen shot 2017-10-18 at 11 07 37 am

Travis build fails to minify culturehq-client/dist/index.js:330

[https://travis-ci.com/CultureHQ/web/builds/58442427](#343 on Travis)

I'm getting the following error on Travis (web):

Creating an optimized production build...
Failed to compile.
Failed to minify the code from this file: 
 	./node_modules/culturehq-client/dist/index.js:330 
Read more here: http://bit.ly/2tRViJ9
error Command failed with exit code 1.
The command "yarn build" failed and exited with 1 during .
Your build has been stopped.

I believe it's an issue due to failing to compile the ES6 syntax.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.