From 804eb6f0249a554f5f594579a22f3764975d8779 Mon Sep 17 00:00:00 2001 From: heyethereum Date: Sat, 3 Aug 2024 13:47:24 +0800 Subject: [PATCH] added inteceptor to include diff headers in diff env --- .env.development | 2 +- .env.production | 2 +- api/qrCodeAPI.tsx | 75 +++++++++++++++++++++++++++++++------- app.config.js | 1 + reducers/qrCodesReducer.ts | 4 +- screens/HistoryScreen.tsx | 2 +- 6 files changed, 67 insertions(+), 19 deletions(-) diff --git a/.env.development b/.env.development index 0560a01..34fe0a0 100644 --- a/.env.development +++ b/.env.development @@ -1,2 +1,2 @@ NODE_ENV=development -BASE_URL=http://localhost:8080 \ No newline at end of file +BASE_URL=http://192.168.1.30:8080 \ No newline at end of file diff --git a/.env.production b/.env.production index afe9e7e..e5547f1 100644 --- a/.env.production +++ b/.env.production @@ -1,3 +1,3 @@ NODE_ENV=production -BASE_URL=https://bk5wiynzsi.execute-api.ap-southeast-1.amazonaws.com/api/ +BASE_URL=https://bk5wiynzsi.execute-api.ap-southeast-1.amazonaws.com/api ENV=production \ No newline at end of file diff --git a/api/qrCodeAPI.tsx b/api/qrCodeAPI.tsx index 944c1a3..07e27a4 100644 --- a/api/qrCodeAPI.tsx +++ b/api/qrCodeAPI.tsx @@ -1,6 +1,7 @@ import axios from 'axios'; import Constants from 'expo-constants'; -const { API_BASE_URL } = Constants.expoConfig.extra; +const { API_BASE_URL, ENVIRONMENT } = Constants.expoConfig.extra; +import { fetchAuthSession, getCurrentUser } from 'aws-amplify/auth'; //const API_BASE_URL = 'https://localhost:8443'; const API_URL_DETECT = "/v1/qrcodetypes/detect"; @@ -12,15 +13,46 @@ const API_URL_DELETE_SCANNED_HISTORY = "/v1/user/deleteScannedHistories" const API_URL_GET_BOOKMARKS = "/v1/user/getBookmarks" const API_URL_SET_BOOKMARK = "/v1/user/setBookmark" const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark" +const API_URL_GET_SCANNED_GMAILS = "/v1/gmail/getEmails" + +// Create an Axios instance +const apiClient = axios.create({ + baseURL: API_BASE_URL, +}); + +// Request interceptor to set headers based on env +apiClient.interceptors.request.use( + async (config) => { + const token = await fetchIdToken(); + const userId = await fetchUserId(); + + if (ENVIRONMENT === 'production') { + if (!config.headers.Authorization) { + config.headers.Authorization = `Bearer ${token}`; + } + } else { + if (!config.headers['X-USER-ID']) { + config.headers['X-USER-ID'] = userId; + } + } + + return config; + }, + (error) => { + return Promise.reject(error); + } +); // Define a generic function to handle all types of requests export const apiRequest = async (config) => { try { + console.log("ENVIRONMENT:", ENVIRONMENT); + console.log(`API Call - ${config.method.toUpperCase()}:`, config.url, config.data || ''); console.log(config); - - const response = await axios(config); + const response = await apiClient(config); console.log('API Response:', response.data); + return response.data; } catch (error) { if (error.response) { @@ -37,6 +69,18 @@ export const apiRequest = async (config) => { } }; +// Function to get the token +const fetchIdToken = async () => { + const { tokens } = await fetchAuthSession(); + return tokens.idToken.toString(); +}; + +// Function to get the user ID +const fetchUserId = async () => { + const currentUser = await getCurrentUser(); + return currentUser.userId; +}; + export const detectQRCodeType = async (data) => { return apiRequest({ method: 'post', @@ -69,48 +113,51 @@ export const checkRedirects = async (data) => { }); }; // GET User's Scanned Histories -export const getScannedHistories = async (userId: string) => { +export const getScannedHistories = async () => { return apiRequest({ method: 'get', - url: `${API_BASE_URL}${API_URL_GET_HISTORIES}`, - headers: { "X-USER-ID": userId }, + url: `${API_BASE_URL}${API_URL_GET_HISTORIES}` }); }; // GET All User's Bookmark -export const getAllUserBookmarks = async (userId: string) => { +export const getAllUserBookmarks = async () => { return apiRequest({ method: 'get', url: `${API_BASE_URL}${API_URL_GET_BOOKMARKS}`, - headers: { "X-USER-ID": userId }, }); }; // Create Bookmark on QR Code -export const setBookmark = async (userId: string, qrCodeId: string) => { +export const setBookmark = async (qrCodeId: string) => { return apiRequest({ method: 'post', url: `${API_BASE_URL}${API_URL_SET_BOOKMARK}`, - headers: { "X-USER-ID": userId}, data: { "qrCodeId": qrCodeId } }); }; // Delete single bookmark -export const deleteBookmark = async (userId: string, qrCodeId: string) => { +export const deleteBookmark = async (qrCodeId: string) => { return apiRequest({ method: 'put', url: `${API_BASE_URL}${API_URL_DELETE_BOOKMARK}`, - headers: { "X-USER-ID": userId}, data: { "qrCodeId": qrCodeId } }); }; // Delete Single Scanned History -export const deleteScannedHistory = async (userId: string, qrCodeId: string) => { +export const deleteScannedHistory = async (qrCodeId: string) => { return apiRequest({ method: 'put', url: `${API_BASE_URL}${API_URL_DELETE_SCANNED_HISTORY}`, - headers: { "X-USER-ID": userId}, data: { "qrCodeId": qrCodeId } }); +}; + +// GET Scan user's GMAILS +export const getScannedGmails = async () => { + return apiRequest({ + method: 'get', + url: `${API_BASE_URL}${API_URL_GET_SCANNED_GMAILS}` + }); }; \ No newline at end of file diff --git a/app.config.js b/app.config.js index 2b55058..ea90d4a 100644 --- a/app.config.js +++ b/app.config.js @@ -9,6 +9,7 @@ export default ({ config }) => { ...config, extra: { API_BASE_URL: process.env.BASE_URL, + ENVIRONMENT: process.env.NODE_ENV }, }; }; diff --git a/reducers/qrCodesReducer.ts b/reducers/qrCodesReducer.ts index 5f4b0b3..2a53f87 100644 --- a/reducers/qrCodesReducer.ts +++ b/reducers/qrCodesReducer.ts @@ -18,7 +18,7 @@ export const toggleBookmark = createAsyncThunk( 'qrCodes/toggleBookmark', async ({ userId, qrCode }: { userId: string, qrCode: QRCodeType }, { dispatch, rejectWithValue }) => { try { - await (qrCode.bookmarked ? deleteBookmark(userId, qrCode.data.id) : setBookmark(userId, qrCode.data.id)); + await (qrCode.bookmarked ? deleteBookmark(qrCode.data.id) : setBookmark(qrCode.data.id)); // Dispatch the action to update local state dispatch(toggleBookmarkInState(qrCode)); return qrCode; @@ -33,7 +33,7 @@ export const deleteQRCode = createAsyncThunk( 'qrCodes/deleteQRCode', async ({ userId, qrCodeId }: { userId: string, qrCodeId: string }, { dispatch, rejectWithValue }) => { try { - await deleteScannedHistory(userId, qrCodeId); + await deleteScannedHistory(qrCodeId); dispatch(deleteQRCodeInState(qrCodeId)); return qrCodeId; } catch (error) { diff --git a/screens/HistoryScreen.tsx b/screens/HistoryScreen.tsx index bf894e5..5dea21b 100644 --- a/screens/HistoryScreen.tsx +++ b/screens/HistoryScreen.tsx @@ -25,7 +25,7 @@ const HistoryScreen: React.FC = () => { try { setHistoriesLoading(true); - const historiesData = await getScannedHistories(userAttributes.sub); + const historiesData = await getScannedHistories(); dispatch(setScannedHistories(historiesData)); setHistoriesLoading(false);