categoryReducer.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { createApi } from '@reduxjs/toolkit/query/react'
  2. import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query"
  3. import { gql } from "graphql-request";
  4. //import { prepareHeaders } from "./index";
  5. export const prepareHeaders = (headers, { getState }) => {
  6. const token = getState().auth.token;
  7. if (token) {
  8. headers.set("Authorization", `Bearer ${token}`);
  9. }
  10. return headers;
  11. }
  12. export const categoryApi = createApi({
  13. reducerPath: 'category',
  14. baseQuery: graphqlRequestBaseQuery({
  15. url: '/graphql',
  16. prepareHeaders
  17. }),
  18. endpoints: (builder) => ({
  19. getRootCategories: builder.query({
  20. query: () => ({
  21. document: gql`
  22. query GetCategories{
  23. CategoryFind(query: "[{\\"parent\\": null}]") {
  24. _id name
  25. }
  26. }
  27. `}),
  28. }),
  29. getCategoryById: builder.query({
  30. query: (_id) => ({
  31. document: gql`
  32. query GetCategory($q: String) {
  33. CategoryFindOne(query: $q) {
  34. _id name
  35. parent { _id name }
  36. subCategories { _id name }
  37. goods { _id name price description
  38. images { url }
  39. }
  40. }
  41. }
  42. `,
  43. variables: { q: JSON.stringify([{ _id }]) }
  44. }),
  45. invalidatesTags: (result, error, arg) => ([{type: 'GoodsCount', id: arg._id}])
  46. }),
  47. }),
  48. })
  49. export const { useGetRootCategoriesQuery, useGetCategoryByIdQuery } = categoryApi;