Skip to content

Commit

Permalink
fix api
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Jun 12, 2024
1 parent 6faa5d1 commit bfafbba
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 6 deletions.
3 changes: 2 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
VITE_API_BASE_URL=http://localhost:8000/
VITE_API_BASE_URL=http://localhost:8000/api/
VITE_SERVICE_NAME=portal
61 changes: 57 additions & 4 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,65 @@
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"
import Cookies from "js-cookie"

import { tagTypes } from "codeforlife/api"

// https://docs.djangoproject.com/en/3.2/ref/csrf/
const getCsrfCookie = () =>
Cookies.get(`${import.meta.env.VITE_SERVICE_NAME}_csrftoken`)

const fetch = fetchBaseQuery({
baseUrl: import.meta.env.VITE_API_BASE_URL,
credentials: "include",
prepareHeaders: (headers, { type }) => {
if (type === "mutation") {
let csrfToken = getCsrfCookie()
if (csrfToken) headers.set("x-csrftoken", csrfToken)
}

return headers
},
})

const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: import.meta.env.VITE_API_BASE_URL,
}),
baseQuery: async (args, api, extraOptions) => {
if (api.type === "mutation" && getCsrfCookie() === undefined) {
// Get the CSRF token.
const { error } = await fetch({ url: "", method: "GET" }, api, {})

// Validate we got the CSRF token.
if (error !== undefined) {
console.error(error)
// TODO
// window.location.href = `${PORTAL_BASE_URL}/error/500`
}
if (getCsrfCookie() === undefined) {
// TODO
// window.location.href = `${PORTAL_BASE_URL}/error/500`
}
}

// Send the HTTP request and fetch the response.
return await fetch(args, api, extraOptions)
},
tagTypes: [...tagTypes, "SchoolTeacherInvitation"],
endpoints: () => ({}),
endpoints: build => ({
logout: build.mutation<null, null>({
query: () => ({
url: "session/logout/",
method: "GET", // Should this be DELETE?
}),
async onQueryStarted(_, { dispatch, queryFulfilled }) {
try {
await queryFulfilled
} catch (error) {
console.error("Failed to log out...", error)
} finally {
dispatch(api.util.resetApiState())
}
},
}),
}),
})

export default api
export const { useLogoutMutation } = api
2 changes: 1 addition & 1 deletion src/api/sso.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const ssoApi = api.injectEndpoints({
}),
loginWithOtp: build.mutation<null, { otp: number }>({
query: body => ({
url: baseUrl + "otp/",
url: baseUrl + "login-with-otp/",
method: "POST",
body,
}),
Expand Down

0 comments on commit bfafbba

Please sign in to comment.