• Stars
    star
    173
  • Rank 220,124 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple, flexible store implementation for Flux. #hubspot-open-source

HubSpot/general-store

NPM version Build Status

general-store aims to provide all the features of a Flux store without prescribing the implementation of that store's data or mutations.

Briefly, a store:

  1. contains any arbitrary value
  2. exposes that value via a get method
  3. responds to specific events from the dispatcher
  4. notifies subscribers when its value changes

That's it. All other features, like Immutability, data fetching, undo, etc. are implementation details.

Read more about the general-store rationale on the HubSpot Product Team Blog.

Install

# npm >= 5.0.0
npm install general-store

# yarn
yarn add general-store
// namespace import
import * as GeneralStore from 'general-store';
// or import just your module
import { define } from 'general-store';

Create a store

GeneralStore uses functions to encapsulate private data.

var dispatcher = new Flux.Dispatcher();
function defineUserStore() {
  // data is stored privately inside the store module's closure
  var users = {
    123: {
      id: 123,
      name: 'Mary',
    },
  };

  return (
    GeneralStore.define()
      .defineName('UserStore')
      // the store's getter should return the public subset of its data
      .defineGet(function() {
        return users;
      })
      // handle actions received from the dispatcher
      .defineResponseTo('USER_ADDED', function(user) {
        users[user.id] = user;
      })
      .defineResponseTo('USER_REMOVED', function(user) {
        delete users[user.id];
      })
      // after a store is "registered" its action handlers are bound
      // to the dispatcher
      .register(dispatcher)
  );
}

If you use a singleton pattern for stores, simply use the result of register from a module.

import { Dispatcher } from 'flux';
import * as GeneralStore from 'general-store';

var dispatcher = new Dispatcher();
var users = {};

var UserStore = GeneralStore.define()
  .defineGet(function() {
    return users;
  })
  .register(dispatcher);

export default UserStore;

Dispatch to the Store

Sending a message to your stores via the dispatcher is easy.

dispatcher.dispatch({
  actionType: 'USER_ADDED', // required field
  data: {
    // optional field, passed to the store's response
    id: 12314,
    name: 'Colby Rabideau',
  },
});

Store Factories

The classic singleton store API is great, but can be hard to test. defineFactory() provides an composable alternative to define() that makes testing easier and allows you to extend store behavior.

var UserStoreFactory = GeneralStore.defineFactory()
  .defineName('UserStore')
  .defineGetInitialState(function() {
    return {};
  })
  .defineResponses({
    USER_ADDED: function(state, user) {
      state[user.id] = user;
      return state;
    },
    USER_REMOVED: function(state, user) {
      delete state[user.id];
      return state;
    },
  });

Like singletons, factories have a register method. Unlike singletons, that register method can be called many times and will always return a new instance of the store described by the factory, which is useful in unit tests.

describe('UserStore', () => {
  var storeInstance;
  beforeEach(() => {
    // each test will have a clean store
    storeInstance = UserStoreFactory.register(dispatcher);
  });

  it('adds users', () => {
    var mockUser = { id: 1, name: 'Joe' };
    dispatcher.dispatch({ actionType: USER_ADDED, data: mockUser });
    expect(storeInstance.get()).toEqual({ 1: mockUser });
  });

  it('removes users', () => {
    var mockUser = { id: 1, name: 'Joe' };
    dispatcher.dispatch({ actionType: USER_ADDED, data: mockUser });
    dispatcher.dispatch({ actionType: USER_REMOVED, data: mockUser });
    expect(storeInstance.get()).toEqual({});
  });
});

To further assist with testing, the InspectStore module allows you to read the internal fields of a store instance (e.g. InspectStore.getState(store)).

Using the Store API

A registered Store provides methods for "getting" its value and subscribing to changes to that value.

UserStore.get(); // returns {}
var subscription = UserStore.addOnChange(function() {
  // handle changes!
});
// addOnChange returns an object with a `remove` method.
// When you're ready to unsubscribe from a store's changes,
// simply call that method.
subscription.remove();

React

GeneralStore provides some convenience functions for supplying data to React components. Both functions rely on the concept of "dependencies" and process those dependencies to return any data kept in a Store and make it easily accessible to a React component.

Dependencies

GeneralStore has a two formats for declaring data dependencies of React components. A SimpleDependency is simply a reference to a Store instance. The value returned will be the result of Store.get(). A CompoundDependency depends on one or more stores and uses a "dereference" function that allows you to perform operations and data manipulation on the data that comes from the stores listed in the dependency:

const FriendsDependency = {
  // compound fields can depend on one or more stores
  // and specify a function to "dereference" the store's value.
  stores: [ProfileStore, UsersStore],
  deref: props => {
    friendIds = ProfileStore.get().friendIds;
    users = UsersStore.get();
    return friendIds.map(id => users[id]);
  },
};

Once you declare your dependencies there are two ways to connect them to a react component.

useStoreDependency

useStoreDependency is a React Hook that enables you to connect to a single dependency inside of a functional component. The useStoreDependency hook accepts a dependency, and optionally a map of props to pass into the deref and a dispatcher instance.

function FriendsList() {
  const friends = GeneralStore.useStoreDependency(
    FriendsDependency,
    {},
    dispatcher
  );
  return (
    <ul>
      {friends.map(friend => (
        <li>{friend.getName()}</li>
      ))}
    </ul>
  );
}

connect

The second option is a Higher-Order Component (commonly "HOC") called connect. It's similar to react-redux's connect function but it takes a DependencyMap. Note that this is different than useStoreDependency which only accepts a single Dependency, even though (as of v4) connect and useStoreDependency have the same implementation under the hood. A DependencyMap is a mapping of string keys to Dependencys:

const dependencies = {
  // simple fields can be expressed in the form `key => store`
  subject: ProfileStore,
  friends: FriendsDependency,
};

connect passes the fields defined in the DependencyMap to the enhanced component as props.

// ProfileContainer.js
function ProfileContainer({ friends, subject }) {
  return (
    <div>
      <h1>{subject.name}</h1>
      {this.renderFriends()}
      <h3>Friends</h3>
      <ul>
        {Object.keys(friends).map(id => (
          <li>{friends[id].name}</li>
        ))}
      </ul>
    </div>
  );
}

export default connect(
  dependencies,
  dispatcher
)(ProfileComponent);

connect also allows you to compose dependencies - the result of the entire dependency map is passed as the second argument to all deref functions. While the above syntax is simpler, if the Friends and Users data was a bit harder to calculate and each required multiple stores, the friends dependency could've been written as a composition like this:

const dependencies = {
  users: UsersStore,
  friends: {
    stores: [ProfileStore],
    deref: (props, deps) => {
      friendIds = ProfileStore.get().friendIds;
      return friendIds.map(id => deps.users[id]);
    },
  },
};

This composition makes separating dependency code and making dependencies testable much easier, since all dependency logic doesn't need to be fully self-contained.

Default Dispatcher Instance

The common Flux architecture has a single central dispatcher. As a convenience GeneralStore allows you to set a global dispatcher which will become the default when a store is registered, the useStoreDependency hook is called inside a functional component, or a component is enhanced with connect.

var dispatcher = new Flux.Dispatcher();
GeneralStore.DispatcherInstance.set(dispatcher);

Now you can register a store without explicitly passing a dispatcher:

const users = {};

const usersStore = GeneralStore.define()
  .defineGet(() => users)
  .register(); // the dispatcher instance is set so no need to explicitly pass it

function MyComponent() {
  // no need to pass it to "useStoreDependency" or "connect" either
  const users = GeneralStore.useStoreDependency(usersStore);
  /* ... */
}

Dispatcher Interface

At HubSpot we use the Facebook Dispatcher, but any object that conforms to the same interface (i.e. has register and unregister methods) should work just fine.

type DispatcherPayload = {
  actionType: string,
  data: any,
};

type Dispatcher = {
  isDispatching: () => boolean,
  register: (handleAction: (payload: DispatcherPayload) => void) => string,
  unregister: (dispatchToken: string) => void,
  waitFor: (dispatchTokens: Array<string>) => void,
};

Redux Devtools Extension

Using Redux devtools extension you can inspect the state of a store and see how the state changes between dispatches. The "Jump" (ability to change store state to what it was after a specific dispatch) feature should work but it is dependent on you using regular JS objects as the backing state.

Using the defineFactory way of creating stores is highly recommended for this integration as you can define a name for your store and always for the state of the store to be inspected programmatically.

Build and test

Install Dependencies

# pull in dependencies
yarn install

# run the type checker and unit tests
yarn test

# if all tests pass, run the dev and prod build
yarn run build-and-test

# if all tests pass, run the dev and prod build then commit and push changes
yarn run deploy

Special Thanks

Logo design by Chelsea Bathurst

More Repositories

1

youmightnotneedjquery

Astro
14,118
star
2

offline

Automatically display online/offline indication to your users
CSS
8,679
star
3

odometer

Smoothly transitions numbers with ease. #hubspot-open-source
CSS
7,259
star
4

vex

A modern dialog library which is highly configurable and easy to style. #hubspot-open-source
CSS
6,927
star
5

messenger

Growl-style alerts and messages for your app. #hubspot-open-source
JavaScript
4,024
star
6

drop

A library for creating dropdowns and other floating elements. #hubspot-open-source
CSS
2,360
star
7

BuckyClient

Collect performance data from the client
CoffeeScript
1,738
star
8

sortable

Drop-in script to make tables sortable
CSS
1,322
star
9

select

Styleable select elements built on Tether. #hubspot-open-source
JavaScript
1,197
star
10

humanize

A simple utility library for making the web more humane. #hubspot-open-source
JavaScript
907
star
11

Singularity

Scheduler (HTTP API and webapp) for running Mesos tasksโ€”long running processes, one-off tasks, and scheduled jobs. #hubspot-open-source
Java
816
star
12

tooltip

CSS Tooltips built on Tether. #hubspot-open-source
CSS
711
star
13

jinjava

Jinja template engine for Java
Java
687
star
14

signet

Display a unique seal in the developer console of your page
CoffeeScript
564
star
15

draft-convert

Extensibly serialize & deserialize Draft.js ContentState with HTML.
JavaScript
483
star
16

hubspot-php

HubSpot PHP API Client
PHP
342
star
17

hubspot-api-python

HubSpot API Python Client Libraries for V3 version of the API
Python
323
star
18

cms-theme-boilerplate

A straight-forward starting point for building a great website on the HubSpot CMS
HTML
320
star
19

hubspot-api-nodejs

HubSpot API NodeJS Client Libraries for V3 version of the API
TypeScript
304
star
20

react-select-plus

Fork of https://github.com/JedWatson/react-select with option group support
JavaScript
281
star
21

SlimFast

Slimming down jars since 2016
Java
270
star
22

dropwizard-guice

Adds support for Guice to Dropwizard
Java
268
star
23

gc_log_visualizer

Generate multiple gnuplot graphs from java gc log data
Python
200
star
24

BuckyServer

Node server that receives metric data over HTTP & forwards to your service of choice
CoffeeScript
195
star
25

hubspot-api-php

HubSpot API PHP Client Libraries for V3 version of the API
PHP
191
star
26

hubspot-cli

A CLI for HubSpot
JavaScript
153
star
27

facewall

Grid visualization of Gravatars for an organization
CoffeeScript
138
star
28

jackson-datatype-protobuf

Java
116
star
29

draft-extend

Build extensible Draft.js editors with configurable plugins and integrated serialization.
JavaScript
116
star
30

prettier-maven-plugin

Java
116
star
31

slack-client

An asynchronous HTTP client for Slack's web API
Java
114
star
32

hubspot-api-ruby

HubSpot API Ruby Client Libraries for V3 version of the API
Ruby
113
star
33

Rosetta

Java library that leverages Jackson to take the pain out of mapping objects to/from the DB, designed to integrate seamlessly with jDBI
Java
110
star
34

Baragon

Load balancer API
Java
105
star
35

mixen

Combine Javascript classes on the fly
CoffeeScript
85
star
36

jquery-zoomer

Zoom up your iFrames
JavaScript
81
star
37

oauth-quickstart-nodejs

A Node JS app to get up and running with the HubSpot API using OAuth 2.0
JavaScript
79
star
38

hapipy

A Python wrapper for the HubSpot APIs #hubspot-open-source
Python
78
star
39

ui-extensions-examples

This repository contains code examples of UI extensions built with HubSpot CRM development tools beta
TypeScript
76
star
40

oneforty-data

Open data on 4,000+ social media apps from oneforty.com #hubspot-open-source
Ruby
70
star
41

cms-react-boilerplate

JavaScript
69
star
42

sample-workflow-custom-code

Sample code snippets for the custom code workflow action.
68
star
43

hubspot-cms-vscode

A HubL language extension for the Visual Studio Code IDE, allowing for ๐Ÿš€ fast local HubSpot CMS Platform development.
TypeScript
64
star
44

Blazar-Archive

An out-of-this world build system!
Java
62
star
45

haPiHP

An updated PHP client for the HubSpot API
PHP
61
star
46

sanetime

A sane date/time python interface #hubspot-open-source
Python
60
star
47

BidHub-CloudCode

The Parse-based brains behind BidHub, our open-source silent auction app.
JavaScript
50
star
48

teeble

A tiny table plugin
JavaScript
49
star
49

hubspot.github.com

HubSpot Open Source projects.
JavaScript
46
star
50

calling-extensions-sdk

A JavaScript SDK for integrating calling apps into HubSpot.
JavaScript
45
star
51

BidHub-iOS

iOS client for BidHub, our open-source silent auction app.
Objective-C
44
star
52

dropwizard-guicier

Java
42
star
53

hubspot-cms-deploy-action

GitHub Action to deploy HubSpot CMS projects
HTML
40
star
54

live-config

Live configuration for Java applications #hubspot-open-source
Java
37
star
55

executr

Let your users execute the CoffeeScript in your documentation
JavaScript
35
star
56

transmute

kind of like lodash but works with Immutable
JavaScript
35
star
57

NioImapClient

High performance, async IMAP client implementation
Java
34
star
58

colorshare

Style up your social share buttons
CSS
32
star
59

recruiting-agency-graphql-theme

A theme based off of the HubSpot CMS Boilerplate. This theme includes modules and templates that demonstrate how to utilize GraphQL as part of a website built with HubSpot CMS and Custom CRM Objects.
HTML
32
star
60

integration-examples-php

PHP
32
star
61

cms-event-registration

JavaScript
32
star
62

ChromeDevToolsClient

A java websocket client for the Chrome DevTools Protocol
Java
31
star
63

canvas

HubSpot Canvas is the design system that we at HubSpot use to build our products.
JavaScript
31
star
64

integration-examples-nodejs

JavaScript
31
star
65

cms-react

A repo to expose CMS react examples, React defaults modules, and more to CMS devs
JavaScript
30
star
66

sample-apps-list

The list of Sample applications using HubSpot Public API
28
star
67

NioSmtpClient

Smtp Client based on Netty
Java
28
star
68

vee

A personal proxy server for web developers
CoffeeScript
28
star
69

cms-js-building-block-examples

DEPRECATED, go to https://github.com/HubSpot/cms-react instead
JavaScript
28
star
70

prettier-plugin-hubl

HTML
25
star
71

jackson-jaxrs-propertyfiltering

Java
25
star
72

local-cms-server-cli

Command line tools for local cms development
CSS
22
star
73

astack

Simple stacktrace analysis tool for the JVM
Python
22
star
74

Horizon

Java
20
star
75

rHAPI

Ruby wrapper for the HubSpot API (HAPI)
Ruby
20
star
76

integrate

Confirm that your application works.
CoffeeScript
20
star
77

moxie

A TCP proxy guaranteed to make you smile. #hubspot-open-source
Python
18
star
78

BidHub-WebAdmin

Keep an eye on BidHub while it's doing its thing.
HTML
18
star
79

sample-apps-webhooks

Sample code and reference for processing HubSpot webhooks
JavaScript
17
star
80

hubspot-immutables

Java
17
star
81

cms-custom-objects-example

CSS
17
star
82

hubspot-academy-tutorials

JavaScript
17
star
83

hbase-support

Supporting configs and tools for HBase at HubSpot
Java
17
star
84

cms-vue-boilerplate

Boilerplate Vue project for creating apps using modules on the HubSpot CMS
JavaScript
17
star
85

sprocket

A better REST API framework for django
Python
17
star
86

sample-apps-manage-crm-objects

Sample application in PHP, Python, Ruby and JavaScript demonstrating HubSpot API to manage CRM Objects
JavaScript
17
star
87

react-decorate

Build composable, stateful decorators for React.
JavaScript
16
star
88

maven-snapshot-accelerator

System to speed up dependency resolution when using Maven snapshots #hubspot-open-source
Java
16
star
89

algebra

Simple abstract data types (wrapping derive4j) in Java
Java
15
star
90

sample-apps-oauth

Sample application demonstrating OAuth 2.0 flow with HubSpot API
Ruby
15
star
91

httpQL

A small library for converting URL query arguments into SQL queries.
Java
15
star
92

cms-webpack-serverless-boilerplate

Boilerplate for bundling serverless functions with webpack locally, prior to uploading to the CMS.
JavaScript
13
star
93

virtualenvchdir

Easily chdir into different virtualenvs #hubspot-open-source
Shell
12
star
94

HubspotEmailTemplate

How to convert a regular html coded email template into ones that use HubSpot jinja tags.
12
star
95

hubstar

CSS
12
star
96

private-app-starter

Boilerplates apps using HubSpot API
PHP
12
star
97

chrome_extension_workshop

Chrome extension workshop
JavaScript
11
star
98

serverless-function-examples

A collection of HubSpot related serverless functions examples.
JavaScript
11
star
99

cos_uploader

A python script for syncing a file tree to the HubSpot COS
Python
11
star
100

collectd-gcmetrics

Python
10
star