Skip to content

Commit

Permalink
refactor: Move token save/restore to util fetch method
Browse files Browse the repository at this point in the history
  • Loading branch information
aliakseikrauchanka committed Jul 23, 2024
1 parent 6501ff4 commit 4462e70
Show file tree
Hide file tree
Showing 16 changed files with 121 additions and 160 deletions.
17 changes: 5 additions & 12 deletions apps/entry-app/src/app/api/agents/agents.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { getAuthData } from '@lifeis/common-ui';
import { utilFetch } from '@lifeis/common-ui';
import { ILog } from '../../domains/log.domain';
import { CONFIG } from '../../../../src/config';

export const createAgent = async (data: { name: string; prefix: string }): Promise<void> => {
const response = await fetch(`${CONFIG.BE_URL}/agents`, {
const response = await utilFetch(`${CONFIG.BE_URL}/agents`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthData().accessToken}`,
},
body: JSON.stringify(data),
});
Expand All @@ -20,11 +19,10 @@ export const createAgent = async (data: { name: string; prefix: string }): Promi
};

export const removeAgent = async (id: string): Promise<void> => {
const response = await fetch(`${CONFIG.BE_URL}/agents/${id}`, {
const response = await utilFetch(`${CONFIG.BE_URL}/agents/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthData().accessToken}`,
},
});

Expand All @@ -36,11 +34,7 @@ export const removeAgent = async (id: string): Promise<void> => {
};

export const getAllAgents = async (): Promise<ILog[]> => {
const response = await fetch(`${CONFIG.BE_URL}/agents`, {
headers: {
Authorization: `Bearer ${getAuthData().accessToken}`,
},
});
const response = await utilFetch(`${CONFIG.BE_URL}/agents`);

if (!response.ok) {
throw new Error('Failed to get agents');
Expand All @@ -58,11 +52,10 @@ export const submitMessage = async ({
}): Promise<{
answer: string;
}> => {
const response = await fetch(`${CONFIG.BE_URL}/agents/${id}`, {
const response = await utilFetch(`${CONFIG.BE_URL}/agents/${id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthData().accessToken}`,
},
body: JSON.stringify({
message,
Expand Down
23 changes: 9 additions & 14 deletions apps/entry-app/src/app/api/assistants/assistants.api.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { utilFetch } from '@lifeis/common-ui';
import { CONFIG } from '../../../config';

export const checkPolishGrammar = async (text: string): Promise<string> => {
const accessToken = localStorage.getItem('accessToken');

try {
// post message
const checkData = await fetch(`${CONFIG.BE_URL}/openai/check-polish-grammar`, {
const checkData = await utilFetch(`${CONFIG.BE_URL}/openai/check-polish-grammar`, {
method: 'POST',
body: JSON.stringify({ message: text }),
headers: {
Expand All @@ -19,23 +20,20 @@ export const checkPolishGrammar = async (text: string): Promise<string> => {
return new Promise((resolve, reject) => {
const intervalId = setInterval(async () => {
try {
const runResponse = await fetch(`${CONFIG.BE_URL}/openai/thread/run?threadId=${threadId}&runId=${runId}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
const runResponse = await utilFetch(
`${CONFIG.BE_URL}/openai/thread/run?threadId=${threadId}&runId=${runId}`,
{
method: 'GET',
},
});
);

const run = await runResponse.json();

if (run.status === 'completed') {
clearInterval(intervalId);

const messagesResponse = await fetch(`${CONFIG.BE_URL}/openai/thread/messages?threadId=${threadId}`, {
const messagesResponse = await utilFetch(`${CONFIG.BE_URL}/openai/thread/messages?threadId=${threadId}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

const messagesData = await messagesResponse.json();
Expand All @@ -53,14 +51,11 @@ export const checkPolishGrammar = async (text: string): Promise<string> => {
};

export const translateToPolish = async (text: string): Promise<string> => {
const accessToken = localStorage.getItem('accessToken');

try {
// post message
const checkData = await fetch(`${CONFIG.BE_URL}/gemini/translate-to-polish`, {
const checkData = await utilFetch(`${CONFIG.BE_URL}/gemini/translate-to-polish`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: text }),
Expand Down
6 changes: 2 additions & 4 deletions apps/entry-app/src/app/api/audio/audio.api.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { utilFetch } from '@lifeis/common-ui';
import { CONFIG } from '../../../config';

export const transcript = async (blob: Blob): Promise<Response> => {
const accessToken = localStorage.getItem('accessToken');

const formData = new FormData();
formData.append('audio', blob);

return fetch(`${CONFIG.BE_URL}/openai/transcribe`, {
return utilFetch(`${CONFIG.BE_URL}/openai/transcribe`, {
method: 'POST',
body: formData,
headers: {
Authorization: `Bearer ${accessToken}`,
MIME: blob.type,
},
});
Expand Down
28 changes: 4 additions & 24 deletions apps/entry-app/src/app/api/insights/insights.api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import { getAuthData } from '@lifeis/common-ui';
import { ILog } from '../../domains/log.domain';
import { utilFetch } from '@lifeis/common-ui';
import { CONFIG } from '../../../../src/config';

export const createLog = async (message: string): Promise<void> => {
const response = await fetch(`${CONFIG.BE_URL}/api/logs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthData().accessToken}`,
},
body: JSON.stringify({ message }),
export const getAllInsights = async (): Promise<string[]> => {
const response = await utilFetch(`${CONFIG.BE_URL}/insights`, {
method: 'GET',
});

if (!response.ok) {
Expand All @@ -18,17 +12,3 @@ export const createLog = async (message: string): Promise<void> => {

return await response.json();
};

export const getInsights = async (): Promise<ILog[]> => {
const response = await fetch(`${CONFIG.BE_URL}/api/insights`, {
headers: {
Authorization: `Bearer ${getAuthData().accessToken}`,
},
});

if (!response.ok) {
throw new Error('Failed to get insights');
}

return await response.json();
};
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { getAuthData } from '@lifeis/common-ui';
import { utilFetch } from '@lifeis/common-ui';
import { ILog } from '../../domains/log.domain';
import { CONFIG } from '../../../../src/config';
import { CONFIG } from '../../../config';

export const createLog = async (message: string): Promise<void> => {
const response = await fetch(`${CONFIG.BE_URL}/api/logs`, {
const response = await utilFetch(`${CONFIG.BE_URL}/logs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthData().accessToken}`,
},
body: JSON.stringify({ message }),
});
Expand All @@ -19,12 +18,8 @@ export const createLog = async (message: string): Promise<void> => {
return await response.json();
};

export const getLogs = async (): Promise<ILog[]> => {
const response = await fetch(`${CONFIG.BE_URL}/api/logs`, {
headers: {
Authorization: `Bearer ${getAuthData().accessToken}`,
},
});
export const getAllLogs = async (): Promise<ILog[]> => {
const response = await utilFetch(`${CONFIG.BE_URL}/logs`);

if (!response.ok) {
throw new Error('Failed to get logs');
Expand Down
12 changes: 9 additions & 3 deletions apps/entry-app/src/app/app.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { useEffect } from 'react';
import { useEffect, useState } from 'react';

import { GoogleOAuthProvider } from '@react-oauth/google';

import { UserSession } from '@lifeis/common-ui';
import { isUserLoggedIn, UserSession } from '@lifeis/common-ui';
import { CONFIG } from '../config';

import { Route, Routes } from 'react-router-dom';
Expand All @@ -16,6 +16,8 @@ import { init } from '@lifeis/common-ui';
import './styles/reset.css';

export default function App() {
const [isLoggedIn, setIsLoggedIn] = useState(isUserLoggedIn());

useEffect(() => {
init({
beUrl: CONFIG.BE_URL,
Expand All @@ -26,7 +28,11 @@ export default function App() {
return (
<GoogleOAuthProvider clientId={CONFIG.CLIENT_ID}>
<header>
<UserSession />
<UserSession
isLoggedIn={isLoggedIn}
onLoginSuccess={() => setIsLoggedIn(true)}
onLogOut={() => setIsLoggedIn(false)}
/>
</header>

<Routes>
Expand Down
21 changes: 5 additions & 16 deletions apps/entry-app/src/app/components/insights/insights.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,13 @@
import { CONFIG } from '../../../config';
import React, { useEffect, useState } from 'react';
import { getAllInsights } from '../../api/insights/insights.api';

export const Insights = () => {
const [insights, setInsights] = useState([]);
export const AllInsights = () => {
const [insights, setInsights] = useState<string[]>([]);

useEffect(() => {
const fetchLogs = async () => {
const accessToken = localStorage.getItem('accessToken');
try {
const data = await fetch(`${CONFIG.BE_URL}/insights`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

setInsights(await data.json());
} catch (e) {
console.log('error happened during fetch');
}
const insights = await getAllInsights();
setInsights(insights);
};
fetchLogs();
}, []);
Expand Down
12 changes: 2 additions & 10 deletions apps/entry-app/src/app/components/log-form/log-form.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CONFIG } from '../../../../src/config';
import React from 'react';
import { createLog } from '../../api/logs/logs.api';

export const LogForm = () => {
const [message, setMessage] = React.useState('');
Expand All @@ -9,17 +9,9 @@ export const LogForm = () => {

const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const accessToken = localStorage.getItem('accessToken');

try {
await fetch(`${CONFIG.BE_URL}/logs`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
});
await createLog(message);
setMessage('');
} catch (e) {
console.log('error happened during fetch');
Expand Down
4 changes: 2 additions & 2 deletions apps/entry-app/src/app/pages/insights.page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { Insights } from '../components/insights/insights';
import { AllInsights } from '../components/insights/insights';
import { Link } from 'react-router-dom';

export const InsightsPage = () => {
Expand All @@ -8,7 +8,7 @@ export const InsightsPage = () => {
<div>
<Link to="/">Click here to go back to root page.</Link>
</div>
<Insights />
<AllInsights />
</main>
);
};
4 changes: 2 additions & 2 deletions apps/entry-server/src/routes/auth-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ router.post('/google', (req, res) => {
});

router.post('/google/refresh', (req, res) => {
const { code } = req.body;
const { refreshToken } = req.body;
const client_id = CLIENT_ID;
const client_secret = CLIENT_SECRET;
const redirect_uri = REDIRECT_URL;
Expand All @@ -54,7 +54,7 @@ router.post('/google/refresh', (req, res) => {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
refresh_token: code,
refresh_token: refreshToken,
client_id,
client_secret,
redirect_uri,
Expand Down
3 changes: 2 additions & 1 deletion libs/common-ui/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './lib/components/button/button';
export * from './lib/components/user-session/user-session';
export * from './lib/services/local-storage.service';
export * from './lib/services/auth-storage.service';
export * from './lib/common-ui';
export * from './lib/utils/util-fetch';
export * from './main';
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { getGitDiff } from 'nx/src/command-line/release/utils/git';
import { CONFIG } from '../../../main';
import { getAuthData, saveAuthData } from '../../services/auth-storage.service';
import { AuthRawResponse } from './domain/auth.domain';

export const authGoogle = async (code: string): Promise<AuthRawResponse> => {
Expand All @@ -14,21 +16,38 @@ export const authGoogle = async (code: string): Promise<AuthRawResponse> => {
throw new Error('Failed to authenticate with Google');
}

return await response.json();
const authResponse = await response.json();

saveAuthData({
accessToken: authResponse.access_token,
refreshToken: authResponse.refresh_token,
});

return authResponse;
};

export const refreshAuthGoogle = async (code: string): Promise<AuthRawResponse> => {
export const refreshAuthGoogle = async (): Promise<AuthRawResponse> => {
const oldTokens = getAuthData();

const response = await fetch(`${CONFIG.BE_URL}/auth/google/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
// How long does refreshToken last?
body: JSON.stringify({ refreshToken: oldTokens.refreshToken }),
});

if (!response.ok) {
throw new Error('Failed to authenticate with Google');
}

return await response.json();
const authResponse = await response.json();

saveAuthData({
...oldTokens,
accessToken: authResponse.access_token,
});

return authResponse;
};
Loading

0 comments on commit 4462e70

Please sign in to comment.