• Stars
    star
    114
  • Rank 308,031 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 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

Integrate Feathers with your Redux store

feathers-redux

Build Status Code Climate Test Coverage Dependency Status Download Status

Integrate Feathers services with your Redux store

Example

On server:

app.use('/users', ...);
app.use('/messages', ...);

On client:

import reduxifyServices from 'feathers-redux';
const feathersClient = feathers(). ...;

// Create Redux actions and reducers for Feathers services
const services = reduxifyServices(feathersClient, ['users', 'messages']);

// Configure Redux store & reducers
export default combineReducers({
  users: services.users.reducer,
  messages: services.messages.reducer,
});

// Feathers service calls may now be dispatched.
store.dispatch(services.messages.get('557XxUL8PalGMgOo'));
store.dispatch(services.messages.find());
store.dispatch(services.messages.create({ text: 'Hello!' }));

Installation

npm install feathers-redux --save

Documentation: reduxifyServices

import reduxifyServices from 'feathers-redux';
const services = reduxifyServices(app, serviceNames, options);

Options:

  • app (required) - The Feathers client app.
  • serviceNames (required, string, array of strings, or object) - The paths of the Feathers services to reduxify.
    • 'messages' is short for { messages: 'messages' }. You can dispatch calls with dispatch(services.messages.create(data, params));.
    • ['users', 'messages'] is short for { users: 'users', messages: 'messages' }.
    • { '/buildings/:buildingid': 'buildings' } will reduxify the Feathers service configured with the path /buildings/:buildingid. You can dispatch calls with dispatch(services.buildings.create(data, params));.
  • options (optional) - Names for props in the Redux store, and for string fragments in the action constants. The default is
{ // Names of props for service's Redux state
  idField: 'id',
  isError: 'isError', // e.g. state.messages.isError
  isLoading: 'isLoading',
  isSaving: 'isSaving',
  isFinished: 'isFinished',
  data: 'data',
  queryResult: 'queryResult',
  store: 'store',
  // Fragments to form action constants
  PENDING: 'PENDING', // e.g. MESSAGES_CREATE_PENDING
  FULFILLED: 'FULFILLED',
  REJECTED: 'REJECTED',
}

reduxifyServices returns an object of the form

{
  messages: { // For the Feathers service with path /messages.
    // action creators
    create(data, params) {}, // Action creator for app.services('messages').create(data, params)
    update(id, data, params) {},
    patch(id, data, params) {},
    remove(id, params) {},
    find(params) {},
    get(id, params) {},
    store(object) {}, // Interface for realtime replication.
    reset() {}, // Reinitializes store for this service.
    // action types
    types: {
      RESET: 'RESET',
      STORE: 'STORE',
      SERVICES_MESSAGES_FIND: 'SERVICES_MESSAGES_FIND',
      SERVICES_MESSAGES_FIND_PENDING: 'SERVICES_MESSAGES_FIND_PENDING',
      SERVICES_MESSAGES_FIND_FULFILLED: 'SERVICES_MESSAGES_FIND_FULFILLED',
      SERVICES_MESSAGES_FIND_REJECTED: 'SERVICES_MESSAGES_FIND_REJECTED',
      // same for all methods GET, CREATE...
    },
    // reducer
    reducer() {}, // Reducers handling actions MESSAGES_CREATE_PENDING, _FULFILLED, and _REJECTED.
  },
  users: { ... },
}

Service calls may be dispatched by

dispatch(services.messages.create(data, params));

Reducers may be combined with

combineReducers({
  users: services.users.reducer,
  messages: services.messages.reducer,
});

ProTip: You have to include redux-promise-middleware and redux-thunk in your middleware.

You may listen to actions dispatched by feathers-redux, for example to manage your side-effects. With redux-saga, it would be done with:

yield take(services.users.types.SERVICES_USERS_CREATE_FULFILLED, function*(action) {
  // do something when user gets created
});

Documentation: getServicesStatus

Its common for React apps to display info messages such as "Messages are being saved." getServicesStatus returns a relevant message for the reduxified Feathers services.

import reduxifyServices, { getServicesStatus } from 'feathers-redux';
const msg = getServicesStatus(state, serviceNames)

Options:

  • state (required) - The state containing state for the services.
  • serviceNames (required, string, array of strings) - The names of the Feathers services.

The services are checked from left to right. They first are checked for an error condition (isError), and if an error is found the function returns an object similar to

{ message: 'users: Error.message',
  className = Error.className, // Can be used to internationalize the message.
  serviceName = 'users';
}

Next they are check for loading or saving, and if one is found the function returns an object similar to

{ message: 'users is loading',
  className = 'isLoading', // Or isSaving.
  serviceName = 'users';
}

Otherwise the object is returned with empty strings.

Realtime replication

The Feathers read-only, realtime replication engine is feathers-offline-realtime. You can connect this engine with

const Realtime = require('feathers-offline-realtime');
const messages = feathersClient.service('/messages');

const messagesRealtime = new Realtime(messages, { subscriber: (records, last) => {
  store.dispatch(services.messages.store({ connected: messagesRealtime.connected, last, records }));
} });

Shape of the store

The above code produces a state shaped like

state = {
  messages: {
    isLoading: boolean, // If get or find have started
    isSaving: boolean, // If update, patch or remove have started
    isFinished: boolean, // If last call finished successfully
    isError: Feathers error, // If last call was unsuccessful
    data: hook.result, // Results from other than a find call
    queryResult: hook.result, // Results from a find call. May be paginated.
    store: {
      connected: boolean, // If replication engine still listening for Feathers service events
      last: { // Read https://github.com/feathersjs/feathers-offline-realtime#event-information.
        action: string, // Replication action.
        eventName: string, // Feathers service event name. e.g. created
        records: object, // Feathers service event record.
      },
      records: [ objects ], // Sorted near realtime contents of remote service
    },
  },
  users: { ... },
};

Autobind Action Creators

Method to bind a given dispatch function with the passed services. This helps with not having to pass down store.dispatch as a prop everywhere the service is being used. Read More: http://redux.js.org/docs/api/bindActionCreators.html

import reduxifyServices, { bindWithDispatch } from 'feathers-redux';

// create a services object as described above 
const rawServices = reduxifyServices(...);

// create a store with rootReducer combining reducers from rawServices
const store = createStore(...)

// use the bindWithDispatch method to bind rawServices' action creators with store.dispatch
const services = bindWithDispatch(store.dispatch, rawServices)
// before 
store.dispatch(services.messages.get('557XxUL8PalGMgOo'));
store.dispatch(services.messages.find());
store.dispatch(services.messages.create({ text: 'Hello!' }));

// after
services.messages.get('557XxUL8PalGMgOo');
services.messages.find();
services.messages.create({ text: 'Hello!' });

Realtime Feathers Updates

If any of your services need real time updates, you can dispatch any of the following actions depending on your use case:

    dispatch(services.messages.onCreated(data));
    dispatch(services.messages.onUpdated(data));
    dispatch(services.messages.onPatched(data));
    dispatch(services.messages.onRemoved(data));

In order for the redux store to update in realtime, these action dispatches should be encapsulated within feathers service.on() event listener:

 const messages = app.service('/messages');

 messages.on('created', (data) => {
      dispatch(services.messages.onCreated(data));
  })
  messages.on('updated', (data) => {
      dispatch(services.messages.onUpdated(data));
  })
  messages.on('patched', (data) => {
      dispatch(services.messages.onPatched(data));
  })
  messages.on('removed', (data) => {
      dispatch(services.messages.onRemoved(data));
  })

Note: idField is used to match events with correct objects.

Action Pending/Loading

The following properties exist in all of the feather services:

  const pendingDefaults = {
    createPending: false,
    findPending: false,
    getPending: false,
    updatePending: false,
    patchPending: false,
    removePending: false
  };

The service pending state will be updated according to the dispatched action.

    dispatch(services.messages.create({ text: 'Hello!' })) `will update the state to:` createPending: true
    dispatch(services.messages.find()) `will update the state to:` findPending: true 
    dispatch(services.messages.get('557XxUL8PalGMgOo')) `will update the state to:` getPending: true
    dispatch(services.messages.update(id, data) `will update the state to:` updatePending: true
    dispatch(services.messages.patch(id, data) `will update the state to:` patchPending: true
    dispatch(services.messages.remove(id, params) `will update the state to:` removePending: true

Examples

example/ contains an example you may run. Its README has instructions.

feathers-redux/test/integration.test.js may answer any questions regarding details.

License

Copyright (c) 2017

Licensed under the MIT license.

More Repositories

1

feathers-vuex

Integration of FeathersJS, Vue, and Nuxt for the artisan developer
TypeScript
445
star
2

authentication

[MOVED] Feathers local, token, and OAuth authentication over REST and Websockets using JSON Web Tokens (JWT) with PassportJS.
JavaScript
317
star
3

feathers-authentication-management

Adds sign up verification, forgotten password reset, and other capabilities to local feathers-authentication
TypeScript
247
star
4

feathers-swagger

Add documentation to your FeatherJS services and feed them to Swagger UI.
JavaScript
225
star
5

feathers-sync

Synchronize service events between Feathers application instances
JavaScript
222
star
6

feathers-reactive

Reactive API extensions for Feathers services
TypeScript
216
star
7

feathers-sequelize

A Feathers service adapter for the Sequelize ORM. Supporting MySQL, MariaDB, Postgres, SQLite, and SQL Server
TypeScript
208
star
8

feathers-react-native-chat

A React Native example chat app using feathers
JavaScript
196
star
9

feathers-hooks-common

Useful hooks for use with FeathersJS services.
TypeScript
193
star
10

feathers-mongoose

Easily create a Mongoose Service for Feathersjs.
JavaScript
189
star
11

feathers-permissions

Simple role and service method permissions for Feathers
JavaScript
184
star
12

cli

The command line interface for scaffolding Feathers applications
JavaScript
155
star
13

feathers-mongodb

A mongodb service for feathers
JavaScript
122
star
14

generator-feathers

A Yeoman generator for a Feathers application
JavaScript
120
star
15

feathers-authentication-hooks

Useful hooks for authentication and authorization
JavaScript
115
star
16

feathers-knex

Service adapters for KnexJS a query builder for PostgreSQL, MySQL, MariaDB, Oracle and SQLite3
JavaScript
112
star
17

client

[MOVED] Client side Feathers build
JavaScript
111
star
18

feathers-chat-vuex-0.7

Feathers Chat application build using feathers-vuex
CSS
102
star
19

feathers-objection

Feathers database adapter for Objection.js, an ORM based on KnexJS SQL query builder for Postgres, Redshift, MSSQL, MySQL, MariaDB, SQLite3, and Oracle. Forked from feathers-knex.
JavaScript
98
star
20

feathers-chat-react

Feathers Chat application build using React and create-react-app
JavaScript
97
star
21

feathers-batch

Batch multiple Feathers service calls into one
JavaScript
96
star
22

feathers-stripe

TypeScript
95
star
23

feathers-blob

Feathers service for blob storage, like S3.
JavaScript
92
star
24

feathers-rethinkdb

A Feathers service adapter for RethinkDB.
JavaScript
85
star
25

feathers-nedb

A service using NeDB, an embedded datastore for Node.js
TypeScript
83
star
26

feathers-mailer

Feathers mailer service using nodemailer
TypeScript
83
star
27

feathers-elasticsearch

Feathersjs adapter for Elasticsearch
JavaScript
78
star
28

validate-joi

Feathers hook utility for schema validation, sanitization and client notification using Joi.
JavaScript
67
star
29

feathers-hooks

Service method hooks for easy authorization and processing
JavaScript
59
star
30

feathers-chat-ts

A Feathers real-time chat application in TypeScript
TypeScript
54
star
31

feathers-rest

The Feathers HTTP(S) transport plugin for REST APIs
JavaScript
52
star
32

feathers-chat-angular

An angular implementation of a feathers-chat client
TypeScript
52
star
33

feathers-chat-vuex

Feathers Chat built with Feathers-Vuex 3.0
CSS
50
star
34

feathers-swift

FeathersJS Swift SDK, written with love.
Swift
50
star
35

feathers-memory

An in memory feathers service
JavaScript
44
star
36

authentication-client

[MOVED] The authentication client
JavaScript
41
star
37

feathers-localstorage

A client side service based on feathers-memory that persists to LocalStorage
JavaScript
38
star
38

socketio

[MOVED] The Feathers Socket.io websocket transport plugin
JavaScript
37
star
39

schema

JavaScript and TypeScript schema definitions
TypeScript
35
star
40

errors

[MOVED] Feathers errors for server and client
JavaScript
35
star
41

authentication-jwt

[MOVED] JWT authentication strategy for feathers-authentication using Passport
JavaScript
30
star
42

configuration

[MOVED] A plugin for configuring a Feathers application
JavaScript
28
star
43

feathers-profiler

Log feathers service calls and gather profile information on them.
JavaScript
27
star
44

feathers-bootstrap

Feathers application bootstrap and configuration using JSON files
JavaScript
26
star
45

authentication-oauth2

[MOVED] OAuth 2 plugin for feathers-authentication
JavaScript
26
star
46

feathers-mailgun

A Feathers service for Mailgun
JavaScript
26
star
47

authentication-local

[MOVED] Local authentication plugin for feathers-authentication
JavaScript
26
star
48

feathers-logger

A little wrapper for convenient logging in feathers
JavaScript
23
star
49

feathers-debugger

Feathers Debugger Chrome extension
JavaScript
23
star
50

generator-feathers-plugin

A Yeoman generator for creating a FeathersJS plugin.
JavaScript
22
star
51

feathers-waterline

A Feathers adapter for the Waterline ORM
JavaScript
21
star
52

feathers-service-tests

A test harness for Feathers service implementations
JavaScript
20
star
53

feathers-authentication-ldap

LDAP authentication strategy for feathers-authentication using Passport
JavaScript
19
star
54

primus

[MOVED] The Feathers Primus websocket transport plugin
JavaScript
18
star
55

feathers-levelup

LevelUP instances as Feathers services
JavaScript
14
star
56

feathers-authentication-popups

Server and client utils for implementing popup-based authentication flows
JavaScript
14
star
57

batch-loader

Reduce requests to backend services by batching calls and caching records.
JavaScript
13
star
58

express

[MOVED] Feathers Express framework bindings and REST transport plugin
JavaScript
13
star
59

feathers-query-filters

Adds support for special query string params used for filtering data
JavaScript
12
star
60

commons

[MOVED] Shared utility functions
JavaScript
11
star
61

transport-commons

[MOVED] Shared functionality for Feathers transports
JavaScript
11
star
62

feathers-mongodb-management

Manage MongoDB Databases, Users & Collections with this Feathers service adapter
JavaScript
11
star
63

feathers-generator

A metalsmith based generator for scaffolding Feathers apps.
JavaScript
10
star
64

feathers-debugger-service

Feathers Debugger service, use with Feathers Debugger.
JavaScript
9
star
65

feathers-cassandra

Feathers service adapter for Cassandra DB based on Express-Cassandra ORM and CassanKnex query builder
JavaScript
8
star
66

rest-client

[MOVED] REST client services for different Ajax libraries
JavaScript
8
star
67

feathers-android

Android client for feathers services
Java
7
star
68

feathers-swift-socketio

FeathersSwift SocketIO Transport Provider
Swift
7
star
69

feathers-twilio

A Feathers service for talking to the Twilio API
JavaScript
7
star
70

website

The old Feathers website
Less
6
star
71

dataloader

JavaScript
6
star
72

feathers-authentication-custom

Custom authentication strategy for feathers-authentication using Passport
JavaScript
5
star
73

authentication-oauth1

[MOVED] A Feathers OAuth1.x authentication strategy
JavaScript
5
star
74

socketio-client

[MOVED] Client services for Socket.io and feathers-socketio
JavaScript
5
star
75

primus-client

[MOVED] Client services for Primus and feathers-primus
JavaScript
5
star
76

feathers-redis

A Feathers redis service adapter
JavaScript
4
star
77

tools

Codemods and other generator and repository management tools
JavaScript
3
star
78

feathers-couchbase

A Couchbase Service for feathers
JavaScript
3
star
79

feathers-swift-rest

REST Transport provider for FeathersSwift
Swift
2
star
80

feathers-ios

Feathers service client for iOS
Swift
2
star
81

feathers-sendgrid

Sendgrid service for Feathers
JavaScript
1
star