-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
repository.mixin.ts
374 lines (354 loc) · 11 KB
/
repository.mixin.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright IBM Corp. 2018,2020. All Rights Reserved.
// Node module: @loopback/repository
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {Binding, BindingScope, createBindingFromClass} from '@loopback/context';
import {Application} from '@loopback/core';
import debugFactory from 'debug';
import {Class} from '../common-types';
import {SchemaMigrationOptions} from '../datasource';
import {juggler, Repository} from '../repositories';
const debug = debugFactory('loopback:repository:mixin');
/**
* A mixin class for Application that creates a .repository()
* function to register a repository automatically. Also overrides
* component function to allow it to register repositories automatically.
*
* @example
* ```ts
* class MyApplication extends RepositoryMixin(Application) {}
* ```
*
* Please note: the members in the mixin function are documented in a dummy class
* called <a href="#RepositoryMixinDoc">RepositoryMixinDoc</a>
*
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function RepositoryMixin<T extends Class<any>>(superClass: T) {
return class extends superClass {
/**
* Add a repository to this application.
*
* @param repoClass - The repository to add.
*
* @example
* ```ts
*
* class NoteRepo {
* model: any;
*
* constructor() {
* const ds: juggler.DataSource = new juggler.DataSource({
* name: 'db',
* connector: 'memory',
* });
*
* this.model = ds.createModel(
* 'note',
* {title: 'string', content: 'string'},
* {}
* );
* }
* };
*
* app.repository(NoteRepo);
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
repository<R extends Repository<any>>(
repoClass: Class<R>,
name?: string,
): Binding<R> {
const binding = createBindingFromClass(repoClass, {
name,
namespace: 'repositories',
type: 'repository',
defaultScope: BindingScope.TRANSIENT,
});
this.add(binding);
return binding;
}
/**
* Retrieve the repository instance from the given Repository class
*
* @param repo - The repository class to retrieve the instance of
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async getRepository<R extends Repository<any>>(repo: Class<R>): Promise<R> {
return this.get(`repositories.${repo.name}`);
}
/**
* Add the dataSource to this application.
*
* @param dataSource - The dataSource to add.
* @param name - The binding name of the datasource; defaults to dataSource.name
*
* @example
* ```ts
*
* const ds: juggler.DataSource = new juggler.DataSource({
* name: 'db',
* connector: 'memory',
* });
*
* app.dataSource(ds);
*
* // The datasource can be injected with
* constructor(@inject('datasources.db') dataSource: DataSourceType) {
*
* }
* ```
*/
dataSource<D extends juggler.DataSource>(
dataSource: Class<D> | D,
name?: string,
): Binding<D> {
// We have an instance of
if (dataSource instanceof juggler.DataSource) {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
name = name || dataSource.name;
const key = `datasources.${name}`;
return this.bind(key).to(dataSource).tag('datasource');
} else if (typeof dataSource === 'function') {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
name = name || dataSource.dataSourceName;
const binding = createBindingFromClass(dataSource, {
name,
namespace: 'datasources',
type: 'datasource',
defaultScope: BindingScope.SINGLETON,
});
this.add(binding);
return binding;
} else {
throw new Error('not a valid DataSource.');
}
}
/**
* Add a component to this application. Also mounts
* all the components repositories.
*
* @param component - The component to add.
*
* @example
* ```ts
*
* export class ProductComponent {
* controllers = [ProductController];
* repositories = [ProductRepo, UserRepo];
* providers = {
* [AUTHENTICATION_STRATEGY]: AuthStrategy,
* [AUTHORIZATION_ROLE]: Role,
* };
* };
*
* app.component(ProductComponent);
* ```
*/
public component(component: Class<unknown>, name?: string) {
super.component(component, name);
this.mountComponentRepositories(component);
}
/**
* Get an instance of a component and mount all it's
* repositories. This function is intended to be used internally
* by component()
*
* @param component - The component to mount repositories of
*/
mountComponentRepositories(component: Class<unknown>) {
const componentKey = `components.${component.name}`;
const compInstance = this.getSync(componentKey);
if (compInstance.repositories) {
for (const repo of compInstance.repositories) {
this.repository(repo);
}
}
}
/**
* Update or recreate the database schema for all repositories.
*
* **WARNING**: By default, `migrateSchema()` will attempt to preserve data
* while updating the schema in your target database, but this is not
* guaranteed to be safe.
*
* Please check the documentation for your specific connector(s) for
* a detailed breakdown of behaviors for automigrate!
*
* @param options - Migration options, e.g. whether to update tables
* preserving data or rebuild everything from scratch.
*/
async migrateSchema(options: SchemaMigrationOptions = {}): Promise<void> {
const operation =
options.existingSchema === 'drop' ? 'automigrate' : 'autoupdate';
// Instantiate all repositories to ensure models are registered & attached
// to their datasources
const repoBindings: Readonly<Binding<unknown>>[] = this.findByTag(
'repository',
);
await Promise.all(repoBindings.map(b => this.get(b.key)));
// Look up all datasources and update/migrate schemas one by one
const dsBindings: Readonly<Binding<object>>[] = this.findByTag(
'datasource',
);
for (const b of dsBindings) {
const ds = await this.get(b.key);
if (operation in ds && typeof ds[operation] === 'function') {
debug('Migrating dataSource %s', b.key);
await ds[operation](options.models);
} else {
debug('Skipping migration of dataSource %s', b.key);
}
}
}
};
}
/**
* Interface for an Application mixed in with RepositoryMixin
*/
export interface ApplicationWithRepositories extends Application {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
repository<R extends Repository<any>>(
repo: Class<R>,
name?: string,
): Binding<R>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getRepository<R extends Repository<any>>(repo: Class<R>): Promise<R>;
dataSource<D extends juggler.DataSource>(
dataSource: Class<D> | D,
name?: string,
): Binding<D>;
component(component: Class<unknown>, name?: string): Binding;
mountComponentRepositories(component: Class<unknown>): void;
migrateSchema(options?: SchemaMigrationOptions): Promise<void>;
}
/**
* A dummy class created to generate the tsdoc for the members in repository
* mixin. Please don't use it.
*
* The members are implemented in function
* <a href="#RepositoryMixin">RepositoryMixin</a>
*/
export class RepositoryMixinDoc {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(...args: any[]) {
throw new Error(
'This is a dummy class created for apidoc!' + 'Please do not use it!',
);
}
/**
* Add a repository to this application.
*
* @param repo - The repository to add.
*
* @example
* ```ts
*
* class NoteRepo {
* model: any;
*
* constructor() {
* const ds: juggler.DataSource = new juggler.DataSource({
* name: 'db',
* connector: 'memory',
* });
*
* this.model = ds.createModel(
* 'note',
* {title: 'string', content: 'string'},
* {}
* );
* }
* };
*
* app.repository(NoteRepo);
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
repository(repo: Class<Repository<any>>): Binding {
throw new Error();
}
/**
* Retrieve the repository instance from the given Repository class
*
* @param repo - The repository class to retrieve the instance of
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async getRepository<R extends Repository<any>>(repo: Class<R>): Promise<R> {
return new repo() as R;
}
/**
* Add the dataSource to this application.
*
* @param dataSource - The dataSource to add.
* @param name - The binding name of the datasource; defaults to dataSource.name
*
* @example
* ```ts
*
* const ds: juggler.DataSource = new juggler.DataSource({
* name: 'db',
* connector: 'memory',
* });
*
* app.dataSource(ds);
*
* // The datasource can be injected with
* constructor(@inject('datasources.db') dataSource: DataSourceType) {
*
* }
* ```
*/
dataSource(
dataSource: Class<juggler.DataSource> | juggler.DataSource,
name?: string,
): Binding {
throw new Error();
}
/**
* Add a component to this application. Also mounts
* all the components repositories.
*
* @param component - The component to add.
*
* @example
* ```ts
*
* export class ProductComponent {
* controllers = [ProductController];
* repositories = [ProductRepo, UserRepo];
* providers = {
* [AUTHENTICATION_STRATEGY]: AuthStrategy,
* [AUTHORIZATION_ROLE]: Role,
* };
* };
*
* app.component(ProductComponent);
* ```
*/
public component(component: Class<{}>): Binding {
throw new Error();
}
/**
* Get an instance of a component and mount all it's
* repositories. This function is intended to be used internally
* by component()
*
* @param component - The component to mount repositories of
*/
mountComponentRepository(component: Class<{}>) {}
/**
* Update or recreate the database schema for all repositories.
*
* **WARNING**: By default, `migrateSchema()` will attempt to preserve data
* while updating the schema in your target database, but this is not
* guaranteed to be safe.
*
* Please check the documentation for your specific connector(s) for
* a detailed breakdown of behaviors for automigrate!
*
* @param options - Migration options, e.g. whether to update tables
* preserving data or rebuild everything from scratch.
*/
async migrateSchema(options?: SchemaMigrationOptions): Promise<void> {}
}