-
Notifications
You must be signed in to change notification settings - Fork 5
/
server-connector.js
33 lines (31 loc) · 1.15 KB
/
server-connector.js
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
import { EJSON } from 'meteor/ejson'
import React, { createContext, useContext, useRef } from 'react'
import { makePagedRun, makeDataMethod, makePruneMethod, makeSingleRun } from './both'
const ConnectorContext = createContext()
export const DataCaptureProvider = ({ handle, children }) => {
const ref = useRef([])
handle.data = ref.current
handle.toEJSON = () => (
EJSON.stringify(ref.current)
)
handle.toScriptTag = () => (
`<script type="text/ejson" id="__NPCollectionCaptureData__">${EJSON.stringify(ref.current)}</script>`
)
return <ConnectorContext.Provider value={ref.current}>
{children}
</ConnectorContext.Provider>
}
export const createConnector = ({ name, collection, validate, query, single = false }) => {
const run = single
? makeSingleRun(collection, query)
: makePagedRun(collection, query)
makeDataMethod(name, validate, run)
makePruneMethod(name, collection, validate, query)
return (args = {}) => {
validate(args)
const captureData = useContext(ConnectorContext)
const docs = run(args)
captureData.push({ name: collection._name, docs: single ? [docs] : docs })
return [docs, false]
}
}