-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathuseFind.ts
More file actions
164 lines (145 loc) · 4.9 KB
/
useFind.ts
File metadata and controls
164 lines (145 loc) · 4.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import { Meteor } from 'meteor/meteor'
import { Mongo } from 'meteor/mongo'
import { useReducer, useMemo, useEffect, Reducer, DependencyList, useRef } from 'react'
import { Tracker } from 'meteor/tracker'
import useSyncEffect from './useSyncEffect'
type useFindActions<T> =
| { type: 'refresh', data: T[] }
| { type: 'addedAt', document: T, atIndex: number }
| { type: 'changedAt', document: T, atIndex: number }
| { type: 'removedAt', atIndex: number }
| { type: 'movedTo', fromIndex: number, toIndex: number }
const useFindReducer = <T>(data: T[], action: useFindActions<T>): T[] => {
switch (action.type) {
case 'refresh':
return action.data
case 'addedAt':
return [
...data.slice(0, action.atIndex),
action.document,
...data.slice(action.atIndex)
]
case 'changedAt':
return [
...data.slice(0, action.atIndex),
action.document,
...data.slice(action.atIndex + 1)
]
case 'removedAt':
return [
...data.slice(0, action.atIndex),
...data.slice(action.atIndex + 1)
]
case 'movedTo':
const doc = data[action.fromIndex]
const copy = [
...data.slice(0, action.fromIndex),
...data.slice(action.fromIndex + 1)
]
copy.splice(action.toIndex, 0, doc)
return copy
}
}
// Check for valid Cursor or null.
// On client, we should have a Mongo.Cursor (defined in
// https://github.com/meteor/meteor/blob/devel/packages/minimongo/cursor.js and
// https://github.com/meteor/meteor/blob/devel/packages/mongo/collection.js).
// On server, however, we instead get a private Cursor type from
// https://github.com/meteor/meteor/blob/devel/packages/mongo/mongo_driver.js
// which has fields _mongo and _cursorDescription.
const checkCursor = <T>(cursor: Mongo.Cursor<T> | Partial<{ _mongo: any, _cursorDescription: any }> | undefined | null) => {
if (cursor !== null && cursor !== undefined && !(cursor instanceof Mongo.Cursor) &&
!(cursor._mongo && cursor._cursorDescription)) {
console.warn(
'Warning: useFind requires an instance of Mongo.Cursor. '
+ 'Make sure you do NOT call .fetch() on your cursor.'
);
}
}
// Synchronous data fetch. It uses cursor observing instead of cursor.fetch() because synchronous fetch will be deprecated.
const fetchData = <T>(cursor: Mongo.Cursor<T>) => {
const data: T[] = []
const observer = cursor.observe({
addedAt (document, atIndex, before) {
data.splice(atIndex, 0, document)
},
})
observer.stop()
return data
}
const useFindClient = <T = any>(factory: () => (Mongo.Cursor<T> | undefined | null), deps: DependencyList = []) => {
const cursor = useMemo(() => {
// To avoid creating side effects in render, opt out
// of Tracker integration altogether.
const cursor = Tracker.nonreactive(factory);
if (Meteor.isDevelopment) {
checkCursor(cursor)
}
return cursor
}, deps)
const [data, dispatch] = useReducer<Reducer<T[], useFindActions<T>>, null>(
useFindReducer,
null,
() => {
if (!(cursor instanceof Mongo.Cursor)) {
return []
}
return fetchData(cursor)
}
)
useSyncEffect(() => {
if (!(cursor instanceof Mongo.Cursor)) {
return
}
const initialData = fetchData(cursor);
dispatch({ type: 'refresh', data: initialData });
const observer = cursor.observe({
addedAt(document, atIndex, before) {
dispatch({ type: 'addedAt', document, atIndex })
},
changedAt(newDocument, oldDocument, atIndex) {
dispatch({ type: 'changedAt', document: newDocument, atIndex })
},
removedAt(oldDocument, atIndex) {
dispatch({ type: 'removedAt', atIndex })
},
movedTo(document, fromIndex, toIndex, before) {
dispatch({ type: 'movedTo', fromIndex, toIndex })
},
// @ts-ignore
_suppress_initial: true
})
return () => {
observer.stop()
}
}, [cursor]);
return cursor ? data : cursor
}
const useFindServer = <T = any>(factory: () => Mongo.Cursor<T> | undefined | null, deps: DependencyList) => (
Tracker.nonreactive(() => {
const cursor = factory()
if (Meteor.isDevelopment) checkCursor(cursor)
return cursor?.fetch?.() ?? null
})
)
export const useFind = Meteor.isServer
? useFindServer
: useFindClient
function useFindDev <T = any>(factory: () => (Mongo.Cursor<T> | undefined | null), deps: DependencyList = []) {
function warn (expects: string, pos: string, arg: string, type: string) {
console.warn(
`Warning: useFind expected a ${expects} in it\'s ${pos} argument `
+ `(${arg}), but got type of \`${type}\`.`
);
}
if (typeof factory !== 'function') {
warn("function", "1st", "reactiveFn", factory);
}
if (!deps || !Array.isArray(deps)) {
warn("array", "2nd", "deps", typeof deps);
}
return useFind(factory, deps);
}
export default Meteor.isDevelopment
? useFindDev
: useFind;