pwmckenna / til

Today I Learned
http://pwmckenna.net
9 stars 8 forks source link

Fluxible Plugin Scaffolding #24

Closed pwmckenna closed 7 years ago

pwmckenna commented 7 years ago

Here's an example that hooks Fluxible action calls, event dispatches, and even fetchr service calls (fluxible-plugin-fetchr)

Doesn't actually do anything...yet :)

import Q from 'q';

export default {
    name: 'HelloWorld',

    plugContext: () => {
        return {
            dehydrate: () => {
                // this is likely when you're about to render server side...
                // this is a good place to log all the activity that went into it
            },
            rehydrate: () => {},
            plugExecuteAction: ({ action, actionContext, ...rest }) => ({
                ...rest,
                actionContext,
                action: (context, payload, done) => {
                    const defer = Q.defer();
                    // you're about to call an action
                    action(context, payload, defer.makeNodeResolver());
                    return defer.promise.finally(() => {
                        // the action has completed
                    }).nodeify(done);
                }
            }),
            plugActionContext: context => {
                // fluxible-plugin-fetchr adds service to your context
                // now you can log all of that
                // https://www.npmjs.com/package/fluxible-plugin-fetchr
                if (context.service) {
                    const service = context.service;
                    const {
                        read,
                        update,
                        delete: del,
                        create,
                        ...rest
                    } = service;
                    context.service = {
                        read: function (...args) {
                            return read.apply(service, args);
                        },
                        update: function (...args) {
                            return update.apply(service, args);
                        },
                        delete: function (...args) {
                            return del.apply(service, args);
                        },
                        create: function (...args) {
                            return create.apply(service, args);
                        },
                        ...rest
                    };
                }

                const dispatch = context.dispatch;
                context.dispatch = (event, ...dispatched) => {
                    // you're about to dispatch an event
                    return dispatch.call(context, event, ...dispatched);
                };
            }
        };
    }
};