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: 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 #2
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 #3
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 #4
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 #5
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 #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: index.ts    From ts-discord-bot-boilerplate with MIT License 5 votes vote down vote up
// Initialize the Client using the IoC.
Container.get<Client>(Client);
Example #11
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 #12
Source File: testApp.ts    From jaebook-server with MIT License 5 votes vote down vote up
routingUseContainer(Container);
Example #13
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 #14
Source File: CashSplitSumService.ts    From cashcash-desktop with MIT License 5 votes vote down vote up
async computeSplitSumList(
        toAddCashTransactionList: CashTransaction[],
        toRemoveCashTransactionList: CashTransaction[],
        transactionalEntityManager: EntityManager,
        toRemoveParameter?: TransactionParameters,
    ): Promise<CashSplitSum[]> {
        const cashAccountService = Container.get(CashAccountService);
        const internalLeafAccountIdList = (await cashAccountService.getInternalLeafList()).map(
            (item) => item.id,
        );

        // Get existing cashSplitSum
        const splitSumList = await this.getList(transactionalEntityManager);
        const sumByAccountIdCurrencyId: Map<string, CashSplitSum> = this.createMap(splitSumList);

        // Compute the substracted part
        const cashSplitRepository: CashSplitRepository = transactionalEntityManager.getCustomRepository(
            CashSplitRepository,
        );
        let oldCashSplitList: CashSplit[];
        if (toRemoveParameter) {
            oldCashSplitList = await cashSplitRepository.findCustom(toRemoveParameter);
        } else {
            const transactionIdList: number[] = toRemoveCashTransactionList
                .filter((transaction) => transaction.id != null)
                .map((transaction) => transaction.id);
            oldCashSplitList = await cashSplitRepository.findByTransactionId(transactionIdList);
        }

        oldCashSplitList = oldCashSplitList.filter((item) =>
            internalLeafAccountIdList.includes(item.accountId),
        );
        this.minus(sumByAccountIdCurrencyId, oldCashSplitList);

        // Compute the added part
        const newCashSplitList: CashSplit[] = _.flatMap(
            toAddCashTransactionList,
            (item: CashTransaction) => item.cashSplitList,
        ).filter((item) => internalLeafAccountIdList.includes(item.accountId));
        this.add(sumByAccountIdCurrencyId, newCashSplitList);

        return Array.from(sumByAccountIdCurrencyId.values());
    }
Example #15
Source File: RecordingComponent.tsx    From BlinkWebUI with GNU General Public License v3.0 5 votes vote down vote up
mediaRepository: MediaRepository = Container.get(mediaRepositoryToken);
Example #16
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 #17
Source File: index.ts    From monopoly with MIT License 5 votes vote down vote up
useContainer(Container);
Example #18
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 #19
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 #20
Source File: connect-database.ts    From Cromwell with MIT License 4 votes vote down vote up
checkData = async (init: boolean) => {
    const cmsModules = await readCmsModules();

    const pluginRepo = getCustomRepository(GenericPlugin.repository);
    const dbPlugins = await pluginRepo.getAll();

    const themeRepo = getCustomRepository(GenericTheme.repository);
    const dbThemes = await themeRepo.getAll();

    const pluginService = Container.get(PluginService);
    const themeService = Container.get(ThemeService);
    const cmsService = Container.get(CmsService);

    // Check versions if some Themes/Plugins were manually updated. 
    // Run activate to update info in DB
    const pluginPackages = await cmsService.readPlugins();
    const promises1 = dbPlugins.map(async ent => {
        const pckg = pluginPackages.find(p => p.name === ent.name);
        if (pckg?.version && pckg.version !== ent.version && ent.name) {
            try {
                await pluginService.activatePlugin(ent.name);
            } catch (error) {
                logger.error('Server connectDatabase: failed to activate plugin ' + ent.name, error);
            }
        }
    });

    const themePackages = await cmsService.readThemes();
    const promises2 = dbThemes.map(async ent => {
        const pckg = themePackages.find(p => p.name === ent.name);
        if (pckg?.version && pckg.version !== ent.version && ent.name) {
            try {
                await themeService.activateTheme(ent.name);
            } catch (error) {
                logger.error('Server connectDatabase: failed to activate theme ' + ent.name, error);
            }
        }
    });

    // Check installed cms modules. All available themes and plugins should be registered in DB
    // If some are not, then activate them here at Server startup
    const promises3 = cmsModules.plugins.map(async pluginName => {
        if (!dbPlugins.find(plugin => plugin.name === pluginName)) {
            try {
                await pluginService.activatePlugin(pluginName);
            } catch (error) {
                logger.error('Server connectDatabase: failed to activate plugin ' + pluginName, error);
            }
        }
    })

    const promises4 = cmsModules.themes.map(async themeName => {
        if (!dbThemes.find(theme => theme.name === themeName)) {
            try {
                await themeService.activateTheme(themeName);
            } catch (error) {
                logger.error('Server connectDatabase: failed to activate theme ' + themeName, error);
            }
        }
    })

    // Check all static content is copied in public
    const promises5 = cmsModules.themes.map(async themeName => {
        const themeStaticDir = await getModuleStaticDir(themeName);
        if (themeStaticDir && await fs.pathExists(themeStaticDir)) {
            try {
                const publicThemesDir = getPublicThemesDir();
                await fs.ensureDir(publicThemesDir);
                await fs.copy(themeStaticDir, resolve(publicThemesDir, themeName), {
                    overwrite: false,
                });
            } catch (e) { logger.log(e) }
        }
    });

    const promises6 = cmsModules.plugins.map(async pluginName => {
        const pluginStaticDir = await getModuleStaticDir(pluginName)
        if (pluginStaticDir && await fs.pathExists(pluginStaticDir)) {
            try {
                const publicPluginsDir = getPublicPluginsDir();
                await fs.ensureDir(publicPluginsDir);
                await fs.copy(pluginStaticDir, resolve(publicPluginsDir, pluginName),
                    { overwrite: false });
            } catch (e) { logger.log(e) }
        }
    });

    await Promise.all([...promises1, ...promises2, ...promises3, ...promises4, ...promises5, ...promises6]);

    if (init) {
        const mockService = Container.get(MockService);
        await mockService.mockAll();
    }
}
Example #21
Source File: index.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 4 votes vote down vote up
async start(
    config: IConfig,
    logger: LoggerService,
    port: number
  ): Promise<http.Server> {
    const pubSub = new PubSub();
    Container.set([{ id: ConfigToken, value: config }]);
    Container.set([{ id: PubSubToken, value: pubSub }]);
    Container.set([{ id: LoggerToken, value: logger }]);

    const platformio = new Platformio(
      config.getPlatformioPath,
      config.platformioStateTempStoragePath,
      config.PATH,
      config.env,
      logger
    );
    Container.set(
      FirmwareService,
      new FirmwareService(
        config.PATH,
        config.firmwaresPath,
        platformio,
        new FirmwareBuilder(platformio),
        pubSub,
        logger
      )
    );
    Container.set(
      UpdatesService,
      new UpdatesService(
        config.configuratorGit.owner,
        config.configuratorGit.repositoryName
      )
    );
    Container.set(
      SerialMonitorService,
      new SerialMonitorService(pubSub, logger)
    );

    const mDnsNotifications = new MulticastDnsNotificationsService(
      pubSub,
      logger
    );
    if (config.multicastDnsSimulatorEnabled) {
      Container.set(
        MulticastDnsService,
        new MulticastDnsSimulatorService(mDnsNotifications)
      );
    } else {
      Container.set(
        MulticastDnsService,
        new MulticastDnsService(mDnsNotifications, logger)
      );
    }

    const deviceService = new DeviceService(logger);
    await deviceService.loadFromFileSystemAt(config.devicesPath);

    Container.set(DeviceService, deviceService);

    if (config.userDefinesLoader === FirmwareParamsLoaderType.Git) {
      Container.set(
        UserDefinesBuilder,
        new UserDefinesBuilder(
          new GitUserDefinesLoader(
            logger,
            config.PATH,
            config.userDefinesStoragePath
          ),
          deviceService
        )
      );
    } else if (config.userDefinesLoader === FirmwareParamsLoaderType.Http) {
      Container.set(
        UserDefinesBuilder,
        new UserDefinesBuilder(new HttpUserDefinesLoader(logger), deviceService)
      );
    }

    if (config.targetsLoader === FirmwareParamsLoaderType.Git) {
      Container.set(
        TargetsLoader,
        new GitTargetsService(
          logger,
          deviceService,
          config.PATH,
          config.targetsStoragePath
        )
      );
    } else if (config.targetsLoader === FirmwareParamsLoaderType.Http) {
      Container.set(
        TargetsLoader,
        new HttpTargetsService(logger, deviceService)
      );
    } else {
      throw new Error('FirmwareTargetsLoaderType is not set');
    }

    Container.set(LuaService, new LuaService(logger));

    const schema = await buildSchema({
      resolvers: [
        FirmwareResolver,
        SourcesResolver,
        UpdatesResolver,
        SerialMonitorResolver,
        MulticastDnsMonitorResolver,
        LuaResolver,
      ],
      container: Container,
      pubSub,
    });
    const server = new ApolloServer({
      schema,
      introspection: true,
    });
    this.app = express();
    server.applyMiddleware({
      app: this.app,
    });

    this.server = this.app.listen({ port });

    /*
      I know, crazy. It is 45 minutes, but on slower network connection it might take a while to download
      and install all Platformio dependencies and build firmware.
     */
    this.server.setTimeout(45 * 60 * 1000);
    server.installSubscriptionHandlers(this.server);

    return this.server;
  }
Example #22
Source File: CashImportService.ts    From cashcash-desktop with MIT License 4 votes vote down vote up
async convertCsvToTransaction(
        parsedCsv: ParseResult,
        selectedImportConfig: CashImportConfig,
        selectedAccount: CashAccount | null,
        accountMap: Map<number, CashAccount>,
        tagMap: Map<number, CashTag>,
        isTest: boolean = false,
        updateProgress: (number) => void = () => {},
    ): Promise<FlatCashTransaction[]> {
        updateProgress(0);
        if (parsedCsv.errors.length !== 0) {
            throw new Error('Error during parsing');
        }
        // Get existing data
        const cashCurrencyService = Container.get(CashCurrencyService);
        const currencyList = await cashCurrencyService.getList();
        const cashAccountService = Container.get(CashAccountService);
        const accountList = await cashAccountService.getList();
        const cashRuleService = Container.get(CashRuleService);
        const unknownIncome = accountList.find((a) => a.code === 'INC_UNK')!;
        const unknownExpense = accountList.find((a) => a.code === 'EXP_UNK')!;
        const rules = await cashRuleService.getList();

        const transactionList: FlatCashTransaction[] = [];
        const csvConfig = selectedImportConfig.jsonConfig as CashImportConfigDetails;
        let data;
        let currentLine;
        if (csvConfig.parsing.header) {
            data = parsedCsv.data.slice(1);
            currentLine = 2;
        } else {
            data = parsedCsv.data;
            currentLine = 1;
        }
        let i = 0;
        for (const oneLine of data) {
            const transaction = new FlatCashTransaction();
            transaction.transactionDate = this.buildTransactionDate(
                oneLine,
                csvConfig,
                currentLine,
            )!;
            transaction.description = this.buildDescription(oneLine, csvConfig, currentLine);
            transaction.detail = this.buildDetail(oneLine, csvConfig, currentLine);
            transaction.importId = this.buildImportId(oneLine, csvConfig, currentLine);
            const amount = this.buildAmount(oneLine, csvConfig, currentLine);
            transaction.currency = this.buildCurrency(
                oneLine,
                csvConfig,
                currencyList,
                currentLine,
            )!;
            if (amount >= 0) {
                transaction.amount = amount;
                transaction.inAccount = this.buildAccount(
                    oneLine,
                    csvConfig,
                    selectedAccount,
                    accountList,
                    currentLine,
                )!;
                transaction.outAccount = unknownIncome;
                transaction.type = CashTransactionType.INCOME;
            } else {
                transaction.amount = -amount;
                transaction.outAccount = this.buildAccount(
                    oneLine,
                    csvConfig,
                    selectedAccount,
                    accountList,
                    currentLine,
                )!;
                transaction.inAccount = unknownExpense;
                transaction.type = CashTransactionType.EXPENSE;
            }
            if (!isTest) {
                if (csvConfig.extra.detectAlreadyImported) {
                    await this.checkAlreadyImport(transaction);
                }
                const cashRuleService = Container.get(CashRuleService);
                await cashRuleService.assignWithRules(
                    transaction,
                    accountMap,
                    tagMap,
                    rules,
                    accountList,
                );
            }
            transactionList.push(transaction);
            if (isTest) {
                return transactionList;
            }
            i++;
            currentLine++;
            await updateProgress(Math.round((i * 100) / data.length));
        }
        await updateProgress(100);
        return transactionList;
    }