Skip to content

Commit bccaba4

Browse files
committed
import axios implementation with auth interceptor
1 parent c908c55 commit bccaba4

File tree

3 files changed

+30
-15
lines changed

3 files changed

+30
-15
lines changed

frontend/src/context/AuthContext.jsx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,9 @@ export function AuthProvider({ children }) {
4242
setLoading(false)
4343
if(user) {
4444

45-
const { token } = await user.getIdTokenResult()
46-
4745
const payload = {}
4846
userServices
49-
.currentUser(payload, token)
47+
.currentUser(payload)
5048
.then(res => {
5149
console.log('res: ', res);
5250
})

frontend/src/services/ApiService/index.js

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
11
import axios from "axios";
2+
import { auth } from '../../firebase'
23

34
const ApiService = (
45
function (){
6+
const axiosAuth = axios.create({
7+
baseURL: import.meta.env.VITE_BASE_URL
8+
})
9+
10+
const axiosPublic = axios.create({
11+
baseURL: import.meta.env.VITE_BASE_URL
12+
})
513

14+
axiosAuth.interceptors.request.use(
15+
async (config) => {
16+
let user = await auth.currentUser
17+
config.headers.token = user ? await user.getIdToken(true): ''
18+
19+
return config
20+
},
21+
(error) => {
22+
return Promise.reject(error)
23+
}
24+
)
25+
626
/**
727
* e.g Make a request for a user (url) with a given ID axios.get('/user?ID=12345')
828
* Optionally the request above could also be done as
@@ -12,17 +32,17 @@ const ApiService = (
1232
* }
1333
* })
1434
*/
15-
function get(url, params) {
16-
return axios.get(url, { params })
35+
function getWithAuth(url, params) {
36+
return axiosAuth.get(url, { params })
1737
}
1838

19-
function post(url, payload, headers) {
20-
return axios.post(url, payload, { headers });
39+
function postWithAuth(url, payload, headers) {
40+
return axiosAuth.post(url, payload, { headers });
2141
}
2242

2343
return {
24-
post,
25-
get
44+
postWithAuth,
45+
getWithAuth
2646
}
2747
}
2848
)()

frontend/src/services/user/index.js

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,9 @@ export const userServices = (
44
const BASE_URL = 'http://localhost:3200'
55

66
// current user
7-
function currentUser (payload, token) {
8-
const url = `${BASE_URL}/current-user`
9-
const headers = {
10-
token: token
11-
}
12-
return ApiService.post(url, payload, headers)
7+
function currentUser (payload) {
8+
const url = `/current-user`
9+
return ApiService.postWithAuth(url, payload)
1310
}
1411

1512
return {

0 commit comments

Comments
 (0)