-
Notifications
You must be signed in to change notification settings - Fork 73
/
MetadataStorage.ts
150 lines (120 loc) · 4.45 KB
/
MetadataStorage.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
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
import { Firestore } from '@google-cloud/firestore';
import { BaseRepository } from './BaseRepository';
import type {
IEntityConstructor,
Constructor,
IEntity,
IEntityRepositoryConstructor,
ValidatorOptions,
} from './types';
import { arraysAreEqual } from './utils';
export interface CollectionMetadata {
name: string;
entityConstructor: IEntityConstructor;
parentEntityConstructor?: IEntityConstructor;
propertyKey?: string;
}
export interface SubCollectionMetadata extends CollectionMetadata {
parentEntityConstructor: IEntityConstructor;
propertyKey: string;
}
export interface CollectionMetadataWithSegments extends CollectionMetadata {
segments: string[];
}
export interface SubCollectionMetadataWithSegments extends SubCollectionMetadata {
segments: string[];
}
export interface FullCollectionMetadata extends CollectionMetadataWithSegments {
subCollections: SubCollectionMetadataWithSegments[];
}
export interface RepositoryMetadata {
target: IEntityRepositoryConstructor;
entity: IEntityConstructor;
}
export interface MetadataStorageConfig {
validateModels: boolean;
validatorOptions?: ValidatorOptions;
throwOnDuplicatedCollection?: boolean;
}
export class MetadataStorage {
readonly collections: Array<CollectionMetadataWithSegments> = [];
protected readonly repositories: Map<IEntityConstructor, RepositoryMetadata> = new Map();
public config: MetadataStorageConfig = {
validateModels: false,
validatorOptions: {},
throwOnDuplicatedCollection: true
};
public getCollection = (pathOrConstructor: string | IEntityConstructor) => {
let collection: CollectionMetadataWithSegments | undefined;
// If is a path like users/user-id/messages/message-id/senders,
// take all the even segments [users/messages/senders] and
// look for an entity with those segments
if (typeof pathOrConstructor === 'string') {
const segments = pathOrConstructor.split('/');
// Return null if incomplete segment
if (segments.length % 2 === 0) {
throw new Error(`Invalid collection path: ${pathOrConstructor}`);
}
const collectionSegments = segments.reduce<string[]>(
(acc, cur, index) => (index % 2 === 0 ? acc.concat(cur) : acc),
[]
);
collection = this.collections.find(c => arraysAreEqual(c.segments, collectionSegments));
} else {
collection = this.collections.find(c => c.entityConstructor === pathOrConstructor);
}
if (!collection) {
return null;
}
const subCollections = this.collections.filter(
s => s.parentEntityConstructor === collection?.entityConstructor
) as SubCollectionMetadataWithSegments[];
return {
...collection,
subCollections,
};
};
public setCollection = (col: CollectionMetadata) => {
const existing = this.getCollection(col.entityConstructor);
if (existing && this.config.throwOnDuplicatedCollection == true) {
throw new Error(`Collection with name ${existing.name} has already been registered`);
}
const colToAdd = {
...col,
segments: [col.name],
};
this.collections.push(colToAdd);
const getWhereImParent = (p: Constructor<IEntity>) =>
this.collections.filter(c => c.parentEntityConstructor === p);
const colsToUpdate = getWhereImParent(col.entityConstructor);
// Update segments for subcollections and subcollections of subcollections
while (colsToUpdate.length) {
const c = colsToUpdate.pop();
if (!c) {
return;
}
const parent = this.collections.find(p => p.entityConstructor === c.parentEntityConstructor);
c.segments = parent?.segments.concat(c.name) || [];
getWhereImParent(c.entityConstructor).forEach(col => colsToUpdate.push(col));
}
};
public getRepository = (param: IEntityConstructor) => {
return this.repositories.get(param) || null;
};
public setRepository = (repo: RepositoryMetadata) => {
const savedRepo = this.getRepository(repo.entity);
if (savedRepo && repo.target !== savedRepo.target) {
throw new Error('Cannot register a custom repository twice with two different targets');
}
if (!(repo.target.prototype instanceof BaseRepository)) {
throw new Error(
'Cannot register a custom repository on a class that does not inherit from BaseFirestoreRepository'
);
}
this.repositories.set(repo.entity, repo);
};
public getRepositories = () => {
return this.repositories;
};
public firestoreRef: Firestore;
}