-
Notifications
You must be signed in to change notification settings - Fork 338
/
Copy pathpublish.ts
52 lines (48 loc) · 1.76 KB
/
publish.ts
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
import {getInMemoryDataLoader} from '../dataloader/getInMemoryDataLoader'
import {serializeDataLoader} from '../dataloader/serializeDataLoader'
import getPubSub from './getPubSub'
import getRedis from './getRedis'
import {Logger} from './Logger'
export interface SubOptions {
mutatorId?: string // passing the socket id of the mutator will omit sending a message to that user
operationId?: string | null
}
const REDIS_DATALOADER_TTL = 25_000
class PublishedDataLoaders {
private promiseLookup = {} as Record<string, Promise<void>>
private async pushToRedis(id: string) {
const dataLoaderWorker = getInMemoryDataLoader(id)!.dataLoaderWorker
const str = await serializeDataLoader(dataLoaderWorker)
// keep the serialized dataloader in redis for long enough for each server to fetch it and make an in-memory copy
await getRedis().set(`dataLoader:${id}`, str, 'PX', REDIS_DATALOADER_TTL)
setTimeout(() => {
delete this.promiseLookup[id]
// all calls to publish within a single mutation SHOULD happen within this timeframe
}, REDIS_DATALOADER_TTL)
}
async add(id: string) {
if (!this.promiseLookup[id]) {
this.promiseLookup[id] = this.pushToRedis(id)
}
return this.promiseLookup[id]
}
}
const publishedDataLoaders = new PublishedDataLoaders()
const publish = async <T>(
topic: T,
channel: string,
type: string,
payload: {[key: string]: any},
subOptions: SubOptions = {}
) => {
const subName = `${topic}Subscription`
const rootValue = {[subName]: {fieldName: type, [type]: payload}}
const {operationId} = subOptions
if (operationId) {
await publishedDataLoaders.add(operationId)
}
getPubSub()
.publish(`${topic}.${channel}`, {rootValue, ...subOptions})
.catch(Logger.error)
}
export default publish