typedi#Container TypeScript Examples

The following examples show how to use typedi#Container. 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: errorMiddleware.ts    From TXQ with MIT License 6 votes vote down vote up
handleExceptions = (error: any) => {
  const logger: Logger = Container.get('logger');

  logger.info(`Exception`, {
    method: '',
    url: '',
    query: '',
    ip: '',
    error: error,
    stack: error.stack,
  });

  process.exit(1);
}
Example #2
Source File: CashRuleService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
private async isValidDescriptionParam(
        testMethod: StringTestMethodType,
        param: string,
    ): Promise<boolean> {
        switch (testMethod) {
            case StringTestMethodType.CONTAINS: {
                const indexService = Container.get(CashTransactionTempIndexService);
                return await indexService.descriptionMatch(param);
            }
        }
        return false;
    }
Example #3
Source File: Utils.ts    From BlinkWebUI with GNU General Public License v3.0 6 votes vote down vote up
static checkCommandStatus(
        regionId: string,
        networkId: string,
        commandStatus: CommandStatus,
        authToken: string
    ): Promise<CommandStatus> {
        return Container.get(networkRepositoryToken)
            .getNetworkCommandStatus(
                regionId,
                networkId,
                commandStatus.id.toString(),
                authToken
            )
            .then((cs: CommandStatus) => {
                if (cs.complete) {
                    return cs;
                }
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        this.checkCommandStatus(regionId, networkId, commandStatus, authToken)
                            .then(resolve)
                            .catch(reject);
                    }, 2000);
                });
            });
    }
Example #4
Source File: errorMiddleware.ts    From TXQ with MIT License 6 votes vote down vote up
handle404Error = (router: Router) => {
  router.use((req: Request, res: Response) => {
    const logger: Logger = Container.get('logger');
    logger.error('404', {
      method: req.method,
      url: req.originalUrl,
      query: req.query,
      ip: req.ip,
    });
    res.status(404);
    res.api.errors.push({
      field: 'endpoint',
      message: 'API endpoint does not exist',
    });
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type,api_key');
    res.header('Access-Control-Allow-Methods', 'POST,GET,HEAD,DELETE,OPTIONS');
    res.api.status = 404;
    res.json(res.api);
  });
}
Example #5
Source File: PermanentData.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
actions = {
    async fillAccount({ commit }: Vuex.ActionContext<IPermanentDataState, any>) {
        const service = Container.get(CashAccountService);
        const list = await service.getList();
        list.sort((a, b) => a.name.localeCompare(b.name));
        const { accountTree, accountMap, accountDescendantMap } = CashAccountUtils.listToTreeAndMap(
            list,
        );
        commit('updateField', { path: 'accountList', value: list });
        commit('updateField', { path: 'accountTree', value: accountTree });
        commit('updateField', { path: 'accountMap', value: accountMap });
        commit('updateField', { path: 'accountDescendantMap', value: accountDescendantMap });
    },
    async fillCurrency({ commit }: Vuex.ActionContext<IPermanentDataState, any>) {
        const service = Container.get(CashCurrencyService);
        const list = await service.getList();
        commit('updateField', { path: 'currencyList', value: list });
    },
    async fillTag({ commit }: Vuex.ActionContext<IPermanentDataState, any>) {
        const service = Container.get(CashTagService);
        const list = await service.getList();
        commit('updateField', { path: 'tagList', value: list });
    },
    async fillBudgetSplit({ commit, rootState }: Vuex.ActionContext<IPermanentDataState, any>) {
        const service = Container.get(CashBudgetSplitService);

        const parameters = {
            ...simpleTransactionParameters,
            outputCurrency: rootState.App.preferences.preferedCurrency,
        };
        const splitList = await service.getListByParam(
            parameters,
            rootState.PermanentData.accountMap,
        );
        const convertService = Container.get(CashConverterService);
        const result = convertService.convertToGraphSplitListAndGetActiveAccounts(splitList);
        commit('updateField', { path: 'budgetSplitList', value: result.splitList });
    },
}
Example #6
Source File: schedule.ts    From ql with MIT License 6 votes vote down vote up
run = async () => {
  const cronService = Container.get(CronService);
  const cronDb = cronService.getDb();

  cronDb
    .find({})
    .sort({ created: 1 })
    .exec((err, docs) => {
      if (err) {
        Logger.error(err);
        process.exit(1);
      }

      if (docs && docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
          const task = docs[i];
          const _schedule = task.schedule && task.schedule.split(' ');
          if (
            _schedule &&
            _schedule.length > 5 &&
            task.status !== CrontabStatus.disabled &&
            !task.isDisabled
          ) {
            schedule.scheduleJob(task.schedule, function () {
              let command = task.command as string;
              if (!command.includes('task ') && !command.includes('ql ')) {
                command = `task ${command}`;
              }
              exec(command);
            });
          }
        }
      }
    });
}
Example #7
Source File: ApolloServerLoaderPlugin.ts    From type-graphql-dataloader with MIT License 6 votes vote down vote up
ApolloServerLoaderPlugin = (
  option?: ApolloServerLoaderPluginOption
): ApolloServerPlugin => ({
  requestDidStart: async () => ({
    async didResolveSource(requestContext: { context: BaseContext }) {
      Object.assign(requestContext.context, {
        _tgdContext: {
          requestId: uuidv4(),
          typeormGetConnection: option?.typeormGetConnection,
        } as TgdContext,
      });
    },
    async willSendResponse(requestContext: { context: BaseContext }) {
      Container.reset(requestContext.context._tgdContext.requestId);
    },
  }),
})
Example #8
Source File: attachCurrentUser.ts    From nodejs-typescript-graphql-starter with MIT License 6 votes vote down vote up
attachCurrentUser = async (req, res, next) => {
  const logger: Logger = Container.get('logger');
  try {
    const UserModel = Container.get('userModel') as mongoose.Model<IUser & mongoose.Document>;
    const userRecord = await UserModel.findById(req.token._id);
    if (req.baseUrl.split('/').includes('graphql')) {
      req.isAuth = false;
      return next();
    }
    if (!userRecord) {
      req.isAuth = false;
      return res.sendStatus(401);
    }
    const currentUser = userRecord.toObject();
    Reflect.deleteProperty(currentUser, 'password');
    Reflect.deleteProperty(currentUser, 'salt');
    req.isAuth = true;
    req.currentUser = currentUser;
    return next();
  } catch (e) {
    logger.error('? Error attaching user to req: %o', e);
    return next(e);
  }
}
Example #9
Source File: iocLoader.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
iocLoader: MicroframeworkLoader = (settings: MicroframeworkSettings | undefined) => {

    /**
     * Setup routing-controllers to use typedi container.
     */
    routingUseContainer(Container);
    ormUseContainer(Container);
    classValidatorUseContainer(Container);
    // typeGraphQLUseContainer(Container);
}
Example #10
Source File: CashRuleService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async assignWithRules(
        transaction: FlatCashTransaction,
        accountMap: Map<number, CashAccount>,
        tagMap: Map<number, CashTag>,
        ruleList?: CashRule[],
        accountList?: CashAccount[],
    ): Promise<boolean> {
        try {
            if (!ruleList) {
                ruleList = await this.getList();
            }
            if (!accountList) {
                const cashAccountService = Container.get(CashAccountService);
                accountList = await cashAccountService.getList();
            }
            const optionalRule = await this.findRule(transaction, ruleList);
            if (optionalRule) {
                this.applyRule(transaction, optionalRule, accountMap, tagMap);
                return true;
            }
            return false;
        } catch (e) {
            throw new CashError("Can't assign rule: " + e.message);
        }
    }
Example #11
Source File: CreateMemoryDatabase.ts    From jaebook-server with MIT License 6 votes vote down vote up
/**
 * 테스트에 사용할 In-memory Database를 만든다
 * @param entities
 */
export async function createMemoryDatabase() {
  useContainer(Container);
  return createConnection({
    type: "sqlite",
    database: ":memory:",
    entities: [__dirname + "/../../src/entities/*{.ts,.js}"],
    dropSchema: true,
    synchronize: true,
    logging: false,
  });
}
Example #12
Source File: CashBudgetSplitService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async getListByParam(
        parameters: SplitParameters = simpleTransactionParameters,
        accountMap: Map<number, CashAccount>,
    ): Promise<ConvertedSplitExtended[]> {
        parameters = CashAccountUtils.adaptAccountParamForLeafAccounts(parameters, accountMap);
        const repo = getManager().getCustomRepository(CashBudgetSplitRepository);
        const cashSplitList = await repo.findCustom(parameters);

        const converterService = Container.get(CashConverterService);
        return await converterService.convertCashSplitList(
            cashSplitList,
            parameters.outputCurrency,
        );
    }
Example #13
Source File: app.ts    From jaebook-server with MIT License 6 votes vote down vote up
/**
   * Express를 시작한다.
   * @param port 포트
   */
  public async createExpressServer(port: number): Promise<void> {
    try {
      routingUseContainer(Container);
      useExpressServer(this.app, routingControllerOptions);
      useSwagger(this.app);
      useSentry(this.app);

      this.app.listen(port, () => {
        logger.info(`Server is running on http://localhost:${port}`);
      });
    } catch (error) {
      logger.error(error);
    }
  }
Example #14
Source File: CashImportService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
private async checkAlreadyImport(currentTransaction: FlatCashTransaction) {
        const cashTransactionService = Container.get(CashTransactionService);

        let sameTransactionExist = false;
        if (currentTransaction.importId) {
            sameTransactionExist = await cashTransactionService.hasTransactionWithImportId(
                currentTransaction.importId,
            );
        } else {
            sameTransactionExist = await cashTransactionService.hasSimilarTransaction(
                currentTransaction,
            );
        }
        if (sameTransactionExist) {
            // This is the same transaction
            currentTransaction.doNotImport = true;
        }
    }
Example #15
Source File: setup.ts    From Cromwell with MIT License 6 votes vote down vote up
export default async function () {
    const testDir = join(getServerTempDir());
    if (fs.pathExistsSync(testDir)) fs.removeSync(testDir);
    await connectDatabase({ synchronize: true, migrationsRun: false }, true);

    const mockService = Container.get(MockService);
    await mockService.mockUsers();
    await mockService.mockTags(12);
    await mockService.mockPosts(12);
    await mockService.mockAttributes();
    await mockService.mockCategories(20);
    await mockService.mockProducts(12);
    await mockService.mockReviews(12);
    await mockService.mockOrders(12);
}
Example #16
Source File: CashRuleService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
private async isValidForAll(
        transaction: FlatCashTransaction,
        jsonFilter: OneJsonFilter[],
    ): Promise<boolean> {
        let transactionIndexUpdated = false;
        for (const filter of jsonFilter.sort(this.sortDetailAndDescriptionLast)) {
            if (
                (!transactionIndexUpdated &&
                    filter.fieldName === FieldNameDetectionType.DESCRIPTION) ||
                filter.fieldName === FieldNameDetectionType.DETAILS
            ) {
                const indexService = Container.get(CashTransactionTempIndexService);
                await indexService.putTransaction(transaction);
                transactionIndexUpdated = true;
            }
            if (!(await this.isValid(transaction, filter))) {
                return false;
            }
        }
        return true;
    }
Example #17
Source File: reset-page.ts    From Cromwell with MIT License 6 votes vote down vote up
resetPageCache = async (pageName: string, routeOptions?: {
    slug?: string;
    id?: string;
}) => {
    // Update/load defaultPages first 
    const cmsSettings = await getCmsSettings();

    if (cmsSettings?.themeName && lastUsedTheme !== cmsSettings.themeName) {
        lastUsedTheme = cmsSettings.themeName;
        const defaultPages = (await getThemeConfigs(cmsSettings.themeName))?.themeConfig?.defaultPages;
        setStoreItem('defaultPages', defaultPages);
    }

    const pageRoute = resolvePageRoute(pageName, routeOptions);

    try {
        await Container.get(RendererService).purgePageCache(pageRoute);
    } catch (error) {
        getLogger(false).error(error);
    }
}
Example #18
Source File: CashRuleService.ts    From cashcash-desktop with MIT License 6 votes vote down vote up
async duplicate(id: string): Promise<CashRule | undefined> {
        const item = await this.get(id);
        if (item) {
            const cashActionService = Container.get(CashActionService);
            const duplicateAction = await cashActionService.duplicate('' + item.actionId);
            item.name = StringUtils.generateDuplicateName(item.name);
            return new CashRule({
                name: StringUtils.generateDuplicateName(item.name),
                priority: item.priority,
                action: duplicateAction,
                filter: item.filter,
            });
        }
        return;
    }
Example #19
Source File: RecordingsPage.tsx    From BlinkWebUI with GNU General Public License v3.0 5 votes vote down vote up
mediaRepository: MediaRepository = Container.get(mediaRepositoryToken);
Example #20
Source File: index.ts    From TXQ with MIT License 5 votes vote down vote up
/**
 * Check ever N minutes for jobs that are in DB in 'pending' that may need to be enqueued
 */
async function startPendingTaskPoller() {
  console.log('sd');
  let enqInitialTxsForSync = Container.get(EnqInitialTxsForSyncAllProjects);
  enqInitialTxsForSync.run();
}
Example #21
Source File: schedule.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
module.exports.handler = async (): Promise<void> => {
    const arbitrageur = Container.get(Arbitrageur)
    await arbitrageur.start()
}
Example #22
Source File: NetworksPage.tsx    From BlinkWebUI with GNU General Public License v3.0 5 votes vote down vote up
networkRepository: NetworkRepository = Container.get(networkRepositoryToken);
Example #23
Source File: index.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
(async () => {
    const arbitrageur = Container.get(Arbitrageur)
    await arbitrageur.startInterval()
})()
Example #24
Source File: index.ts    From monopoly with MIT License 5 votes vote down vote up
useContainer(Container);
Example #25
Source File: testApp.ts    From jaebook-server with MIT License 5 votes vote down vote up
routingUseContainer(Container);
Example #26
Source File: index.ts    From nodejs-typescript-graphql-starter with MIT License 5 votes vote down vote up
graphQlResolvers = {
  users: async () => {
    const UserModel = Container.get('userModel') as mongoose.Model<IUser & mongoose.Document>;
    const users = await UserModel.find({});
    return users;
  },
}
Example #27
Source File: reset-page.ts    From Cromwell with MIT License 5 votes vote down vote up
resetAllPagesCache = async () => {
    try {
        await Container.get(RendererService).purgeEntireCache();
    } catch (error) {
        getLogger(false).error(error);
    }
}
Example #28
Source File: authorizationChecker.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export function authorizationChecker(connection: Connection): (action: Action, roles: string[]) => Promise<boolean> | boolean {
    const log = new Logger(__filename);
    const authService = Container.get<AuthService>(AuthService);

    return async function innerAuthorizationChecker(action: Action, roles: any): Promise<boolean> {
        // here you can use request/response objects from action
        // also if decorator defines roles it needs to access the action
        // you can use them to provide granular access check
        // checker must return either boolean (true or false)
        // either promise that resolves a boolean value
        const userId = await authService.parseBasicAuthFromRequest(action.request);

        if (userId === undefined) {
            log.warn('No credentials given');
            return false;
        }

        console.log(roles);

        if (roles[0] === 'customer') {
            action.request.user = await authService.validateCustomer(userId);
            if (action.request.user === undefined) {
                log.warn('Invalid credentials given');
                return false;
            }

            log.info('Successfully checked credentials');
            return true;

        } else {

            action.request.user = await authService.validateUser(userId);
            if (action.request.user === undefined) {
                log.warn('Invalid credentials given');
                return false;
            }

            log.info('Successfully checked credentials');
            return true;

        }
    };
}
Example #29
Source File: MainLayout.tsx    From BlinkWebUI with GNU General Public License v3.0 5 votes vote down vote up
// eslint-disable-next-line react/sort-comp
    authRepository: AuthRepository = Container.get(authRepositoryToken);