Skip to content

Commit

Permalink
[preview] Optimize preview fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoerge committed Feb 16, 2018
1 parent 4442fcc commit c1e0ca3
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions packages/@sanity/preview/src/observeWithPaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,35 @@ import {combineSelections, reassemble, toGradientQuery} from './utils/optimizeQu
let _globalListener
const getGlobalListener = () => {
if (!_globalListener) {
_globalListener = Observable
.from(client.listen('*[!(_id in path("_.**"))]', {}, {includeResult: false}))
.share()
_globalListener = Observable.from(
client.listen('*[!(_id in path("_.**"))]', {}, {includeResult: false})
).share()
}
return _globalListener
}

function listen(id) {
return Observable.of({type: 'welcome', documentId: id})
.concat(getGlobalListener())
.filter(event => event.documentId === id)
return getGlobalListener().filter(event => event.documentId === id)
}

function fetchAllDocumentSnapshots(selections) {
function fetchAllDocumentPaths(selections) {
const combinedSelections = combineSelections(selections)
return client.observable
.fetch(toGradientQuery(combinedSelections))
.map(result => reassemble(result, combinedSelections))
}

const debouncedFetchDocumentSnapshot = debounceCollect(fetchAllDocumentSnapshots, 50)
const fetchDocumentPathsFast = debounceCollect(fetchAllDocumentPaths, 0)
const fetchDocumentPathsSlow = debounceCollect(fetchAllDocumentPaths, 1000)

// todo: keep for debugging purposes for now
// function fetchDocumentSnapshot(id, selection) {
// function fetchDocumentPaths(id, selection) {
// return client.observable.fetch(`*[_id==$id]{_id,_type,${selection.join(',')}}`, {id})
// .map(result => result[0])
// }

export default function observeWithPaths(id, paths) {
return debouncedFetchDocumentSnapshot(id, paths)
.concat(listen(id)
.debounceTime(1000)
.switchMap(event => debouncedFetchDocumentSnapshot(id, paths)))
return fetchDocumentPathsFast(id, paths).concat(
listen(id).switchMap(event => fetchDocumentPathsSlow(id, paths))
)
}

0 comments on commit c1e0ca3

Please sign in to comment.