authReducer.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import { gql } from "graphql-request";
  2. import { createApi } from '@reduxjs/toolkit/query/react'
  3. import { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query' //npm install
  4. import { jwtDecode } from "../utills";
  5. import { createSlice, current } from "@reduxjs/toolkit";
  6. import { history } from "../App";
  7. //import { prepareHeaders } from "./index";
  8. export const prepareHeaders = (headers, { getState }) => {
  9. const token = getState().auth.token;
  10. if (token) {
  11. headers.set("Authorization", `Bearer ${token}`);
  12. }
  13. return headers;
  14. }
  15. export const loginApi = createApi({
  16. reducerPath: "authApi",
  17. baseQuery: graphqlRequestBaseQuery({
  18. url: '/graphql',
  19. prepareHeaders
  20. }),
  21. endpoints: (builder) => ({
  22. login: builder.mutation({
  23. query: ({ login, password }) => ({
  24. document: gql`
  25. query login($login: String, $password: String) {
  26. login(login: $login, password: $password)
  27. }
  28. `,
  29. variables: { login, password }
  30. })
  31. }),
  32. userFind: builder.query({
  33. query: (_id) => ({
  34. document: gql`
  35. query UserFind($q: String) {
  36. UserFindOne(query: $q){
  37. _id login nick avatar {_id url} createdAt
  38. }
  39. }
  40. `,
  41. variables: { q: JSON.stringify([{ _id }]) }
  42. }),
  43. providesTags: (result, error, id) => ([{ type: 'User', id }])
  44. }),
  45. setNick: builder.mutation({
  46. query: ({ _id, nick }) => ({
  47. document: gql`
  48. mutation SetNick($_id:String, $nick: String){
  49. UserUpsert(user: {_id: $_id, nick: $nick}){
  50. _id, nick
  51. }
  52. }
  53. `,
  54. variables: { _id, nick }
  55. }),
  56. invalidatesTags: (result, error, arg) => ([{ type: 'User', id: arg._id }])
  57. }),
  58. saveUser: builder.mutation({
  59. query: ({ user }) => ({
  60. document: gql`
  61. mutation UserUpsert($user: UserInput) {
  62. UserUpsert(user: $user) {
  63. _id
  64. }
  65. }
  66. `,
  67. variables: { user }
  68. }),
  69. invalidatesTags: (result, error, arg) => ([{ type: 'User', id: arg._id }])
  70. }),
  71. }),
  72. })
  73. export let authReducerPath = 'auth';
  74. const authSlice = createSlice({
  75. name: authReducerPath,
  76. initialState: {},
  77. reducers: {
  78. logout(state) { //type - auth/logout
  79. // state.token = undefined
  80. history.push('/');
  81. return {}
  82. }
  83. },
  84. extraReducers: builder => {
  85. builder.addMatcher(loginApi.endpoints.login.matchFulfilled,
  86. (state, { payload }) => {
  87. const tokenPayload = jwtDecode(payload.login);
  88. if (tokenPayload) {
  89. state.token = payload.login;
  90. state.payload = tokenPayload;
  91. state.currentUser = { _id: tokenPayload.sub.id };
  92. history.push('/');
  93. }
  94. });
  95. builder.addMatcher(loginApi.endpoints.userFind.matchFulfilled,
  96. (state, { payload }) => {
  97. let retrievedUser = payload?.UserFindOne;
  98. if (retrievedUser?._id === state.currentUser?._id)
  99. state.currentUser = retrievedUser;
  100. });
  101. builder.addMatcher(loginApi.endpoints.saveUser.matchFulfilled,
  102. (state, { payload }) => {
  103. let a = '';
  104. let b = '';
  105. });
  106. builder.addMatcher(loginApi.endpoints.saveUser.matchRejected,
  107. (state, data) => {
  108. let a = '';
  109. let b = '';
  110. });
  111. }
  112. })
  113. const actionAboutMe = () =>
  114. async (dispatch, getState) => {
  115. const auth = getState().auth
  116. if (auth.token) {
  117. dispatch(loginApi.endpoints.userFind.initiate(auth.currentUser._id))
  118. }
  119. }
  120. const { logout: actionAuthLogout } = authSlice.actions;
  121. let authApiReducer = loginApi.reducer;
  122. let authReducer = authSlice.reducer;
  123. let authApiReducerPath = loginApi.reducerPath;
  124. export const { useLoginMutation, useUserFindQuery, useSaveUserMutation } = loginApi;
  125. export { authApiReducer, authReducer, authApiReducerPath, actionAuthLogout, actionAboutMe }