This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrepository.ts
48 lines (37 loc) · 1.72 KB
/
repository.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
import { IAggregateConstructor, IAggregateRepositoryConstructor } from '../aggregate';
import 'reflect-metadata';
import { REPOSITORY } from './constants';
import { Registry } from '../registry';
import { ClassDescriptor, Constructor } from '../types';
interface RepositoryConfig {
streamName: string;
aggregate: IAggregateConstructor;
}
const legacyClass = ({ streamName, aggregate }, clazz: Constructor<any>) => {
clazz.prototype.streamName = streamName;
clazz.prototype.aggregate = aggregate;
Reflect.defineMetadata(REPOSITORY, [...(Reflect.getMetadata(REPOSITORY, Registry) || []), clazz], Registry);
// Cast as any because TS doesn't recognize the return type as being a
// subtype of the decorated class when clazz is typed as
// `Constructor<HTMLElement>` for some reason.
// `Constructor<HTMLElement>` is helpful to make sure the decorator is
// applied to elements however.
// tslint:disable-next-line:no-any
return clazz as any;
};
const standardClass = ({ streamName, aggregate }, descriptor: ClassDescriptor) => {
// This callback is called once the class is otherwise fully defined
descriptor.finisher = function(clazz: Constructor<any>) {
clazz.prototype.streamName = streamName;
clazz.prototype.aggregate = aggregate;
Reflect.defineMetadata(REPOSITORY, [...(Reflect.getMetadata(REPOSITORY, Registry) || []), clazz], Registry);
return undefined;
}
return descriptor;
};
export const Repository = (config: RepositoryConfig) =>
(classOrDescriptor: IAggregateRepositoryConstructor<any> | ClassDescriptor) =>
(typeof classOrDescriptor === 'function')
? legacyClass(config, classOrDescriptor)
: standardClass(config, classOrDescriptor)
;