Compare commits
9 Commits
a92c43ab1b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| b3f95a6ad9 | |||
| 3560afabcc | |||
| 6caac5743b | |||
| d09664ad57 | |||
| e43a8b0865 | |||
| 6efb75ab30 | |||
| 6549729fed | |||
| 63e4654502 | |||
| a812e650ce |
1
.env.example
Normal file
1
.env.example
Normal file
@ -0,0 +1 @@
|
||||
NEXT_PUBLIC_API_URL=http://your.api/api
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -122,7 +122,7 @@ dist
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
|
||||
.yarn
|
||||
.DS_Store
|
||||
|
||||
.idea
|
||||
|
||||
BIN
.yarn/install-state.gz
Normal file
BIN
.yarn/install-state.gz
Normal file
Binary file not shown.
21
openapi-ts.config.ts
Normal file
21
openapi-ts.config.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { defaultPlugins, defineConfig } from "@hey-api/openapi-ts";
|
||||
|
||||
export default defineConfig({
|
||||
input: "../back/combined.yaml",
|
||||
output: "src/client",
|
||||
plugins: [
|
||||
...defaultPlugins,
|
||||
{
|
||||
asClass: true,
|
||||
name: "@hey-api/sdk",
|
||||
validator: "zod",
|
||||
},
|
||||
{
|
||||
name: "@hey-api/client-next",
|
||||
runtimeConfigPath:"./src/hey-api-config.ts",
|
||||
},
|
||||
{
|
||||
name: "@hey-api/typescript",
|
||||
},
|
||||
],
|
||||
});
|
||||
@ -17,7 +17,8 @@
|
||||
"prettier:write": "prettier --write \"**/*.{ts,tsx}\"",
|
||||
"test": "npm run prettier:check && npm run lint && npm run typecheck && npm run jest",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"storybook:build": "storybook build"
|
||||
"storybook:build": "storybook build",
|
||||
"openapi-ts": "openapi-ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mantine/core": "8.1.2",
|
||||
@ -38,11 +39,13 @@
|
||||
"react-imask": "^7.6.1",
|
||||
"react-redux": "^9.2.0",
|
||||
"redux-persist": "^6.0.0",
|
||||
"sharp": "^0.34.3"
|
||||
"sharp": "^0.34.3",
|
||||
"zod": "^4.0.10"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.27.4",
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@hey-api/openapi-ts": "0.80.1",
|
||||
"@ianvs/prettier-plugin-sort-imports": "^4.4.2",
|
||||
"@storybook/nextjs": "^8.6.8",
|
||||
"@storybook/react": "^8.6.8",
|
||||
|
||||
@ -1,15 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { FC, useEffect, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useSelector } from "react-redux";
|
||||
import { Button, Text } from "@mantine/core";
|
||||
import { Auth } from "@/client";
|
||||
import SCOPES from "@/constants/scopes";
|
||||
import { Scopes } from "@/enums/Scopes";
|
||||
import { notifications } from "@/lib/notifications";
|
||||
import { RootState } from "@/lib/store";
|
||||
import { AuthService } from "@/mocks/authService";
|
||||
import { RootState } from "@/lib/store/store";
|
||||
|
||||
const ConsentButton: FC = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const auth = useSelector((state: RootState) => state.auth);
|
||||
const [clientName, setClientName] = useState<string>(Scopes.UNDEFINED);
|
||||
const [serviceRequiredAccess, setServiceRequiredAccess] =
|
||||
@ -25,18 +27,7 @@ const ConsentButton: FC = () => {
|
||||
};
|
||||
|
||||
const requestConsent = () => {
|
||||
if (!auth.loginChallenge || auth.scope.length === 0) return;
|
||||
|
||||
new AuthService()
|
||||
.requestConsent(auth.loginChallenge)
|
||||
.then(response => response.data)
|
||||
.then(({ clientName }) => {
|
||||
setClientName(clientName);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
notifications.error({ message: error.toString() });
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@ -45,18 +36,38 @@ const ConsentButton: FC = () => {
|
||||
}, []);
|
||||
|
||||
const confirmAccess = () => {
|
||||
if (!auth.loginChallenge) return;
|
||||
|
||||
new AuthService()
|
||||
.approveConsent(auth.loginChallenge)
|
||||
.then(response => response.data)
|
||||
.then(({ redirectUrl }) => {
|
||||
window.location.href = redirectUrl;
|
||||
const phoneNumber = auth.phoneNumber;
|
||||
if (!phoneNumber) {
|
||||
console.error("Phone number is not set");
|
||||
return;
|
||||
}
|
||||
const consentChallenge = searchParams.get("consent_challenge");
|
||||
if (!consentChallenge) {
|
||||
console.error("Consent challenge is missing in the URL");
|
||||
return;
|
||||
}
|
||||
Auth.postAuthConsentAccept({
|
||||
body: {
|
||||
consent_challenge: consentChallenge,
|
||||
phone_number: phoneNumber,
|
||||
},
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
notifications.error({ message: error.toString() });
|
||||
.then(response => response.data)
|
||||
.then(response => {
|
||||
if (!response) {
|
||||
console.error("Response is empty");
|
||||
return;
|
||||
}
|
||||
const { redirect_url, ok, message } = response;
|
||||
notifications.guess(ok, { message });
|
||||
|
||||
if (redirect_url) {
|
||||
window.location.href = redirect_url;
|
||||
} else {
|
||||
console.error("Redirect URL is missing in the response");
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import PageContainer from "@/components/PageContainer/PageContainer";
|
||||
import PageItem from "@/components/PageBlock/PageItem";
|
||||
import Logo from "@/components/Logo/Logo";
|
||||
import PageContainer from "@/components/layout/PageContainer/PageContainer";
|
||||
import PageItem from "@/components/layout/PageBlock/PageItem";
|
||||
import Logo from "@/components/ui/Logo/Logo";
|
||||
import ConsentForm from "@/app/consent/components/ConsentForm/ConsentForm";
|
||||
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import LoginForm from "@/components/LoginForm/LoginForm";
|
||||
import Logo from "@/components/Logo/Logo";
|
||||
import PageItem from "@/components/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/PageContainer/PageContainer";
|
||||
import LoginForm from "@/components/features/LoginForm/LoginForm";
|
||||
import Logo from "@/components/ui/Logo/Logo";
|
||||
import PageItem from "@/components/layout/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/layout/PageContainer/PageContainer";
|
||||
|
||||
export default function CreateIdPage() {
|
||||
return (
|
||||
|
||||
@ -6,11 +6,11 @@ import {
|
||||
mantineHtmlProps,
|
||||
MantineProvider,
|
||||
} from "@mantine/core";
|
||||
import Header from "@/components/Header/Header";
|
||||
import Header from "@/components/layout/Header/Header";
|
||||
import { theme } from "@/theme";
|
||||
import "@/app/global.css";
|
||||
import { Notifications } from "@mantine/notifications";
|
||||
import Footer from "@/components/Footer/Footer";
|
||||
import Footer from "@/components/layout/Footer/Footer";
|
||||
import ReduxProvider from "@/providers/ReduxProvider";
|
||||
|
||||
export const metadata = {
|
||||
|
||||
@ -1,18 +1,20 @@
|
||||
import LoginForm from "@/components/LoginForm/LoginForm";
|
||||
import Logo from "@/components/Logo/Logo";
|
||||
import PageItem from "@/components/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/PageContainer/PageContainer";
|
||||
import LoginForm from "@/components/features/LoginForm/LoginForm";
|
||||
import PageItem from "@/components/layout/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/layout/PageContainer/PageContainer";
|
||||
import Logo from "@/components/ui/Logo/Logo";
|
||||
|
||||
interface LoginPageProps {
|
||||
searchParams: { login_challenge?: string };
|
||||
searchParams: Promise<{ login_challenge?: string }>;
|
||||
}
|
||||
|
||||
export default function LoginPage({ searchParams }: LoginPageProps) {
|
||||
export default async function LoginPage({ searchParams }: LoginPageProps) {
|
||||
const params = await searchParams;
|
||||
|
||||
return (
|
||||
<PageContainer center>
|
||||
<PageItem fullScreenMobile>
|
||||
<Logo title={"Вход"} />
|
||||
<LoginForm loginChallenge={searchParams.login_challenge} />
|
||||
<LoginForm loginChallenge={params.login_challenge} />
|
||||
</PageItem>
|
||||
</PageContainer>
|
||||
);
|
||||
|
||||
@ -4,13 +4,17 @@ import { useMemo } from "react";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Button, Stack, Title } from "@mantine/core";
|
||||
import styles from "@/app/services/components/ServicesList/ServicesList.module.css";
|
||||
import TitleWithLines from "@/components/TitleWithLines/TitleWithLines";
|
||||
import TitleWithLines from "@/components/ui/TitleWithLines/TitleWithLines";
|
||||
import SCOPES from "@/constants/scopes";
|
||||
import { Scopes } from "@/enums/Scopes";
|
||||
import { setTargetService } from "@/lib/features/targetService/targetServiceSlice";
|
||||
import { useAppDispatch } from "@/lib/store";
|
||||
import ServiceData from "@/types/ServiceData";
|
||||
import { setTargetService } from "@/lib/store/features/targetService/targetServiceSlice";
|
||||
import { useAppDispatch } from "@/lib/store/store";
|
||||
|
||||
type ServiceData = {
|
||||
id: number;
|
||||
code: Scopes;
|
||||
name: string;
|
||||
};
|
||||
const ServicesList = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const services = useMemo(
|
||||
@ -56,7 +60,9 @@ const ServicesList = () => {
|
||||
<Stack
|
||||
className={styles.container}
|
||||
gap={"lg"}>
|
||||
{services.map((service, i) => getServiceButton(service, i))}
|
||||
{services.map((service, i) =>
|
||||
getServiceButton(service as unknown as ServiceData, i)
|
||||
)}
|
||||
<TitleWithLines title="Скоро будет" />
|
||||
{getServiceInDevelopment("Analytics")}
|
||||
</Stack>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import Logo from "@/components/Logo/Logo";
|
||||
import PageItem from "@/components/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/PageContainer/PageContainer";
|
||||
import Logo from "@/components/ui/Logo/Logo";
|
||||
import PageItem from "@/components/layout/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/layout/PageContainer/PageContainer";
|
||||
import ServicesList from "@/app/services/components/ServicesList/ServicesList";
|
||||
|
||||
export default function ServicesPage() {
|
||||
|
||||
@ -3,9 +3,9 @@
|
||||
import { FC, useEffect, useState } from "react";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { Button } from "@mantine/core";
|
||||
import { setLastSendTime } from "@/lib/features/verification/verificationSlice";
|
||||
import { RootState } from "@/lib/store";
|
||||
import { MAX_COUNTDOWN } from "@/constants/verification";
|
||||
import { setLastSendTime } from "@/lib/store/features/verification/verificationSlice";
|
||||
import { RootState } from "@/lib/store/store";
|
||||
|
||||
const ResendVerificationCode: FC = () => {
|
||||
const [countdown, setCountdown] = useState(0);
|
||||
|
||||
@ -7,10 +7,9 @@ import { Button, PinInput, Stack } from "@mantine/core";
|
||||
import { useForm } from "@mantine/form";
|
||||
import ResendVerificationCode from "@/app/verify-phone/components/ResendVerificationCode/ResendVerificationCode";
|
||||
import style from "@/app/verify-phone/components/VerifyPhoneForm/VerifyPhone.module.css";
|
||||
import { setScope } from "@/lib/features/auth/authSlice";
|
||||
import { Auth } from "@/client";
|
||||
import { notifications } from "@/lib/notifications";
|
||||
import { RootState, useAppDispatch } from "@/lib/store";
|
||||
import { AuthService } from "@/mocks/authService";
|
||||
import { RootState } from "@/lib/store/store";
|
||||
|
||||
type VerifyNumberForm = {
|
||||
code: string;
|
||||
@ -26,33 +25,40 @@ const VerifyPhoneForm: FC = () => {
|
||||
},
|
||||
});
|
||||
const authState = useSelector((state: RootState) => state.auth);
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const handleSubmit = (values: VerifyNumberForm) => {
|
||||
if (!authState.phoneNumber || !authState.loginChallenge) return;
|
||||
|
||||
new AuthService()
|
||||
.approveLogin(
|
||||
authState.phoneNumber,
|
||||
values.code,
|
||||
authState.loginChallenge
|
||||
)
|
||||
.then(response => response.data)
|
||||
.then(({ redirectUrl, scope }) => {
|
||||
dispatch(setScope(scope));
|
||||
window.location.href = redirectUrl;
|
||||
if (!authState.phoneNumber || !authState.loginChallenge) return;
|
||||
console.log(authState.phoneNumber.replace(/ /g, ""));
|
||||
|
||||
Auth.postAuthOtpVerify({
|
||||
body: {
|
||||
phone_number: authState.phoneNumber,
|
||||
login_challenge: authState.loginChallenge,
|
||||
otp: values.code,
|
||||
},
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
notifications.error({ message: error.toString() });
|
||||
.then(response => response.data)
|
||||
.then(response => {
|
||||
if (!response) return;
|
||||
const { redirect_url, ok } = response;
|
||||
if (!ok) {
|
||||
notifications.error({
|
||||
message: "Ошибка при подтверждении номера",
|
||||
});
|
||||
return;
|
||||
}
|
||||
window.location.href = redirect_url;
|
||||
});
|
||||
};
|
||||
|
||||
const navigateToLogin = () => redirect("/");
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack>
|
||||
<form
|
||||
style={{ justifyItems: "center" }}
|
||||
onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack maw={500}>
|
||||
<PinInput
|
||||
length={6}
|
||||
placeholder="_"
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import Logo from "@/components/Logo/Logo";
|
||||
import PageItem from "@/components/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/PageContainer/PageContainer";
|
||||
import VerifyPhoneForm from "@/app/verify-phone/components/VerifyPhoneForm/VerifyPhoneForm";
|
||||
import PageItem from "@/components/layout/PageBlock/PageItem";
|
||||
import PageContainer from "@/components/layout/PageContainer/PageContainer";
|
||||
import Logo from "@/components/ui/Logo/Logo";
|
||||
|
||||
export default function CreateIdPage() {
|
||||
return (
|
||||
|
||||
17
src/client/client.gen.ts
Normal file
17
src/client/client.gen.ts
Normal file
@ -0,0 +1,17 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { ClientOptions } from './types.gen';
|
||||
import { type Config, type ClientOptions as DefaultClientOptions, createClient, createConfig } from './client';
|
||||
import { createClientConfig } from '../hey-api-config';
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
* and the returned object will become the client's initial configuration.
|
||||
*
|
||||
* You may want to initialize your client this way instead of calling
|
||||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends DefaultClientOptions = ClientOptions> = (override?: Config<DefaultClientOptions & T>) => Config<Required<DefaultClientOptions> & T>;
|
||||
|
||||
export const client = createClient(createClientConfig(createConfig<ClientOptions>()));
|
||||
177
src/client/client/client.ts
Normal file
177
src/client/client/client.ts
Normal file
@ -0,0 +1,177 @@
|
||||
import type { Client, Config, RequestOptions } from './types';
|
||||
import {
|
||||
buildUrl,
|
||||
createConfig,
|
||||
createInterceptors,
|
||||
getParseAs,
|
||||
mergeConfigs,
|
||||
mergeHeaders,
|
||||
setAuthParams,
|
||||
} from './utils';
|
||||
|
||||
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
|
||||
body?: any;
|
||||
headers: ReturnType<typeof mergeHeaders>;
|
||||
};
|
||||
|
||||
export const createClient = (config: Config = {}): Client => {
|
||||
let _config = mergeConfigs(createConfig(), config);
|
||||
|
||||
const getConfig = (): Config => ({ ..._config });
|
||||
|
||||
const setConfig = (config: Config): Config => {
|
||||
_config = mergeConfigs(_config, config);
|
||||
return getConfig();
|
||||
};
|
||||
|
||||
const interceptors = createInterceptors<Response, unknown, RequestOptions>();
|
||||
|
||||
// @ts-expect-error
|
||||
const request: Client['request'] = async (options) => {
|
||||
const opts = {
|
||||
..._config,
|
||||
...options,
|
||||
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
||||
headers: mergeHeaders(_config.headers, options.headers),
|
||||
};
|
||||
|
||||
if (opts.security) {
|
||||
await setAuthParams({
|
||||
...opts,
|
||||
security: opts.security,
|
||||
});
|
||||
}
|
||||
|
||||
if (opts.requestValidator) {
|
||||
await opts.requestValidator(opts);
|
||||
}
|
||||
|
||||
if (opts.body && opts.bodySerializer) {
|
||||
opts.body = opts.bodySerializer(opts.body);
|
||||
}
|
||||
|
||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||
if (opts.body === undefined || opts.body === '') {
|
||||
opts.headers.delete('Content-Type');
|
||||
}
|
||||
|
||||
for (const fn of interceptors.request._fns) {
|
||||
if (fn) {
|
||||
await fn(opts);
|
||||
}
|
||||
}
|
||||
|
||||
const url = buildUrl(opts);
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = opts.fetch!;
|
||||
let response = await _fetch(url, {
|
||||
...opts,
|
||||
body: opts.body as ReqInit['body'],
|
||||
});
|
||||
|
||||
for (const fn of interceptors.response._fns) {
|
||||
if (fn) {
|
||||
response = await fn(response, opts);
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
response,
|
||||
};
|
||||
|
||||
if (response.ok) {
|
||||
if (
|
||||
response.status === 204 ||
|
||||
response.headers.get('Content-Length') === '0'
|
||||
) {
|
||||
return {
|
||||
data: {},
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
const parseAs =
|
||||
(opts.parseAs === 'auto'
|
||||
? getParseAs(response.headers.get('Content-Type'))
|
||||
: opts.parseAs) ?? 'json';
|
||||
|
||||
let data: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'formData':
|
||||
case 'json':
|
||||
case 'text':
|
||||
data = await response[parseAs]();
|
||||
break;
|
||||
case 'stream':
|
||||
return {
|
||||
data: response.body,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
if (parseAs === 'json') {
|
||||
if (opts.responseValidator) {
|
||||
await opts.responseValidator(data);
|
||||
}
|
||||
|
||||
if (opts.responseTransformer) {
|
||||
data = await opts.responseTransformer(data);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
const textError = await response.text();
|
||||
let jsonError: unknown;
|
||||
|
||||
try {
|
||||
jsonError = JSON.parse(textError);
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
|
||||
const error = jsonError ?? textError;
|
||||
let finalError = error;
|
||||
|
||||
for (const fn of interceptors.error._fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(error, response, opts)) as string;
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || ({} as string);
|
||||
|
||||
if (opts.throwOnError) {
|
||||
throw finalError;
|
||||
}
|
||||
|
||||
return {
|
||||
error: finalError,
|
||||
...result,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
buildUrl,
|
||||
connect: (options) => request({ ...options, method: 'CONNECT' }),
|
||||
delete: (options) => request({ ...options, method: 'DELETE' }),
|
||||
get: (options) => request({ ...options, method: 'GET' }),
|
||||
getConfig,
|
||||
head: (options) => request({ ...options, method: 'HEAD' }),
|
||||
interceptors,
|
||||
options: (options) => request({ ...options, method: 'OPTIONS' }),
|
||||
patch: (options) => request({ ...options, method: 'PATCH' }),
|
||||
post: (options) => request({ ...options, method: 'POST' }),
|
||||
put: (options) => request({ ...options, method: 'PUT' }),
|
||||
request,
|
||||
setConfig,
|
||||
trace: (options) => request({ ...options, method: 'TRACE' }),
|
||||
};
|
||||
};
|
||||
21
src/client/client/index.ts
Normal file
21
src/client/client/index.ts
Normal file
@ -0,0 +1,21 @@
|
||||
export type { Auth } from '../core/auth';
|
||||
export type { QuerySerializerOptions } from '../core/bodySerializer';
|
||||
export {
|
||||
formDataBodySerializer,
|
||||
jsonBodySerializer,
|
||||
urlSearchParamsBodySerializer,
|
||||
} from '../core/bodySerializer';
|
||||
export { buildClientParams } from '../core/params';
|
||||
export { createClient } from './client';
|
||||
export type {
|
||||
Client,
|
||||
ClientOptions,
|
||||
Config,
|
||||
CreateClientConfig,
|
||||
Options,
|
||||
OptionsLegacyParser,
|
||||
RequestOptions,
|
||||
RequestResult,
|
||||
TDataShape,
|
||||
} from './types';
|
||||
export { createConfig } from './utils';
|
||||
173
src/client/client/types.ts
Normal file
173
src/client/client/types.ts
Normal file
@ -0,0 +1,173 @@
|
||||
import type { Auth } from '../core/auth';
|
||||
import type {
|
||||
Client as CoreClient,
|
||||
Config as CoreConfig,
|
||||
} from '../core/types';
|
||||
import type { Middleware } from './utils';
|
||||
|
||||
export interface Config<T extends ClientOptions = ClientOptions>
|
||||
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
|
||||
CoreConfig {
|
||||
/**
|
||||
* Base URL for all requests made by this client.
|
||||
*/
|
||||
baseUrl?: T['baseUrl'];
|
||||
/**
|
||||
* Fetch API implementation. You can use this option to provide a custom
|
||||
* fetch instance.
|
||||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
/**
|
||||
* Return the response data parsed in a specified format. By default, `auto`
|
||||
* will infer the appropriate method from the `Content-Type` response header.
|
||||
* You can override this behavior with any of the {@link Body} methods.
|
||||
* Select `stream` if you don't want to parse response data at all.
|
||||
*
|
||||
* @default 'auto'
|
||||
*/
|
||||
parseAs?:
|
||||
| 'arrayBuffer'
|
||||
| 'auto'
|
||||
| 'blob'
|
||||
| 'formData'
|
||||
| 'json'
|
||||
| 'stream'
|
||||
| 'text';
|
||||
/**
|
||||
* Throw an error instead of returning it in the response?
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
throwOnError?: T['throwOnError'];
|
||||
}
|
||||
|
||||
export interface RequestOptions<
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends Config<{
|
||||
throwOnError: ThrowOnError;
|
||||
}> {
|
||||
/**
|
||||
* Any body that you want to add to your request.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
|
||||
*/
|
||||
body?: unknown;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
/**
|
||||
* Security mechanism(s) to use for the request.
|
||||
*/
|
||||
security?: ReadonlyArray<Auth>;
|
||||
url: Url;
|
||||
}
|
||||
|
||||
export type RequestResult<
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
> = ThrowOnError extends true
|
||||
? Promise<{
|
||||
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
|
||||
response: Response;
|
||||
}>
|
||||
: Promise<
|
||||
(
|
||||
| {
|
||||
data: TData extends Record<string, unknown>
|
||||
? TData[keyof TData]
|
||||
: TData;
|
||||
error: undefined;
|
||||
}
|
||||
| {
|
||||
data: undefined;
|
||||
error: TError extends Record<string, unknown>
|
||||
? TError[keyof TError]
|
||||
: TError;
|
||||
}
|
||||
) & {
|
||||
response: Response;
|
||||
}
|
||||
>;
|
||||
|
||||
export interface ClientOptions {
|
||||
baseUrl?: string;
|
||||
throwOnError?: boolean;
|
||||
}
|
||||
|
||||
type MethodFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
>(
|
||||
options: Omit<RequestOptions<ThrowOnError>, 'method'>,
|
||||
) => RequestResult<TData, TError, ThrowOnError>;
|
||||
|
||||
type RequestFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
>(
|
||||
options: Omit<RequestOptions<ThrowOnError>, 'method'> &
|
||||
Pick<Required<RequestOptions<ThrowOnError>>, 'method'>,
|
||||
) => RequestResult<TData, TError, ThrowOnError>;
|
||||
|
||||
type BuildUrlFn = <
|
||||
TData extends {
|
||||
body?: unknown;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
url: string;
|
||||
},
|
||||
>(
|
||||
options: Pick<TData, 'url'> & Options<TData>,
|
||||
) => string;
|
||||
|
||||
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
|
||||
interceptors: Middleware<Response, unknown, RequestOptions>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
* and the returned object will become the client's initial configuration.
|
||||
*
|
||||
* You may want to initialize your client this way instead of calling
|
||||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
|
||||
override?: Config<ClientOptions & T>,
|
||||
) => Config<Required<ClientOptions> & T>;
|
||||
|
||||
export interface TDataShape {
|
||||
body?: unknown;
|
||||
headers?: unknown;
|
||||
path?: unknown;
|
||||
query?: unknown;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
|
||||
|
||||
export type Options<
|
||||
TData extends TDataShape = TDataShape,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
> = OmitKeys<RequestOptions<ThrowOnError>, 'body' | 'path' | 'query' | 'url'> &
|
||||
Omit<TData, 'url'>;
|
||||
|
||||
export type OptionsLegacyParser<
|
||||
TData = unknown,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
> = TData extends { body?: any }
|
||||
? TData extends { headers?: any }
|
||||
? OmitKeys<RequestOptions<ThrowOnError>, 'body' | 'headers' | 'url'> & TData
|
||||
: OmitKeys<RequestOptions<ThrowOnError>, 'body' | 'url'> &
|
||||
TData &
|
||||
Pick<RequestOptions<ThrowOnError>, 'headers'>
|
||||
: TData extends { headers?: any }
|
||||
? OmitKeys<RequestOptions<ThrowOnError>, 'headers' | 'url'> &
|
||||
TData &
|
||||
Pick<RequestOptions<ThrowOnError>, 'body'>
|
||||
: OmitKeys<RequestOptions<ThrowOnError>, 'url'> & TData;
|
||||
406
src/client/client/utils.ts
Normal file
406
src/client/client/utils.ts
Normal file
@ -0,0 +1,406 @@
|
||||
import { getAuthToken } from '../core/auth';
|
||||
import type {
|
||||
QuerySerializer,
|
||||
QuerySerializerOptions,
|
||||
} from '../core/bodySerializer';
|
||||
import { jsonBodySerializer } from '../core/bodySerializer';
|
||||
import {
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from '../core/pathSerializer';
|
||||
import type { Client, ClientOptions, Config, RequestOptions } from './types';
|
||||
|
||||
interface PathSerializer {
|
||||
path: Record<string, unknown>;
|
||||
url: string;
|
||||
}
|
||||
|
||||
const PATH_PARAM_RE = /\{[^{}]+\}/g;
|
||||
|
||||
type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
|
||||
type MatrixStyle = 'label' | 'matrix' | 'simple';
|
||||
type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
|
||||
|
||||
const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
||||
let url = _url;
|
||||
const matches = _url.match(PATH_PARAM_RE);
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
let explode = false;
|
||||
let name = match.substring(1, match.length - 1);
|
||||
let style: ArraySeparatorStyle = 'simple';
|
||||
|
||||
if (name.endsWith('*')) {
|
||||
explode = true;
|
||||
name = name.substring(0, name.length - 1);
|
||||
}
|
||||
|
||||
if (name.startsWith('.')) {
|
||||
name = name.substring(1);
|
||||
style = 'label';
|
||||
} else if (name.startsWith(';')) {
|
||||
name = name.substring(1);
|
||||
style = 'matrix';
|
||||
}
|
||||
|
||||
const value = path[name];
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeArrayParam({ explode, name, style, value }),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeObjectParam({
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value: value as Record<string, unknown>,
|
||||
valueOnly: true,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (style === 'matrix') {
|
||||
url = url.replace(
|
||||
match,
|
||||
`;${serializePrimitiveParam({
|
||||
name,
|
||||
value: value as string,
|
||||
})}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const replaceValue = encodeURIComponent(
|
||||
style === 'label' ? `.${value as string}` : (value as string),
|
||||
);
|
||||
url = url.replace(match, replaceValue);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
export const createQuerySerializer = <T = unknown>({
|
||||
allowReserved,
|
||||
array,
|
||||
object,
|
||||
}: QuerySerializerOptions = {}) => {
|
||||
const querySerializer = (queryParams: T) => {
|
||||
const search: string[] = [];
|
||||
if (queryParams && typeof queryParams === 'object') {
|
||||
for (const name in queryParams) {
|
||||
const value = queryParams[name];
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const serializedArray = serializeArrayParam({
|
||||
allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: 'form',
|
||||
value,
|
||||
...array,
|
||||
});
|
||||
if (serializedArray) search.push(serializedArray);
|
||||
} else if (typeof value === 'object') {
|
||||
const serializedObject = serializeObjectParam({
|
||||
allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: 'deepObject',
|
||||
value: value as Record<string, unknown>,
|
||||
...object,
|
||||
});
|
||||
if (serializedObject) search.push(serializedObject);
|
||||
} else {
|
||||
const serializedPrimitive = serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name,
|
||||
value: value as string,
|
||||
});
|
||||
if (serializedPrimitive) search.push(serializedPrimitive);
|
||||
}
|
||||
}
|
||||
}
|
||||
return search.join('&');
|
||||
};
|
||||
return querySerializer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Infers parseAs value from provided Content-Type header.
|
||||
*/
|
||||
export const getParseAs = (
|
||||
contentType: string | null,
|
||||
): Exclude<Config['parseAs'], 'auto'> => {
|
||||
if (!contentType) {
|
||||
// If no Content-Type header is provided, the best we can do is return the raw response body,
|
||||
// which is effectively the same as the 'stream' option.
|
||||
return 'stream';
|
||||
}
|
||||
|
||||
const cleanContent = contentType.split(';')[0]?.trim();
|
||||
|
||||
if (!cleanContent) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
cleanContent.startsWith('application/json') ||
|
||||
cleanContent.endsWith('+json')
|
||||
) {
|
||||
return 'json';
|
||||
}
|
||||
|
||||
if (cleanContent === 'multipart/form-data') {
|
||||
return 'formData';
|
||||
}
|
||||
|
||||
if (
|
||||
['application/', 'audio/', 'image/', 'video/'].some((type) =>
|
||||
cleanContent.startsWith(type),
|
||||
)
|
||||
) {
|
||||
return 'blob';
|
||||
}
|
||||
|
||||
if (cleanContent.startsWith('text/')) {
|
||||
return 'text';
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
export const setAuthParams = async ({
|
||||
security,
|
||||
...options
|
||||
}: Pick<Required<RequestOptions>, 'security'> &
|
||||
Pick<RequestOptions, 'auth' | 'query'> & {
|
||||
headers: Headers;
|
||||
}) => {
|
||||
for (const auth of security) {
|
||||
const token = await getAuthToken(auth, options.auth);
|
||||
|
||||
if (!token) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = auth.name ?? 'Authorization';
|
||||
|
||||
switch (auth.in) {
|
||||
case 'query':
|
||||
if (!options.query) {
|
||||
options.query = {};
|
||||
}
|
||||
options.query[name] = token;
|
||||
break;
|
||||
case 'cookie':
|
||||
options.headers.append('Cookie', `${name}=${token}`);
|
||||
break;
|
||||
case 'header':
|
||||
default:
|
||||
options.headers.set(name, token);
|
||||
break;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
export const buildUrl: Client['buildUrl'] = (options) => {
|
||||
const url = getUrl({
|
||||
baseUrl: options.baseUrl as string,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
querySerializer:
|
||||
typeof options.querySerializer === 'function'
|
||||
? options.querySerializer
|
||||
: createQuerySerializer(options.querySerializer),
|
||||
url: options.url,
|
||||
});
|
||||
return url;
|
||||
};
|
||||
|
||||
export const getUrl = ({
|
||||
baseUrl,
|
||||
path,
|
||||
query,
|
||||
querySerializer,
|
||||
url: _url,
|
||||
}: {
|
||||
baseUrl?: string;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
querySerializer: QuerySerializer;
|
||||
url: string;
|
||||
}) => {
|
||||
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
|
||||
let url = (baseUrl ?? '') + pathUrl;
|
||||
if (path) {
|
||||
url = defaultPathSerializer({ path, url });
|
||||
}
|
||||
let search = query ? querySerializer(query) : '';
|
||||
if (search.startsWith('?')) {
|
||||
search = search.substring(1);
|
||||
}
|
||||
if (search) {
|
||||
url += `?${search}`;
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
export const mergeConfigs = (a: Config, b: Config): Config => {
|
||||
const config = { ...a, ...b };
|
||||
if (config.baseUrl?.endsWith('/')) {
|
||||
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
|
||||
}
|
||||
config.headers = mergeHeaders(a.headers, b.headers);
|
||||
return config;
|
||||
};
|
||||
|
||||
export const mergeHeaders = (
|
||||
...headers: Array<Required<Config>['headers'] | undefined>
|
||||
): Headers => {
|
||||
const mergedHeaders = new Headers();
|
||||
for (const header of headers) {
|
||||
if (!header || typeof header !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const iterator =
|
||||
header instanceof Headers ? header.entries() : Object.entries(header);
|
||||
|
||||
for (const [key, value] of iterator) {
|
||||
if (value === null) {
|
||||
mergedHeaders.delete(key);
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const v of value) {
|
||||
mergedHeaders.append(key, v as string);
|
||||
}
|
||||
} else if (value !== undefined) {
|
||||
// assume object headers are meant to be JSON stringified, i.e. their
|
||||
// content value in OpenAPI specification is 'application/json'
|
||||
mergedHeaders.set(
|
||||
key,
|
||||
typeof value === 'object' ? JSON.stringify(value) : (value as string),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return mergedHeaders;
|
||||
};
|
||||
|
||||
type ErrInterceptor<Err, Res, Options> = (
|
||||
error: Err,
|
||||
response: Res,
|
||||
options: Options,
|
||||
) => Err | Promise<Err>;
|
||||
|
||||
type ReqInterceptor<Options> = (options: Options) => void | Promise<void>;
|
||||
|
||||
type ResInterceptor<Res, Options> = (
|
||||
response: Res,
|
||||
options: Options,
|
||||
) => Res | Promise<Res>;
|
||||
|
||||
class Interceptors<Interceptor> {
|
||||
_fns: (Interceptor | null)[];
|
||||
|
||||
constructor() {
|
||||
this._fns = [];
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._fns = [];
|
||||
}
|
||||
|
||||
getInterceptorIndex(id: number | Interceptor): number {
|
||||
if (typeof id === 'number') {
|
||||
return this._fns[id] ? id : -1;
|
||||
} else {
|
||||
return this._fns.indexOf(id);
|
||||
}
|
||||
}
|
||||
exists(id: number | Interceptor) {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
return !!this._fns[index];
|
||||
}
|
||||
|
||||
eject(id: number | Interceptor) {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
if (this._fns[index]) {
|
||||
this._fns[index] = null;
|
||||
}
|
||||
}
|
||||
|
||||
update(id: number | Interceptor, fn: Interceptor) {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
if (this._fns[index]) {
|
||||
this._fns[index] = fn;
|
||||
return id;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
use(fn: Interceptor) {
|
||||
this._fns = [...this._fns, fn];
|
||||
return this._fns.length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// `createInterceptors()` response, meant for external use as it does not
|
||||
// expose internals
|
||||
export interface Middleware<Res, Err, Options> {
|
||||
error: Pick<Interceptors<ErrInterceptor<Err, Res, Options>>, 'eject' | 'use'>;
|
||||
request: Pick<Interceptors<ReqInterceptor<Options>>, 'eject' | 'use'>;
|
||||
response: Pick<Interceptors<ResInterceptor<Res, Options>>, 'eject' | 'use'>;
|
||||
}
|
||||
|
||||
// do not add `Middleware` as return type so we can use _fns internally
|
||||
export const createInterceptors = <Res, Err, Options>() => ({
|
||||
error: new Interceptors<ErrInterceptor<Err, Res, Options>>(),
|
||||
request: new Interceptors<ReqInterceptor<Options>>(),
|
||||
response: new Interceptors<ResInterceptor<Res, Options>>(),
|
||||
});
|
||||
|
||||
const defaultQuerySerializer = createQuerySerializer({
|
||||
allowReserved: false,
|
||||
array: {
|
||||
explode: true,
|
||||
style: 'form',
|
||||
},
|
||||
object: {
|
||||
explode: true,
|
||||
style: 'deepObject',
|
||||
},
|
||||
});
|
||||
|
||||
const defaultHeaders = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
export const createConfig = <T extends ClientOptions = ClientOptions>(
|
||||
override: Config<Omit<ClientOptions, keyof T> & T> = {},
|
||||
): Config<Omit<ClientOptions, keyof T> & T> => ({
|
||||
...jsonBodySerializer,
|
||||
headers: defaultHeaders,
|
||||
parseAs: 'auto',
|
||||
querySerializer: defaultQuerySerializer,
|
||||
...override,
|
||||
});
|
||||
40
src/client/core/auth.ts
Normal file
40
src/client/core/auth.ts
Normal file
@ -0,0 +1,40 @@
|
||||
export type AuthToken = string | undefined;
|
||||
|
||||
export interface Auth {
|
||||
/**
|
||||
* Which part of the request do we use to send the auth?
|
||||
*
|
||||
* @default 'header'
|
||||
*/
|
||||
in?: 'header' | 'query' | 'cookie';
|
||||
/**
|
||||
* Header or query parameter name.
|
||||
*
|
||||
* @default 'Authorization'
|
||||
*/
|
||||
name?: string;
|
||||
scheme?: 'basic' | 'bearer';
|
||||
type: 'apiKey' | 'http';
|
||||
}
|
||||
|
||||
export const getAuthToken = async (
|
||||
auth: Auth,
|
||||
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
|
||||
): Promise<string | undefined> => {
|
||||
const token =
|
||||
typeof callback === 'function' ? await callback(auth) : callback;
|
||||
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (auth.scheme === 'bearer') {
|
||||
return `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (auth.scheme === 'basic') {
|
||||
return `Basic ${btoa(token)}`;
|
||||
}
|
||||
|
||||
return token;
|
||||
};
|
||||
88
src/client/core/bodySerializer.ts
Normal file
88
src/client/core/bodySerializer.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import type {
|
||||
ArrayStyle,
|
||||
ObjectStyle,
|
||||
SerializerOptions,
|
||||
} from './pathSerializer';
|
||||
|
||||
export type QuerySerializer = (query: Record<string, unknown>) => string;
|
||||
|
||||
export type BodySerializer = (body: any) => any;
|
||||
|
||||
export interface QuerySerializerOptions {
|
||||
allowReserved?: boolean;
|
||||
array?: SerializerOptions<ArrayStyle>;
|
||||
object?: SerializerOptions<ObjectStyle>;
|
||||
}
|
||||
|
||||
const serializeFormDataPair = (
|
||||
data: FormData,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (typeof value === 'string' || value instanceof Blob) {
|
||||
data.append(key, value);
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
const serializeUrlSearchParamsPair = (
|
||||
data: URLSearchParams,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (typeof value === 'string') {
|
||||
data.append(key, value);
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
export const formDataBodySerializer = {
|
||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
||||
body: T,
|
||||
): FormData => {
|
||||
const data = new FormData();
|
||||
|
||||
Object.entries(body).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => serializeFormDataPair(data, key, v));
|
||||
} else {
|
||||
serializeFormDataPair(data, key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
export const jsonBodySerializer = {
|
||||
bodySerializer: <T>(body: T): string =>
|
||||
JSON.stringify(body, (_key, value) =>
|
||||
typeof value === 'bigint' ? value.toString() : value,
|
||||
),
|
||||
};
|
||||
|
||||
export const urlSearchParamsBodySerializer = {
|
||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
||||
body: T,
|
||||
): string => {
|
||||
const data = new URLSearchParams();
|
||||
|
||||
Object.entries(body).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
|
||||
} else {
|
||||
serializeUrlSearchParamsPair(data, key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return data.toString();
|
||||
},
|
||||
};
|
||||
151
src/client/core/params.ts
Normal file
151
src/client/core/params.ts
Normal file
@ -0,0 +1,151 @@
|
||||
type Slot = 'body' | 'headers' | 'path' | 'query';
|
||||
|
||||
export type Field =
|
||||
| {
|
||||
in: Exclude<Slot, 'body'>;
|
||||
/**
|
||||
* Field name. This is the name we want the user to see and use.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Field mapped name. This is the name we want to use in the request.
|
||||
* If omitted, we use the same value as `key`.
|
||||
*/
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
in: Extract<Slot, 'body'>;
|
||||
/**
|
||||
* Key isn't required for bodies.
|
||||
*/
|
||||
key?: string;
|
||||
map?: string;
|
||||
};
|
||||
|
||||
export interface Fields {
|
||||
allowExtra?: Partial<Record<Slot, boolean>>;
|
||||
args?: ReadonlyArray<Field>;
|
||||
}
|
||||
|
||||
export type FieldsConfig = ReadonlyArray<Field | Fields>;
|
||||
|
||||
const extraPrefixesMap: Record<string, Slot> = {
|
||||
$body_: 'body',
|
||||
$headers_: 'headers',
|
||||
$path_: 'path',
|
||||
$query_: 'query',
|
||||
};
|
||||
const extraPrefixes = Object.entries(extraPrefixesMap);
|
||||
|
||||
type KeyMap = Map<
|
||||
string,
|
||||
{
|
||||
in: Slot;
|
||||
map?: string;
|
||||
}
|
||||
>;
|
||||
|
||||
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
}
|
||||
|
||||
for (const config of fields) {
|
||||
if ('in' in config) {
|
||||
if (config.key) {
|
||||
map.set(config.key, {
|
||||
in: config.in,
|
||||
map: config.map,
|
||||
});
|
||||
}
|
||||
} else if (config.args) {
|
||||
buildKeyMap(config.args, map);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
};
|
||||
|
||||
interface Params {
|
||||
body: unknown;
|
||||
headers: Record<string, unknown>;
|
||||
path: Record<string, unknown>;
|
||||
query: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const stripEmptySlots = (params: Params) => {
|
||||
for (const [slot, value] of Object.entries(params)) {
|
||||
if (value && typeof value === 'object' && !Object.keys(value).length) {
|
||||
delete params[slot as Slot];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const buildClientParams = (
|
||||
args: ReadonlyArray<unknown>,
|
||||
fields: FieldsConfig,
|
||||
) => {
|
||||
const params: Params = {
|
||||
body: {},
|
||||
headers: {},
|
||||
path: {},
|
||||
query: {},
|
||||
};
|
||||
|
||||
const map = buildKeyMap(fields);
|
||||
|
||||
let config: FieldsConfig[number] | undefined;
|
||||
|
||||
for (const [index, arg] of args.entries()) {
|
||||
if (fields[index]) {
|
||||
config = fields[index];
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('in' in config) {
|
||||
if (config.key) {
|
||||
const field = map.get(config.key)!;
|
||||
const name = field.map || config.key;
|
||||
(params[field.in] as Record<string, unknown>)[name] = arg;
|
||||
} else {
|
||||
params.body = arg;
|
||||
}
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(arg ?? {})) {
|
||||
const field = map.get(key);
|
||||
|
||||
if (field) {
|
||||
const name = field.map || key;
|
||||
(params[field.in] as Record<string, unknown>)[name] = value;
|
||||
} else {
|
||||
const extra = extraPrefixes.find(([prefix]) =>
|
||||
key.startsWith(prefix),
|
||||
);
|
||||
|
||||
if (extra) {
|
||||
const [prefix, slot] = extra;
|
||||
(params[slot] as Record<string, unknown>)[
|
||||
key.slice(prefix.length)
|
||||
] = value;
|
||||
} else {
|
||||
for (const [slot, allowed] of Object.entries(
|
||||
config.allowExtra ?? {},
|
||||
)) {
|
||||
if (allowed) {
|
||||
(params[slot as Slot] as Record<string, unknown>)[key] = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stripEmptySlots(params);
|
||||
|
||||
return params;
|
||||
};
|
||||
179
src/client/core/pathSerializer.ts
Normal file
179
src/client/core/pathSerializer.ts
Normal file
@ -0,0 +1,179 @@
|
||||
interface SerializeOptions<T>
|
||||
extends SerializePrimitiveOptions,
|
||||
SerializerOptions<T> {}
|
||||
|
||||
interface SerializePrimitiveOptions {
|
||||
allowReserved?: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface SerializerOptions<T> {
|
||||
/**
|
||||
* @default true
|
||||
*/
|
||||
explode: boolean;
|
||||
style: T;
|
||||
}
|
||||
|
||||
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
|
||||
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
|
||||
type MatrixStyle = 'label' | 'matrix' | 'simple';
|
||||
export type ObjectStyle = 'form' | 'deepObject';
|
||||
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
|
||||
|
||||
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return '.';
|
||||
case 'matrix':
|
||||
return ';';
|
||||
case 'simple':
|
||||
return ',';
|
||||
default:
|
||||
return '&';
|
||||
}
|
||||
};
|
||||
|
||||
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
|
||||
switch (style) {
|
||||
case 'form':
|
||||
return ',';
|
||||
case 'pipeDelimited':
|
||||
return '|';
|
||||
case 'spaceDelimited':
|
||||
return '%20';
|
||||
default:
|
||||
return ',';
|
||||
}
|
||||
};
|
||||
|
||||
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return '.';
|
||||
case 'matrix':
|
||||
return ';';
|
||||
case 'simple':
|
||||
return ',';
|
||||
default:
|
||||
return '&';
|
||||
}
|
||||
};
|
||||
|
||||
export const serializeArrayParam = ({
|
||||
allowReserved,
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value,
|
||||
}: SerializeOptions<ArraySeparatorStyle> & {
|
||||
value: unknown[];
|
||||
}) => {
|
||||
if (!explode) {
|
||||
const joinedValues = (
|
||||
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
|
||||
).join(separatorArrayNoExplode(style));
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return `.${joinedValues}`;
|
||||
case 'matrix':
|
||||
return `;${name}=${joinedValues}`;
|
||||
case 'simple':
|
||||
return joinedValues;
|
||||
default:
|
||||
return `${name}=${joinedValues}`;
|
||||
}
|
||||
}
|
||||
|
||||
const separator = separatorArrayExplode(style);
|
||||
const joinedValues = value
|
||||
.map((v) => {
|
||||
if (style === 'label' || style === 'simple') {
|
||||
return allowReserved ? v : encodeURIComponent(v as string);
|
||||
}
|
||||
|
||||
return serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name,
|
||||
value: v as string,
|
||||
});
|
||||
})
|
||||
.join(separator);
|
||||
return style === 'label' || style === 'matrix'
|
||||
? separator + joinedValues
|
||||
: joinedValues;
|
||||
};
|
||||
|
||||
export const serializePrimitiveParam = ({
|
||||
allowReserved,
|
||||
name,
|
||||
value,
|
||||
}: SerializePrimitiveParam) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
throw new Error(
|
||||
'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
|
||||
);
|
||||
}
|
||||
|
||||
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
|
||||
};
|
||||
|
||||
export const serializeObjectParam = ({
|
||||
allowReserved,
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value,
|
||||
valueOnly,
|
||||
}: SerializeOptions<ObjectSeparatorStyle> & {
|
||||
value: Record<string, unknown> | Date;
|
||||
valueOnly?: boolean;
|
||||
}) => {
|
||||
if (value instanceof Date) {
|
||||
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
|
||||
}
|
||||
|
||||
if (style !== 'deepObject' && !explode) {
|
||||
let values: string[] = [];
|
||||
Object.entries(value).forEach(([key, v]) => {
|
||||
values = [
|
||||
...values,
|
||||
key,
|
||||
allowReserved ? (v as string) : encodeURIComponent(v as string),
|
||||
];
|
||||
});
|
||||
const joinedValues = values.join(',');
|
||||
switch (style) {
|
||||
case 'form':
|
||||
return `${name}=${joinedValues}`;
|
||||
case 'label':
|
||||
return `.${joinedValues}`;
|
||||
case 'matrix':
|
||||
return `;${name}=${joinedValues}`;
|
||||
default:
|
||||
return joinedValues;
|
||||
}
|
||||
}
|
||||
|
||||
const separator = separatorObjectExplode(style);
|
||||
const joinedValues = Object.entries(value)
|
||||
.map(([key, v]) =>
|
||||
serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name: style === 'deepObject' ? `${name}[${key}]` : key,
|
||||
value: v as string,
|
||||
}),
|
||||
)
|
||||
.join(separator);
|
||||
return style === 'label' || style === 'matrix'
|
||||
? separator + joinedValues
|
||||
: joinedValues;
|
||||
};
|
||||
118
src/client/core/types.ts
Normal file
118
src/client/core/types.ts
Normal file
@ -0,0 +1,118 @@
|
||||
import type { Auth, AuthToken } from './auth';
|
||||
import type {
|
||||
BodySerializer,
|
||||
QuerySerializer,
|
||||
QuerySerializerOptions,
|
||||
} from './bodySerializer';
|
||||
|
||||
export interface Client<
|
||||
RequestFn = never,
|
||||
Config = unknown,
|
||||
MethodFn = never,
|
||||
BuildUrlFn = never,
|
||||
> {
|
||||
/**
|
||||
* Returns the final request URL.
|
||||
*/
|
||||
buildUrl: BuildUrlFn;
|
||||
connect: MethodFn;
|
||||
delete: MethodFn;
|
||||
get: MethodFn;
|
||||
getConfig: () => Config;
|
||||
head: MethodFn;
|
||||
options: MethodFn;
|
||||
patch: MethodFn;
|
||||
post: MethodFn;
|
||||
put: MethodFn;
|
||||
request: RequestFn;
|
||||
setConfig: (config: Config) => Config;
|
||||
trace: MethodFn;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
/**
|
||||
* Auth token or a function returning auth token. The resolved value will be
|
||||
* added to the request payload as defined by its `security` array.
|
||||
*/
|
||||
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
|
||||
/**
|
||||
* A function for serializing request body parameter. By default,
|
||||
* {@link JSON.stringify()} will be used.
|
||||
*/
|
||||
bodySerializer?: BodySerializer | null;
|
||||
/**
|
||||
* An object containing any HTTP headers that you want to pre-populate your
|
||||
* `Headers` object with.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
|
||||
*/
|
||||
headers?:
|
||||
| RequestInit['headers']
|
||||
| Record<
|
||||
string,
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| (string | number | boolean)[]
|
||||
| null
|
||||
| undefined
|
||||
| unknown
|
||||
>;
|
||||
/**
|
||||
* The request method.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
|
||||
*/
|
||||
method?:
|
||||
| 'CONNECT'
|
||||
| 'DELETE'
|
||||
| 'GET'
|
||||
| 'HEAD'
|
||||
| 'OPTIONS'
|
||||
| 'PATCH'
|
||||
| 'POST'
|
||||
| 'PUT'
|
||||
| 'TRACE';
|
||||
/**
|
||||
* A function for serializing request query parameters. By default, arrays
|
||||
* will be exploded in form style, objects will be exploded in deepObject
|
||||
* style, and reserved characters are percent-encoded.
|
||||
*
|
||||
* This method will have no effect if the native `paramsSerializer()` Axios
|
||||
* API function is used.
|
||||
*
|
||||
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
|
||||
*/
|
||||
querySerializer?: QuerySerializer | QuerySerializerOptions;
|
||||
/**
|
||||
* A function validating request data. This is useful if you want to ensure
|
||||
* the request conforms to the desired shape, so it can be safely sent to
|
||||
* the server.
|
||||
*/
|
||||
requestValidator?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function transforming response data before it's returned. This is useful
|
||||
* for post-processing data, e.g. converting ISO strings into Date objects.
|
||||
*/
|
||||
responseTransformer?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function validating response data. This is useful if you want to ensure
|
||||
* the response conforms to the desired shape, so it can be safely passed to
|
||||
* the transformers and returned to the user.
|
||||
*/
|
||||
responseValidator?: (data: unknown) => Promise<unknown>;
|
||||
}
|
||||
|
||||
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
|
||||
? true
|
||||
: [T] extends [never | undefined]
|
||||
? [undefined] extends [T]
|
||||
? false
|
||||
: true
|
||||
: false;
|
||||
|
||||
export type OmitNever<T extends Record<string, unknown>> = {
|
||||
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true
|
||||
? never
|
||||
: K]: T[K];
|
||||
};
|
||||
3
src/client/index.ts
Normal file
3
src/client/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
export * from './types.gen';
|
||||
export * from './sdk.gen';
|
||||
82
src/client/sdk.gen.ts
Normal file
82
src/client/sdk.gen.ts
Normal file
@ -0,0 +1,82 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Options as ClientOptions, TDataShape, Client } from './client';
|
||||
import type { PostAuthOtpRequestData, PostAuthOtpRequestResponses, PostAuthOtpRequestErrors, PostAuthOtpVerifyData, PostAuthOtpVerifyResponses, PostAuthOtpVerifyErrors, PostAuthConsentAcceptData, PostAuthConsentAcceptResponses, PostAuthConsentAcceptErrors } from './types.gen';
|
||||
import { zPostAuthOtpRequestData, zPostAuthOtpRequestResponse, zPostAuthOtpVerifyData, zPostAuthOtpVerifyResponse, zPostAuthConsentAcceptData, zPostAuthConsentAcceptResponse } from './zod.gen';
|
||||
import { client as _heyApiClient } from './client.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<TData, ThrowOnError> & {
|
||||
/**
|
||||
* You can provide a client instance returned by `createClient()` instead of
|
||||
* individual options. This might be also useful if you want to implement a
|
||||
* custom client.
|
||||
*/
|
||||
client?: Client;
|
||||
/**
|
||||
* You can pass arbitrary values through the `meta` object. This can be
|
||||
* used to access values that aren't defined as part of the SDK function.
|
||||
*/
|
||||
meta?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export class Auth {
|
||||
/**
|
||||
* Request OTP
|
||||
*/
|
||||
public static postAuthOtpRequest<ThrowOnError extends boolean = false>(options: Options<PostAuthOtpRequestData, ThrowOnError>) {
|
||||
return (options.client ?? _heyApiClient).post<PostAuthOtpRequestResponses, PostAuthOtpRequestErrors, ThrowOnError>({
|
||||
requestValidator: async (data) => {
|
||||
return await zPostAuthOtpRequestData.parseAsync(data);
|
||||
},
|
||||
responseValidator: async (data) => {
|
||||
return await zPostAuthOtpRequestResponse.parseAsync(data);
|
||||
},
|
||||
url: '/auth/otp/request',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify OTP
|
||||
*/
|
||||
public static postAuthOtpVerify<ThrowOnError extends boolean = false>(options: Options<PostAuthOtpVerifyData, ThrowOnError>) {
|
||||
return (options.client ?? _heyApiClient).post<PostAuthOtpVerifyResponses, PostAuthOtpVerifyErrors, ThrowOnError>({
|
||||
requestValidator: async (data) => {
|
||||
return await zPostAuthOtpVerifyData.parseAsync(data);
|
||||
},
|
||||
responseValidator: async (data) => {
|
||||
return await zPostAuthOtpVerifyResponse.parseAsync(data);
|
||||
},
|
||||
url: '/auth/otp/verify',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept consent
|
||||
*/
|
||||
public static postAuthConsentAccept<ThrowOnError extends boolean = false>(options: Options<PostAuthConsentAcceptData, ThrowOnError>) {
|
||||
return (options.client ?? _heyApiClient).post<PostAuthConsentAcceptResponses, PostAuthConsentAcceptErrors, ThrowOnError>({
|
||||
requestValidator: async (data) => {
|
||||
return await zPostAuthConsentAcceptData.parseAsync(data);
|
||||
},
|
||||
responseValidator: async (data) => {
|
||||
return await zPostAuthConsentAcceptResponse.parseAsync(data);
|
||||
},
|
||||
url: '/auth/consent/accept',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
151
src/client/types.gen.ts
Normal file
151
src/client/types.gen.ts
Normal file
@ -0,0 +1,151 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type RequestOtpRequest = {
|
||||
/**
|
||||
* Phone number to send OTP to
|
||||
*/
|
||||
phone_number: string;
|
||||
};
|
||||
|
||||
export type RequestOtpResponse = {
|
||||
/**
|
||||
* Confirmation message
|
||||
*/
|
||||
message: string;
|
||||
/**
|
||||
* Status of the request
|
||||
*/
|
||||
ok: boolean;
|
||||
};
|
||||
|
||||
export type VerifyOtpRequest = {
|
||||
/**
|
||||
* Phone number to verify OTP for
|
||||
*/
|
||||
phone_number: string;
|
||||
/**
|
||||
* One-time password to verify
|
||||
*/
|
||||
otp: string;
|
||||
/**
|
||||
* Login challenge for verification
|
||||
*/
|
||||
login_challenge: string;
|
||||
};
|
||||
|
||||
export type VerifyOtpResponse = {
|
||||
/**
|
||||
* URL to redirect to after successful verification
|
||||
*/
|
||||
redirect_url: string;
|
||||
/**
|
||||
* Status of the verification
|
||||
*/
|
||||
ok: boolean;
|
||||
/**
|
||||
* Confirmation message
|
||||
*/
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type AcceptConsentRequest = {
|
||||
/**
|
||||
* The consent challenge to accept
|
||||
*/
|
||||
consent_challenge: string;
|
||||
/**
|
||||
* Phone number associated with the consent
|
||||
*/
|
||||
phone_number: string;
|
||||
};
|
||||
|
||||
export type AcceptConsentResponse = {
|
||||
/**
|
||||
* URL to redirect to after accepting consent
|
||||
*/
|
||||
redirect_url: string;
|
||||
/**
|
||||
* Status of the consent acceptance
|
||||
*/
|
||||
ok: boolean;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type PostAuthOtpRequestData = {
|
||||
body: RequestOtpRequest;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/auth/otp/request';
|
||||
};
|
||||
|
||||
export type PostAuthOtpRequestErrors = {
|
||||
/**
|
||||
* Bad request
|
||||
*/
|
||||
400: RequestOtpResponse;
|
||||
};
|
||||
|
||||
export type PostAuthOtpRequestError = PostAuthOtpRequestErrors[keyof PostAuthOtpRequestErrors];
|
||||
|
||||
export type PostAuthOtpRequestResponses = {
|
||||
/**
|
||||
* OTP requested successfully
|
||||
*/
|
||||
200: RequestOtpResponse;
|
||||
};
|
||||
|
||||
export type PostAuthOtpRequestResponse = PostAuthOtpRequestResponses[keyof PostAuthOtpRequestResponses];
|
||||
|
||||
export type PostAuthOtpVerifyData = {
|
||||
body: VerifyOtpRequest;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/auth/otp/verify';
|
||||
};
|
||||
|
||||
export type PostAuthOtpVerifyErrors = {
|
||||
/**
|
||||
* Bad request
|
||||
*/
|
||||
400: VerifyOtpResponse;
|
||||
};
|
||||
|
||||
export type PostAuthOtpVerifyError = PostAuthOtpVerifyErrors[keyof PostAuthOtpVerifyErrors];
|
||||
|
||||
export type PostAuthOtpVerifyResponses = {
|
||||
/**
|
||||
* OTP verified successfully
|
||||
*/
|
||||
200: VerifyOtpResponse;
|
||||
};
|
||||
|
||||
export type PostAuthOtpVerifyResponse = PostAuthOtpVerifyResponses[keyof PostAuthOtpVerifyResponses];
|
||||
|
||||
export type PostAuthConsentAcceptData = {
|
||||
body: AcceptConsentRequest;
|
||||
path?: never;
|
||||
query?: never;
|
||||
url: '/auth/consent/accept';
|
||||
};
|
||||
|
||||
export type PostAuthConsentAcceptErrors = {
|
||||
/**
|
||||
* Bad request
|
||||
*/
|
||||
400: AcceptConsentResponse;
|
||||
};
|
||||
|
||||
export type PostAuthConsentAcceptError = PostAuthConsentAcceptErrors[keyof PostAuthConsentAcceptErrors];
|
||||
|
||||
export type PostAuthConsentAcceptResponses = {
|
||||
/**
|
||||
* Consent accepted successfully
|
||||
*/
|
||||
200: AcceptConsentResponse;
|
||||
};
|
||||
|
||||
export type PostAuthConsentAcceptResponse = PostAuthConsentAcceptResponses[keyof PostAuthConsentAcceptResponses];
|
||||
|
||||
export type ClientOptions = {
|
||||
baseUrl: `${string}://${string}` | (string & {});
|
||||
};
|
||||
68
src/client/zod.gen.ts
Normal file
68
src/client/zod.gen.ts
Normal file
@ -0,0 +1,68 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
export const zRequestOtpRequest = z.object({
|
||||
phone_number: z.string().max(15)
|
||||
});
|
||||
|
||||
export const zRequestOtpResponse = z.object({
|
||||
message: z.string(),
|
||||
ok: z.boolean()
|
||||
});
|
||||
|
||||
export const zVerifyOtpRequest = z.object({
|
||||
phone_number: z.string().max(15),
|
||||
otp: z.string().max(6),
|
||||
login_challenge: z.string()
|
||||
});
|
||||
|
||||
export const zVerifyOtpResponse = z.object({
|
||||
redirect_url: z.string(),
|
||||
ok: z.boolean(),
|
||||
message: z.string()
|
||||
});
|
||||
|
||||
export const zAcceptConsentRequest = z.object({
|
||||
consent_challenge: z.string(),
|
||||
phone_number: z.string().max(15)
|
||||
});
|
||||
|
||||
export const zAcceptConsentResponse = z.object({
|
||||
redirect_url: z.string(),
|
||||
ok: z.boolean(),
|
||||
message: z.string()
|
||||
});
|
||||
|
||||
export const zPostAuthOtpRequestData = z.object({
|
||||
body: zRequestOtpRequest,
|
||||
path: z.optional(z.never()),
|
||||
query: z.optional(z.never())
|
||||
});
|
||||
|
||||
/**
|
||||
* OTP requested successfully
|
||||
*/
|
||||
export const zPostAuthOtpRequestResponse = zRequestOtpResponse;
|
||||
|
||||
export const zPostAuthOtpVerifyData = z.object({
|
||||
body: zVerifyOtpRequest,
|
||||
path: z.optional(z.never()),
|
||||
query: z.optional(z.never())
|
||||
});
|
||||
|
||||
/**
|
||||
* OTP verified successfully
|
||||
*/
|
||||
export const zPostAuthOtpVerifyResponse = zVerifyOtpResponse;
|
||||
|
||||
export const zPostAuthConsentAcceptData = z.object({
|
||||
body: zAcceptConsentRequest,
|
||||
path: z.optional(z.never()),
|
||||
query: z.optional(z.never())
|
||||
});
|
||||
|
||||
/**
|
||||
* Consent accepted successfully
|
||||
*/
|
||||
export const zPostAuthConsentAcceptResponse = zAcceptConsentResponse;
|
||||
@ -1,12 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { motion, MotionProps } from 'framer-motion';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
interface MotionWrapperProps extends MotionProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function MotionWrapper({ children, ...props }: MotionWrapperProps) {
|
||||
return <motion.div {...props}>{children}</motion.div>;
|
||||
}
|
||||
@ -4,11 +4,14 @@ import { FC, useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button, Stack } from "@mantine/core";
|
||||
import { useForm } from "@mantine/form";
|
||||
import PhoneInput from "@/components/PhoneInput/PhoneInput";
|
||||
import { useAppDispatch } from "@/lib/store";
|
||||
import { setLoginChallenge, setPhoneNumber } from "@/lib/features/auth/authSlice";
|
||||
import { AuthService } from "@/mocks/authService";
|
||||
import { Auth } from "@/client";
|
||||
import PhoneInput from "@/components/ui/PhoneInput/PhoneInput";
|
||||
import { notifications } from "@/lib/notifications";
|
||||
import {
|
||||
setLoginChallenge,
|
||||
setPhoneNumber,
|
||||
} from "@/lib/store/features/auth/authSlice";
|
||||
import { useAppDispatch } from "@/lib/store/store";
|
||||
|
||||
type LoginForm = {
|
||||
phoneNumber: string;
|
||||
@ -39,21 +42,26 @@ const LoginForm: FC<Props> = ({ loginChallenge, isCreatingId = false }) => {
|
||||
}, [loginChallenge]);
|
||||
|
||||
const handleSubmit = (values: LoginForm) => {
|
||||
dispatch(setPhoneNumber(values.phoneNumber));
|
||||
|
||||
new AuthService().requestLogin(values.phoneNumber)
|
||||
const phoneNumber = values.phoneNumber.replace(/ /g, "");
|
||||
dispatch(setPhoneNumber(phoneNumber));
|
||||
Auth.postAuthOtpRequest({
|
||||
body: { phone_number: phoneNumber },
|
||||
})
|
||||
.then(response => response.data)
|
||||
.then(({ ok, message }) => {
|
||||
if (!ok) {
|
||||
notifications.error({ message });
|
||||
} else {
|
||||
.then(response => {
|
||||
console.log(response);
|
||||
if (!response) {
|
||||
notifications.error({
|
||||
message: "Ошибка при отправке запроса",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const { ok, message } = response;
|
||||
notifications.guess(ok, { message });
|
||||
if (ok) {
|
||||
router.push("/verify-phone");
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
notifications.error({ message: error.toString() });
|
||||
})
|
||||
});
|
||||
};
|
||||
|
||||
const navigateToCreateId = () => router.push("/create-id");
|
||||
@ -61,8 +69,10 @@ const LoginForm: FC<Props> = ({ loginChallenge, isCreatingId = false }) => {
|
||||
const navigateToLogin = () => router.push("/");
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack>
|
||||
<form
|
||||
style={{ justifyItems: "center" }}
|
||||
onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack maw={500}>
|
||||
<PhoneInput
|
||||
{...form.getInputProps("phoneNumber")}
|
||||
setPhoneMask={setPhoneMask}
|
||||
6
src/components/layout/Footer/Footer.module.css
Normal file
6
src/components/layout/Footer/Footer.module.css
Normal file
@ -0,0 +1,6 @@
|
||||
.footer {
|
||||
padding: var(--mantine-spacing-md);
|
||||
@media (max-width: 48em) {
|
||||
padding: 0
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
import Link from "next/link";
|
||||
import { Group, Text } from "@mantine/core";
|
||||
import styles from "@/components/layout/Footer/Footer.module.css";
|
||||
|
||||
const Footer = () => {
|
||||
return (
|
||||
@ -7,7 +8,7 @@ const Footer = () => {
|
||||
justify={"flex-end"}
|
||||
align={"flex-end"}
|
||||
h={"7vh"}
|
||||
p={"md"}>
|
||||
className={styles.footer}>
|
||||
<Group gap={"xl"}>
|
||||
<Link
|
||||
href={"#"}
|
||||
@ -1,5 +1,5 @@
|
||||
import { Group } from "@mantine/core";
|
||||
import { ColorSchemeToggle } from "@/components/ColorSchemeToggle/ColorSchemeToggle";
|
||||
import { ColorSchemeToggle } from "@/components/ui/ColorSchemeToggle/ColorSchemeToggle";
|
||||
|
||||
const Header = () => {
|
||||
return (
|
||||
12
src/components/layout/MotionWrapper/MotionWrapper.tsx
Normal file
12
src/components/layout/MotionWrapper/MotionWrapper.tsx
Normal file
@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { ReactNode } from "react";
|
||||
import { motion, MotionProps } from "framer-motion";
|
||||
|
||||
interface MotionWrapperProps extends MotionProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function MotionWrapper({ children, ...props }: MotionWrapperProps) {
|
||||
return <motion.div {...props}>{children}</motion.div>;
|
||||
}
|
||||
@ -37,5 +37,15 @@
|
||||
bottom: 0;
|
||||
z-index: 100;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.mobile-footer {
|
||||
display: none;
|
||||
@media (max-width: 48em) {
|
||||
display: block;
|
||||
margin-top: auto;
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
import { CSSProperties, FC, ReactNode } from "react";
|
||||
import classNames from "classnames";
|
||||
import { MotionWrapper } from "@/components/MotionWrapper/MotionWrapper";
|
||||
import { MotionWrapper } from "@/components/layout/MotionWrapper/MotionWrapper";
|
||||
import Footer from "@/components/layout/Footer/Footer";
|
||||
import styles from "./PageItem.module.css";
|
||||
|
||||
type Props = {
|
||||
@ -31,6 +32,11 @@ const PageItem: FC<Props> = ({
|
||||
fullScreenMobile && styles["container-full-screen-mobile"]
|
||||
)}>
|
||||
{children}
|
||||
{fullScreenMobile && (
|
||||
<div className={styles["mobile-footer"]}>
|
||||
<Footer />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -7,7 +7,7 @@ import {
|
||||
useComputedColorScheme,
|
||||
useMantineColorScheme,
|
||||
} from "@mantine/core";
|
||||
import style from "@/components/ColorSchemeToggle/ColorSchemeToggle.module.css";
|
||||
import style from "./ColorSchemeToggle.module.css";
|
||||
|
||||
export function ColorSchemeToggle() {
|
||||
const { setColorScheme } = useMantineColorScheme();
|
||||
@ -32,7 +32,7 @@ const Logo = ({ title }: Props) => {
|
||||
<Title
|
||||
order={4}
|
||||
mb={"lg"}
|
||||
style={{ color: myColor[6] }}>
|
||||
style={{ color: myColor[6], textAlign: "center" }}>
|
||||
{title}
|
||||
</Title>
|
||||
</Center>
|
||||
@ -1,16 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { IMaskInput } from "react-imask";
|
||||
import {
|
||||
InputBase,
|
||||
type InputBaseProps,
|
||||
type PolymorphicComponentProps,
|
||||
} from "@mantine/core";
|
||||
import CountrySelect from "@/components/PhoneInput/components/CountrySelect";
|
||||
import { Country } from "@/components/PhoneInput/types";
|
||||
import getInitialDataFromValue from "@/components/PhoneInput/utils/getInitialDataFromValue";
|
||||
import getPhoneMask from "@/components/PhoneInput/utils/getPhoneMask";
|
||||
import CountrySelect from "@/components/ui/PhoneInput/components/CountrySelect";
|
||||
import { Country } from "@/components/ui/PhoneInput/types";
|
||||
import getInitialDataFromValue from "@/components/ui/PhoneInput/utils/getInitialDataFromValue";
|
||||
import getPhoneMask from "@/components/ui/PhoneInput/utils/getPhoneMask";
|
||||
|
||||
type AdditionalProps = {
|
||||
onChange: (value: string | null) => void;
|
||||
@ -20,14 +20,13 @@ type AdditionalProps = {
|
||||
|
||||
type InputProps = Omit<
|
||||
PolymorphicComponentProps<typeof IMaskInput, InputBaseProps>,
|
||||
"onChange" | "defaultValue"
|
||||
"onChange" | "defaultValue" | "value"
|
||||
>;
|
||||
|
||||
export type Props = AdditionalProps & InputProps;
|
||||
|
||||
const PhoneInput = ({
|
||||
initialCountryCode = "RU",
|
||||
value: _value,
|
||||
onChange: _onChange,
|
||||
setPhoneMask: _setPhoneMask,
|
||||
...props
|
||||
@ -41,8 +40,6 @@ const PhoneInput = ({
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [dropdownWidth, setDropdownWidth] = useState<number>(300);
|
||||
|
||||
const lastNotifiedValue = useRef<string | null>(value ?? "");
|
||||
|
||||
const onChange = (numberWithoutCode: string) => {
|
||||
setValue(numberWithoutCode);
|
||||
_onChange(`+${country.callingCode} ${numberWithoutCode}`);
|
||||
@ -57,14 +54,6 @@ const PhoneInput = ({
|
||||
setPhoneMask(initialData.current.format, country);
|
||||
}, [initialData.current.format]);
|
||||
|
||||
useEffect(() => {
|
||||
const localValue = value.trim();
|
||||
if (localValue !== lastNotifiedValue.current) {
|
||||
lastNotifiedValue.current = localValue;
|
||||
onChange(localValue);
|
||||
}
|
||||
}, [country.code, value]);
|
||||
|
||||
const { readOnly, disabled } = props;
|
||||
const leftSectionWidth = 90;
|
||||
|
||||
@ -73,12 +62,8 @@ const PhoneInput = ({
|
||||
setDropdownWidth(inputRef.current?.offsetWidth);
|
||||
}, [inputRef.current?.offsetWidth]);
|
||||
|
||||
return (
|
||||
<InputBase
|
||||
{...props}
|
||||
component={IMaskInput}
|
||||
inputRef={inputRef}
|
||||
leftSection={
|
||||
const countrySelect = useMemo(
|
||||
() => (
|
||||
<CountrySelect
|
||||
disabled={disabled || readOnly}
|
||||
country={country}
|
||||
@ -93,7 +78,16 @@ const PhoneInput = ({
|
||||
leftSectionWidth={leftSectionWidth}
|
||||
inputWidth={dropdownWidth}
|
||||
/>
|
||||
}
|
||||
),
|
||||
[country, leftSectionWidth, dropdownWidth, disabled, readOnly]
|
||||
);
|
||||
|
||||
return (
|
||||
<InputBase
|
||||
{...props}
|
||||
component={IMaskInput}
|
||||
inputRef={inputRef}
|
||||
leftSection={countrySelect}
|
||||
leftSectionWidth={leftSectionWidth}
|
||||
styles={{
|
||||
input: {
|
||||
@ -105,10 +99,9 @@ const PhoneInput = ({
|
||||
"1px solid var(--mantine-color-default-border)",
|
||||
},
|
||||
}}
|
||||
inputMode={"numeric"}
|
||||
mask={mask}
|
||||
value={value}
|
||||
onAccept={value => setValue(value)}
|
||||
onAccept={onChange}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@ -10,9 +10,10 @@ import {
|
||||
Text,
|
||||
useCombobox,
|
||||
} from "@mantine/core";
|
||||
import style from "@/components/PhoneInput/PhoneInput.module.css";
|
||||
import { Country } from "@/components/PhoneInput/types";
|
||||
import countryOptionsDataMap from "@/components/PhoneInput/utils/countryOptionsDataMap";
|
||||
import style from "@/components/ui/PhoneInput/PhoneInput.module.css";
|
||||
import { Country } from "@/components/ui/PhoneInput/types";
|
||||
import countryOptionsDataMap from "@/components/ui/PhoneInput/utils/countryOptionsDataMap";
|
||||
|
||||
|
||||
const countryOptionsData = Object.values(countryOptionsDataMap);
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
import countries from "i18n-iso-countries";
|
||||
import ru from "i18n-iso-countries/langs/ru.json";
|
||||
import { type CountryCode, getCountries } from "libphonenumber-js";
|
||||
import getFlagEmoji from "@/components/PhoneInput/utils/getFlagEmoji";
|
||||
import getFlagEmoji from "@/components/ui/PhoneInput/utils/getFlagEmoji";
|
||||
import { getCountryCallingCode } from "libphonenumber-js/max";
|
||||
import { Country } from "@/components/PhoneInput/types";
|
||||
import { Country } from "@/components/ui/PhoneInput/types";
|
||||
|
||||
countries.registerLocale(ru);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import { CountryCode } from "libphonenumber-js";
|
||||
import { Country } from "@/components/PhoneInput/types";
|
||||
import countryOptionsDataMap from "@/components/PhoneInput/utils/countryOptionsDataMap";
|
||||
import getPhoneMask from "@/components/PhoneInput/utils/getPhoneMask";
|
||||
import { Country } from "@/components/ui/PhoneInput/types";
|
||||
import countryOptionsDataMap from "@/components/ui/PhoneInput/utils/countryOptionsDataMap";
|
||||
import getPhoneMask from "@/components/ui/PhoneInput/utils/getPhoneMask";
|
||||
|
||||
type InitialDataFromValue = {
|
||||
country: Country;
|
||||
6
src/hey-api-config.ts
Normal file
6
src/hey-api-config.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import type { CreateClientConfig } from './client/client.gen';
|
||||
|
||||
export const createClientConfig: CreateClientConfig = (config) => ({
|
||||
...config,
|
||||
baseUrl: process.env.NEXT_PUBLIC_API_URL,
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
import { combineReducers } from "@reduxjs/toolkit";
|
||||
import targetServiceReducer from "@/lib/features/targetService/targetServiceSlice";
|
||||
import verificationReducer from "@/lib/features/verification/verificationSlice";
|
||||
import authReducer from "@/lib/features/auth/authSlice";
|
||||
|
||||
const rootReducer = combineReducers({
|
||||
targetService: targetServiceReducer,
|
||||
verification: verificationReducer,
|
||||
auth: authReducer,
|
||||
});
|
||||
|
||||
export default rootReducer;
|
||||
12
src/lib/store/features/rootReducer.ts
Normal file
12
src/lib/store/features/rootReducer.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { combineReducers } from "@reduxjs/toolkit";
|
||||
import authReducer from "@/lib/store/features/auth/authSlice";
|
||||
import targetServiceReducer from "@/lib/store/features/targetService/targetServiceSlice";
|
||||
import verificationReducer from "@/lib/store/features/verification/verificationSlice";
|
||||
|
||||
const rootReducer = combineReducers({
|
||||
targetService: targetServiceReducer,
|
||||
verification: verificationReducer,
|
||||
auth: authReducer,
|
||||
});
|
||||
|
||||
export default rootReducer;
|
||||
@ -2,7 +2,7 @@ import { configureStore } from "@reduxjs/toolkit";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { persistReducer, persistStore } from "redux-persist";
|
||||
import storage from "redux-persist/lib/storage";
|
||||
import rootReducer from "@/lib/features/rootReducer";
|
||||
import rootReducer from "@/lib/store/features/rootReducer";
|
||||
|
||||
const persistConfig = {
|
||||
key: "root",
|
||||
@ -1,75 +0,0 @@
|
||||
import { AxiosResponse } from "axios";
|
||||
import { Scopes } from "@/enums/Scopes";
|
||||
|
||||
type MockOkMessage = {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
type MockApproveLoginResponse = {
|
||||
redirectUrl: string;
|
||||
scope: Scopes[];
|
||||
}
|
||||
|
||||
type MockRequestConsentResponse = {
|
||||
clientName: string;
|
||||
}
|
||||
|
||||
type MockApproveConsentResponse = {
|
||||
redirectUrl: string;
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
async requestLogin(phoneNumber: string): Promise<AxiosResponse<MockOkMessage>> {
|
||||
return Promise.resolve({
|
||||
data: { ok: true, message: "Mock response" } as MockOkMessage,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {},
|
||||
config: {} as any,
|
||||
});
|
||||
}
|
||||
|
||||
async approveLogin(
|
||||
phoneNumber: string,
|
||||
code: string,
|
||||
loginChallenge: string
|
||||
): Promise<AxiosResponse<MockApproveLoginResponse>> {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
redirectUrl:
|
||||
"http://oauth2.logidex.ru/oauth2/auth?client_id=crm-client&login_verifier=c-4HxjyA0rUMMOYQG-kHStU5pxFeOdViKOyk-eT_qv7vNPHu3xdysdYj3Jwq2gh6vRSHdO6xA7NQgneUho5I_LyENNTFqRkjWwhAsy7Ad9DFhcAWVRCU1rI3ksy38-UTWlto7vKVVhGgRzvlk-coa273uLz-BEo64oUl9B_gcojLnLjO1Q1W6Hu8_nJxqyQBhLPcFOZ1vDVnNcQF5UbB9bld3Wr_1nn3r7sQMBQR54Vphcku6a37GYbPVMVGHo0nBGf6rps6Xg4L6IsD5hlsHzsw5OX3W0MDJ6o--VxHr_HveAH8K7R21Q59JtHa-26pO4KGjetGfgr8rPOTRtsZiKApjZ8qjM9pEgusPj39ysmqYo1wmJo1ZXz8wXh-t3UO0pGIZogmzEOLs5bPCCbXrjG7VaQ78jufSAG2pmhMJxR9AmWsaJms16lev1dBFn-IBdrr4LqYrsVQMqpZstF18ENSURAKejHc8l8m4xocy2-D-ZaeZX0k0vnuGsNTbxT79D1u_-ALm2n0LRwcsK5VCF8v5oO_aMFxcSO87QHU8wy8Wj3um3IBb0sCQXDCpsYIlwqczWNWmxaGXDsmqqUYvZdvWKEXMI5BbbVc44h4_sOaa6BKAaNSceC2GHqN94GWz8dmsX7xyfXMsHYR8_hUFsztN8OstrQkRddJ8een4mdW777W3PYe_U4UL2S2az4L7tC5DTifDCHTfYknb4baQ3UT7x4N8eCd2_Xlkl4gQKU5Mm8njZWucWsLjdW7NG8Q_aDQEl45VunmaQ8iKOTrn1BiNzRHnYdOm15C8nnxHyZ9pO8IKELxUGIKnwP8eF6-A-Rj_bLWWIBquLTRgBrR153gu5Srh2Xl8-LU4ffxM6ipO1nHJMPg3_5493yS1ua_ZWUuht_d4C4Y6j6xuFJHx-bKrCIffiGiSUnpKkepzGnTHCS02wNDVItheAUnlO18zbxsHBFM1tjQQrLIB3cxQRrK12NmIgOheiQMzkSwpQ2CmdRnVpJBGy8Nzp7X_YP-nVC9ctzFR1YrTEw-ZH0wVYjPu_vsijwUtqq3mABD8lw%3D&redirect_uri=http%3A%2F%2Fcrm.logidex.ru%2Fcallback&response_type=code&scope=openid&state=csrf_token",
|
||||
scope: ["openid"] as Scopes[],
|
||||
},
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {},
|
||||
config: {} as any,
|
||||
});
|
||||
}
|
||||
|
||||
async requestConsent(consentChallenge: string): Promise<AxiosResponse<MockRequestConsentResponse>> {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
clientName: "crm",
|
||||
},
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {},
|
||||
config: {} as any,
|
||||
});
|
||||
}
|
||||
|
||||
async approveConsent(consentChallenge: string): Promise<AxiosResponse<MockApproveConsentResponse>> {
|
||||
return Promise.resolve({
|
||||
data: {
|
||||
redirectUrl:
|
||||
"http://oauth2.logidex.ru/oauth2/auth?client_id=crm-client&consent_verifier=hU0HetHSHoqc4ZMvwsjMaFUsVckZ3B6ztXyQim4vwcptp4Dp9cIvSByiFHvThLkaIVl2f7uDxB8hUcUoG1-DvNDC3qcGCskLlNn0tDlNcxb41LZtS28D8iZJAUiZedqDdGCfhkuH4TioErId5m-8-y5Y-PYrosfcrqsVfK88vZ5kgViMIjROe68Vc_O5kxpPUymt5I_-oUeFMdrDnjpVcTipwTJIG-WutbtUBHp6tA3FXIfo-0ai-o8yr2Lv2bQiBSegYKA4GmfrQ25xn7_yQGLyGVBVsKPCNRQAyRvdeqFEVGm-3SUxvIJCeyCXaZrHxENSUbxo6xd1m_oVHqye8hXcZSWmFVOa4eo4Rw6OWsnN3AWl75XLt_maKcL_LZftkQERtJBgV2-8C1QYJXwoPS0uTFANq39s2778KIP0XbufiB3UW1QvmUdzKKH43K4MnB-F9ah26nzaw8HwEBTbDGclvkq7TFAozKddwnumgrqRkbElwC3eqr5LnpMfGR1vCVBP81sPjx26LoiKOpmuamfT-O37EsVHdooeP8ry2IjCx0KrUe5wI93XiUc4RIMn_MsO8zaifyNrzFfvVQ7VPNj3QasM4O4drDyGLict1fWiNZP_KVFeAnojOp258nPqDn76VSzROweummzSD-lC56zviX9pZjmGb0RpXb8eeB2Nc4uWCy3dYw4kxEFQSqwU7liqI9paZLv0Vl1PrvS4GL_vv3zh4YKpp8h1yT0IWDnEL75dmIeSBXB7eTkZy8ING1HdwvfH1TdYImCrmLTi93JWtSJvsZWklUBQsFQ900hYPYGK4WVdxRQOTsHrJhJwOex5so7mrnowHpXQuUU6eDi9p2Yj0_YN2XuPIs1I9iS2F2S6t1_kNRmJupzo3g09bY8AGNsSDeEwp2riqXQ_o3xgATaIUycbve2qcOIr89kHomYSCc0YiQnka3zBb5RRTlYhDuQlgeHuEnIBWU2oLYcnyP-zlbeSxRbYuYu4uxXtLHDT9E6tDxqXxSYvw4AzUw-EwQX8v0LamJnQLHCSwD7F8S0M5COSm_Pv56DhtBevnU7PqrpZ-FKOXm89A2HXx9XO8qQMG-tg3y5TZ5vVfTwJ6WkzZNkZSWAZGiwQX4wiQmjep4wlKgP3ZQ8VV0CVS6R9f1DMwY8tCvuJFumd_OORK7-q_bgg3Xp3Njc%3D&redirect_uri=http%3A%2F%2Fcrm.logidex.ru%2Fcallback&response_type=code&scope=openid&state=csrf_token",
|
||||
},
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {},
|
||||
config: {} as any,
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -3,7 +3,7 @@
|
||||
import { ReactNode } from "react";
|
||||
import { Provider } from "react-redux";
|
||||
import { PersistGate } from "redux-persist/integration/react";
|
||||
import { persistor, store } from "@/lib/store";
|
||||
import { persistor, store } from "@/lib/store/store";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
|
||||
Reference in New Issue
Block a user