inversify#injectable TypeScript Examples

The following examples show how to use inversify#injectable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: kinesis-stream.service.ts    From nr-apm-stack with Apache License 2.0 6 votes vote down vote up
@injectable()
/**
 * Coordinates transforming the data and then bulk uploading it to OpenSearch
 */
export class KinesisStreamService {
  /**
   * Construct the KinesisStreamService
   * @param ecsTransformService
   * @param openSearch
   * @param logger
   */
  constructor(
    @inject(TYPES.EcsTransformService) private ecsTransformService: EcsTransformService,
    @inject(TYPES.OpenSearchService) private openSearch: OpenSearchService,
    @inject(TYPES.LoggerService) private logger: LoggerService,
  ) {}

  /* eslint-disable @typescript-eslint/no-unused-vars */
  /**
   * Handle the Kinesis event by transforming and then bulk uploading to OpenSearch
   * @param event The event containing the data to transform
   * @param context The lambda context
   * @returns A promise to wait on
   */
  public async handle(event: KinesisStreamEvent, context: Context): Promise<OpenSearchBulkResult> {
    this.logger.log(`Transforming ${event.Records.length} kinesis records to ES documents`);
    const docs = this.ecsTransformService.transform(event);
    this.logger.log(`Submitting ${docs.length} documents to ES`);
    return this.openSearch.bulk(docs).then((value) => {
      this.logger.log(`${docs.length - value.errors.length} documents added`);
      this.logger.log(`${value.errors.length} documents failed`);
      return value;
    });
  }
  /* eslint-enable @typescript-eslint/no-unused-vars */
}
Example #2
Source File: FormatResponder.ts    From node-experience with MIT License 6 votes vote down vote up
@injectable()
class FormatResponder implements IFormatResponder
{
    getFormatData = (data: unknown, metadata: Record<string, any> = null): any =>
    {
        return {
            data,
            metadata: metadata ?? undefined
        };
    };
}
Example #3
Source File: env-config.service.ts    From The-TypeScript-Workshop with MIT License 6 votes vote down vote up
@injectable()
export class EnvConfigService implements ConfigService {
  getAll(): Record<string, string | undefined> {
    return process.env;
  }

  get(key: string): string | undefined {
    return process.env[key];
  }
}
Example #4
Source File: CommonManagers.ts    From rewind with MIT License 6 votes vote down vote up
/**
 * Creates the Rewind app that serves multiple useful osu! tools.
 *
 * Common settings are set here so that they can be shared with other tools.
 *
 * Example: Preferred skin can be set at only one place and is shared among all tools.
 */
@injectable()
export class CommonManagers {
  constructor(
    public readonly skinManager: SkinManager,
    public readonly skinSettingsStore: SkinSettingsStore,
    public readonly audioSettingsService: AudioSettingsStore,
    public readonly beatmapBackgroundSettingsStore: BeatmapBackgroundSettingsStore,
    public readonly beatmapRenderSettingsStore: BeatmapRenderSettingsStore,
    public readonly hitErrorBarSettingsStore: HitErrorBarSettingsStore,
    public readonly analysisCursorSettingsStore: AnalysisCursorSettingsStore,
    public readonly replayCursorSettingsStore: ReplayCursorSettingsStore,
    public readonly playbarSettingsStore: PlaybarSettingsStore,
    private readonly rewindLocalStorage: RewindLocalStorage,
  ) {}

  // This should only be called after there is a connection to the backend.
  async initialize() {
    this.rewindLocalStorage.initialize();
    await this.skinManager.loadPreferredSkin();
  }
}
Example #5
Source File: ResourcePool.ts    From GWebGPUEngine with MIT License 6 votes vote down vote up
@injectable()
export class ResourcePool {
  @inject(IDENTIFIER.RenderEngine)
  private readonly engine: IRendererService;

  // 资源池
  private resourcePool: Record<string, IFramebuffer> = {};

  /**
   * 负责实例化虚拟资源,通过引擎服务
   * @param resource 虚拟资源
   */
  public getOrCreateResource(resource: ResourceEntry): IFramebuffer {
    if (!this.resourcePool[resource.name]) {
      const { width, height, usage } = resource.descriptor;
      this.resourcePool[resource.name] = this.engine.createFramebuffer({
        color: this.engine.createTexture2D({
          width,
          height,
          wrapS: gl.CLAMP_TO_EDGE,
          wrapT: gl.CLAMP_TO_EDGE,
          usage,
        }),
      });
    }

    return this.resourcePool[resource.name];
  }

  public clean() {
    this.resourcePool = {};
  }
}
Example #6
Source File: component.ts    From malagu with MIT License 6 votes vote down vote up
export function applyComponentDecorator(option: ComponentOption, target: any) {

    const isAlreadyDecorated = Reflect.hasOwnMetadata(inversify_METADATA_KEY.PARAM_TYPES, target);

    if (!isAlreadyDecorated) {
        decorate(injectable(), target);
    }

    const metadata: ComponentMetadata = {
        target,
        ids: Array.isArray(option.id) ? option.id : [ option.id || target ],
        sysTags: option.sysTags!,
        rebind: option.rebind!,
        proxy: option.proxy!,
        scope: option.scope!,
        name: option.name,
        tag: option.tag,
        default: option.default,
        when: option.when,
        onActivation: option.onActivation
    };

    let metadatas: ComponentMetadata[] = Reflect.getMetadata(
        METADATA_KEY.component,
        Reflect
    );

    if (!metadatas) {
        metadatas = [];
        Reflect.defineMetadata(
            METADATA_KEY.component,
            metadatas,
            Reflect
        );
    }
    metadatas.push(metadata);
    return metadata;
}
Example #7
Source File: issuesReporter.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
@injectable()
export class IssuesReporterService {

  private issues: Issue[] = [];

  public get hasIssue(): boolean {
    return this.issues.length !== 0;
  }

  public registerIssue(type: IssueType, error: Error): void {
    this.issues.push({ type, error });
  }

  public reportIssue(): Issue | undefined {
    return this.issues[0];
  }

  public reportAllIssues(): Issue[] {
    return this.issues;
  }

}
Example #8
Source File: dynamo-projection.repository.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
@injectable()
export class DynamoProjectionRepository<P extends Projection> extends DynamoRepository<P> implements ProjectionRepository<P> {
  constructor(
    @inject(WINSTON_SYMBOLS.WinstonConfiguration)
    private readonly projectionLogger: Logger) {
    super(projectionLogger);
  }

  /**
   * Get projection by id
   * @param table
   * @param id
   */
  async get(table: string, id: Uuid): Promise<P> {
    return super.get(table, 'id', id);
  }
}
Example #9
Source File: fetchLoggedUser.middleware.ts    From rest-api.ts with MIT License 6 votes vote down vote up
@injectable()
export class FetchLoggedUserMiddleware extends BaseMiddleware {
  constructor(
    @inject(TYPES.DatabaseService)
    private readonly databaseService: DatabaseService,
    @inject(TYPES.JsonWebTokenService)
    private readonly jsonWebTokenService: JsonWebTokenService,
  ) {
    super();
  }

  public async handler(
    req: Request & {user: User},
    res: Response,
    next: NextFunction,
  ): Promise<void | Response> {
    const repository = await this.databaseService.getRepository(UserRepository);
    const token = req.headers.authorization?.replace('bearer ', '');

    if (token === undefined) {
      return res.status(403).send('You must provide an `Authorization` header');
    }

    try {
      const payload = this.jsonWebTokenService.decode(token);
      req.user = await repository.findOneOrFail({
        where: {id: payload.userId},
        relations: ['products'],
      });
    } catch (e) {
      return res.status(403).send('Invalid token');
    }

    next();
  }
}
Example #10
Source File: kinesis-stream-wrapper.service.ts    From nr-apm-stack with Apache License 2.0 5 votes vote down vote up
@injectable()
/**
 * Coordinates transforming the data and then bulk uploading it to OpenSearch
 */
export class KinesisStreamWrapperService {
  /**
   * Construct the wrapper service. The tagging of KinesisStreamService with localhost alters the binding behaviour.
   * @param kinesisStreamService
   */
  constructor(
    @inject(TYPES.KinesisStreamService) @tagged('localhost', true) private kinesisStreamService: KinesisStreamService,
    @inject(TYPES.LoggerService) private logger: LoggerService,
  ) {}

  /**
   * Handle received data by wrapping in a mock KinesisStreamRecord and forwarding on
   * @param data The data to wrap
   * @returns Promise with the result
   */
  async handleData(data: OsDocumentData, print: boolean): Promise<OpenSearchBulkResult> {
    const event: KinesisStreamEvent = {
      Records: [this.wrapDataIntoRecord(data)],
    };
    // unused so any value will work
    const context: Context = {} as Context;
    const kss = await this.kinesisStreamService.handle(event, context);
    if (print) {
      this.logger.log(JSON.stringify(kss, null, '  '));
    }
    return kss;
  }

  /**
   * Wraps data into a KinesisStreamRecord
   * @param data The data to wrap
   * @returns The mocked KinesisStreamRecord
   */
  private wrapDataIntoRecord(data: OsDocumentData): KinesisStreamRecord {
    return {
      awsRegion: 'ca-central-1',
      eventID: 'string',
      eventName: 'string',
      eventSource: 'string',
      eventSourceARN: 'string',
      eventVersion: 'string',
      invokeIdentityArn: 'string',
      kinesis: {
        approximateArrivalTimestamp: 0,
        data: Buffer.from(JSON.stringify(data), 'utf8').toString('base64'),
        kinesisSchemaVersion: 'string',
        partitionKey: 'string',
        sequenceNumber: 'string',
      },
    };
  }
}
Example #11
Source File: TokenMikroSqlRepository.ts    From node-experience with MIT License 5 votes vote down vote up
@injectable()
class TokenMikroSqlRepository extends BaseMikroSqlRepository<ITokenDomain> implements ITokenRepository<ITokenDomain>
{
    constructor()
    {
        super(Token.name, TokenSchema);
    }
}