icns-frontend/utils/url.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-12-15 06:02:50 +00:00
import { TwitterLoginSuccess } from "../types";
import { TWITTER_LOGIN_ERROR } from "../constants/error-message";
2022-12-15 15:43:18 +00:00
import { WALLET_INSTALL_URL } from "../constants/wallet";
2022-12-15 06:02:50 +00:00
2022-12-23 13:30:35 +00:00
export async function request<TResponse>(
2022-12-05 10:50:13 +00:00
url: string,
config: RequestInit = {},
2022-12-20 14:09:26 +00:00
customConfig?: {
isErrorIgnore?: boolean;
},
2022-12-05 10:50:13 +00:00
): Promise<TResponse> {
2022-12-23 13:30:35 +00:00
const response = await fetch(url, config);
const data = await response.json();
if (
(!response.ok || data.error || data.errors) &&
!customConfig?.isErrorIgnore
) {
const { error, errors } = data;
2022-12-26 09:03:54 +00:00
const errorMessage =
(error && error.toString()) || (errors && errors.toString());
2022-12-23 13:30:35 +00:00
throw new Error(errorMessage);
}
return data;
2022-12-05 10:50:13 +00:00
}
export function buildQueryString(query: Record<string, any>): string {
return Object.entries(query)
.map(([key, value]) =>
key && value
? `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
: "",
)
.join("&");
}
2022-12-15 06:02:50 +00:00
export const checkTwitterAuthQueryParameter = (
query: string,
): TwitterLoginSuccess => {
// Twitter Login Error Check
if (query.match("error")) {
throw new Error(TWITTER_LOGIN_ERROR);
}
// Twitter state, auth code check
const [, state, code] =
query.match(/^(?=.*state=([^&]+)|)(?=.*code=([^&]+)|).+$/) || [];
return {
state,
code,
};
};
2022-12-15 15:43:18 +00:00
export const replaceToInstallPage = () => {
window.location.href = WALLET_INSTALL_URL;
};