querystring#ParsedUrlQuery TypeScript Examples
The following examples show how to use
querystring#ParsedUrlQuery.
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: tables.utils.ts From condo with MIT License | 7 votes |
parseQuery = (query: ParsedUrlQuery): ParsedQueryType => {
const filters = getFiltersFromQuery(query)
const sorters = getSortersFromQuery(query)
const queryOffset = get(query, 'offset', '0')
const offset = Number(queryOffset) ? Number(queryOffset) : 0
const queryTab = get(query, 'tab')
const tab = Array.isArray(queryTab) ? undefined : queryTab
return { filters, sorters, offset, tab }
}
Example #2
Source File: tables.utils.ts From condo with MIT License | 7 votes |
getFiltersFromQuery = (query: ParsedUrlQuery): { [x: string]: QueryArgType } => {
const { filters } = query
if (!filters || typeof filters !== 'string') {
return {}
}
try {
const json = JSON.parse(filters)
const result = {}
Object.keys(json).forEach((key) => {
const value = json[key]
if (Array.isArray(value)) {
result[key] = value.filter((v) => typeof v === 'string' && Boolean(v))
} else {
if (typeof value === 'string' && !!value) result[key] = value
}
})
return result
} catch (e) {
return {}
}
}
Example #3
Source File: tables.utils.ts From condo with MIT License | 7 votes |
getSortersFromQuery = (query: ParsedUrlQuery): SorterColumn[] => {
let sorters = get(query, 'sort', [])
if (!Array.isArray(sorters)) {
sorters = sorters.split(',')
}
return sorters
.map((sorter) => {
const [column, order] = sorter.split('_')
if (!column || !order || !SHORT_TO_FULL_ORDERS_MAP[order]) return
return { columnKey: column, order: SHORT_TO_FULL_ORDERS_MAP[order] }
})
.filter(Boolean)
}
Example #4
Source File: helpers.ts From condo with MIT License | 6 votes |
getFiltersFromQuery = <T>(query: ParsedUrlQuery): T | Record<string, never> => {
const { filters } = query
if (!filters || typeof filters !== 'string') {
return {}
}
try {
return JSON.parse(filters)
} catch (e) {
return {}
}
}
Example #5
Source File: address.ts From Account-Manager with MIT License | 6 votes |
parseQueryParams = (url: string): ParsedUrlQuery => {
const questionMarkIndex = url.indexOf('?');
if (questionMarkIndex === -1) return {};
const parsedQueryParamObject = parse(url.slice(questionMarkIndex + 1));
return Object.entries(parsedQueryParamObject).reduce((acc, [queryParam, value]) => {
if (!value) return acc;
if (Array.isArray(value))
return {
...acc,
[queryParam]: value.join(','),
};
return {
...acc,
[queryParam]: value,
};
}, {});
}
Example #6
Source File: createURLWithQuery.ts From solana-pay with Apache License 2.0 | 6 votes |
export function createURLWithQuery(url: string | URL, base: string | URL, query: ParsedUrlQuery): URL {
url = new URL(url, base);
for (const [key, value] of Object.entries(query)) {
if (value) {
if (Array.isArray(value)) {
for (const v of value) {
url.searchParams.append(key, v);
}
} else {
url.searchParams.append(key, value);
}
}
}
return url;
}
Example #7
Source File: helpers.ts From condo with MIT License | 6 votes |
getPageSizeFromQuery = (query: ParsedUrlQuery): number => {
const queryValue = Number(get(query, 'pagesize', TICKET_PAGE_SIZE))
if (POSSIBLE_PAGE_SIZE.indexOf(queryValue) !== -1) {
return queryValue
}
const nearest = POSSIBLE_PAGE_SIZE
.map(validPageSize => ({ validPageSize, difference: Math.abs(queryValue - validPageSize) }))
.sort((a, b) => a.difference - b.difference)[0].validPageSize
return nearest
}
Example #8
Source File: helpers.ts From condo with MIT License | 6 votes |
getSortStringFromQuery = (query: ParsedUrlQuery): Array<string> => {
const sort = get(query, 'sort', [])
if (Array.isArray(sort)) {
return sort
}
return sort.split(',')
}
Example #9
Source File: helpers.ts From condo with MIT License | 6 votes |
getSortStringFromQuery = (query: ParsedUrlQuery): Array<string> => {
const sort = get(query, 'sort', [])
if (Array.isArray(sort)) {
return sort
}
return sort.split(',')
}
Example #10
Source File: helpers.ts From condo with MIT License | 6 votes |
getSortStringFromQuery = (query: ParsedUrlQuery): Array<string> => {
const sort = get(query, 'sort', [])
if (Array.isArray(sort)) {
return sort
}
return sort.split(',')
}
Example #11
Source File: common.ts From node-saml with MIT License | 6 votes |
getAdditionalParams = (params: {
relayState: string;
globalAdditionalParams: NodeJS.Dict<string>;
operationAdditionalParams: NodeJS.Dict<string>;
overrideParams?: ParsedUrlQuery;
}): ParsedUrlQuery => {
const { relayState, globalAdditionalParams, operationAdditionalParams, overrideParams } = params;
const additionalParams: ParsedUrlQuery = {};
if (typeof relayState === "string" && relayState.length > 0) {
additionalParams.RelayState = relayState;
}
return Object.assign(
additionalParams,
globalAdditionalParams,
operationAdditionalParams,
overrideParams ?? {}
);
}
Example #12
Source File: fetchDatasets.ts From nextclade with MIT License | 6 votes |
export async function initializeDatasets(urlQuery: ParsedUrlQuery) {
const datasetsIndexJson = await fetchDatasetsIndex()
const { datasets, defaultDatasetName, defaultDatasetNameFriendly } =
getLatestCompatibleEnabledDatasets(datasetsIndexJson)
// Check if URL params specify dataset params and try to find the corresponding dataset
const currentDataset = await getDatasetFromUrlParams(urlQuery, datasets)
const currentDatasetName = currentDataset?.attributes.name.value
return { datasets, defaultDatasetName, defaultDatasetNameFriendly, currentDatasetName }
}
Example #13
Source File: fetchDatasets.ts From nextclade with MIT License | 6 votes |
export async function getDatasetFromUrlParams(urlQuery: ParsedUrlQuery, datasets: Dataset[]) {
const inputFastaUrl = getQueryParamMaybe(urlQuery, 'input-fasta')
// If there are no input sequences, we are not going to run, so skip the rest
if (!inputFastaUrl) {
return undefined
}
// Retrieve dataset-related URL params and try to find a dataset based on these params
const datasetName = getQueryParamMaybe(urlQuery, 'dataset-name')
if (!datasetName) {
throw new Error(
"Incorrect URL parameters: 'input-fasta' is set, but 'dataset-name' is not. " +
"Nextclade won't run to avoid producing incorrect results. " +
"Please set 'dataset-name' explicitly in the URL parameters",
)
}
const datasetRef = getQueryParamMaybe(urlQuery, 'dataset-reference')
const datasetTag = getQueryParamMaybe(urlQuery, 'dataset-tag')
const dataset = findDataset(datasets, datasetName, datasetRef, datasetTag)
if (!dataset) {
throw new Error(
`Incorrect URL parameters: unable to find dataset with name='${datasetName}', ref='${datasetRef ?? ''}', tag='${
datasetTag ?? ''
}' `,
)
}
return dataset
}
Example #14
Source File: ntrip.ts From caster with GNU General Public License v3.0 | 6 votes |
private getSourcetable(query?: ParsedUrlQuery): Promise<string> {
// Parse filters if provided
let filters: Sourcetable.Filters | undefined;
if (query !== undefined) {
let {auth, strict, match, filter}: any = query;
if (auth !== undefined) auth = !!auth;
if (strict !== undefined) strict = !!strict;
if (match !== undefined) match = ((match instanceof Array) ? match : [match])
.map(filters => filters.split(';'));
if (filter !== undefined) filter = ((filter instanceof Array) ? filter : [filter])
.map(filters => filters.split(';'))
.map(Sourcetable.parseAdvancedFilters);
filters = {
auth: auth,
strict: strict,
simple: match,
advanced: filter
};
}
return this.caster.generateSourcetable(filters);
}
Example #15
Source File: parseUrl.ts From nextclade with MIT License | 6 votes |
/** Borrowed from Next.js */
export function searchParamsToUrlQuery(searchParams: URLSearchParams): ParsedUrlQuery {
const query: ParsedUrlQuery = {}
searchParams.forEach((value, key) => {
if (typeof query[key] === 'undefined') {
query[key] = value
} else if (Array.isArray(query[key])) {
;(query[key] as string[]).push(value)
} else {
query[key] = [query[key] as string, value]
}
})
return query
}
Example #16
Source File: requestSigner.ts From MDDL with MIT License | 6 votes |
getSortedQueryArgs = (queryArgs: ParsedUrlQuery) => {
const sortedKeys = Object.keys(queryArgs).sort()
return sortedKeys
.map((k) => {
if (Array.isArray(queryArgs[k])) {
return (queryArgs[k] as string[]).sort().join('')
}
return queryArgs[k]
})
.join('')
}
Example #17
Source File: useWebappVersion.ts From apps with GNU Affero General Public License v3.0 | 6 votes |
getVersion = (query: ParsedUrlQuery): string | undefined => {
if (query.android) {
return 'android';
}
if (query.pwa) {
return 'pwa';
}
return undefined;
}
Example #18
Source File: getQueryParamMaybe.ts From nextclade with MIT License | 5 votes |
export function getQueryParamMaybe(urlQuery: ParsedUrlQuery, param: string): string | undefined {
return takeFirstMaybe(urlQuery?.[param]) ?? undefined
}
Example #19
Source File: helpers.ts From condo with MIT License | 5 votes |
getPageIndexFromQuery = (query: ParsedUrlQuery): number => {
return Math.floor(Number(get(query, 'offset', 0)) / getPageSizeFromQuery(query)) + 1
}
Example #20
Source File: canonical.ts From apps with GNU Affero General Public License v3.0 | 5 votes |
parsedQueryToString = (query: ParsedUrlQuery): string => {
const keys = Object.keys(query);
if (!keys.length) {
return '';
}
return `?${keys.map((key) => `${key}=${query[key]}`).join('&')}`;
}
Example #21
Source File: helpers.ts From condo with MIT License | 5 votes |
getSortStringFromQuery = (query: ParsedUrlQuery): Array<string> => {
const sort = get(query, 'sort', [])
if (Array.isArray(sort)) {
return sort
}
return sort.split(',')
}
Example #22
Source File: helpers.ts From condo with MIT License | 5 votes |
getPageIndexFromQuery = (query: ParsedUrlQuery): number => {
return Math.floor(Number(get(query, 'offset', 0)) / PROPERTY_PAGE_SIZE) + 1
}
Example #23
Source File: helpers.ts From condo with MIT License | 5 votes |
getPageIndexFromQuery = (query: ParsedUrlQuery): number => {
return Math.floor(Number(get(query, 'offset', 0)) / EMPLOYEE_PAGE_SIZE) + 1
}
Example #24
Source File: actions.ts From frontend with Apache License 2.0 | 5 votes |
/**
* Performs the callback POST request to check 3rd party authentication
* was successful. Fetches user data on success. Throws localized string
* ID on error.
* @param dispatch Reducer dispatch function used to update user context
* @param query URL query object with code and state to POST to backend
* as well as login provider name to determine the API endpoint
*/
export async function login(
dispatch: Dispatch<UserStateAction>,
query: ParsedUrlQuery
) {
dispatch({ type: 'loading' })
let res: Response
try {
res = await fetch(`${LOGIN_PROVIDERS_URL}/${query.service}`, {
method: 'POST',
credentials: 'include', // Must use the session cookie
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
code: query.code,
state: query.state,
})
})
} catch {
dispatch({ type: 'interrupt' })
throw 'network-error-try-again'
}
if (res.ok) {
getUserData(dispatch)
} else {
dispatch({ type: 'interrupt' })
// Some errors come with an explanation from backend, others are unexpected
const data = await res.json()
const msg = {
'User already logged in?': 'error-already-logged-in'
}[data.error]
throw msg ?? 'network-error-try-again'
}
}
Example #25
Source File: helpers.ts From condo with MIT License | 5 votes |
getPageIndexFromQuery = (query: ParsedUrlQuery): number => {
return Math.floor(Number(get(query, 'offset', 0)) / CONTACT_PAGE_SIZE) + 1
}
Example #26
Source File: createInputFromUrlParamMaybe.ts From nextclade with MIT License | 5 votes |
export function createInputFromUrlParamMaybe(urlQuery: ParsedUrlQuery, paramName: string) {
const url = getQueryParamMaybe(urlQuery, paramName)
if (!url) {
return undefined
}
return new AlgorithmInputUrl(url)
}
Example #27
Source File: translateUrl.ts From next-translate-routes with MIT License | 4 votes |
translatePathParts = ({
locale,
pathParts,
routeBranch,
query,
}: {
locale: string
/** Can be a bare name or a dynamic value */
pathParts: string[]
routeBranch: TRouteBranch
query?: ParsedUrlQuery
}): { augmentedQuery?: ParsedUrlQuery; translatedPathParts: string[] } => {
const { children } = routeBranch
if (!Array.isArray(pathParts)) {
throw new Error('Wrong pathParts argument in translatePathParts')
}
if (pathParts.length === 0) {
return { translatedPathParts: [], augmentedQuery: query }
}
const pathPart = pathParts[0]
const nextPathParts = pathParts.slice(1)
if (!pathPart) {
return translatePathParts({ locale, pathParts: nextPathParts, routeBranch, query })
}
const candidates = getAllCandidates(locale, children).filter((child) =>
pathParts.length === 1 // Last path part
? !child.children ||
child.children.some((grandChild) => grandChild.name === 'index' || /\[\[\.{3}\w+\]\]/.exec(grandChild.name))
: !!child.children,
)
let currentQuery = query
let childRouteBranch = candidates.find(({ name }) => pathPart === name)
// If defined: pathPart is a route segment name that should be translated.
// If dynamic, the value should already be contained in the query.
if (!childRouteBranch) {
// If not defined: pathPart is either a dynamic value either a wrong path.
childRouteBranch = candidates.find((candidate) => getSingleDynamicPathPartName(candidate.name))
if (childRouteBranch) {
// Single dynamic route segment value => store it in the query
currentQuery = {
...currentQuery,
[childRouteBranch.name.replace(/\[|\]|\./g, '')]: pathPart,
}
} else {
childRouteBranch = candidates.find((candidate) => getSpreadDynamicPathPartName(candidate.name))
if (childRouteBranch) {
// Catch all route => store it in the query, then return the current data.
currentQuery = {
...currentQuery,
[childRouteBranch.name.replace(/\[|\]|\./g, '')]: pathParts,
}
return {
translatedPathParts: [childRouteBranch.name], // [childRouteBranch.paths[locale] || childRouteBranch.paths.default],
augmentedQuery: currentQuery,
}
}
// No route match => return the remaining path as is
return { translatedPathParts: pathParts, augmentedQuery: query }
}
}
// Get the descendants translated path parts and query values
const { augmentedQuery, translatedPathParts: nextTranslatedPathsParts } = childRouteBranch?.children
? translatePathParts({ locale, pathParts: nextPathParts, routeBranch: childRouteBranch, query: currentQuery })
: { augmentedQuery: currentQuery, translatedPathParts: [] }
const translatedPathPart = childRouteBranch.paths[locale] || childRouteBranch.paths.default
return {
translatedPathParts: [
...(ignoreSegmentPathRegex.test(translatedPathPart) ? [] : [translatedPathPart]),
...(nextTranslatedPathsParts || []),
],
augmentedQuery,
}
}
Example #28
Source File: Home.spec.tsx From space-traveling with MIT License | 4 votes |
describe('Home', () => {
beforeAll(() => {
mockedPush.mockImplementation(() => Promise.resolve());
const MockedRouterContext = RouterContext as React.Context<unknown>;
RouterWrapper = ({ children }): JSX.Element => {
return (
<MockedRouterContext.Provider
value={{
push: mockedPush,
}}
>
{children}
</MockedRouterContext.Provider>
);
};
mockedPrismic.mockReturnValue({
query: () => {
return Promise.resolve(mockedQueryReturn);
},
});
mockedFetch.mockImplementation(() => {
return Promise.resolve({
json: () =>
Promise.resolve({
next_page: null,
results: [
{
uid: 'criando-um-app-cra-do-zero',
first_publication_date: '2021-03-25T19:27:35+0000',
data: {
title: 'Criando um app CRA do zero',
subtitle:
'Tudo sobre como criar a sua primeira aplicação utilizando Create React App',
author: 'Danilo Vieira',
},
},
],
}),
});
});
});
it('should be able to return prismic posts documents using getStaticProps', async () => {
const postsPaginationReturn = mockedQueryReturn;
const getStaticPropsContext: GetStaticPropsContext<ParsedUrlQuery> = {};
const response = (await getStaticProps(
getStaticPropsContext
)) as GetStaticPropsResult;
expect(response.props.postsPagination).toEqual(postsPaginationReturn);
});
it('should be able to render logo', () => {
const postsPagination = mockedQueryReturn;
render(<App postsPagination={postsPagination} />);
screen.getByAltText('logo');
});
it('should be able to render posts documents info', () => {
const postsPagination = mockedQueryReturn;
render(<App postsPagination={postsPagination} />);
screen.getByText('Como utilizar Hooks');
screen.getByText('Pensando em sincronização em vez de ciclos de vida');
screen.getByText('15 mar 2021');
screen.getByText('Joseph Oliveira');
screen.getByText('Criando um app CRA do zero');
screen.getByText(
'Tudo sobre como criar a sua primeira aplicação utilizando Create React App'
);
screen.getByText('15 mar 2021');
screen.getByText('Danilo Vieira');
});
it('should be able to navigate to post page after a click', () => {
const postsPagination = mockedQueryReturn;
render(<App postsPagination={postsPagination} />, {
wrapper: RouterWrapper,
});
const firstPostTitle = screen.getByText('Como utilizar Hooks');
const secondPostTitle = screen.getByText('Criando um app CRA do zero');
fireEvent.click(firstPostTitle);
fireEvent.click(secondPostTitle);
expect(mockedPush).toHaveBeenNthCalledWith(
1,
'/post/como-utilizar-hooks',
expect.anything(),
expect.anything()
);
expect(mockedPush).toHaveBeenNthCalledWith(
2,
'/post/criando-um-app-cra-do-zero',
expect.anything(),
expect.anything()
);
});
it('should be able to load more posts if available', async () => {
const postsPagination = { ...mockedQueryReturn };
postsPagination.results = [
{
uid: 'como-utilizar-hooks',
first_publication_date: '2021-03-15T19:25:28+0000',
data: {
title: 'Como utilizar Hooks',
subtitle: 'Pensando em sincronização em vez de ciclos de vida',
author: 'Joseph Oliveira',
},
},
];
render(<App postsPagination={postsPagination} />);
screen.getByText('Como utilizar Hooks');
const loadMorePostsButton = screen.getByText('Carregar mais posts');
fireEvent.click(loadMorePostsButton);
await waitFor(
() => {
expect(mockedFetch).toHaveBeenCalled();
},
{ timeout: 200 }
);
screen.getByText('Criando um app CRA do zero');
});
it('should not be able to load more posts if not available', async () => {
const postsPagination = mockedQueryReturn;
postsPagination.next_page = null;
render(<App postsPagination={postsPagination} />);
screen.getByText('Como utilizar Hooks');
screen.getByText('Criando um app CRA do zero');
const loadMorePostsButton = screen.queryByText('Carregar mais posts');
expect(loadMorePostsButton).not.toBeInTheDocument();
});
});
Example #29
Source File: Post.spec.tsx From space-traveling with MIT License | 4 votes |
describe('Post', () => {
beforeAll(() => {
mockedUseRouter.mockReturnValue({
isFallback: false,
});
mockedPrismic.mockReturnValue({
getByUID: () => {
return Promise.resolve(mockedGetByUIDReturn);
},
query: () => {
return Promise.resolve(mockedQueryReturn);
},
});
});
it('should be able to return prismic posts documents paths using getStaticPaths', async () => {
const getStaticPathsReturn = [
{
params: {
slug: 'como-utilizar-hooks',
},
},
{
params: {
slug: 'criando-um-app-cra-do-zero',
},
},
];
const getStaticPathsContext: GetStaticPathsContext = {};
const response = (await getStaticPaths(
getStaticPathsContext
)) as GetStaticPathsResult;
expect(response.paths).toEqual(getStaticPathsReturn);
});
it('should be able to return prismic post document using getStaticProps', async () => {
const routeParam = parse('como-utilizar-hooks');
const postReturn = mockedGetByUIDReturn;
const getStaticPropsContext: GetStaticPropsContext<ParsedUrlQuery> = {
params: routeParam,
};
const response = (await getStaticProps(
getStaticPropsContext
)) as GetStaticPropsResult;
expect(response.props.post).toEqual(postReturn);
});
it('should be able to render post document info', () => {
const postProps = mockedGetByUIDReturn;
render(<Post post={postProps} />);
screen.getByText('Como utilizar Hooks');
screen.getByText('25 mar 2021');
screen.getByText('Joseph Oliveira');
screen.getByText('4 min');
screen.getByText('Proin et varius');
screen.getByText(/Nullam dolor sapien/);
screen.getByText('Cras laoreet mi');
screen.getByText(/Ut varius quis velit sed cursus/);
});
it('should be able to render loading message if fallback', () => {
mockedUseRouter.mockReturnValueOnce({
isFallback: true,
});
const postProps = mockedGetByUIDReturn;
render(<Post post={postProps} />);
screen.getByText('Carregando...');
});
it('should be able to render Header component', () => {
const postProps = mockedGetByUIDReturn;
render(<Post post={postProps} />);
screen.getByAltText('logo');
});
});