lodash#toNumber TypeScript Examples

The following examples show how to use lodash#toNumber. 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: formatter.ts    From S2 with MIT License 5 votes vote down vote up
parseNumberWithPrecision = (value: number | string) => {
  return Number.parseFloat((toNumber(value) || 0).toPrecision(PRECISION));
}
Example #2
Source File: errors.test.ts    From selling-partner-api-sdk with MIT License 4 votes vote down vote up
describe(`client`, () => {
  it(`should throw ${SellingPartnerForbiddenError.name} when pass invalid token`, async () => {
    expect.assertions(2)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)
    const requestId = 'ABC'

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response.setHeader('x-amzn-requestid', requestId).sendStatus(StatusCodes.FORBIDDEN)
        response.send({
          errors: [
            {
              code: 'Forbidden',
              message: 'Forbidden',
            },
          ],
        })
      })

    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toBeInstanceOf(
      SellingPartnerForbiddenError,
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'requestId',
      requestId,
    )
  })

  it(`should throw ${SellingPartnerNotFoundRegionError.name} if cannot extract region from base path`, async () => {
    expect.assertions(2)

    const basePath = 'example.com'
    const { CA } = amazonMarketplaces

    const client = new Promise(() => {
      assertMarketplaceHasSellingPartner(CA)

      const configuration: APIConfigurationParameters = {
        accessToken: 'Atza|...',
        basePath,
      }
      return new SellersApiClient(configuration)
    })

    await expect(client).rejects.toBeInstanceOf(SellingPartnerNotFoundRegionError)
    await expect(client).rejects.toHaveProperty('basePath', basePath)
  })

  it(`should throw ${SellingPartnerMismatchRegionError.name} if mismatch between region in default base path and region parameter`, async () => {
    expect.assertions(3)

    const region = 'us'
    const { CA } = amazonMarketplaces

    const client = new Promise(() => {
      assertMarketplaceHasSellingPartner(CA)

      const configuration: APIConfigurationParameters = {
        accessToken: 'Atza|...',
        region,
      }

      return new SellersApiClient(configuration)
    })

    await expect(client).rejects.toBeInstanceOf(SellingPartnerMismatchRegionError)
    await expect(client).rejects.toHaveProperty('defaultRegion', 'us-east-1')
    await expect(client).rejects.toHaveProperty('region', region)
  })

  it(`should throw ${SellingPartnerTooManyRequestsError.name} if reach api limit`, async () => {
    expect.assertions(2)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)
    const defaultRateLimit = '0.1'

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response
          .setHeader('x-amzn-RateLimit-Limit', defaultRateLimit)
          .sendStatus(StatusCodes.TOO_MANY_REQUESTS)
        response.send({
          errors: [
            {
              code: 'TooManyRequests',
              message: 'Too many requests',
            },
          ],
        })
      })

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }
    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toBeInstanceOf(
      SellingPartnerTooManyRequestsError,
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'rateLimit',
      toNumber(defaultRateLimit),
    )
  })

  it(`should handle unknown error`, async () => {
    expect.assertions(3)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR)
        response.send({
          errors: [],
        })
      })

    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toThrow(SellingPartnerUnknownError)

    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'message',
      'Request failed with status code 500',
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'code',
      'ERR_BAD_RESPONSE',
    )
  })

  it(`should throw original error if cannot handle`, async () => {
    expect.assertions(3)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR)
      })

    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toThrow(AxiosError)

    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'message',
      'Request failed with status code 500',
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'code',
      'ERR_BAD_RESPONSE',
    )
  })
})
Example #3
Source File: build.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
Build = (props: IProps) => {
  const [pipelineDetail, comboPipelines] = buildStore.useStore((s) => [s.pipelineDetail, s.comboPipelines]);
  const { getPipelineDetail, getComboPipelines, getExecuteRecords } = buildStore.effects;
  const { clearComboPipelines, clearPipelineDetail } = buildStore.reducers;
  const params = routeInfoStore.useStore((s) => s.params);
  const [getComboPipelinesLoading, addPipelineLoading, batchCreateTaskLoading] = useLoading(buildStore, [
    'getComboPipelines',
    'addPipeline',
    'batchCreateTask',
  ]);
  const {
    setup: { categoryTitle, type, iconType, addTitle },
    goToDetailLink,
    renderCreateModal,
    showModal,
  } = props;
  const keyProp = type === 'dataTask' ? 'ymlName' : 'branch';

  const reducer = (state: IState, action: { type: string; data: any }): IState => {
    switch (action.type) {
      case 'changeCategory': {
        let filteredPipelines = comboPipelines;
        if (action.data) {
          filteredPipelines = comboPipelines.filter((data) => {
            const { source, ymlName } = data;
            const keyValue = data[keyProp];
            return `${keyValue}-${source}-${ymlName}` === action.data;
          });
        }
        return {
          ...state,
          chosenCategory: action.data,
          pipelines: filteredPipelines,
          activeItem: extractData(filteredPipelines[0]),
        };
      }
      case 'comboPipelinesUpdate': {
        return {
          ...state,
          pipelines: comboPipelines,
          categoryOptions: comboPipelines.map((data: any) => {
            const { source, ymlName } = data;
            const keyValue = data[keyProp];
            return {
              label: `${keyValue}${
                source !== 'dice'
                  ? source === 'qa'
                    ? `(${i18n.t('dop:code quality analysis')}: ${ymlName})`
                    : `(${source}: ${ymlName})`
                  : `(${ymlName})`
              }`,
              value: `${keyValue}-${source}-${ymlName}`,
            };
          }),
          activeItem: params.pipelineID ? state.activeItem : extractData(comboPipelines[0]),
        };
      }
      case 'switchPipeline': {
        const { activeItem: newActiveItem } = action.data;
        if (!newActiveItem || isEqual(state.activeItem, newActiveItem)) {
          return state;
        }
        return { ...state, activeItem: newActiveItem };
      }
      default:
        return state;
    }
  };

  const [states, dispatch] = React.useReducer(reducer, initialState);
  const { chosenCategory, activeItem, pipelines, categoryOptions } = states;

  useUnmount(() => {
    clearComboPipelines();
    clearPipelineDetail();
  });

  React.useEffect(() => {
    getComboPipelines();
  }, [getComboPipelines]);

  React.useEffect(() => {
    const { pipelineID } = params;
    if (pipelineID) {
      const id = toNumber(pipelineID);
      getPipelineDetail({ pipelineID: id }).then((res) => {
        if (res) {
          const detailType = { ...extractData(res), workspace: res.extra.diceWorkspace };
          if (!isEqual(activeItem, detailType)) {
            // when add new for different branch / refresh
            dispatch({ type: 'switchPipeline', data: { activeItem: detailType } });
          }
        }
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [getPipelineDetail, params]); // when switch pipeline or create new

  const isTargetComboPipeline = React.useCallback(
    ({ branch, pagingYmlNames, source, workspace }: any) => {
      return (
        activeItem &&
        isEqualWith(
          { branch, source, workspace },
          activeItem,
          (v1, v2) => v1.source === v2.source && v1.branch === v2.branch && v1.workspace === v2.workspace,
        ) &&
        pagingYmlNames.includes(activeItem.ymlName)
      );
    },
    [activeItem],
  );

  const getExecuteRecordsByPageNo = React.useCallback(
    ({ pageNo }: { pageNo: number }) => {
      if (isEmpty(comboPipelines)) {
        return;
      }
      const targetCombo = comboPipelines.find(isTargetComboPipeline);
      if (targetCombo && activeItem) {
        getExecuteRecords({ ...activeItem, pagingYmlNames: targetCombo.pagingYmlNames, pageNo });
      }
    },
    [activeItem, comboPipelines, getExecuteRecords, isTargetComboPipeline],
  );

  useUpdateEffect(() => {
    activeItem && !isEmpty(comboPipelines) && getExecuteRecordsByPageNo({ pageNo: 1 });
  }, [activeItem, comboPipelines]);

  useUpdateEffect(() => {
    if (activeItem && !isEqual(extractData(pipelineDetail), activeItem)) {
      const target = pipelines.find((p) => isEqual(extractData(p), activeItem));
      target && goToDetailLink({ pipelineID: target.pipelineID }, isEmpty(pipelineDetail));
    }
  }, [activeItem]);

  useUpdateEffect(() => {
    // update pipeline list and select source according to comboPipelines
    comboPipelines && dispatch({ type: 'comboPipelinesUpdate', data: null });
  }, [comboPipelines, dispatch]);

  const renderBuildStatus = ({
    status: inputStatus,
    cancelUser,
  }: {
    status: string;
    cancelUser: { name?: string };
  }) => {
    const definedStatus = statusMap.find((s) => s.status === inputStatus);
    if (definedStatus) {
      const { jumping, colorClass } = definedStatus;
      let { msg } = definedStatus;
      if (inputStatus === 'StopByUser') {
        const { name = '' } = cancelUser || {};
        msg = i18n.t('user {name} canceled', { name });
      }
      const statusStyle = `flow-${colorClass} ${jumping ? 'jumping' : ''}`;
      return (
        <Tooltip title={msg}>
          <div className={`${statusStyle} status-icon`} />
        </Tooltip>
      );
    }
    return null;
  };

  const renderList = () => {
    return (
      <List
        itemLayout="horizontal"
        dataSource={pipelines}
        renderItem={({
          pipelineID,
          commit,
          status,
          cancelUser,
          timeCreated,
          branch,
          ymlName,
          pagingYmlNames,
          source,
          triggerMode,
          workspace,
        }: BUILD.IComboPipeline) => {
          const limitedCommitId = commit ? commit.slice(0, 6) : '';
          const isDisable = disableStatus.includes(status);
          const liProps: any = {};
          const isBigData = source === 'bigdata';
          const displayName = isBigData ? ymlName.slice(ymlName.lastIndexOf('/') + 1) : branch;
          const toolTipName = isBigData ? ymlName : branch;
          if (!isDisable) {
            liProps.onClick = () =>
              dispatch({ type: 'switchPipeline', data: { activeItem: { branch, source, ymlName, workspace } } });
          }

          const cls = classnames({
            'build-item': true,
            'build-item-yml': !isBigData,
            disable: isDisable,
            active: !isDisable && isTargetComboPipeline({ branch, source, pagingYmlNames, workspace }),
          });
          return (
            <div key={pipelineID} className={cls} {...liProps}>
              <div className="w-full flex flex-col justify-between items-center">
                <div className="title flex justify-between items-center">
                  <Tooltip title={toolTipName} overlayClassName="commit-tip">
                    <span className="branch-name font-medium nowrap">
                      <CustomIcon type={iconType} />
                      <span className="nowrap">{displayName}</span>
                    </span>
                  </Tooltip>
                  {!isBigData && renderBuildStatus({ status, cancelUser })}
                </div>
                <IF check={!isBigData}>
                  <div className="yml-name nowrap flex justify-between items-center">
                    <Tooltip title={ymlName} overlayClassName="commit-tip">
                      <span className="name nowrap">
                        <CustomIcon type="wj" />
                        <span className="nowrap">{ymlName}</span>
                      </span>
                    </Tooltip>
                    <div className="workspace">{workspace}</div>
                  </div>
                </IF>
                <div className="item-footer">
                  {!isBigData && (
                    <span>
                      <CustomIcon type="commit" />
                      <span>{limitedCommitId || ''}</span>
                    </span>
                  )}
                  <span className="time">
                    {fromNow(timeCreated)}
                    {triggerMode === 'cron' && <CustomIcon type="clock" />}
                  </span>
                  {isBigData && renderBuildStatus({ status, cancelUser })}
                </div>
              </div>
            </div>
          );
        }}
      />
    );
  };

  const renderLeftSection = () => {
    return (
      <Spin spinning={getComboPipelinesLoading || addPipelineLoading || batchCreateTaskLoading}>
        <div className="build-list-wrap">
          <div className="mr-8 mb-3 ml-3">
            <Select
              showSearch
              className="w-full"
              optionFilterProp="children"
              value={chosenCategory}
              onChange={(e: any) => dispatch({ type: 'changeCategory', data: e })}
              dropdownClassName="branch-select"
              filterOption={(input: any, option: any) => {
                return get(option, 'props.title').toLowerCase().indexOf(input.toLowerCase()) >= 0;
              }}
            >
              <Option value="" title="">
                {categoryTitle}
              </Option>
              {categoryOptions.map(({ label, value }: { label: string; value: string }) =>
                type === 'dataTask' ? (
                  <Option key={value} title={label} value={value}>
                    {label.slice(label.lastIndexOf('/') + 1)}
                  </Option>
                ) : (
                  <Option key={value} title={label} value={value}>
                    {label}
                  </Option>
                ),
              )}
            </Select>
          </div>
          <div className="build-list">{renderList()}</div>
        </div>
      </Spin>
    );
  };

  const getList = (pipelineID: number, buildDetailItem: BUILD.IActiveItem, isRerun: boolean) => {
    getComboPipelines();
    if (isEqual(activeItem, buildDetailItem)) {
      if (isRerun) {
        goToDetailLink({ pipelineID });
      } else {
        getPipelineDetail({ pipelineID });
      }
      getExecuteRecordsByPageNo({ pageNo: 1 });
    }
  };

  const renderRightSection = () => (
    <BuildDetail
      getPipelines={getList}
      activeItem={activeItem}
      goToDetailLink={goToDetailLink}
      getExecuteRecordsByPageNo={getExecuteRecordsByPageNo}
    />
  );

  return (
    <SplitPage className="runtime-build-main">
      <SplitPage.Left width={300} className="pr-0 spin-h-full">
        {renderLeftSection()}
      </SplitPage.Left>
      <SplitPage.Right pl32>{renderRightSection()}</SplitPage.Right>
      <TopButtonGroup>
        <Button type="primary" onClick={showModal}>
          {addTitle}
        </Button>
      </TopButtonGroup>
      {renderCreateModal()}
    </SplitPage>
  );
}