lodash#isInteger TypeScript Examples

The following examples show how to use lodash#isInteger. 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: responseBuilder.ts    From ts-di-starter with MIT License 6 votes vote down vote up
/**
   * Determine http code from error
   *
   * @param {Error} error error object or something and inheirits from it
   * @returns {number} http code
   * @private
   */
  private static getCodeFromError(error): number {
    // eslint-disable-next-line no-magic-numbers
    if (error.code && isInteger(error.code) && error.code >= 100 && error.code < 600) {
      return error.code;
    }

    if (error.code) {
      log.warn(`Unexpected error code: ${error.code}`);
    }

    return HTTP_STATUS.INTERNAL_SERVER_ERROR;
  }
Example #2
Source File: is-actionable.ts    From js-client with MIT License 6 votes vote down vote up
isActionableCommand = (value: any): value is ActionableCommand => {
	try {
		const cmd = <ActionableCommand>value;
		switch (cmd.type) {
			case 'query':
				return isString(cmd.userQuery);
			case 'template':
				return isUUID(cmd.templateID);
			case 'savedQuery':
				return isUUID(cmd.queryID);
			case 'dashboard':
				return isUUID(cmd.dashboardID) && (isString(cmd.dashboardVariable) || isNull(cmd.dashboardVariable));
			case 'url':
				return (
					isString(cmd.urlTemplate) &&
					isBoolean(cmd.modal) &&
					(isInteger(cmd.modalWidthPercentage) || isNull(cmd.modalWidthPercentage))
				);
			default:
				throw Error();
		}
	} catch {
		return false;
	}
}
Example #3
Source File: is-resource.ts    From js-client with MIT License 6 votes vote down vote up
isResource = (value: any): value is Resource => {
	try {
		const r = <Resource>value;
		return (
			isUUID(r.id) &&
			isNumericID(r.userID) &&
			r.groupIDs.every(isNumericID) &&
			isString(r.name) &&
			isString(r.description) &&
			r.labels.every(isString) &&
			isBoolean(r.isGlobal) &&
			isDate(r.lastUpdateDate) &&
			isInteger(r.version) &&
			isString(r.hash) &&
			isInteger(r.size)
		);
	} catch {
		return false;
	}
}
Example #4
Source File: is-search2.ts    From js-client with MIT License 6 votes vote down vote up
isSearch2 = (value: any): value is Search2 => {
	try {
		const s = <Search2>value;
		return (
			isNumericID(s.userID) &&
			(isUndefined(s.groupID) || isNumericID(s.groupID)) &&
			s.states.every(isSearch2State) &&
			isInteger(s.attachedClients) &&
			isInteger(s.storedData)
		);
	} catch {
		return false;
	}
}
Example #5
Source File: is-system-settings.ts    From js-client with MIT License 6 votes vote down vote up
isSystemSettings = (value: any): value is SystemSettings => {
	try {
		const s = <SystemSettings>value;
		return (
			isString(s.mapTileURL) &&
			isBoolean(s.disableMapTileProxy) &&
			isBoolean(s.webServerIsDistributed) &&
			isInteger(s.maxFileSize) &&
			isInteger(s.maxResourceSize)
		);
	} catch {
		return false;
	}
}
Example #6
Source File: is-version.ts    From js-client with MIT License 5 votes vote down vote up
isVersion = (value: any): value is Version => {
	try {
		const v = <Version>value;
		return isInteger(v.major) && isInteger(v.minor) && isInteger(v.patch);
	} catch {
		return false;
	}
}
Example #7
Source File: scan-rule.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
export default function ScanRule(props: IProps) {
  const { operationAuth, scopeId, scopeType, tableKey } = props;
  const [
    { isEdit, visible, currentId, metricValue, appendedRowKeys, optionalRowKeys, loading, operationOptionalRules },
    updater,
    update,
  ] = useUpdate({
    isEdit: false,
    visible: false,
    currentId: '',
    metricValue: '',
    appendedRowKeys: [],
    optionalRowKeys: [],
    loading: false,
    operationOptionalRules: [],
  });

  const [appendedScanRules, optionalScanRules] = scanRuleStore.useStore((s) => [
    s.appendedScanRules,
    s.optionalScanRules,
  ]);

  React.useEffect(() => {
    updater.operationOptionalRules(optionalScanRules);
  }, [optionalScanRules, updater]);

  const {
    getAppendedScanRules,
    deleteScanRule,
    getOptionalScanRules,
    updateScanRule,
    batchDeleteScanRule,
    batchInsertScanRule,
  } = scanRuleStore;

  const [tableLoading] = useLoading(scanRuleStore, ['getAppendedScanRules']);

  const updateOptionalScanRules = (record: SCAN_RULE.AppendedItem) => {
    updater.operationOptionalRules((prev: any) => prev.map((p: any) => (p.id === record.id ? { ...record } : p)));
  };

  const appendedRowSelection = {
    selectedRowKeys: appendedRowKeys,
    onChange: (selectedRowKeys: string[] | number[]) => onAppendedSelectChange(selectedRowKeys),
    getCheckboxProps: (record: any) => ({
      disabled: record.scopeId === '-1',
    }),
  };

  const optionalRowSelection = {
    selectedRowKeys: optionalRowKeys,
    onChange: (rowKeys: string[] | number[]) => onOptionalSelectChange(rowKeys),
  };
  const optionalColumns: Array<ColumnProps<object>> = [
    {
      title: i18n.t('cmp:rule-name'),
      dataIndex: 'metricKey',
      width: 200,
    },
    {
      title: i18n.t('Description'),
      dataIndex: 'metricKeyDesc',
    },
    {
      title: i18n.t('Comparison operator'),
      dataIndex: 'operational',
      align: 'center',
      width: 176,
    },
    {
      title: i18n.t('dop:Access control value'),
      dataIndex: 'metricValue',
      align: 'center',
      width: 160,
      render: (val: string, record: any) => {
        if (record.valueType === 'RATING') {
          return (
            <Select
              style={{ width: 120 }}
              value={val}
              onChange={(value) => handleChange(value, record)}
              getPopupContainer={() => document.body}
            >
              {map(valueRateMap, (rate) => (
                <Option value={rate.value} key={rate.value}>
                  {rate.label}
                </Option>
              ))}
            </Select>
          );
        }
        return (
          <Input
            style={{ width: 120 }}
            value={val}
            suffix={valueTypeMap[record.valueType]}
            onChange={(e) => handleChange(e.target.value, record)}
          />
        );
      },
    },
  ];

  const appendedColumns: Array<ColumnProps<SCAN_RULE.AppendedItem>> = [
    {
      title: i18n.t('cmp:rule-name'),
      dataIndex: 'metricKey',
      width: 200,
    },
    {
      title: i18n.t('Description'),
      dataIndex: 'metricKeyDesc',
    },
    {
      title: i18n.t('Comparison operator'),
      dataIndex: 'operational',
      align: 'center',
      width: 176,
    },
    {
      title: i18n.t('dop:Access control value'),
      dataIndex: 'metricValue',
      width: 160,
      render: (item: string, record: SCAN_RULE.AppendedItem) => {
        const ruleType = valueTypeMap[record.valueType];
        if (isEdit && record.id === currentId) {
          if (record.valueType === 'RATING') {
            return (
              <Select
                style={{ width: 120 }}
                onChange={(value) => updater.metricValue(`${value}`)}
                defaultValue={isEdit && get(valueRateMap[item], 'label', '')}
              >
                {map(valueRateMap, (rate) => (
                  <Option value={rate.value} key={rate.value}>
                    {rate.label}
                  </Option>
                ))}
              </Select>
            );
          }
          return <Input defaultValue={item} suffix={ruleType} onChange={(e) => updater.metricValue(e.target.value)} />;
        }
        return record.valueType === 'RATING' ? get(valueRateMap[item], 'label', '') : `${item}${ruleType}`;
      },
    },
  ];

  const actions = {
    render: (record: SCAN_RULE.AppendedItem) => {
      if (isEdit && record.id === currentId) {
        return [
          {
            title: i18n.t('Cancel'),
            onClick: () => updater.isEdit(!isEdit),
          },
          {
            title: i18n.t('Save'),
            onClick: async () => {
              const { id, description, valueType, decimalScale } = record;
              const isIllegal = checkRule([{ valueType, metricValue, decimalScale }]);
              if (isIllegal) {
                message.error(i18n.t('dop:please enter the correct data'));
                return;
              }
              await updateScanRule({
                id,
                description,
                metricValue,
                scopeType: record.scopeType,
                scopeId: record.scopeId,
              });
              reloadAppendedList();
              updater.isEdit(!isEdit);
            },
          },
        ];
      } else {
        const isHandle = record.scopeId !== '-1';
        return [
          {
            title: (
              <WithAuth
                noAuthTip={i18n.t('dop:Platform default rules. Please add custom rules if necessary.')}
                pass={operationAuth && isHandle}
              >
                <span>{i18n.t('Edit')}</span>
              </WithAuth>
            ),
            onClick: () => update({ isEdit: isHandle, currentId: record.id }),
          },
          {
            title: (
              <WithAuth
                noAuthTip={i18n.t('dop:Platform default rules. Please add custom rules if necessary.')}
                pass={operationAuth && isHandle}
              >
                <span>{i18n.t('Delete')}</span>
              </WithAuth>
            ),
            onClick: () => {
              Modal.confirm({
                title: `${i18n.t('common:confirm to delete')}?`,
                onOk: async () => {
                  await deleteScanRule({ id: record.id, scopeId, scopeType });
                  reloadAppendedList();
                },
              });
            },
          },
        ];
      }
    },
  };

  useEffectOnce(() => {
    getAppendedScanRules({
      scopeId,
      scopeType,
    });
  });

  function onAppendedSelectChange(selectedRowKeys: number[] | string[]) {
    updater.appendedRowKeys(selectedRowKeys);
  }

  function onOptionalSelectChange(rowKeys: number[] | string[]) {
    updater.optionalRowKeys(rowKeys);
  }

  function handleChange(value: any, record: any) {
    updateOptionalScanRules({ ...record, metricValue: value });
    if (value === '') {
      // 当输入框的值清空后自动去除CheckBox的勾选
      updater.optionalRowKeys(optionalRowKeys.filter((x: number) => x !== record.id));
    } else if (!optionalRowKeys.includes(record.id)) {
      // 当输入框有值且CheckBox未选中时自动勾选
      updater.optionalRowKeys([...optionalRowKeys, record.id]);
    }
  }

  function reloadAppendedList() {
    getAppendedScanRules({
      scopeId,
      scopeType,
    });
  }

  function handleBatchDelete() {
    Modal.confirm({
      title: i18n.t('dop:Are you sure to delete in batches?'),
      content: i18n.t('dop:batch-delete-tip-content'),
      async onOk() {
        await batchDeleteScanRule({ scopeId, scopeType, ids: appendedRowKeys });
        reloadAppendedList();
        updater.appendedRowKeys([]);
      },
    });
  }

  function checkRule(metrics: any[]) {
    let isIllegal = false;

    for (const { valueType, metricValue: value, decimalScale } of metrics) {
      const rule = (!value && value !== '0') || +value < 0;

      if (valueType === 'WORK_DUR' || valueType === 'MILLISEC' || valueType === 'INT') {
        if (rule || !isInteger(+value)) {
          isIllegal = true;
          break;
        }
      }
      if (valueType === 'RATING') {
        if (!value) {
          isIllegal = true;
          break;
        }
      }
      if (valueType === 'PERCENT') {
        const isLegalLength = get(`${value}`.split('.'), '1.length', 0) <= decimalScale;
        if (rule || value[value.length - 1] === '.' || !isFinite(+value) || !isLegalLength) {
          isIllegal = true;
          break;
        }
      }
      if (valueType === 'FLOAT') {
        if (rule || !isFinite(+value)) {
          isIllegal = true;
          break;
        }
      }
    }
    return isIllegal;
  }

  const handleOk = async () => {
    const metrics = operationOptionalRules.filter((x) => {
      return optionalRowKeys.includes(x.id);
    });
    const isIllegal = checkRule(metrics);
    if (isIllegal) {
      message.error(i18n.t('dop:please enter the correct data'));
      return;
    }

    const formatMetrics = metrics.map((y) => ({
      description: y.description,
      metricKeyId: y.id,
      metricValue: y.metricValue,
    }));
    await batchInsertScanRule({ scopeType, scopeId, metrics: formatMetrics });
    update({
      visible: false,
      optionalRowKeys: [],
    });
    reloadAppendedList();
  };

  return (
    <>
      <div className="mb-3">
        <WithAuth pass={operationAuth}>
          <Button
            type="primary"
            onClick={async () => {
              update({
                visible: !visible,
                loading: true,
              });
              await getOptionalScanRules({
                scopeId,
                scopeType,
              });
              updater.loading(false);
            }}
          >
            {i18n.t('dop:Add Access Control Rule')}
          </Button>
        </WithAuth>
        {appendedRowKeys.length > 0 && (
          <WithAuth pass={operationAuth}>
            <Button ghost type="primary" className="ml-2" onClick={handleBatchDelete}>
              {i18n.t('batch deletion')}
            </Button>
          </WithAuth>
        )}
      </div>
      <ErdaTable
        tableKey={tableKey}
        loading={tableLoading}
        columns={appendedColumns}
        dataSource={appendedScanRules}
        rowKey="id"
        rowSelection={appendedRowSelection}
        actions={actions}
        onChange={() => reloadAppendedList()}
      />
      <Modal
        width={800}
        visible={visible}
        destroyOnClose
        title={firstCharToUpper(i18n.t('dop:Add Access Control Rule').toLowerCase())}
        closable={false}
        afterClose={() => updater.visible(false)}
        okButtonProps={{ disabled: optionalRowKeys.length === 0 }}
        onCancel={() => {
          update({
            visible: false,
            optionalRowKeys: [],
          });
        }}
        onOk={handleOk}
      >
        <ErdaTable
          pagination={{
            pageSize: 10,
          }}
          loading={loading}
          columns={optionalColumns}
          dataSource={operationOptionalRules}
          rowKey="id"
          rowSelection={optionalRowSelection}
          scroll={{ x: 800 }}
        />
      </Modal>
    </>
  );
}