-
Notifications
You must be signed in to change notification settings - Fork 0
session
Aakash Rajur edited this page Oct 7, 2018
·
1 revision
while creating user session
, we've the following plan of actions:
- create or restore user session with
CREATE_SESSION
query and receive oursession jwt token
. - Establish our subscription with that token to isolate user
subscription
withApolloServer channel
mechanism. - Save
session
to cookies, store all latest notifications in the state. - Pass session and notifications on to the child component.
-
graphQLSubscribe
is convenience function for subscription. read more at src/utils/library.js
import PropTypes from "prop-types";
import React, {Component} from 'react';
import {compose, withApollo} from 'react-apollo';
import {
CREATE_SESSION,
ON_SERVER_NOTIFICATION,
TASKS_UPDATED
} from "./query";
import {TASK_ALL, TASK_CANCELLED, TASK_COMPLETED, TASK_CREATED} from "../utils/constants";
import {graphQLSubscribe, parseNotification, parseTasksChanged} from "../utils/library";
const DEFAULT_SESSION = "{}";
export const sessionCreator = graphql(CREATE_SESSION, {
options: () => ({fetchPolicy: 'network-only'}),
props: ({data: {session = DEFAULT_SESSION}}) => {
session = JSON.parse(session);
return {...session};
}});
export function withSession(Child) {
return sessionCreator(withApollo(
class Session extends Component {
static propTypes = {
token: PropTypes.string,
action: PropTypes.string,
client: PropTypes.object
};
constructor(props) {
super(props);
this.state = {};
}
componentDidUpdate(prevProps) {
if (prevProps.action !== this.props.action) {
const {action, token, client} = this.props;
if (action === 'NEW_SESSION') {
document.cookie = `session=${token};`;
}
graphQLSubscribe(
client,
//convenience function to intercept payload, parse and transform it
parseNotification(this.onSubscriptionData('notification')),
ON_SERVER_NOTIFICATION, {
token
}
);
graphQLSubscribe(
client,
//convenience function to intercept payload, parse and transform it
parseTasksChanged(this.onSubscriptionData('stat')),
TASKS_UPDATED, {
token
}
);
}
}
render() {
const {props, state} = this;
return <Child {...props} {...state}/>;
}
onSubscriptionData(key) {
return (data) => this.setState({[key]: data});
}
}
));
}
Explore more at src/graphql/hoc.js
- Server
- Client