lodash#isEmpty TypeScript Examples

The following examples show how to use lodash#isEmpty. 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: utils.ts    From redux-with-domain with MIT License 7 votes vote down vote up
// get state by path
// parent module's data aside in .base
export function getStateByNamespace(state, namespace, initialState) {
  const path = toStorePath(namespace)
  const initialStateKeys = keys(initialState)
  const findState = get(state, path)
  if (findState === undefined) {
    throw Error(`Please check if you forget to add module ${path} `)
  }

  if (isEmpty(initialState)) {
    if (findState['@@loading']) {
      return findState
    }
    return get(state, `${path}.base`) // not in base
  }
  let isModuleState = true
  initialStateKeys.forEach(key => {
    if (!has(findState, key)) {
      isModuleState = false
    }
  })
  if (isModuleState) return findState
  return get(state, `${path}.base`)
}
Example #2
Source File: test-utils.ts    From ui5-language-assistant with Apache License 2.0 7 votes vote down vote up
export function testValidationsScenario(opts: {
  xmlText: string;
  model: UI5SemanticModel;
  validators: Partial<UI5ValidatorsConfig>;
  assertion: (issues: UI5XMLViewIssue[]) => void;
}): void {
  if (
    isEmpty(opts.validators.attribute) &&
    isEmpty(opts.validators.element) &&
    isEmpty(opts.validators.document)
  ) {
    throw new Error(
      "No validators provided, no relevant scenario can be tested in this manner!"
    );
  }

  const rangeMarkersRegExp = new RegExp(
    `[${START_RANGE_MARKER}${END_RANGE_MARKER}]`,
    "gu"
  );
  const xmlTextNoMarkers = opts.xmlText.replace(rangeMarkersRegExp, "");
  const { cst, tokenVector } = parse(xmlTextNoMarkers);
  const ast = buildAst(cst as DocumentCstNode, tokenVector);

  const issues = validateXMLView({
    validators: {
      document: [],
      element: [],
      attribute: [],
      ...opts.validators,
    },
    xmlView: ast,
    model: opts.model,
  });
  opts.assertion(issues);
}
Example #3
Source File: server-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
/**
 * Format the raw data to { [layerId]: availableDates }
 * @param rawLayers Layers data return by the server 'GetCapabilities' request
 * @param layerIdPath path to layer's id
 * @param datesPath path to layer's available dates
 * @returns an object shape like { [layerId]: availableDates }
 */
function formatCapabilitiesInfo(
  rawLayers: any,
  layerIdPath: string,
  datesPath: string,
): AvailableDates {
  return rawLayers.reduce((acc: any, layer: any) => {
    const layerId = get(layer, layerIdPath);
    const rawDates = get(layer, datesPath, []);

    const dates: (string | { _text: string })[] = isString(rawDates)
      ? rawDates.split(',')
      : rawDates;

    const availableDates = dates
      .filter((date) => !isEmpty(date))
      .map((date) =>
        // adding 12 hours to avoid  errors due to daylight saving
        moment.utc(get(date, '_text', date)).set({ hour: 12 }).valueOf(),
      );

    const { [layerId]: oldLayerDates } = acc;
    return {
      ...acc,
      [layerId]: union(availableDates, oldLayerDates),
    };
  }, {});
}
Example #4
Source File: query.utils.ts    From nestjs-rest-microservices with MIT License 7 votes vote down vote up
async getPage(page: any): Promise<number> {
    let result = 1

    if (isEmpty(page)) return result

    if (!isNil(page)) result = parseInt(page, 10)
    if (result < 1) result = 1

    return result
  }
Example #5
Source File: search-map-getter.ts    From one-platform with MIT License 6 votes vote down vote up
/**
 * Get a nested value from an object/array using a string selector
 * @param data the input data object
 * @param prop the property selector
 * @param options additional options for response
 * @returns the object matching the selector, or null if nothing found
 */
export default function getValueBySelector(data: any, prop: string, opts: IOptions = { stringify: false }): any | null {
  const { stringify, fallback } = opts;
  const propsArray = prop
    .replace(/\[(\w+)\]/g, '.$1')
    .replace(/^\./, '')
    .split('.');

  let cursor = cloneDeep(data);
  try {
    const res = propsArray.reduce((value, propName) => {
      if (propName in cursor) {
        cursor = cursor[propName];
        return cursor;
      }
      logger.info('throwing...');
      throw new Error(`${propName} is not a property of ${typeof cursor}`);
    }, null);

    if (!isEmpty(res) && !isString(res) && stringify) {
      return JSON.stringify(res);
    }
    return res;
  } catch (err) {
    logger.debug(err);
    if (fallback) {
      return fallback;
    }
    throw err;
  }
}
Example #6
Source File: paginate-array-result.ts    From barista with Apache License 2.0 6 votes vote down vote up
export async function PaginateRawQuery<T>(
  manager: EntityManager,
  rawSql: string,
  queryParameters: any[] = [],
  page: number,
  pageSize: number,
  dataTransformer: any = entity => ({}),
): Promise<GetManyDefaultResponse<T>> {
  const totalResult = await manager.query(`SELECT COUNT(*) FROM (${rawSql}) as Count`, queryParameters);
  const total = !isEmpty(totalResult) ? +totalResult[0].count : undefined;
  page = Math.max(0, page - 1);
  const paramsLength = queryParameters.length;
  const data = await manager.query(`${rawSql} OFFSET $${paramsLength + 1} LIMIT $${paramsLength + 2}`, [
    ...queryParameters,
    page * pageSize,
    pageSize,
  ]);

  return {
    count: data.length,
    data: data.map(_ => dataTransformer(_)),
    page: page + 1,
    total,
    pageCount: pageSize && total ? Math.ceil(total / pageSize) : undefined,
  };
}
Example #7
Source File: utils.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export function getParentFqn(fqn: string, name: string): string | undefined {
  if (!isEmpty(fqn) && fqn.endsWith("." + name)) {
    return fqn.substring(0, fqn.length - (name.length + 1));
  }
  return undefined;
}
Example #8
Source File: api.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
fetchDetailsData = async (
  id: Id,
  queryParams: ToBeFixed,
  toggleNotification: Function
) => {
  try {
    const stringifiedProps = !isEmpty(queryParams)
      ? `?${stringify(queryParams, { encode: false })}`
      : "";
    const { data } = await axiosInstance.get(
      getApiURL(`moderate/single/${id}${stringifiedProps}`)
    );

    return data;
  } catch (err: ToBeFixed) {
    handleAPIError(err, toggleNotification);
  }
}
Example #9
Source File: OptionalDescriptionField.tsx    From amplication with Apache License 2.0 6 votes vote down vote up
OptionalDescriptionField = (props: Props) => {
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [, meta] = useField(props.name);

  const { value } = meta;

  const showField = !isEmpty(value) || isOpen;

  const handleClick = useCallback(() => {
    setIsOpen(true);
  }, [setIsOpen]);

  return showField ? (
    <TextField
      name={props.name}
      label={props.label}
      disabled={props.disabled}
      autoComplete="off"
      textarea
      rows={3}
    />
  ) : (
    <Button onClick={handleClick} buttonStyle={EnumButtonStyle.Clear}>
      <Icon icon="plus" />
      Add description
    </Button>
  );
}
Example #10
Source File: col-cell.ts    From S2 with MIT License 6 votes vote down vote up
protected hasHiddenColumnCell() {
    const {
      interaction: { hiddenColumnFields = [] },
      tooltip: { operation },
    } = this.spreadsheet.options;

    const hiddenColumnsDetail = this.spreadsheet.store.get(
      'hiddenColumnsDetail',
      [],
    );

    if (
      isEmpty(hiddenColumnsDetail) ||
      isEmpty(hiddenColumnFields) ||
      !operation.hiddenColumns
    ) {
      return false;
    }
    return !!hiddenColumnsDetail.find((column) =>
      isEqualDisplaySiblingNodeId(column?.displaySiblingNode, this.meta.id),
    );
  }
Example #11
Source File: Last30DaysViews.tsx    From hub with Apache License 2.0 6 votes vote down vote up
prepareSeries = (stats: PackageViewsStats, version?: string): Series[] => {
  if (isEmpty(stats)) return [];

  let data: number[][] = [];
  if (isUndefined(version)) {
    data = sumViewsPerVersions(stats);
  } else {
    data = getSeriesDataPerPkgVersionViews(stats, version);
  }

  return data.length > 0 ? [{ data: data }] : [];
}
Example #12
Source File: organizations.controller.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
@Get()
  @Header('Content-Type', 'application/json')
  async findOrganizations(@Query() query: RequestQuery): Promise<QueryResponse> {
    this.logger.info('OrganizationController#findOrganizations.call', query)

    const args = {
      ...(await this.queryUtils.getQueryParams(query))
    }

    const { count } = await this.organizationsService
      .count({
        where: !isEmpty(query.q) ? JSON.stringify({ name: { $like: query.q } }) : undefined
      })
      .toPromise()

    const data: OrganizationsQueryResult = await this.organizationsService
      .findAll({
        attributes: args.attributes,
        where: !isEmpty(query.q) ? JSON.stringify({ name: { $like: query.q } }) : undefined,
        order: JSON.stringify(args.order),
        offset: args.offset,
        limit: args.limit
      })
      .toPromise()

    const result: QueryResponse = {
      totalRecords: count,
      totalPages: Math.ceil(count / args.limit),
      page: args.page,
      limit: args.limit,
      ...data
    }

    this.logger.info('OrganizationController#findOrganizations.result', result)

    return result
  }
Example #13
Source File: handleComponetStateApi.ts    From brick-design with MIT License 6 votes vote down vote up
export function setComponentState(
  state: StateType,
  payload: PlainObjectType,
): StateType {
  const { selectedInfo, pageConfig, undo, redo } = state;
  if (!selectedInfo) {
    warn('Please select the components');
    return state;
  }
  const { selectedKey } = selectedInfo;
  undo.push({ pageConfig });
  redo.length = 0;
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldConfigs) => {
      const config = oldConfigs[selectedKey];
      if (isEmpty(payload) && config.state) {
        delete config.state;
      } else {
        config.state = payload;
      }
    }),
    undo,
    redo,
  };
}
Example #14
Source File: assetInfoDbService.ts    From nautilus-wallet with MIT License 6 votes vote down vote up
public async addIfNotExists(assets: IAssetInfo[]) {
    if (isEmpty(assets)) {
      return;
    }

    assets = uniqBy(assets, (a) => a.id);
    const paramIds = assets.map((a) => a.id);
    const dbIds = await dbContext.assetInfo.where("id").anyOf(paramIds).primaryKeys();
    const uncommited = difference(paramIds, dbIds);

    if (!isEmpty(uncommited)) {
      await dbContext.assetInfo.bulkAdd(assets.filter((a) => uncommited.includes(a.id)));
    }
  }
Example #15
Source File: AuthHelper.ts    From node-experience with MIT License 5 votes vote down vote up
static validatePermissions(permissions: string[]): void
    {
        if (!isEmpty(permissions) && isEmpty(intersection(permissions, Permissions.permissions())))
        {
            throw new WrongPermissionsException();
        }
    }
Example #16
Source File: useBaseForm.ts    From generator-earth with MIT License 5 votes vote down vote up
export function useBaseForm({
    formData,
    resetTable,
    updateTable,
    autoSubmit = true,
    adaptFormData = values => values,
}: IProps = {}): [
        // antd-form 实例
        FormInstance,
        // 提交表单
        (values: IAnyObject) => void,
        // 重置表单
        () => void,
        // 导出表单数据
        (api: string) => void
    ] {

    const [form] = Form.useForm()

    // 初始化调用,进入页面请求列表
    useEffect(() => {
        initFetch()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    function initFetch(): void {
        if (!formData) {
            return;
        }
        if (!isEmpty(formData)) {
            form.setFieldsValue(formData)
            // 这时使用redux缓存数据更新,可以直接请求上传查看页面
            autoSubmit && updateTable && updateTable(formData)
            return;
        }
        // 首次进入页面,自动触发submit
        autoSubmit && form.submit()
    }

    // 手动触发提交表单
    function onFinish(values: IAnyObject): void {
        // 重置table
        resetTable && resetTable()
        // _formData里的一些值需要适配
        const _formData: IAnyObject = adaptFormData(values)
        // action
        updateTable && updateTable(_formData)
    }

    // 重置表单
    function onReset(): void {
        form.resetFields()
    }

    // 导出表单
    async function onExport(exportApi: string) {
        console.log(form.getFieldsValue())
        if (!exportApi) return
        try {
            await download(exportApi, { ...formData, ...form.getFieldsValue() })
        } catch (e) {
            showError(e)
        }
    }

    return [form, onFinish, onReset, onExport]
}
Example #17
Source File: Validation.tsx    From symphony-ui-toolkit with Apache License 2.0 5 votes vote down vote up
public async updateState(value: string): Promise<string[]> {
    let errorsMap = {};
    let valid = true;
    let errors = [];
    let validationResults;
    if (this.props.validator) {
      if (this.props.validator instanceof Array) {
        validationResults = await Promise.all(
          this.props.validator.map((validator) => validator(value))
        );
        errorsMap = validationResults.reduce(
          (prev, curr) => ({ ...prev, ...curr }),
          {}
        );
      } else {
        errorsMap = await this.props.validator(value);
      }
    }

    valid = (!errorsMap || isEmpty(errorsMap)) && !this.state.errorsChildMap;
    if (this.props.onValidationChanged && valid !== this.state.isValid) {
      this.props.onValidationChanged(valid, errorsMap);
    }

    // compute props errors
    if (!valid && this.props.errorMessage) {
      Object.entries(errorsMap).forEach(([errorId, errorVal]) => {
        if (errorVal) {
          if (this.props.errorMessage instanceof Object) {
            errors.push(this.props.errorMessage[errorId]);
          } else {
            errors.push(this.props.errorMessage);
          }
        }
      });
    }

    // compute child errors
    if (!valid && this.state.errorsChildMap) {
      Object.entries(this.state.errorsChildMap).forEach(
        ([errorId, errorVal]) => {
          if (errorVal) {
            if (
              this.props.errorMessage instanceof Object &&
              this.props.errorMessage[errorId]
            ) {
              // get message error from props if exists in errorMessage
              errors.push(this.props.errorMessage[errorId]);
            } else {
              // otherwise display the default one
              errors.push(errorVal);
            }
          }
        }
      );
    }

    if (this.props.errors) {
      errors = this.props.errors;
    }
    // don't change the value here otherwise there are risks we get into an infinite loop
    this.setState({ isValid: valid, errors });
    return errors;
  }
Example #18
Source File: index.tsx    From strapi-plugin-comments with MIT License 5 votes vote down vote up
DetailsEntity = ({
  data = {},
  schema = {},
  config = {},
  filters,
  onFiltersChange,
}) => {
  const { entryLabel = {} } = config;
  const { attributes = {} } = schema;
  const keys = Object.keys(attributes);
  const entityLabelKey = first(entryLabel[data?.uid]);

  const FIELDS_LIMIT = 5;
  const itemKeys = take(
    keys.filter(
      (_) =>
        attributes[_].type === "string" &&
        !isNil(data[_]) &&
        _ !== entityLabelKey
    ),
    FIELDS_LIMIT
  );

  const formatLabel = (label = "") =>
    label
      .split("_")
      .map((_) => capitalize(_))
      .join(" ");

  const entityIsRenderable =
    data && !isEmpty(data) && (!isEmpty(itemKeys) || data[entityLabelKey]);

  return (
    <Box padding={4}>
      {entityIsRenderable && (
        <Box marginBottom={4}>
          <Typography
            variant="sigma"
            textColor="neutral600"
            id="entity-details"
          >
            {getMessage("page.details.panel.entity", "Details")}
          </Typography>
          <Box paddingTop={2} paddingBottom={4}>
            <Divider />
          </Box>
          <Stack size={itemKeys.length}>
            <Flex direction="column" alignItems="flex-start">
              <Typography fontWeight="bold">
                {formatLabel(entityLabelKey)}
              </Typography>
              <Typography>{data[entityLabelKey]}</Typography>
            </Flex>
            {itemKeys.map((_) => (
              <Flex
                key={`prop_${_}`}
                direction="column"
                alignItems="flex-start"
              >
                <Typography fontWeight="bold">{formatLabel(_)}</Typography>
                <Typography>{data[_]}</Typography>
              </Flex>
            ))}
          </Stack>
        </Box>
      )}
      <Box>
        <Typography variant="sigma" textColor="neutral600" id="view-filters">
          {getMessage("page.details.filters.label", "View")}
        </Typography>
        <Box paddingTop={2} paddingBottom={4}>
          <Divider />
        </Box>
        <DetailsFilters data={filters} onChange={onFiltersChange} />
      </Box>
    </Box>
  );
}
Example #19
Source File: NewVersionTile.tsx    From amplication with Apache License 2.0 5 votes vote down vote up
function NewVersionTile({ applicationId }: Props) {
  const history = useHistory();

  const { data, loading } = useQuery<TData>(GET_LOOKUP_FIELDS, {
    variables: {
      appId: applicationId,
    },
  });
  const { trackEvent } = useTracking();

  const handleClick = useCallback(
    (event) => {
      trackEvent(EVENT_DATA);
      history.push(`/${applicationId}/fix-related-entities`);
    },
    [history, trackEvent, applicationId]
  );

  const requiredFixesCount = useMemo(() => {
    if (!data) return 0;

    return data.app.entities.reduce((accumulator, entity) => {
      const sum =
        entity.fields?.filter((field) =>
          isEmpty(field.properties.relatedFieldId)
        ).length || 0;
      return accumulator + sum;
    }, 0);
  }, [data]);

  if (requiredFixesCount === 0) return null;

  return (
    <>
      <div className={`${CLASS_NAME}__gap`} />
      <div className={`${CLASS_NAME}__wrapper`}>
        <div className={`${CLASS_NAME}__new-release`}>New Release!</div>
        <Panel
          className={`${CLASS_NAME}`}
          clickable
          onClick={handleClick}
          panelStyle={EnumPanelStyle.Bordered}
        >
          <div className={`${CLASS_NAME}__content`}>
            <div className={`${CLASS_NAME}__content__details`}>
              <h2>Improved Relation Fields</h2>
              Version 0.3.2 includes big improvements in how we manage related
              entities. The changes require your attention.
              {loading ? (
                <CircularProgress />
              ) : (
                <span className={`${CLASS_NAME}__content__details__summary`}>
                  <Icon icon="info_circle" size="medium" />
                  {requiredFixesCount}
                  {requiredFixesCount > 1
                    ? " relation needs "
                    : " relations need "}
                  your attention
                </span>
              )}
            </div>
            <SvgThemeImage image={EnumImages.Relations} />
          </div>
        </Panel>
      </div>
    </>
  );
}