qs#stringify TypeScript Examples

The following examples show how to use qs#stringify. 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: BetterTradeLink.tsx    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
export default function BetterTradeLink({ version }: { version: Version }) {
  const location = useLocation()
  const search = useParsedQueryString()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: version !== DEFAULT_VERSION ? version : undefined
      })}`
    }
  }, [location, search, version])

  return (
    <VersionLinkContainer>
      There is a better price for this trade on{' '}
      <StyledInternalLink to={linkDestination}>
        <b>Uniswap {version.toUpperCase()} ↗</b>
      </StyledInternalLink>
    </VersionLinkContainer>
  )
}
Example #2
Source File: BetterTradeLink.tsx    From luaswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export function DefaultVersionLink() {
  const location = useLocation()
  const search = useParsedQueryString()
  const version = useToggledVersion()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: DEFAULT_VERSION
      })}`
    }
  }, [location, search])

  return (
    <VersionLinkContainer>
      Showing {version.toUpperCase()} price.{' '}
      <StyledInternalLink to={linkDestination}>
        <b>Switch to LuaSwap {DEFAULT_VERSION.toUpperCase()} ↗</b>
      </StyledInternalLink>
    </VersionLinkContainer>
  )
}
Example #3
Source File: BetterTradeLink.tsx    From luaswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function BetterTradeLink({ version }: { version: Version }) {
  const location = useLocation()
  const search = useParsedQueryString()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: version !== DEFAULT_VERSION ? version : undefined
      })}`
    }
  }, [location, search, version])

  return (
    <VersionLinkContainer>
      There is a better price for this trade on{' '}
      <StyledInternalLink to={linkDestination}>
        <b>LuaSwap {version.toUpperCase()} ↗</b>
      </StyledInternalLink>
    </VersionLinkContainer>
  )
}
Example #4
Source File: VersionSwitch.tsx    From sushiswap-exchange with GNU General Public License v3.0 6 votes vote down vote up
export default function VersionSwitch() {
  const version = useToggledVersion()
  const location = useLocation()
  const query = useParsedQueryString()
  const versionSwitchAvailable = location.pathname === '/swap' || location.pathname === '/send'

  const toggleDest = useMemo(() => {
    return versionSwitchAvailable
      ? {
          ...location,
          search: `?${stringify({ ...query, use: version === Version.v1 ? undefined : Version.v1 })}`
        }
      : location
  }, [location, query, version, versionSwitchAvailable])

  const handleClick = useCallback(
    e => {
      if (!versionSwitchAvailable) e.preventDefault()
    },
    [versionSwitchAvailable]
  )

  const toggle = (
    <VersionToggle enabled={versionSwitchAvailable} to={toggleDest} onClick={handleClick}>
      <VersionLabel enabled={version === Version.v2 || !versionSwitchAvailable}>V2</VersionLabel>
      <VersionLabel enabled={version === Version.v1 && versionSwitchAvailable}>V1</VersionLabel>
    </VersionToggle>
  )
  return versionSwitchAvailable ? (
    toggle
  ) : (
    <MouseoverTooltip text="This page is only compatible with SushiSwap LP Token.">{toggle}</MouseoverTooltip>
  )
}
Example #5
Source File: BetterTradeLink.tsx    From goose-frontend-amm with GNU General Public License v3.0 6 votes vote down vote up
export default function BetterTradeLink({ version }: { version: Version }) {
  const location = useLocation()
  const search = useParsedQueryString()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: version !== DEFAULT_VERSION ? version : undefined
      })}`
    }
  }, [location, search, version])

  return (
    <YellowCard style={{ marginTop: '12px', padding: '8px 4px' }}>
      <AutoColumn gap="sm" justify="center" style={{ alignItems: 'center', textAlign: 'center' }}>
        <Text style={{ lineHeight: '145.23%' }} fontSize="14px">
          There is a better price for this trade on{' '}
          <StyledInternalLink to={linkDestination}>
            <b>Uniswap {version.toUpperCase()} ↗</b>
          </StyledInternalLink>
        </Text>
      </AutoColumn>
    </YellowCard>
  )
}
Example #6
Source File: utils.ts    From fsxa-api with Apache License 2.0 6 votes vote down vote up
encodeQueryParams = (params: Record<string, unknown>) => {
  return stringify(params)
}
Example #7
Source File: FSXARemoteApi.ts    From fsxa-api with Apache License 2.0 6 votes vote down vote up
private buildStringifiedQueryParams(params: Record<'keys' | string, any>) {
    const result: Record<string, any> = {}
    Object.keys(params).forEach((key) => {
      if (Array.isArray(params[key])) {
        result[key] = params[key].map(JSON.stringify)
      } else if (typeof params[key] === 'object') {
        result[key] = JSON.stringify(params[key])
      } else {
        result[key] = params[key]
      }
    })
    return stringify(result, {
      indices: false,
      encode: false,
    })
  }
Example #8
Source File: BetterTradeLink.tsx    From dyp with Do What The F*ck You Want To Public License 6 votes vote down vote up
export function DefaultVersionLink() {
  const location = useLocation()
  const search = useParsedQueryString()
  const version = useToggledVersion()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: DEFAULT_VERSION
      })}`
    }
  }, [location, search])

  return (
    <VersionLinkContainer>
      Showing {version.toUpperCase()} price.{' '}
      <StyledInternalLink to={linkDestination}>
        <b>Switch to Uniswap {DEFAULT_VERSION.toUpperCase()} ↗</b>
      </StyledInternalLink>
    </VersionLinkContainer>
  )
}
Example #9
Source File: VersionSwitch.tsx    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
export default function VersionSwitch() {
  const version = useToggledVersion()
  const location = useLocation()
  const query = useParsedQueryString()
  const versionSwitchAvailable = location.pathname === '/swap' || location.pathname === '/send'

  const toggleDest = useMemo(() => {
    return versionSwitchAvailable
      ? {
          ...location,
          search: `?${stringify({ ...query, use: version === Version.v1 ? undefined : Version.v1 })}`
        }
      : location
  }, [location, query, version, versionSwitchAvailable])

  const handleClick = useCallback(
    e => {
      if (!versionSwitchAvailable) e.preventDefault()
    },
    [versionSwitchAvailable]
  )

  const toggle = (
    <VersionToggle enabled={versionSwitchAvailable} to={toggleDest} onClick={handleClick}>
      <VersionLabel enabled={version === Version.v2 || !versionSwitchAvailable}>V2</VersionLabel>
      <VersionLabel enabled={version === Version.v1 && versionSwitchAvailable}>V1</VersionLabel>
    </VersionToggle>
  )
  return versionSwitchAvailable ? (
    toggle
  ) : (
    <MouseoverTooltip text="This page is only compatible with Uniswap V2.">{toggle}</MouseoverTooltip>
  )
}
Example #10
Source File: BetterTradeLink.tsx    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function BetterTradeLink({ version }: { version: Version }) {
  const theme = useContext(ThemeContext)
  const location = useLocation()
  const search = useParsedQueryString()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: version !== DEFAULT_VERSION ? version : undefined
      })}`
    }
  }, [location, search, version])

  return (
    <YellowCard style={{ marginTop: '12px', padding: '8px 4px' }}>
      <AutoColumn gap="sm" justify="center" style={{ alignItems: 'center', textAlign: 'center' }}>
        <Text lineHeight="145.23%;" fontSize={16} fontWeight={600} color={theme.colors.text1}>
          There is a better price for this trade on{' '}
          <StyledInternalLink to={linkDestination}>
            <b>Uniswap {version.toUpperCase()} ↗</b>
          </StyledInternalLink>
        </Text>
      </AutoColumn>
    </YellowCard>
  )
}
Example #11
Source File: VersionSwitch.tsx    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
export default function VersionSwitch() {
  const version = useToggledVersion()
  const location = useLocation()
  const query = useParsedQueryString()
  const versionSwitchAvailable = location.pathname === '/swap' || location.pathname === '/send'

  const toggleDest = useMemo(() => {
    return versionSwitchAvailable
      ? {
          ...location,
          search: `?${stringify({ ...query, use: version === Version.v1 ? undefined : Version.v1 })}`
        }
      : location
  }, [location, query, version, versionSwitchAvailable])

  const handleClick = useCallback(
    e => {
      if (!versionSwitchAvailable) e.preventDefault()
    },
    [versionSwitchAvailable]
  )

  const toggle = (
    <VersionToggle enabled={versionSwitchAvailable} to={toggleDest} onClick={handleClick}>
      <VersionLabel enabled={version === Version.v2 || !versionSwitchAvailable}>V2</VersionLabel>
      <VersionLabel enabled={version === Version.v1 && versionSwitchAvailable}>V1</VersionLabel>
    </VersionToggle>
  )
  return versionSwitchAvailable ? (
    toggle
  ) : (
    <MouseoverTooltip text="This page is only compatible with Uniswap V2.">{toggle}</MouseoverTooltip>
  )
}
Example #12
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 #13
Source File: api.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
fetchData = async (queryParams, toggleNotification) => {
  try {
    const { data } = await axiosInstance.get(
      getApiURL(
        `moderate/all${
          queryParams ? `?${stringify(queryParams, { encode: false })}` : ""
        }`
      )
    );

    return data;
  } catch (err) {
    handleAPIError(err, toggleNotification);
  }
}
Example #14
Source File: BetterTradeLink.tsx    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
export default function BetterTradeLink({ version }: { version: Version }) {
  const theme = useContext(ThemeContext)
  const location = useLocation()
  const search = useParsedQueryString()

  const linkDestination = useMemo(() => {
    return {
      ...location,
      search: `?${stringify({
        ...search,
        use: version !== DEFAULT_VERSION ? version : undefined
      })}`
    }
  }, [location, search, version])

  return (
    <YellowCard style={{ marginTop: '12px', padding: '8px 4px' }}>
      <AutoColumn gap="sm" justify="center" style={{ alignItems: 'center', textAlign: 'center' }}>
        <Text lineHeight="145.23%;" fontSize={14} fontWeight={400} color={theme.text1}>
          There is a better price for this trade on{' '}
          <StyledInternalLink to={linkDestination}>
            <b>Uniswap {version.toUpperCase()} ↗</b>
          </StyledInternalLink>
        </Text>
      </AutoColumn>
    </YellowCard>
  )
}
Example #15
Source File: FSXARemoteApi.ts    From fsxa-api with Apache License 2.0 5 votes vote down vote up
/**
   * This methods builds an URL for the CaaS.
   * Based upon the optional {@link buildCaaSUrlParams buildCaaSUrlParams} object the returning url can link to any desired document.
   * @param id a specific CaaS document id
   * @param locale the locale of CaaS document (id of the document must be set)
   * @param remoteProject name of the remote project
   * @param additionalParams additional URL parameters
   * @param filters filters for CaaS documents - for more details read the [CaaS Platform documentation](https://docs.e-spirit.com/module/caas-platform/CaaS_Platform_Documentation_EN.html#use-of-filters)
   * @param page number of the page you want to access
   * @param pagesize number of the resulting CaaS documents
   * @returns a string that contains the CaaS URL with the configured parameters as query parameters
   */
  buildCaaSUrl({
    id,
    locale,
    remoteProject,
    additionalParams,
    filters,
    page,
    pagesize,
  }: buildCaaSUrlParams = {}) {
    let project = this.projectID
    if (remoteProject) {
      project = this.getRemoteProject(remoteProject)
    }

    let baseURL = `${this.caasURL}/${this.tenantID}/${project}.${this.contentMode}.content`

    if (id) {
      baseURL += `/${id}`
      if (locale) {
        baseURL += `.${locale}`
      }
    }

    const params: string[] = []
    const additionalParamsDefined = additionalParams && Object.keys(additionalParams).length > 0
    if (additionalParamsDefined) {
      params.push(this.buildStringifiedQueryParams(additionalParams))
    }

    if (filters) {
      let localeFilter: QueryBuilderQuery[] = []
      if (locale) {
        localeFilter = [
          {
            operator: ComparisonQueryOperatorEnum.EQUALS,
            value: locale.split('_')[0],
            field: 'locale.language',
          },
          {
            operator: ComparisonQueryOperatorEnum.EQUALS,
            value: locale.split('_')[1],
            field: 'locale.country',
          },
        ]
      }
      const allFilters = [...filters, ...localeFilter]
      // const query = [...filters.map(filter => JSON.stringify(this._queryBuilder.build(filter)))]
      const query = this._queryBuilder.buildAll(allFilters).map((v) => JSON.stringify(v))
      if (query) {
        params.push('filter=' + query.join('&filter='))
      }
    }

    if (page) {
      params.push('page=' + page)
    }

    if (pagesize) {
      params.push('pagesize=' + pagesize)
    }

    if (params.length) {
      baseURL += `?${params.join('&')}`
    }

    return baseURL
  }
Example #16
Source File: useKyStrategy.ts    From react-starter-boilerplate with MIT License 5 votes vote down vote up
useKyStrategy = (): ApiClientContextValue => {
  const client = useMemo(() => {
    return Ky.create({
      headers: {
        'Content-Type': 'application/json',
      },
      prefixUrl: `${process.env.REACT_APP_API_URL}`,
      hooks: {
        beforeRequest: [requestSuccessHook],
        beforeError: [responseErrorHook],
      },
      retry: 1,
    });
  }, []);

  const queryFn = useCallback(
    <TData>(): QueryFunction<TData> =>
      async ({ queryKey: [url] }) => {
        if (typeof url === 'string') {
          const lowerCaseUrl = url.toLowerCase();
          return await client.get(lowerCaseUrl).json<TData>();
        }
        throw new Error('Invalid QueryKey');
      },
    [client],
  );

  const infiniteQueryFn = useCallback(
    <TArgs, TParams, TResponse, TError>(
        _query: InfiniteQueryFn<TArgs, TParams, TResponse>,
        options?: UseInfiniteQueryOptions<TArgs, TParams, TError, TResponse>,
      ): QueryFunction<TParams> =>
      async ({ pageParam = 0 }) => {
        const { endpoint, args } = _query(options?.args);
        const cursorKey = options?.cursorKey;
        // End format of url is e.g /users?page=2&sortOrder=ASC&limit=5&sortBy=name
        return await client
          .get(`${endpoint}?${cursorKey}=${pageParam}&${stringify(args, { addQueryPrefix: false })}`)
          .json<TParams>();
      },
    [client],
  );

  const mutationFn = useCallback(
    <TParams = unknown, TData = unknown>(mutation: MutationFn<TParams, TData>): MutationFunction<TData, TParams> =>
      async (variables) => {
        const { endpoint, params, method } = mutation(variables);

        const kyConfig: Options = {
          json: params ?? undefined,
          method: method || 'POST',
        };

        return await client(endpoint, kyConfig).json<TData>();
      },
    [client],
  );

  return {
    queryFn,
    infiniteQueryFn,
    mutationFn,
  };
}
Example #17
Source File: useAxiosStrategy.ts    From react-starter-boilerplate with MIT License 5 votes vote down vote up
useAxiosStrategy = (): ApiClientContextValue => {
  const client = useMemo(() => {
    const axios = Axios.create({
      headers: {
        'Content-Type': 'application/json',
      },
      baseURL: `${process.env.REACT_APP_API_URL}`,
    });

    axios.interceptors.request.use(requestSuccessInterceptor);
    axios.interceptors.response.use(responseSuccessInterceptor, responseFailureInterceptor);

    return axios;
  }, []);

  const queryFn = useCallback(
    <TData>(): QueryFunction<TData> =>
      async ({ queryKey: [url] }) => {
        if (typeof url === 'string') {
          const lowerCaseUrl = url.toLowerCase();
          const { data } = await client.get(`/${lowerCaseUrl}`);
          return data;
        }
        throw new Error('Invalid QueryKey');
      },
    [client],
  );

  const infiniteQueryFn = useCallback(
    <TArgs, TParams, TResponse, TError>(
        query: InfiniteQueryFn<TArgs, TParams, TResponse>,
        options?: UseInfiniteQueryOptions<TArgs, TParams, TError, TResponse>,
      ): QueryFunction<TParams> =>
      async ({ pageParam = options?.startPage ?? 0 }) => {
        const { endpoint, args } = query(options?.args);
        const cursorKey = options?.cursorKey;
        // End format of url is e.g /users?page=2&sortOrder=ASC&limit=5&sortBy=name
        const { data } = await client.get(
          `/${endpoint}?${cursorKey}=${pageParam}&${stringify(args, { addQueryPrefix: false })}`,
        );
        return data;
      },
    [client],
  );

  const mutationFn = useCallback(
    <TParams = unknown, TData = unknown>(mutation: MutationFn<TParams, TData>): MutationFunction<TData, TParams> =>
      async (variables) => {
        const { endpoint, params, method } = mutation(variables);

        const axiosConfig: AxiosRequestConfig = {
          url: `/${endpoint}`,
          data: params ? JSON.stringify(params) : undefined,
          method: method || 'POST',
        };
        const { data } = await client.request(axiosConfig);
        return data;
      },
    [client],
  );

  return {
    queryFn,
    infiniteQueryFn,
    mutationFn,
  };
}