Created
January 2, 2018 12:19
-
-
Save azazdeaz/32050e0cd051c58805d3bf49c8244708 to your computer and use it in GitHub Desktop.
wip live apollo link
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import { visit, Kind } from 'graphql/language' | |
import { ApolloLink, Observable } from 'apollo-link' | |
import traverse from 'traverse' | |
import createLiveSubscription from './createLiveSubscription' | |
import debounce from 'lodash/debounce' | |
export function parseLiveDirectives(query) { | |
return visit(query, { | |
[Kind.FIELD]: { | |
enter(node, key, parent) { | |
if ((node.directives || []).find(d => d.name.value === 'live')) { | |
parent.push({ | |
kind: 'Field', | |
name: { | |
kind: 'Name', | |
value: `${node.name.value}_liveKeys` | |
}, | |
arguments: node.arguments, | |
directives: [], | |
selectionSet: null | |
}) | |
} | |
} | |
}, | |
[Kind.DIRECTIVE]: { | |
leave(node) { | |
if (node.name.value === 'live') { | |
return null | |
} | |
} | |
} | |
}) | |
} | |
export default class LiveLink extends ApolloLink { | |
request(operation, forward) { | |
operation.query = parseLiveDirectives(operation.query) | |
const originalContext = operation.getContext() | |
return new Observable(observer => { | |
const liveUpdates = createLiveSubscription(debounce(() => { | |
console.log(`@live reload ${operation.operationName}`) | |
operation.setContext(originalContext) | |
this.subscription.unsubscribe() | |
this.subscription = forward(operation).subscribe(subscriber) | |
}, 100)) | |
const subscriber = { | |
next: data => { | |
const liveKeys = [] | |
traverse(data).forEach(function (value) { | |
if (this.key && this.key.endsWith('_liveKeys')) { | |
liveKeys.push(...value) | |
} | |
}) | |
console.log('data', operation.operationName, data) | |
console.log('settingLiveKeys', liveKeys) | |
liveUpdates.setLiveKeys(liveKeys) | |
observer.next(data); | |
}, | |
error: error => observer.error(error), | |
} | |
this.subscription = forward(operation).subscribe(subscriber) | |
return () => { | |
console.log('CLOSE QUERY', operation.operationName) | |
liveUpdates.unsubscribe() | |
this.subscription.unsubscribe() | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment