slices.mjs 1 KB
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const loginPrepareHeaders = (headers, context) => {
  const { getState } = context
  const state = getState()
  const { data: { access_token } = {} } = loginApiSlice.endpoints.getToken.select()(state)
  if (access_token) {
    headers.set('authorization', `Bearer ${access_token}`)
  }
  return headers
}

export const loginApiSlice = createApi({
  reducerPath: 'login',
  tagTypes: ['Token'],
  keepUnusedDataFor: 60,
  baseQuery: fetchBaseQuery({
    baseUrl: '/login',
  }),
  refetchOnReconnect: true,
  endpoints: builder => ({
    getToken: builder.query({
      query: () => ({
        url: '/token?refresh',
        method: 'GET',
      }),
      providesTags(result, error, arg) {
        const { expires_at, access_token } = result
        return ['Token']
      },
    }),
  }),
})

export const { useGetTokenQuery } = loginApiSlice
export const invalidateToken = (dispatch) => dispatch(loginApiSlice.util.invalidateTags(['Token']))