88 lines
2.9 KiB
TypeScript
88 lines
2.9 KiB
TypeScript
import { useApi } from "@/api";
|
|
import { PayloadUpdate, ResponseCreate } from "@/api/resources/Session";
|
|
import { ESourceAuthorization } from "@/api/resources/User";
|
|
import { getClientTimezone, language } from "@/locales";
|
|
import { actions, selectors } from "@/store";
|
|
import { useCallback, useMemo } from "react"
|
|
import { useDispatch, useSelector } from "react-redux";
|
|
|
|
|
|
export const useSession = () => {
|
|
const dispatch = useDispatch();
|
|
const api = useApi();
|
|
const session = useSelector(selectors.selectSession);
|
|
|
|
const feature = useSelector(selectors.selectFeature)
|
|
const { checked, dateOfCheck } = useSelector(selectors.selectPrivacyPolicy);
|
|
const utm = useSelector(selectors.selectUTM);
|
|
|
|
const timezone = getClientTimezone();
|
|
|
|
const createSession = useCallback(async (source: ESourceAuthorization): Promise<ResponseCreate> => {
|
|
if (session[source]?.length) return {
|
|
sessionId: session[source],
|
|
status: "old"
|
|
};
|
|
try {
|
|
const session = await api.createSession({
|
|
feature,
|
|
locale: language,
|
|
timezone,
|
|
source,
|
|
sign: checked,
|
|
signDate: dateOfCheck.length ? dateOfCheck : undefined,
|
|
utm
|
|
});
|
|
if (session?.sessionId?.length && session?.status === "success") {
|
|
dispatch(actions.session.update({
|
|
session: session.sessionId,
|
|
source
|
|
}));
|
|
localStorage.setItem(`${source}_sessionId`, session.sessionId);
|
|
}
|
|
return session
|
|
} catch (error) {
|
|
console.log(error)
|
|
return {
|
|
status: "error",
|
|
sessionId: ""
|
|
}
|
|
}
|
|
}, [api, checked, dateOfCheck, dispatch, feature, session, timezone, utm])
|
|
|
|
const updateSession = useCallback(async (data: Omit<PayloadUpdate["data"], "feature">, source: ESourceAuthorization, sessionId?: string) => {
|
|
try {
|
|
const _sessionId = sessionId || session[source];
|
|
const result = await api.updateSession({
|
|
sessionId: _sessionId,
|
|
data: {
|
|
feature,
|
|
...data
|
|
}
|
|
});
|
|
return result;
|
|
} catch (error) {
|
|
console.log(error)
|
|
}
|
|
}, [api, feature, session])
|
|
|
|
const deleteSession = useCallback(async (source: ESourceAuthorization) => {
|
|
localStorage.removeItem(`${source}_sessionId`);
|
|
dispatch(actions.session.update({
|
|
session: "",
|
|
source
|
|
}))
|
|
}, [dispatch])
|
|
|
|
return useMemo(() => ({
|
|
session,
|
|
createSession,
|
|
updateSession,
|
|
deleteSession
|
|
}), [
|
|
createSession,
|
|
deleteSession,
|
|
session,
|
|
updateSession
|
|
])
|
|
} |