Passed
Pull Request — main (#27)
by Lorenzo
01:56
created

InjectBean.ts ➔ hasName   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
crap 1
1 5
import { logger } from '@/core';
2
import { ExpressBean } from '@/ExpressBeansTypes';
3
4
function hasName(singletonClass: any) {
5 6
  return singletonClass.name;
6
}
7
8
function isABean(singletonClass: any) {
9 5
  return !!singletonClass._beanUUID && !!singletonClass._instance && !!singletonClass._className;
10
}
11
12
function getSingleton<T>(singletonClass: T): T {
13 7
  if (!singletonClass) {
14 1
    throw new Error('Please specify the type of Bean. Example: @InjectBean(BeanClass)');
15
  }
16
17 6
  if (!hasName(singletonClass)) {
18 1
    throw new Error(`Cannot get instance for ${JSON.stringify(singletonClass)}: it is not an ExpressBean`);
19
  }
20
21 5
  if (!isABean(singletonClass)) {
22 2
    const className = (singletonClass as any).name;
23 2
    throw new Error(`Cannot get instance from ${className}. Make sure that ${className} has @Bean as class decorator`);
24
  }
25
26 3
  const bean = singletonClass as unknown as ExpressBean;
27 3
  return bean._instance;
28
}
29
30
/**
31
 * Gets singleton instance by its static property
32
 * @decorator
33
 * @param singletonClass
34
 */
35 5
export function InjectBean<T>(singletonClass: NonNullable<T>) {
36 7
  return (_value: unknown, context: ClassFieldDecoratorContext) => () => {
37 7
    const singletonInstance = getSingleton(singletonClass);
38 3
    const className = (singletonInstance as unknown as ExpressBean)._className;
39 3
    logger.debug(`initializing ${String(context.name)} with instance of bean ${className}`);
40 3
    return singletonInstance as any;
41
  };
42
}
43