-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrapher-link-executor.ts
80 lines (64 loc) · 2.75 KB
/
grapher-link-executor.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
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
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { Grapher } from 'meteor/cultofcoders:grapher';
interface CollectionsCollection {
[key: string]: Mongo.Collection<any>
}
interface LinksCollection {
[key: string]: Grapher.Link<any>
}
let done = false;
const collections: CollectionsCollection = {}; //store collections uniquely
const standardLinks: LinksCollection = {}; // standard links stored under properties with names that correspond to collection names
const inverseLinks: LinksCollection = {}; // inverse links stored under properties with names that correspond to collection names
export function addLinks<T>(collection: Mongo.Collection<T>, links: Grapher.Link<any>) {
if (done) {
throw new Meteor.Error(
'addLinks(): Link Execution Finished',
'Link exectutor has already finished adding links. addLinks cannnot be called after links have been added. Are you calling addLinks from Meteor.startup?'
);
}
const collectionName = collection._name;
collections[collectionName] = collection;
Meteor._ensure(standardLinks, collectionName);
Meteor._ensure(inverseLinks, collectionName);
Object.keys(links).forEach((key) => {
let link = links[key];
const oldLink = standardLinks[collectionName][key] || inverseLinks[collectionName][key];
if (oldLink) {
throw new Meteor.Error('Existing Link', `Link for "${key}" already exists on ${collectionName} collection`, JSON.stringify({ oldLink, newLink: link }));
}
const linkCollectionName = link?.collection?._name;
if (linkCollectionName && !collections[linkCollectionName]) {
collections[linkCollectionName] = link.collection
}
if (link.inversedBy) {
inverseLinks[collectionName][key] = link;
} else {
standardLinks[collectionName][key] = link;
}
});
};
export const executeLinks = () => {
if (done) {
throw new Meteor.Error(
'executeLinks(): Link Execution Finished',
'Link execution can only run once.'
);
}
done = true;
Object.keys(collections).forEach(collectionName => {
const collection = collections[collectionName];
const standardLinkNames = Object.keys(standardLinks[collectionName] || {});
if (standardLinkNames.length) {
collection.addLinks(standardLinks[collectionName]);
}
});
Object.keys(collections).forEach(collectionName => {
const collection = collections[collectionName];
const inverseLinkNames = Object.keys(inverseLinks[collectionName] || {})
if (inverseLinkNames.length) {
collection.addLinks(inverseLinks[collectionName]);
}
});
};