lodash#get TypeScript Examples

The following examples show how to use lodash#get. 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: analysis-utils.ts    From prism-frontend with MIT License 7 votes vote down vote up
export function getAlertMessage(
  aggregateData: AsyncReturnType<typeof fetchApiData>,
  alert: Alert,
): string | undefined {
  const { wcsConfig } = alert.alertConfig;
  const { scale, offset } = wcsConfig || {};
  const { min: alertMin, max: alertMax } = alert;

  let alertMessage;

  aggregateData.forEach((data) => {
    const minValue = scaleValueIfDefined(
      get(data, 'stats_min') as number,
      scale,
      offset,
    ) as number;
    const maxValue = scaleValueIfDefined(
      get(data, 'stats_max') as number,
      scale,
      offset,
    );

    if (!isNil(alertMin) && minValue < alertMin!) {
      // eslint-disable-next-line fp/no-mutation
      alertMessage = `Minimum value ${minValue} is below the threshold ${alertMin}.`;
    }

    if (!isNil(alertMax) && maxValue > alertMax!) {
      // eslint-disable-next-line fp/no-mutation
      alertMessage = `Maximum value ${maxValue} is above the threshold ${alertMax}.`;
    }
  });
  return alertMessage;
}
Example #3
Source File: fix-api-json.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
// Exported for test purpose
export function addViewDefaultAggregation(
  libraryName: string,
  content: unknown
): void {
  const symbol = find(
    get(content, "symbols"),
    (symbol) => symbol.name === "sap.ui.core.mvc.View"
  );
  if (symbol !== undefined) {
    const metadata = get(symbol, "ui5-metadata");
    if (metadata !== undefined) {
      metadata.defaultAggregation = "content";
    }
  }
}
Example #4
Source File: functions.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
buildNestedStructure = (
  entities: Array<Comment>,
  id: Id | null = null,
  field: string = "threadOf",
  dropBlockedThreads = false,
  blockNestedThreads = false
): Array<Comment> =>
  entities
    .filter((entity: Comment) => {
      // mongo by default not return `null` for empty data
      const entityField: any = get(entity, field);
      if (entityField === null && id === null) {
        return true;
      }
      let data = entityField;
      if (data && typeof id === "string") {
        data = data.toString();
      }
      return (
        (data && data === id) ||
        (isObject(entityField) && (entityField as any).id === id)
      );
    })
    .map((entity: Comment) => ({
      ...entity,
      [field]: undefined,
      related: undefined,
      blockedThread: blockNestedThreads || entity.blockedThread,
      children:
        entity.blockedThread && dropBlockedThreads
          ? []
          : buildNestedStructure(
              entities,
              entity.id,
              field,
              dropBlockedThreads,
              entity.blockedThread
            ),
    }))
Example #5
Source File: index.tsx    From prism-frontend with MIT License 6 votes vote down vote up
function App() {
  const isAuthenticated = useIsAuthenticated();

  const authRequired: boolean = get(appConfig, 'WFPAuthRequired', false);

  return (
    <ThemeProvider theme={muiTheme}>
      {/* Used to show notifications from redux as a snackbar. Notifications are stored in notificationState */}
      <Notifier />
      <Router>
        {isAuthenticated || !authRequired ? <Wrapper /> : <Login />}
      </Router>
    </ThemeProvider>
  );
}
Example #6
Source File: isAuthenticated.ts    From openapi-mock-express-middleware with MIT License 6 votes vote down vote up
isAuthorized = (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
): void | express.Response => {
  if (!res.locals.operation || !(res.locals.operation instanceof Operation)) {
    return next();
  }

  const securityRequirements: OpenAPIV3.SecurityRequirementObject[] =
    res.locals.operation.getSecurityRequirements();
  const { securitySchemes } = res.locals.operation;

  if (
    securityRequirements.some(
      (schemes) =>
        schemes &&
        securitySchemes &&
        Object.keys(schemes).some((scheme) => {
          const securityScheme = get(securitySchemes, scheme);
          return !!securityScheme && checkAuthByType(securityScheme, req);
        })
    )
  ) {
    return res.status(401).json({ message: 'Unauthorized request' });
  }

  return next();
}
Example #7
Source File: pivot-facet-spec.ts    From S2 with MIT License 6 votes vote down vote up
jest.mock('src/sheet-type', () => {
  const container = new Canvas({
    width: 100,
    height: 100,
    container: document.body,
  });
  const panelScrollGroup = new Group({}) as GridGroup;
  panelScrollGroup.updateGrid = () => {};
  container.add(panelScrollGroup);
  return {
    SpreadSheet: jest.fn().mockImplementation(() => {
      return {
        dataCfg: assembleDataCfg(),
        options: assembleOptions(),
        container,
        theme: getTheme({}),
        store: new Store(),
        panelScrollGroup,
        panelGroup: container.addGroup(),
        foregroundGroup: container.addGroup(),
        backgroundGroup: container.addGroup(),
        isFrozenRowHeader: jest.fn(),
        isTableMode: jest.fn().mockReturnValue(false),
        isPivotMode: jest.fn().mockReturnValue(true),
        getTotalsConfig: jest.fn().mockReturnValue({}),
        getLayoutWidthType: jest.fn().mockReturnValue('adaptive'),
        emit: jest.fn(),
        getColumnLeafNodes: jest.fn().mockReturnValue([]),
        isScrollContainsRowHeader: jest.fn(),
        isHierarchyTreeType: jest.fn(),
        facet: {
          getFreezeCornerDiffWidth: jest.fn(),
        },
        getCanvasElement: () => container.get('el'),
      };
    }),
  };
});
Example #8
Source File: events.ts    From XFlow with MIT License 6 votes vote down vote up
removeTools = async (e: any, cmds: IGraphCommandService) => {
  const { edge } = e
  if (!edge) {
    return
  }
  if (edge.hasTools('ondbclick')) {
    cmds.executeCommand(XFlowEdgeCommands.UPDATE_EDGE.id, {
      edgeConfig: {
        ...get(edge, 'data'),
        vertices: edge.getVertices(),
      },
    })
    edge.removeTools()
  }
}
Example #9
Source File: block.ts    From easy-email with MIT License 6 votes vote down vote up
getParentByType = <T extends IBlockData>(
  context: { content: IBlockData },
  idx: string,
  type: BlockType
): T | null => {
  if (!idx) return null;
  let parentIdx = getParentIdx(idx);
  while (parentIdx) {
    const parent = get(context, parentIdx) as T;
    if (parent && parent.type === type) return parent;
    parentIdx = getParentIdx(idx);
  }

  return null;
}
Example #10
Source File: createPropertyRule.ts    From backstage with Apache License 2.0 6 votes vote down vote up
createPropertyRule = (propertyType: 'metadata' | 'spec') =>
  createCatalogPermissionRule({
    name: `HAS_${propertyType.toUpperCase()}`,
    description: `Allow entities which have the specified ${propertyType} subfield.`,
    resourceType: RESOURCE_TYPE_CATALOG_ENTITY,
    apply: (resource: Entity, key: string, value?: string) => {
      const foundValue = get(resource[propertyType], key);
      if (value !== undefined) {
        return value === foundValue;
      }
      return !!foundValue;
    },
    toQuery: (key: string, value?: string) => ({
      key: `${propertyType}.${key}`,
      ...(value !== undefined && { values: [value] }),
    }),
  })
Example #11
Source File: index.ts    From reaction-role with MIT License 6 votes vote down vote up
constructor(token: string, mongodb_uri?: string, logging = true) {
		super({
			partials: ["CHANNEL", "REACTION", "MESSAGE"],
		});
		this._token = token;
		this.mongodb_uri = mongodb_uri;
		this.logging = logging;
		if (mongodb_uri) {
			const adapter = new MongoDBAdapter({
				databaseName: "RR",
				defaultDir: "ReactionRole",
				mongodbURL: mongodb_uri,
			});
			const db = new Database(adapter);
			this.onGet(async () => {
				const data = (await db.get("config")) as IConfig;
				return data;
			})
				.onSet(async (new_data) => {
					await db.set("config", new_data);
				})
				.onDelete(async (message_id) => {
					await db.delete(`config.${message_id}`);
				});
		}
	}
Example #12
Source File: global-secondary-index.ts    From dyngoose with ISC License 6 votes vote down vote up
/**
   * Performs a query and returns the first item matching your filters.
   *
   * The regular DynamoDB.GetItem does not work for indexes, because DynamoDB only enforces a
   * unique cross of the tale's primary HASH and RANGE key. The combination of those two values
   * must always be unique, however, for a GlobalSecondaryIndex, there is no uniqueness checks
   * or requirements. This means that querying for a record by the HASH and RANGE on a
   * GlobalSecondaryIndex it is always possible there are multiple matching records.
   *
   * So use this with caution. It sets the DynamoDB Limit parameter to 1, which means this will
   * not work for additional filtering. If you want to provide additional filtering, use the
   * .query() method and pass your filters, then handle if the query has more than one result.
   *
   * Avoid use whenever you do not have uniqueness for the GlobalSecondaryIndex's HASH + RANGE.
   */
  public async get(filters: QueryFilters<T>, input: GlobalSecondaryIndexGetInput = {}): Promise<T | undefined> {
    if (!has(filters, this.metadata.hash.propertyName)) {
      throw new QueryError('Cannot perform .get() on a GlobalSecondaryIndex without specifying a hash key value')
    } else if (this.metadata.range != null && !has(filters, this.metadata.range.propertyName)) {
      throw new QueryError('Cannot perform .get() on a GlobalSecondaryIndex without specifying a range key value')
    } else if (Object.keys(filters).length > 2) {
      throw new QueryError('Cannot perform a .get() on a GlobalSecondaryIndex with additional filters, use .query() instead')
    }

    (input as GlobalSecondaryIndexQueryInput).limit = 1

    // because you are specifying the hashKey and rangeKey, we can apply a limit to this search
    // DynamoDB will start the search at the first match and limit means it will only process
    // that document and return it, however, you cannot use any additional filters on this .get
    // method; for that, you need to use .query()
    const results = await this.query(filters, input)

    if (results.count > 0) {
      return results[0]
    }
  }
Example #13
Source File: handleComponentSchema.ts    From brick-design with MIT License 6 votes vote down vote up
/**
 * 清除所有子节点
 * @param state
 * @returns {{undo: *, pageConfig, redo: *}}
 */

export function clearChildNodes(state: StateType): StateType {
  const { pageConfig, selectedInfo, undo, redo } = state;
  if (!selectedInfo) {
    warn(
      'Please select the component or property you want to clear the child nodes',
    );
    return state;
  }
  const { selectedKey, propName } = selectedInfo;
  const childNodes = get(pageConfig, getLocation(selectedKey));
  if (!childNodes) return state;
  undo.push({ pageConfig });

  redo.length = 0;
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldState) => {
      deleteChildNodes(oldState, childNodes, propName);
      update(oldState, getLocation(selectedKey), (childNodes) => {
        /**
         * 如果 没有propName说明要清除组件的所有子节点
         */
        if (!propName) {
          return undefined;
        } else {
          return restObject(childNodes, propName);
        }
      });
    }),
    undo,
    redo,
  };
}
Example #14
Source File: SideDrawerField.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
export default function ConnectService({
  column,
  control,
  disabled,
  docRef,
}: ISideDrawerFieldProps) {
  const theme = useTheme();

  const config = column.config ?? {};
  const displayKey = config.titleKey ?? config.primaryKey;

  return (
    <Controller
      control={control}
      name={column.key}
      render={({ onChange, onBlur, value }) => {
        const handleDelete = (hit: any) => () => {
          // if (multiple)
          onChange(
            value.filter(
              (v) => get(v, config.primaryKey) !== get(hit, config.primaryKey)
            )
          );
          // else form.setFieldValue(field.name, []);
        };

        return (
          <>
            {!disabled && (
              <ConnectServiceSelect
                config={(config as any) ?? {}}
                value={value}
                onChange={onChange}
                docRef={docRef}
                TextFieldProps={{
                  label: "",
                  hiddenLabel: true,
                  fullWidth: true,
                  onBlur,
                  // SelectProps: {
                  //   renderValue: () => `${value?.length ?? 0} selected`,
                  // },
                }}
              />
            )}

            {Array.isArray(value) && (
              <Grid
                container
                spacing={1}
                style={{ marginTop: theme.spacing(1) }}
              >
                {value.map((snapshot) => (
                  <Grid item key={get(snapshot, config.primaryKey)}>
                    <Chip
                      component="li"
                      size="medium"
                      label={get(snapshot, displayKey)}
                      onDelete={disabled ? undefined : handleDelete(snapshot)}
                    />
                  </Grid>
                ))}
              </Grid>
            )}
          </>
        );
      }}
    />
  );
}
Example #15
Source File: semantic-model-provider.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
libraryFixes: Record<TestModelVersion, Record<string, LibraryFix[]>> = {
  "1.60.14": {
    "sap.ushell": [
      (content: Json): void => {
        const symbol = find(
          get(content, "symbols"),
          (symbol) => symbol.name === "sap.ushell.services.EndUserFeedback"
        );
        const method = find(
          get(symbol, "methods"),
          (method) => method.name === "getLegalText"
        );
        remove(method.parameters, (parameter) => get(parameter, "name") === "");
      },
    ],
  },
  "1.71.14": {},
  "1.74.0": {
    "sap.ui.generic.app": [
      (content: Json): void => {
        // Removing from this library. There is another symbol with the same name in library "sap.fe".
        remove(
          get(content, "symbols"),
          (symbol) =>
            get(symbol, "name") ===
            "sap.ui.generic.app.navigation.service.NavigationHandler"
        );
      },
    ],
    "sap.ushell": [
      (content: Json): void => {
        const symbols = get(content, "symbols");
        remove(symbols, (symbol) => get(symbol, "basename") === "");
      },
    ],
  },
  "1.75.0": {
    // No consistency tests on this library version yet
  },
}
Example #16
Source File: serializer.ts    From voxelsrv with MIT License 5 votes vote down vote up
function recursiveAddTypes(protocol, protocolData, path) {
	if (protocolData === undefined) return;

	if (protocolData.types) protocol.addTypes(protocolData.types);

	recursiveAddTypes(protocol, get(protocolData, path.shift()), path);
}
Example #17
Source File: index.tsx    From prism-frontend with MIT License 5 votes vote down vote up
function AdminLevelDataLayers({ layer }: { layer: AdminLevelDataLayerProps }) {
  const dispatch = useDispatch();
  const map = useSelector(mapSelector);
  const boundaryId = layer.boundary || getBoundaryLayerSingleton().id;

  const layerData = useSelector(layerDataSelector(layer.id)) as
    | LayerData<AdminLevelDataLayerProps>
    | undefined;
  const { data } = layerData || {};
  const { features } = data || {};
  const { t } = useSafeTranslation();

  useEffect(() => {
    // before loading layer check if it has unique boundary?
    const boundaryLayers = getBoundaryLayers();
    const boundaryLayer = LayerDefinitions[
      boundaryId as LayerKey
    ] as BoundaryLayerProps;

    if ('boundary' in layer) {
      if (Object.keys(LayerDefinitions).includes(boundaryId)) {
        boundaryLayers.map(l => dispatch(removeLayer(l)));
        dispatch(addLayer({ ...boundaryLayer, isPrimary: true }));

        // load unique boundary only once
        // to avoid double loading which proven to be performance issue
        if (!isLayerOnView(map, boundaryId)) {
          dispatch(loadLayerData({ layer: boundaryLayer }));
        }
      } else {
        dispatch(
          addNotification({
            message: `Invalid unique boundary: ${boundaryId} for ${layer.id}`,
            type: 'error',
          }),
        );
      }
    }
    if (!features) {
      dispatch(loadLayerData({ layer }));
    }
  }, [dispatch, features, layer, boundaryId, map]);

  if (!features) {
    return null;
  }

  if (!isLayerOnView(map, boundaryId)) {
    return null;
  }

  return (
    <GeoJSONLayer
      before={`layer-${boundaryId}-line`}
      id={`layer-${layer.id}`}
      data={features}
      fillPaint={fillPaintData(layer)}
      fillOnClick={async (evt: any) => {
        // by default add `data_field` to the tooltip
        dispatch(
          addPopupData({
            [layer.title]: {
              data: getRoundedData(get(evt.features[0], 'properties.data'), t),
              coordinates: evt.lngLat,
            },
          }),
        );
        // then add feature_info_props as extra fields to the tooltip
        dispatch(
          addPopupData(
            getFeatureInfoPropsData(layer.featureInfoProps || {}, evt),
          ),
        );
      }}
    />
  );
}