summaryrefslogtreecommitdiff
path: root/app/infrastructure/registry.js
blob: 4542796e9f56c28744a3e188bb95808c4e6f4478 (plain)
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
export class Resolver {
  constructor(factory) {
    this.factory = factory;
  }

  resolveWith(container) {
    if (this.isConstructor()) {
      return this.resolveDependenciesUsing(container);
    }
    else {
      return this.factory(container);
    }
  }

  parseConstructor(func) {
    const code = func.toString();
    const regex = /function ([a-zA-Z]*)\((.*)\) *\{/;
    return code.match(regex);
  }

  isConstructor() {
    return this.factory.name;
    //return this.parseConstructor(this.factory)[1] != '';
  }

  resolveDependenciesUsing(container) {
    const ctor = this.parseConstructor(this.factory);
    const parameters = ctor.slice(2)[0].split(',').filter(Boolean);
    const dependencies = parameters.map((parameter) => {
      return container.resolve(parameter.trim());
    });
    return new this.factory(...dependencies);
  }
}

export class Registration {
  constructor(factory) {
    this.factory = factory;
  }

  create(container) {
    return new Resolver(this.factory).resolveWith(container);
  }

  asSingleton() {
    const originalFactory = this.factory;
    let item = null;
    this.factory = (container) => {
      if (item == null) {
        item = new Resolver(originalFactory).resolveWith(container);
      }
      return item;
    };
  }
}

export default class Registry {
  constructor() {
    this.registrations = new Map();
  }

  register(key, factory) {
    if (!this.isRegistered(key)) {
      this.registrations.set(key, new Set());
    }
    const registration = new Registration(factory);
    this.registrations.get(key).add(registration);
    return registration;
  }

  isRegistered(key) {
    return this.registrations.has(key);
  }

  resolve(key) {
    if (!this.isRegistered(key)) {
      throw `"${key}" is not registered`;
    }

    try {
      const registration = this._registrationsFor(key)[0];
      return registration.create(this);
    } catch(error) {
      console.error(`ERROR: Could not resolve "${key}" ${error}`);
      throw error;
    }
  }

  resolveAll(key) {
    return this._registrationsFor(key).map(registration => registration.create(this));
  }

  _registrationsFor(key) {
    return Array.from(this.registrations.get(key));
  }
}