rxjs#lastValueFrom TypeScript Examples

The following examples show how to use rxjs#lastValueFrom. 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: user.mdoel.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 8 votes vote down vote up
describe('comparePasswordMethod', () => {
  test('should be true if password is matched', async () => {
    const hashed = await hash('123456', 10);
    const contextMock = {
      password: hashed,
    };

    const result = await lastValueFrom(
      comparePasswordMethod.call(contextMock, '123456'),
    );
    expect(result).toBeTruthy();
  });

  test('should be false if password is not matched', async () => {
    const hashed = await hash('123456', 10);
    const contextMock = {
      password: hashed,
    };

    // input password is wrong
    const result = await lastValueFrom(
      comparePasswordMethod.call(contextMock, '000000'),
    );
    expect(result).toBeFalsy();
  });
});
Example #2
Source File: manifest-service.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
   * Registers the given intention, allowing the application to interact with public capabilities matching the intention.
   *
   * The intention can match multiple capabilities by using wildcards (such as `*` or `?`) in the qualifier.
   *
   * <strong>This operation requires that the 'Intention Registration API' is enabled for your application.</strong>
   *
   * @return A Promise that resolves to the identity of the registered intention,
   *         or that rejects if the registration failed.
   */
  public registerIntention(intention: Intention): Promise<string> {
    const register$ = Beans.get(MessageClient).request$<string>(ManifestRegistryTopics.RegisterIntention, intention);
    return lastValueFrom(register$.pipe(mapToBody()));
  }
Example #3
Source File: submission.hook.service.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
public async process(submission: SubmissionEntity): Promise<void> {
    await Promise.all(submission.form.hooks.map(async (hook) => {
      if (!hook.enabled) {
        return
      }

      try {
        const response = await lastValueFrom(this.httpService.post(
          hook.url,
          this.format(submission, hook.format)
        ))

        this.logger.info({
          submission: submission.id,
          form: submission.formId,
          webhook: hook.url,
        }, 'sent hook')
      } catch (e) {
        this.logger.error({
          submission: submission.id,
          form: submission.formId,
          webhook: hook.url,
          error: serializeError(e),
        }, 'failed to post webhook')
        throw e
      }
    }))
  }
Example #4
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get TWS's current time.
   */
  getCurrentTime(): Promise<number> {
    return lastValueFrom(
      this.subscriptions
        .register<number>(
          () => {
            this.api.reqCurrentTime();
          },
          undefined,
          [[EventName.currentTime, this.onCurrentTime]],
          "reqCurrentTime" // use same instance id each time, to make sure there is only 1 pending request at time
        )
        .pipe(map((v: { all: number }) => v.all)),
      {
        defaultValue: 0,
      }
    );
  }
Example #5
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get the accounts to which the logged user has access to.
   */
  getManagedAccounts(): Promise<string[]> {
    return lastValueFrom(
      this.subscriptions
        .register<string[]>(
          () => {
            this.api.reqManagedAccts();
          },
          undefined,
          [[EventName.managedAccounts, this.onManagedAccts]],
          "getManagedAccounts" // use same instance id each time, to make sure there is only 1 pending request at time
        )
        .pipe(map((v: { all: string[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #6
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Request contract information from TWS.
   * This method will provide all the contracts matching the contract provided.
   *
   * It can also be used to retrieve complete options and futures chains.
   * Though it is now (in API version > 9.72.12) advised to use reqSecDefOptParams for that purpose.
   *
   * This information will be emitted as contractDetails event.
   *
   * @param contract The contract used as sample to query the available contracts.
   */
  getContractDetails(contract: Contract): Promise<ContractDetails[]> {
    return lastValueFrom(
      this.subscriptions
        .register<ContractDetails[]>(
          (reqId) => {
            this.api.reqContractDetails(reqId, contract);
          },
          undefined,
          [
            [EventName.contractDetails, this.onContractDetails],
            [EventName.contractDetailsEnd, this.onContractDetailsEnd],
          ]
        )
        .pipe(map((v: { all: ContractDetails[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #7
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Requests security definition option parameters for viewing a contract's option chain.
   * 
   * This information will be emitted as securityDefinitionOptionParameter event.
   *
   * @param underlyingSymbol The underlying symbol to query the available contracts. 
   * @param futFopExchange The exchange on which the returned options are trading. Can be set to the empty string "" for all exchanges.
   * @param underlyingSecType The type of the underlying security, i.e. STK. 
   * @param underlyingConId the contract ID of the underlying security.
   */
  getSecDefOptParams(
    underlyingSymbol: string, futFopExchange: string, underlyingSecType: SecType, underlyingConId: number): Promise<SecurityDefinitionOptionParameterType[]> {
    return lastValueFrom(
      this.subscriptions
        .register<SecurityDefinitionOptionParameterType[]>(
          (reqId) => {
            this.api.reqSecDefOptParams(reqId, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId);
          },
          undefined,
          [
            [EventName.securityDefinitionOptionParameter, this.onSecurityDefinitionOptionParameter],
            [EventName.securityDefinitionOptionParameterEnd, this.onSecurityDefinitionOptionParameterEnd],
          ]
        )
        .pipe(map((v: { all: SecurityDefinitionOptionParameterType[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #8
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Fetch a snapshot of real time market data.
   * Returns market data for an instrument either in real time or 10-15 minutes delayed (depending on the market data type specified,
   * see [[setMarketDataType]]).
   * getMarketDataSingle will collect market data for a maximum of 11 seconds and then return the result.
   *
   * @param contract The [[Contract]] for which the data is being requested
   * @param genericTickList comma  separated ids of the generic ticks
   * Look at getMarketData documentation for a list of available generic ticks.
   * @param regulatorySnapshot Snapshot for US stocks requests NBBO snapshots for users which have "US Securities Snapshot Bundle" subscription
   * but not corresponding Network A, B, or C subscription necessary for streaming * market data.
   * One-time snapshot of current market price that will incur a fee of 1 cent to the account per snapshot.
   */
  getMarketDataSnapshot(
    contract: Contract,
    genericTickList: string,
    regulatorySnapshot: boolean
  ): Promise<MutableMarketData> {
    return lastValueFrom(
      this.getMarketData(
        contract,
        genericTickList,
        true,
        regulatorySnapshot
      ).pipe(map((v: { all: MutableMarketData }) => v.all)),
      {
        defaultValue: new MutableMarketData(),
      }
    );
  }
Example #9
Source File: local.strategy.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
// When using Observable as return type, the exeption in the pipeline is ignored.
  // In our case, the `UnauthorizedException` is **NOT** caught and handled as expected.
  // The flow is NOT prevented by the exception and continue to send a `Observable` to
  // the next step aka calling `this.authService.login` in `AppController#login` method.
  // Then the jwt token is generated in any case(eg. wrong username or wrong password),
  // the authenticatoin worflow does not work as expected.
  //
  // The solution is customizing `PassportSerializer`.
  // Example: https://github.com/jmcdo29/zeldaPlay/blob/master/apps/api/src/app/auth/session.serializer.ts
  //
  // validate(username: string, password: string): Observable<any> {
  //   return this.authService
  //     .validateUser(username, password)
  //     .pipe(throwIfEmpty(() => new UnauthorizedException()));
  // }

  async validate(username: string, password: string): Promise<UserPrincipal> {
    const user: UserPrincipal = await lastValueFrom(
      this.authService.validateUser(username, password),
    );

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
Example #10
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get the timestamp of earliest available historical data for a contract and data type.
   *
   * @param reqId An identifier for the request.
   * @param contract [[Contract]] object for which head timestamp is being requested.
   * @param whatToShow Type of data for head timestamp - "BID", "ASK", "TRADES", etc
   * @param useRTH Use regular trading hours only, `true` for yes or `false` for no.
   * @param formatDate Set to 1 to obtain the bars' time as yyyyMMdd HH:mm:ss, set to 2 to obtain it like system time format in seconds.
   */
  getHeadTimestamp(
    contract: Contract,
    whatToShow: string,
    useRTH: boolean,
    formatDate: number
  ): Promise<string> {
    return lastValueFrom(
      this.subscriptions
        .register<string>(
          (reqId) => {
            this.api.reqHeadTimestamp(
              reqId,
              contract,
              whatToShow,
              useRTH,
              formatDate
            );
          },
          (reqId) => {
            this.api.cancelHeadTimestamp(reqId);
          },
          [[EventName.headTimestamp, this.onHeadTimestamp]],
          `${JSON.stringify(contract)}:${whatToShow}:${useRTH}:${formatDate}`
        )
        .pipe(map((v: { all: string }) => v.all)),
      {
        defaultValue: "",
      }
    );
  }
Example #11
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get venues for which market data is returned on getMarketDepthL2 (those with market makers).
   */
  getMarketDepthExchanges(): Promise<DepthMktDataDescription[]> {
    return lastValueFrom(
      this.subscriptions
        .register<DepthMktDataDescription[]>(
          () => {
            this.api.reqMktDepthExchanges();
          },
          undefined,
          [[EventName.mktDepthExchanges, this.onMktDepthExchanges]],
          "reqMktDepthExchanges" // use same instance id each time, to make sure there is only 1 pending request at time
        )
        .pipe(map((v: { all: DepthMktDataDescription[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #12
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get data histogram of specified contract.
   *
   * @param contract [[Contract]] object for which histogram is being requested
   * @param useRTH Use regular trading hours only, `true` for yes or `false` for no.
   * @param duration Period duration of which data is being requested
   * @param durationUnit Duration unit of which data is being requested
   */
  getHistogramData(
    contract: Contract,
    useRTH: boolean,
    duration: number,
    durationUnit: DurationUnit
  ): Promise<HistogramEntry[]> {
    return lastValueFrom(
      this.subscriptions
        .register<HistogramEntry[]>(
          (reqId) => {
            this.api.reqHistogramData(
              reqId,
              contract,
              useRTH,
              duration,
              durationUnit
            );
          },
          (reqId) => {
            this.api.cancelHistogramData(reqId);
          },
          [[EventName.histogramData, this.onHistogramData]],
          `${JSON.stringify(contract)}:${useRTH}:${duration}:${durationUnit}`
        )
        .pipe(map((v: { all: HistogramEntry[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #13
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Requests all current open orders in associated accounts at the current moment.
   */
  getAllOpenOrders(): Promise<OpenOrder[]> {
    return lastValueFrom(
      this.subscriptions
        .register<OpenOrder[]>(
          () => {
            this.api.reqAllOpenOrders();
          },
          undefined,
          [
            [EventName.openOrder, this.onOpenOrder],
            [EventName.orderStatus, this.onOrderStatus],
            [EventName.orderBound, this.onOrderBound],
            [EventName.openOrderEnd, this.onOpenOrderEnd],
          ],
          "getAllOpenOrders"  // use same instance id each time, to make sure there is only 1 pending request at time
        )
        .pipe(map((v: { all: OpenOrder[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #14
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Requests the next valid order ID at the current moment.
   */
  getNextValidOrderId(): Promise<number> {
    return lastValueFrom(
      this.subscriptions
        .register<number>(
          () => {
            this.api.reqIds();
          },
          undefined,
          [[EventName.nextValidId, this.onNextValidId]]
        )
        .pipe(map((v: { all: number }) => v.all)),
      {
        defaultValue: -1,
      }
    );
  }
Example #15
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get execution details of all executed trades.
   * @param filter  filter trade data on [[ExecutionFilter]]
   */
  getExecutionDetails(filter: ExecutionFilter): Promise<ExecutionDetail[]> {
    return lastValueFrom(
      this.subscriptions
        .register<ExecutionDetail[]>(
          (reqId) => {
            this.api.reqExecutions(reqId, filter);
          },
          undefined,
          [
            [EventName.execDetails, this.onExecDetails],
            [EventName.execDetailsEnd, this.onExecDetailsEnd],
          ]
        )
        .pipe(map((v: { all: ExecutionDetail[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #16
Source File: initiate-search.ts    From js-client with MIT License 6 votes vote down vote up
initiateSearch = (
	rawSubscription: APISubscription<RawSearchMessageReceived, RawSearchMessageSent>,
	query: string,
	options: InitiateSearchOptions,
): Promise<RawSearchInitiatedMessageReceived> => {
	// Generate a unique ID for the search initiating request
	const requestID = uuidv4();

	// Create a promise to receive search initation results
	const results$ = QUERY_INIT_RESULTS.pipe(
		// We only want results relevant to this request
		filter(({ requestID: msgRequestID }) => msgRequestID === requestID),

		// There's only one response to the request, so we're done after the first
		first(),

		// If msg.data.Error is nil, the backend is happy  - continue
		// If msg.data.Error is NON-nil, there's a problem - reject
		concatMap(({ msg }) => (isNil(msg.data.Error) ? of(msg) : throwError(msg))),

		// If we didn't throw, everything is fine. Send a RawAcceptSearchMessageSent to continue setting up the search
		tap(msg =>
			rawSubscription.send(<RawAcceptSearchMessageSent>{
				type: 'search',
				data: { OK: true, OutputSearchSubproto: msg.data.OutputSearchSubproto },
			}),
		),

		// It takes the backend a fraction of a second to be ready for requests after we set up the search
		delay(200),
	);

	const resultsP = lastValueFrom(results$);

	// Now that we're ready to receive results (with resultsP), we can push on the queue to kick off the search initiation process
	QUERY_QUEUE.next({ requestID, rawSubscription, query, options });

	return resultsP;
}
Example #17
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Get commication reports details of all executed trades.
   * @param filter  filter trade data on [[ExecutionFilter]]
   */
  getCommissionReport(filter: ExecutionFilter): Promise<CommissionReport[]> {
    return lastValueFrom(
      this.subscriptions
        .register<CommissionReport[]>(
          (reqId) => {
            this.api.reqExecutions(reqId, filter);
          },
          undefined,
          [
            [EventName.execDetailsEnd, this.onExecDetailsEnd],
            [EventName.commissionReport, this.onComissionReport],
          ]
        )
        .pipe(map((v: { all: CommissionReport[] }) => v.all)),
      {
        defaultValue: [],
      }
    );
  }
Example #18
Source File: api-next.ts    From ib with MIT License 6 votes vote down vote up
/**
   * Search contracts where name or symbol matches the given text pattern.
   *
   * @param pattern Either start of ticker symbol or (for larger strings) company name.
   */
  searchContracts(pattern: string): Promise<ContractDescription[]> {
    return lastValueFrom(
      this.subscriptions
        .register<ContractDescription[]>(
          (reqId) => {
            this.api.reqMatchingSymbols(reqId, pattern);
          },
          undefined,
          [[EventName.symbolSamples, this.onSymbolSamples]]
        )
        .pipe(map((v: { all: ContractDescription[] }) => v.all))
    );
  }
Example #19
Source File: manifest-service.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
   * Registers given capability. If the capability has public visibility, other applications can browse the capability and interact with it.
   *
   * @return A Promise that resolves to the identity of the registered capability,
   *         or that rejects if the registration failed.
   */
  public registerCapability<T extends Capability>(capability: T): Promise<string> {
    const register$ = Beans.get(MessageClient).request$<string>(ManifestRegistryTopics.RegisterCapability, capability);
    return lastValueFrom(register$.pipe(mapToBody()));
  }
Example #20
Source File: broker-gateway.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
public isConnected(): Promise<boolean> {
    return lastValueFrom(this._brokerInfo$).then(() => true).catch(() => false);
  }
Example #21
Source File: historical-ticks-bid-ask.ts    From ib with MIT License 5 votes vote down vote up
/**
   * Start the app.
   */
  start(): void {
    const scriptName = path.basename(__filename);
    logger.debug(`Starting ${scriptName} script`);

    if (!this.cmdLineArgs.conid) {
      this.error("-conid argument missing.");
    }
    if (!this.cmdLineArgs.exchange) {
      this.error("-exchange argument missing.");
    }
    if (!this.cmdLineArgs.start && !this.cmdLineArgs.end) {
      this.error("-start or -end argument missing.");
    }
    if (this.cmdLineArgs.start && this.cmdLineArgs.end) {
      this.error("-start and -end argument specified, only use one of both.");
    }
    if (!this.cmdLineArgs.count) {
      this.error("-count argument missing.");
    }

    this.connect();

    // We use lastValueFrom here as we are not interested in getting
    // incremental updates.
    // If you do so (e.g. to show results incrementally as received from TWS),
    // use .subscribe({next: update => ...}) instead.

    lastValueFrom(
      this.api.getHistoricalTicksBidAsk(
        {
          conId: this.cmdLineArgs.conid as number,
          exchange: this.cmdLineArgs.exchange as string,
        },
        this.cmdLineArgs.start as string,
        this.cmdLineArgs.end as string,
        this.cmdLineArgs.count as number,
        this.cmdLineArgs.rth as number ?? 1,
        false
      )
    )
      .then((ticks) => {
        this.printObject(ticks);
        this.stop();
      })
      .catch((err: IBApiNextError) => {
        this.error(
          `getHistoricalTicksBidAsk failed with '${err.error.message}'`
        );
      });
  }
Example #22
Source File: historical-ticks-last.ts    From ib with MIT License 5 votes vote down vote up
/**
   * Start the app.
   */
  start(): void {
    const scriptName = path.basename(__filename);
    logger.debug(`Starting ${scriptName} script`);

    if (!this.cmdLineArgs.conid) {
      this.error("-conid argument missing.");
    }
    if (!this.cmdLineArgs.exchange) {
      this.error("-exchange argument missing.");
    }
    if (!this.cmdLineArgs.start && !this.cmdLineArgs.end) {
      this.error("-start or -end argument missing.");
    }
    if (this.cmdLineArgs.start && this.cmdLineArgs.end) {
      this.error("-start and -end argument specified, only use one of both.");
    }
    if (!this.cmdLineArgs.count) {
      this.error("-count argument missing.");
    }

    this.connect();

    // We use lastValueFrom here as we are not interested in getting
    // incremental updates.
    // If you do so (e.g. to show results incrementally as received from TWS),
    // use .subscribe({next: update => ...}) instead.

    lastValueFrom(
      this.api.getHistoricalTicksLast(
        {
          conId: this.cmdLineArgs.conid as number,
          exchange: this.cmdLineArgs.exchange as string,
        },
        this.cmdLineArgs.start as string,
        this.cmdLineArgs.end as string,
        this.cmdLineArgs.count as number,
        this.cmdLineArgs.rth as number ?? 1
      )
    )
      .then((ticks) => {
        this.printObject(ticks);
        this.stop();
      })
      .catch((err: IBApiNextError) => {
        this.error(
          `getHistoricalTicksBidAsk failed with '${err.error.message}'`
        );
      });
  }
Example #23
Source File: misc-helpers.ts    From s-libs with MIT License 5 votes vote down vote up
export async function pipeAndCollect<I, O>(
  source: I[],
  operator: OperatorFunction<I, O>,
): Promise<O[]> {
  return lastValueFrom(of(...source).pipe(operator, toArray()));
}
Example #24
Source File: historical-ticks-mid.ts    From ib with MIT License 5 votes vote down vote up
/**
   * Start the app.
   */
  start(): void {
    const scriptName = path.basename(__filename);
    logger.debug(`Starting ${scriptName} script`);

    if (!this.cmdLineArgs.conid) {
      this.error("-conid argument missing.");
    }
    if (!this.cmdLineArgs.exchange) {
      this.error("-exchange argument missing.");
    }
    if (!this.cmdLineArgs.start && !this.cmdLineArgs.end) {
      this.error("-start or -end argument missing.");
    }
    if (this.cmdLineArgs.start && this.cmdLineArgs.end) {
      this.error("-start and -end argument specified, only use one of both.");
    }
    if (!this.cmdLineArgs.count) {
      this.error("-count argument missing.");
    }

    this.connect();

    // We use lastValueFrom here as we are not interested in getting
    // incremental updates.
    // If you do so (e.g. to show results incrementally as received from TWS),
    // use .subscribe({next: update => ...}) instead.

    lastValueFrom(
      this.api.getHistoricalTicksMid(
        {
          conId: this.cmdLineArgs.conid as number,
          exchange: this.cmdLineArgs.exchange as string,
        },
        this.cmdLineArgs.start as string,
        this.cmdLineArgs.end as string,
        this.cmdLineArgs.count as number,
        this.cmdLineArgs.rth as number ?? 1
      )
    )
      .then((ticks) => {
        this.printObject(ticks);
        this.stop();
      })
      .catch((err: IBApiNextError) => {
        this.error(`getHistoricalTicksMid failed with '${err.error.message}'`);
      });
  }
Example #25
Source File: PoolsTask.ts    From guardian with Apache License 2.0 5 votes vote down vote up
async start(guardian: AcalaGuardian) {
    const { apiRx, getTokenPrecision } = await guardian.isReady();

    const { currencyId } = this.arguments;

    const stableCoin = apiRx.consts.cdpEngine.getStableCurrencyId;
    const nativeCoin = apiRx.consts.currencies.getNativeCurrencyId;

    let pairs: TradingPair[];

    if (currencyId === 'all') {
      const tradingPair = await lastValueFrom(apiRx.query.dex.liquidityPool.entries().pipe(take(1)));

      pairs = tradingPair
        .map(([key, value]) => {
          const [balance1, balance2] = value;

          if (balance1 && balance2) {
            return key.args[0];
          }

          return undefined;
        })
        .filter((p): p is TradingPair => p !== undefined);
    } else {
      const currencies = castArray(currencyId);
      pairs = currencies
        .map((x) => apiRx.createType('CurrencyId', x))
        .map((currencyId) => {
          return currencyId.eq(nativeCoin)
            ? apiRx.createType('TradingPair', [currencyId, stableCoin])
            : apiRx.createType('TradingPair', [stableCoin, currencyId]);
        });
    }

    // ignore non-token currency
    // TODO: support any currency
    pairs = pairs.filter(([base, quote]) => {
      return base.isToken && quote.isToken && !base.eq(quote);
    });

    return from(pairs).pipe(
      mergeMap((pair) =>
        apiRx.query.dex.liquidityPool(pair).pipe(
          map(([base, other]) => {
            const [baseCurrency, otherCurrency] = pair;
            const basePrecision = getTokenPrecision(baseCurrency.asToken.toString());
            assert(basePrecision);
            const otherPrecision = getTokenPrecision(otherCurrency.asToken.toString());
            assert(otherPrecision);
            const _base = FixedPointNumber.fromInner(base.toString(), basePrecision);
            const _other = FixedPointNumber.fromInner(other.toString(), otherPrecision);
            const price = baseCurrency.eq(stableCoin) ? _base.div(_other) : _other.div(_base);
            price.setPrecision(18);
            return {
              currencyId: pair.toString(),
              price: price._getInner().toFixed(0),
              baseLiquidity: base.toString(),
              otherLiquidity: other.toString()
            };
          })
        )
      )
    );
  }
Example #26
Source File: broker-gateway.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 5 votes vote down vote up
public async postMessage(channel: MessagingChannel, message: Message): Promise<void> {
    if (isPlatformStopped()) {
      throw GatewayErrors.PLATFORM_STOPPED_ERROR;
    }

    // If not connected to the broker, wait until connected. If connected, continue execution immediately
    // without spawning a microtask. Otherwise, messages cannot be published during platform shutdown.
    const brokerInfo = this._brokerInfo || await lastValueFrom(this._brokerInfo$);

    const messageId = UUID.randomUUID();
    const envelope: MessageEnvelope = {
      transport: MessagingTransport.ClientToBroker,
      channel: channel,
      message: message,
    };
    envelope.message.headers
      .set(MessageHeaders.MessageId, messageId)
      .set(MessageHeaders.Timestamp, Date.now())
      .set(MessageHeaders.AppSymbolicName, this._appSymbolicName)
      .set(MessageHeaders.ClientId, brokerInfo.clientId);

    // Install Promise that resolves once the broker has acknowledged the message, or that rejects otherwise.
    const postError$ = new Subject<never>();
    const whenPosted = new Promise<void>((resolve, reject) => {
      merge(this.message$, postError$)
        .pipe(
          filterByTopicChannel<MessageDeliveryStatus>(messageId),
          take(1),
          pluckMessage(),
          timeout({first: this._messageDeliveryTimeout, with: () => throwError(() => GatewayErrors.MESSAGE_DISPATCH_ERROR(this._messageDeliveryTimeout, envelope))}),
          mergeMap(statusMessage => statusMessage.body!.ok ? EMPTY : throwError(() => statusMessage.body!.details)),
          takeUntil(this._platformStopping$),
        )
        .subscribe({
          error: reject,
          complete: resolve,
        });
    });

    try {
      brokerInfo.window.postMessage(envelope, brokerInfo.origin);
    }
    catch (error) {
      postError$.error(error);
    }

    await whenPosted;
  }
Example #27
Source File: user.controller.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('UserController', () => {
  let controller: UserController;
  let service: UserService;
  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      providers: [
        {
          provide: UserService,
          useValue: {
            findById: jest.fn(),
          },
        },
      ],
      controllers: [UserController],
    }).compile();

    controller = app.get<UserController>(UserController);
    service = app.get<UserService>(UserService);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });

  it('getUser', async () => {
    jest
      .spyOn(service, 'findById')
      .mockImplementationOnce((id: string, withPosts: boolean) =>
        of({
          username: 'hantsy',
          password: 'mysecret',
          email: '[email protected]',
          firstName: 'hantsy',
          lastName: 'bai',
        } as any),
      );
    const user = await lastValueFrom(controller.getUser('id', false));
    expect(user.firstName).toBe('hantsy');
    expect(user.lastName).toBe('bai');
    expect(service.findById).toBeCalledWith('id', false);
  });
});
Example #28
Source File: generate-auto-extractors.spec.ts    From js-client with MIT License 5 votes vote down vote up
describe('generateAutoExtractors()', () => {
	const generateAutoExtractors = makeGenerateAutoExtractors(TEST_BASE_API_CONTEXT);

	// Use a randomly generated tag, so that we know exactly what we're going to query
	const tag = uuidv4();

	// The number of entries to generate
	const count = 1000;

	// The start date for generated queries
	const start = new Date(2010, 0, 0);

	// The end date for generated queries; one minute between each entry
	const end = addMinutes(start, count - 1);

	beforeAll(async () => {
		// Generate and ingest some entries
		const ingestJSONEntries = makeIngestJSONEntries(TEST_BASE_API_CONTEXT);
		const values: Array<CreatableJSONEntry> = range(0, count).map(i => {
			const timestamp = addMinutes(start, i).toISOString();
			return {
				timestamp,
				tag,
				data: JSON.stringify({ timestamp, value: i }, null, 2), // Add vertical whitespace, so that JSON is recommended over CSV
			};
		});

		await ingestJSONEntries(values);

		// Check the list of tags until our new tag appears
		const getAllTags = makeGetAllTags(TEST_BASE_API_CONTEXT);
		while (!(await getAllTags()).includes(tag)) {
			// Give the backend a moment to catch up
			await sleep(1000);
		}
	}, 25000);

	it(
		'Should generate auto extractors',
		integrationTest(async () => {
			const subscribeToOneSearch = makeSubscribeToOneSearch(TEST_BASE_API_CONTEXT);
			const query = `tag=${tag} limit 10`;
			const search = await subscribeToOneSearch(query, { filter: { dateRange: { start, end } } });

			const entries = await lastValueFrom(
				search.entries$.pipe(
					map(e => e as RawSearchEntries),
					takeWhile(e => !e.finished, true),
				),
			);

			const exploreResults = await generateAutoExtractors({ tag, entries });

			expect(Object.keys(exploreResults).length).withContext('we should get >0 AX suggestions').toBeGreaterThan(0);
			expect(exploreResults['json']).withContext('we should have a JSON AX suggestion').toBeDefined();
			expect(exploreResults['json'].length).withContext('we should have >0 JSON AX suggestions').toBeGreaterThan(0);

			exploreResults['json'].forEach(ax => {
				expect(ax.autoExtractor.tag).withContext('the suggested AX tag should match the provided tag').toEqual(tag);
				expect(ax.autoExtractor.module).withContext('the suggested AX module should be json').toEqual('json');
				expect(ax.confidence).withContext('json is the right module, so its confidence should be 10').toEqual(10);
				expect(ax.autoExtractor.parameters)
					.withContext('the suggested AX module should break out the fields in the entries')
					.toEqual('timestamp value');
				expect(ax.explorerEntries.length).withContext('explore should have >0 elements').toBeGreaterThan(0);
				ax.explorerEntries.forEach(exploreEntry => {
					expect(exploreEntry.elements.length)
						.withContext('explore should have two elements: one for each field (timestamp and value)')
						.toEqual(2);
					exploreEntry.elements.forEach(elt => {
						expect(elt.filters.length).withContext('we should have filters on explore elements').toBeGreaterThan(0);
					});
				});
			});

			// We can't really make assertions about what the other AX generators are going to do when we look at JSON data
		}),
		25000,
	);
});
Example #29
Source File: sendgrid.service.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
describe('SendgridService', () => {
  let service: SendgridService;
  let mailService: MailService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        SendgridService,
        {
          provide: SENDGRID_MAIL,
          useValue: {
            send: jest.fn(),
          },
        },
      ],
    }).compile();

    service = module.get<SendgridService>(SendgridService);
    mailService = module.get<MailService>(SENDGRID_MAIL);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('MailService should be defined', () => {
    expect(mailService).toBeDefined();
  });

  it('should call MailService.send', async () => {
    const msg = {
      to: '[email protected]',
      from: '[email protected]', // Use the email address or domain you verified above
      subject: 'Sending with Twilio SendGrid is Fun',
      text: 'and easy to do anywhere, even with Node.js',
      html: '<strong>and easy to do anywhere, even with Node.js</strong>',
    };

    const sendSpy = jest
      .spyOn(mailService, 'send')
      .mockResolvedValue({} as any);

    await lastValueFrom(service.send(msg));
    expect(sendSpy).toBeCalledTimes(1);
    expect(sendSpy).toBeCalledWith(msg, false);
  });
});