Skip to content

Instantly share code, notes, and snippets.

@johanobergman
Last active November 8, 2016 09:53
Show Gist options
  • Save johanobergman/8f829faa0eb76cdc22a8 to your computer and use it in GitHub Desktop.
Save johanobergman/8f829faa0eb76cdc22a8 to your computer and use it in GitHub Desktop.
Remember the rangeBehaviors of a Relay connection

To remember a connection, run RangeBehaviors.remember in relay.prepareVariables with a name, the connection arguments and an optional rangeBehavior operation:

prepareVariables(variables) {
    var { startDate, endDate } = variables;

    RangeBehaviors.remember('items', { startDate, endDate }, 'prepend'); // append if not specified

    return variables;
}

To populate rangeBehaviors in a RANGE_ADD mutation, run RangeBehaviors.get. The callback will run for every remembered connection.

getConfigs() {
    var rangeBehaviors = RangeBehaviors.get('items', ({startDate, endDate}) => {
            return dateIsBetween(this.props.date, startDate, endDate);
        }
    );

    return [{
        type: 'RANGE_ADD',
        parentName: 'viewer',
        parentID: this.props.viewer.id,
        connectionName: 'items',
        edgeName: 'itemEdge',
        rangeBehaviors
    }];
}

Returning true in the callback will result in a rangeBehavior with the value (append/prepend) that was specified in RangeBehaviors.remember. Returning false will give the rangeBehavior the value of an empty string, in order to tell relay that nothing has to be done. You can also return append/prepend directly in the callback in order to override the default.

var rangeBehaviors = {};
export default {
remember(name, args, defaultBehavior = 'append') {
rangeBehaviors[name] = rangeBehaviors[name] || [];
let params = Object.keys(args).sort();
let key = params.map(param => `${param}(${args[param]})`).join('.');
rangeBehaviors[name].push({ key, args, defaultBehavior });
},
get(name, callback) {
return rangeBehaviors[name].reduce((prev, {key, args, defaultBehavior}) => {
prev[key] = getBehavior(callback(args), defaultBehavior);
return prev;
}, {});
}
};
function getBehavior(behavior, defaultBehavior) {
if ( ! behavior) return '';
return behavior === true ? defaultBehavior : behavior;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment