Skip to content

Commit

Permalink
feat: replace TokenRegistry with useSyncExternalStore
Browse files Browse the repository at this point in the history
  • Loading branch information
endv-bogdanb committed Jul 30, 2023
1 parent 4f0e439 commit 93b4b01
Show file tree
Hide file tree
Showing 19 changed files with 247 additions and 192 deletions.
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
4 changes: 2 additions & 2 deletions src/features/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Navigate, Outlet } from "react-router";
import { useSession } from "@utils";
import { tokenSlice } from "@utils";

export function ProtectedRoute() {
const session = useSession();
const session = tokenSlice.useSlice();

if (!session?.token || !session.refreshToken) {
return <Navigate to={""} />;
Expand Down
6 changes: 3 additions & 3 deletions src/features/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { useEffect, useState } from "react";
import { Link, Outlet } from "react-router-dom";
import { Divider, Space } from "@mantine/core";
import { Layout } from "@components/Layout";
import { getPublicUrl, httpClient, TokenRegistry, useSession } from "@utils";
import { getPublicUrl, httpClient, tokenSlice } from "@utils";

export function Root() {
const [version, setVersion] = useState<string | null>(null);

const session = useSession();
const session = tokenSlice.useSlice();

useEffect(() => {
const ab = new AbortController();
Expand Down Expand Up @@ -43,7 +43,7 @@ export function Root() {
to=""
onClick={(e) => {
e.preventDefault();
TokenRegistry.reset();
tokenSlice.dispatch({ type: "reset" });
}}
>
logout
Expand Down
14 changes: 9 additions & 5 deletions src/features/apollo/ApolloLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useNavigate } from "react-router-dom";
import { gql, useMutation } from "@apollo/client";
import { Login } from "@components";
import { TokenRegistry } from "@utils";
import { tokenSlice } from "@utils";

const LOGIN_MUTATION = gql`
mutation Login($username: String!, $password: String!) {
Expand All @@ -23,11 +23,15 @@ export function ApolloLogin() {
try {
const { data } = await login({ variables: value });

console.log(data);
tokenSlice.dispatch({
type: "set",
payload: {
token: data.token,
refreshToken: data.refreshToken,
user: data.user,
},
});

TokenRegistry.token = data.token;
TokenRegistry.refreshToken = data.refreshToken;
TokenRegistry.user = data.user;
navigate("users");
} catch (e) {
console.log("err", e);
Expand Down
15 changes: 11 additions & 4 deletions src/features/gql/GqlLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useNavigate } from "react-router-dom";
import { Login } from "@components";
import { loginResSchema, TLoginReq, TLoginRes } from "@models";
import { httpClient, TokenRegistry } from "@utils";
import { httpClient, tokenSlice } from "@utils";

async function login(variables: TLoginReq): Promise<TLoginRes> {
const { data } = (await httpClient("gql/", {
Expand Down Expand Up @@ -29,9 +29,16 @@ export function GqlLogin() {
onLogin={async (value) => {
try {
const data = await login(value);
TokenRegistry.token = data.token;
TokenRegistry.refreshToken = data.refreshToken;
TokenRegistry.user = data.user;

tokenSlice.dispatch({
type: "set",
payload: {
token: data.token,
refreshToken: data.refreshToken,
user: data.user,
},
});

navigate("users");
} catch (e) {
console.log("err", e);
Expand Down
13 changes: 9 additions & 4 deletions src/features/query/QueryLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useNavigate } from "react-router-dom";
import { useMutation } from "@tanstack/react-query";
import { Login } from "@components";
import { loginResSchema, TLoginReq } from "@models";
import { httpClient, TokenRegistry } from "@utils";
import { httpClient, tokenSlice } from "@utils";

export function QueryLogin() {
const navigate = useNavigate();
Expand All @@ -26,9 +26,14 @@ export function QueryLogin() {
try {
const data = await login.mutateAsync(value);

TokenRegistry.token = data.token;
TokenRegistry.refreshToken = data.refreshToken;
TokenRegistry.user = data.user;
tokenSlice.dispatch({
type: "set",
payload: {
token: data.token,
refreshToken: data.refreshToken,
user: data.user,
},
});

navigate("users");
} catch (e) {
Expand Down
13 changes: 9 additions & 4 deletions src/features/swr/SwrLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useNavigate } from "react-router-dom";
import useSWRMutation from "swr/mutation";
import { Login } from "@components";
import { loginResSchema, TLoginReq } from "@models";
import { httpClient, TokenRegistry } from "@utils";
import { httpClient, tokenSlice } from "@utils";

export function SwrLogin() {
const navigate = useNavigate();
Expand Down Expand Up @@ -30,9 +30,14 @@ export function SwrLogin() {
throw data;
}

TokenRegistry.token = data.token;
TokenRegistry.refreshToken = data.refreshToken;
TokenRegistry.user = data.user;
tokenSlice.dispatch({
type: "set",
payload: {
token: data.token,
refreshToken: data.refreshToken,
user: data.user,
},
});

navigate("users");
} catch (e) {
Expand Down
13 changes: 9 additions & 4 deletions src/features/toolkit-query/ToolkitLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useNavigate } from "react-router-dom";
import { FetchBaseQueryError } from "@reduxjs/toolkit/dist/query";
import { Login } from "@components";
import { TokenRegistry } from "@utils";
import { tokenSlice } from "@utils";
import { useLoginMutation } from "./store/api/api";

export function ToolkitLogin() {
Expand All @@ -16,9 +16,14 @@ export function ToolkitLogin() {
try {
const { token, refreshToken, user } = await login(value).unwrap();

TokenRegistry.token = token;
TokenRegistry.refreshToken = refreshToken;
TokenRegistry.user = user;
tokenSlice.dispatch({
type: "set",
payload: {
token,
refreshToken,
user,
},
});

navigate("users");
} catch (e) {
Expand Down
14 changes: 8 additions & 6 deletions src/features/toolkit-query/store/api/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import {
FetchBaseQueryError,
} from "@reduxjs/toolkit/dist/query";
import { refreshResSchema } from "@models";
import { TokenRegistry } from "@utils";
import { tokenSlice } from "@utils";

const mutex = new Mutex();

const authorisedQuery = fetchBaseQuery({
baseUrl: "/api",
prepareHeaders: (headers) => {
headers.append("Authorization", `Bearer ${TokenRegistry.token}`);
headers.append("Authorization", `Bearer ${tokenSlice.state.token}`);
return headers;
},
});
Expand All @@ -34,7 +34,7 @@ export const baseQuery: BaseQueryFn<
{
url: "/refresh",
method: "POST",
body: { refreshToken: TokenRegistry.refreshToken },
body: { refreshToken: tokenSlice.state.refreshToken },
},
api,
extraOptions,
Expand All @@ -47,10 +47,12 @@ export const baseQuery: BaseQueryFn<
data: { token, refreshToken },
} = data;

TokenRegistry.token = token;
TokenRegistry.refreshToken = refreshToken;
tokenSlice.dispatch({
type: "set",
payload: { token, refreshToken },
});
} else {
TokenRegistry.reset();
tokenSlice.dispatch({ type: "reset" });
}
} finally {
release();
Expand Down
6 changes: 3 additions & 3 deletions src/features/urql/Urql.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Outlet } from "react-router-dom";
import { cacheExchange, createClient, fetchExchange, Provider } from "urql";
import { TokenRegistry } from "@utils";
import { tokenSlice } from "@utils";

const client = createClient({
url: "gql/",
Expand All @@ -9,8 +9,8 @@ const client = createClient({
return {
headers: {
accept: "*/*", // NOTE: https://github.com/mswjs/msw/issues/1593#issuecomment-1509003528
authorization: TokenRegistry.token
? `Bearer ${TokenRegistry.token}`
authorization: tokenSlice.state.token
? `Bearer ${tokenSlice.state.token}`
: "",
},
};
Expand Down
14 changes: 10 additions & 4 deletions src/features/urql/UrqlLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useNavigate } from "react-router-dom";
import { useMutation } from "urql";
import { Login } from "@components";
import { TokenRegistry } from "@utils";
import { tokenSlice } from "@utils";

const LoginMutation = `
mutation Login($username: String!, $password: String!){
Expand All @@ -25,9 +25,15 @@ export function UrqlLogin() {

if (error) throw error;

TokenRegistry.token = data.token;
TokenRegistry.refreshToken = data.refreshToken;
TokenRegistry.user = data.user;
tokenSlice.dispatch({
type: "set",
payload: {
token: data.token,
refreshToken: data.refreshToken,
user: data.user,
},
});

navigate("users");
} catch (e) {
console.log("err", e);
Expand Down
4 changes: 2 additions & 2 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ReactDOM from "react-dom/client";
import { createHashRouter, RouterProvider } from "react-router-dom";
import { MantineProvider } from "@mantine/core";
import { routes } from "@routes";
import { getPublicUrl, TokenRegistry } from "@utils";
import { getPublicUrl, tokenSlice } from "@utils";

const router = createHashRouter(routes);

Expand All @@ -29,7 +29,7 @@ import("./backend/browser")
return Promise.resolve();
})
.then(() => {
TokenRegistry.setup();
tokenSlice.dispatch({ type: "setup" });
return Promise.resolve();
})
.then(() => start());
93 changes: 0 additions & 93 deletions src/utils/TokenRegistry.ts

This file was deleted.

Loading

0 comments on commit 93b4b01

Please sign in to comment.