lodash#snakeCase TypeScript Examples

The following examples show how to use lodash#snakeCase. 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: server-utils.ts    From prism-frontend with MIT License 6 votes vote down vote up
/**
 * Executes a getFeatureInfo request
 *
 * @return object of key: string - value: string with formatted values given label type.
 */
async function runFeatureInfoRequest(
  url: string,
  wmsParams: RequestFeatureInfo,
  layers: WMSLayerProps[],
): Promise<{ [name: string]: string }> {
  // Transform to snake case.
  const wmsParamsInSnakeCase = Object.entries(wmsParams).reduce(
    (obj, item) => ({
      ...obj,
      [snakeCase(item[0])]: item[1],
    }),
    {},
  );

  const res = await fetch(formatUrl(`${url}/ows`, wmsParamsInSnakeCase));
  const resJson: GeoJSON.FeatureCollection = await res.json();

  const parsedProps = resJson.features.map(feature => {
    // Get fields from layer configuration.
    const [layerId] = (feature?.id as string).split('.');

    const featureInfoProps =
      layers?.find(l => l.serverLayerName === layerId)?.featureInfoProps || {};

    const searchProps = Object.keys(featureInfoProps);

    const properties = feature.properties ?? {};

    return Object.keys(properties)
      .filter(k => searchProps.includes(k))
      .reduce(
        (obj, key) => ({
          ...obj,
          [featureInfoProps[key].label]: formatFeatureInfo(
            properties[key],
            featureInfoProps[key].type,
          ),
        }),
        {},
      );
  });

  return parsedProps.reduce((obj, item) => ({ ...obj, ...item }), {});
}
Example #2
Source File: parseReactBlockToBlockData.tsx    From easy-email with MIT License 6 votes vote down vote up
describe('Test parseXml', () => {
  const componentNames = Object.keys(componentsMap).filter(item => item !== 'MjmlBlock');
  it.each(componentNames)('$name is valid block', (componentName) => {


    const Com = componentsMap[componentName];
    const type = snakeCase(kebabCase(componentName)).toUpperCase();
    const block = BlockManager.getBlockByType(BasicType[type]);


    expect(parseReactBlockToBlockData(<Com />)).toEqual(block?.create());
  });
});
Example #3
Source File: query-builder.ts    From typeorm-query-builder-wrapper with MIT License 6 votes vote down vote up
/**
   * Transform key to snake_case and optionally with alias.
   *
   * @param {string} key Field key from query params.
   * @param {string} alias Alias, ex. t1, optional.
   * @return {*}  {string}
   */
  private transformKey(key: string, alias?: string): string {
    let tKey = snakeCase(key);
    if (alias || this.qb.alias) {
      tKey = `${alias ? alias : this.qb.alias}.${tKey}`;
    }

    return tKey;
  }
Example #4
Source File: utils.ts    From qiankun with MIT License 6 votes vote down vote up
export function getWrapperId(id: string) {
  return `__qiankun_microapp_wrapper_for_${snakeCase(id)}__`;
}
Example #5
Source File: proof.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
getInformation() {
    let factEntries: [string, string | number | boolean | undefined][] = [];
    Object.values(this.truth.providers).forEach(facts => {
      const transformedFacts = Object.entries(facts).map(([key, value]) => {
        const factCategory = key.includes('GEOLOCATION')
          ? FactCategory.GEOLOCATION
          : FactCategory.DEVICE;
        return [`${snakeCase(factCategory)}.${snakeCase(key)}`, value] as [
          string,
          string | number | boolean | undefined
        ];
      });
      factEntries = factEntries.concat(transformedFacts);
    });
    return Object.fromEntries(factEntries) as Facts;
  }
Example #6
Source File: enquire.ts    From Adachi-BOT with MIT License 5 votes vote down vote up
private static toUpperSnakeCase( str: string ): string {
		return "#{" + snakeCase( str ).toUpperCase() + "}";
	}
Example #7
Source File: index.ts    From jitsu with MIT License 5 votes vote down vote up
allSourcesMap: { [sourceId: string]: SourceConnector } = allSources.reduce(
  (accumulator: { [key: string]: SourceConnector }, current: SourceConnector) => ({
    ...accumulator,
    [snakeCase(current.id)]: current,
  }),
  {}
)
Example #8
Source File: DataTableView.tsx    From querybook with Apache License 2.0 5 votes vote down vote up
@bind
    public getInitialTabKey() {
        const queryParam = getQueryString();
        return queryParam['tab'] || snakeCase(tabDefinitions[0].key);
    }
Example #9
Source File: index.tsx    From prism-frontend with MIT License 4 votes vote down vote up
DataTable = ({ classes, maxResults }: DataTableProps) => {
  const tableLoading = useSelector(isLoading);
  const analysisLoading = useSelector(isExposureAnalysisLoadingSelector);
  const loading = tableLoading || analysisLoading;
  const tableDefinition = useSelector(getTableDefinition);
  const analysisDefinition = useSelector(getAnalysisDefinition);
  const definition = tableDefinition || analysisDefinition;
  const tableData = useSelector(getTableData);
  const analysisData = useSelector(getAnalysisData);
  const data = tableData.rows.length !== 0 ? tableData : analysisData;
  const { t } = useSafeTranslation();

  if (!definition) {
    return null;
  }

  const { table, title, id, legendText, chart } = definition;
  const csvData = exportDataTableToCSV(analysisData);
  const handleDownload = (payload: string, e: React.ChangeEvent<{}>) => {
    e.preventDefault();
    downloadToFile(
      {
        content: payload,
        isUrl: false,
      },
      `${snakeCase(id)}_${snakeCase(legendText)}`,
      'text/csv',
    );
  };

  const downloadAsCSVTranslated = t('Download as CSV');

  return (
    <div>
      <h2>{title}</h2>
      <p>{legendText}</p>

      {table && (
        <p>
          <Button>
            <a href={process.env.PUBLIC_URL + table}>
              {downloadAsCSVTranslated}
            </a>
          </Button>
        </p>
      )}

      {csvData && (
        <p>
          <Button onClick={e => handleDownload(csvData, e)}>
            {downloadAsCSVTranslated}
          </Button>
        </p>
      )}

      {!loading && chart && <Chart title={title} config={chart} data={data} />}

      {loading ? (
        <Box
          display="flex"
          justifyContent="center"
          alignItems="center"
          height={300}
        >
          <CircularProgress size={40} color="secondary" />
        </Box>
      ) : (
        <Paper className={classes.root}>
          <TableContainer className={classes.container}>
            <Table stickyHeader aria-label={`table showing ${title}`}>
              <TableHead>
                <DataTableRow
                  className={classes.headCells}
                  columns={data.columns}
                  rowData={data.rows[0]}
                />
              </TableHead>
              <TableBody>
                {data.rows.slice(1, maxResults).map((rowData, idx) => (
                  <DataTableRow
                    // eslint-disable-next-line react/no-array-index-key
                    key={idx}
                    className={classes.tableCells}
                    columns={data.columns}
                    rowData={rowData}
                  />
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      )}
    </div>
  );
}
Example #10
Source File: SourceEditor.tsx    From jitsu with MIT License 4 votes vote down vote up
SourceEditor: React.FC<CommonSourcePageProps> = ({ editorMode }) => {
  const history = useHistory()
  const allSourcesList = sourcesStore.list
  const { source, sourceId } = useParams<{ source?: string; sourceId?: string }>()

  const sourceDataFromCatalog = useMemo<CatalogSourceConnector>(() => {
    let sourceType = source
      ? source
      : sourceId
      ? sourcesStore.list.find(src => src.sourceId === sourceId)?.sourceProtoType
      : undefined

    return sourceType
      ? sourcesCatalog.find((source: CatalogSourceConnector) => snakeCase(source.id) === snakeCase(sourceType))
      : undefined
  }, [sourceId, allSourcesList])

  const [initialSourceData, setInitialSourceData] = useState<SourceEditorInitialSourceData>(
    () =>
      sourceEditorUtils.reformatCatalogIntoSelectedStreams(allSourcesList.find(src => src.sourceId === sourceId)) ??
      createInitialSourceData(sourceDataFromCatalog)
  )

  const [state, setState] = useState<SourceEditorState>(initialState)

  const [controlsDisabled, setControlsDisabled] = useState<boolean | string>(false)
  const [tabsDisabled, setTabsDisabled] = useState<SourceEditorDisabledTabs>(null)
  const [showDocumentation, setShowDocumentation] = useState<boolean>(false)

  const handleSetControlsDisabled = useCallback((disabled: boolean | string, disableRequestId: string): void => {
    const tooltipMessage: string | undefined = typeof disabled === "string" ? disabled : undefined
    if (disabled) {
      setControlsDisabled(disabled)
      disableControlsRequestsRegistry.set(disableRequestId, { tooltipMessage })
    } else {
      disableControlsRequestsRegistry.delete(disableRequestId)
      // enable back only if controls are not disabled by any other callers
      if (disableControlsRequestsRegistry.size === 0) {
        setControlsDisabled(disabled)
      } else {
        // set the tooltip message by a last `disable` caller
        let disabled: boolean | string = true
        disableControlsRequestsRegistry.forEach(({ tooltipMessage }) => {
          if (tooltipMessage) disabled = tooltipMessage
        })
        setControlsDisabled(disabled)
      }
    }
  }, [])

  const handleSetTabsDisabled = useCallback<SetSourceEditorDisabledTabs>((tabKeys, action) => {
    setTabsDisabled(state => {
      const newState = new Set(state)
      tabKeys.forEach(key => (action === "disable" ? newState.add(key) : newState.delete(key)))
      return newState
    })
  }, [])

  const handleBringSourceData = () => {
    let sourceEditorState = state
    setState(state => {
      sourceEditorState = state
      return state
    })
    return sourceEditorUtils.getSourceDataFromState(sourceEditorState, sourceDataFromCatalog, initialSourceData)
  }

  const validateCountErrors = async (): Promise<number> => {
    const configurationErrorsCount = await state.configuration.validateGetErrorsCount()
    const streamsErrorsCount = await state.streams.validateGetErrorsCount()

    setState(state => {
      const newState = cloneDeep(state)
      newState.configuration.errorsCount = configurationErrorsCount
      newState.streams.errorsCount = streamsErrorsCount
      return newState
    })

    return configurationErrorsCount + streamsErrorsCount
  }

  const validateAllForms = async () => {
    const someFieldsErrored = !!(await validateCountErrors())
    if (someFieldsErrored) throw new Error("some values are invalid")
  }

  const getTestConnectionResponse = async (): Promise<TestConnectionResponse> => {
    const sourceData = handleBringSourceData()
    const testResult = await sourcePageUtils.testConnection(sourceData, true)
    return testResult
  }

  const assertCanConnect = async (config?: {
    testConnectionResponse?: TestConnectionResponse
    ignoreErrors?: string[]
  }): Promise<void> => {
    const response = config?.testConnectionResponse ?? (await getTestConnectionResponse())
    if (!response.connected && !config?.ignoreErrors?.includes(response.connectedErrorType))
      throw new ErrorDetailed({
        message: response.connectedErrorMessage,
        name: response.connectedErrorType,
        payload: response.connectedErrorPayload,
      })
  }

  const handleValidateAndTestConnection: HandleValidateTestConnection = async (methodConfig): Promise<void> => {
    await validateAllForms()
    const controlsDisableRequestId = uniqueId("validateAndTest-")
    handleSetControlsDisabled("Validating source configuration", controlsDisableRequestId)
    try {
      await assertCanConnect({ ignoreErrors: methodConfig?.ignoreErrors })
    } finally {
      handleSetControlsDisabled(false, controlsDisableRequestId)
    }
  }

  const handleSave = useCallback<HandleSaveSource>(
    async methodConfig => {
      let sourceEditorState = null
      setState(state => {
        sourceEditorState = state // hack for getting the most recent state in the async function
        return { ...state, stateChanged: false }
      })

      if (editorMode === "edit") await validateAllForms()

      const sourceData = handleBringSourceData()
      const testConnectionResults = await sourcePageUtils.testConnection(sourceData, true)

      await assertCanConnect({
        testConnectionResponse: testConnectionResults,
        ignoreErrors: methodConfig?.ignoreErrors,
      })

      let sourceDataToSave: SourceData = {
        ...sourceData,
        ...testConnectionResults,
      }

      let savedSourceData: SourceData = sourceDataToSave
      if (editorMode === "add") {
        savedSourceData = await flowResult(sourcesStore.add(sourceDataToSave))
      }
      if (editorMode === "edit") {
        await flowResult(sourcesStore.replace(sourceDataToSave))
      }
      await connectionsHelper.updateDestinationsConnectionsToSource(
        savedSourceData.sourceId,
        savedSourceData.destinations
      )

      handleLeaveEditor({ goToSourcesList: true })

      if (savedSourceData.connected) {
        actionNotification.success(editorMode === "add" ? "New source has been added!" : "Source has been saved")
      } else {
        actionNotification.warn(
          `Source has been saved, but test has failed with '${firstToLower(
            savedSourceData.connectedErrorMessage
          )}'. Data from this source will not be available`
        )
      }
    },
    [editorMode, state]
  )

  const handleLeaveEditor = useCallback<(options?: { goToSourcesList?: boolean }) => void>(options => {
    options.goToSourcesList ? history.push(projectRoute(sourcesPageRoutes.root)) : history.goBack()
  }, [])

  const handleValidateStreams = async (): Promise<void> => {
    const streamsErrorsCount = await state.streams.validateGetErrorsCount()
    if (streamsErrorsCount) throw new Error("some streams settings are invalid")
  }

  return (
    <SourceEditorView
      state={state}
      controlsDisabled={controlsDisabled}
      tabsDisabled={tabsDisabled}
      editorMode={editorMode}
      showDocumentationDrawer={showDocumentation}
      initialSourceData={initialSourceData}
      sourceDataFromCatalog={sourceDataFromCatalog}
      setSourceEditorState={setState}
      handleSetControlsDisabled={handleSetControlsDisabled}
      handleSetTabsDisabled={handleSetTabsDisabled}
      setShowDocumentationDrawer={setShowDocumentation}
      handleBringSourceData={handleBringSourceData}
      handleSave={handleSave}
      setInitialSourceData={setInitialSourceData}
      handleLeaveEditor={handleLeaveEditor}
      handleValidateAndTestConnection={handleValidateAndTestConnection}
      handleValidateStreams={handleValidateStreams}
      handleReloadStreams={state.streams.forceReloadStreamsList}
    />
  )
}