Browse Source

rtk_tree_view_clear_promise

Gennadysht 1 year ago
parent
commit
e4e0bdecd2

+ 0 - 37
src/gql/gqlGoods.js

@@ -1,37 +0,0 @@
-import { gql } from "../utills/gql";
-import { createFullQuery } from "./gqlUtils";
-export const gqlGoodFindOne = (id) => {
-    let params = createFullQuery({ searchStr: id, searchFieldNames: ["_id"] });
-    const gqlQuery = `
-                query GoodFindOne($q: String) {
-                    GoodFindOne(query: $q) {
-                        _id name  price description
-                        images { url }
-                    }
-                }
-                `;
-    return gql(gqlQuery, params);
-}
-
-export const gqlGoodFind = (fromPage, pageSize, searchStr = '', queryExt = {}) => {
-    let params = createFullQuery(getGoodsSearchParams(searchStr, queryExt), { fromPage, pageSize });
-    const gqlQuery = `
-                query GoodFind($q: String) {
-                    GoodFind(query: $q) {
-                        _id name  price description
-                        images { url }
-                    }
-                }
-                `;
-    return gql(gqlQuery, params);
-}
-export const gqlGoodsCount = (query = '', queryExt = {}) => {
-    let params = createFullQuery(getGoodsSearchParams(query, queryExt));
-    const gqlQuery = `query GoodsCount($q: String) { GoodCount(query: $q) }`;
-    return gql(gqlQuery, params);
-}
-const getGoodsSearchParams = (searchStr, queryExt) => (
-    {
-        searchStr: searchStr, searchFieldNames: ["name", "description"],
-        queryExt
-    });

+ 0 - 31
src/gql/gqlUtils.js

@@ -1,31 +0,0 @@
-const createQuery = (searchStr, searchFieldNames) => {
-    let result = [];
-    if (searchStr) {
-        for (let searchFieldName of searchFieldNames) {
-            //result[searchFieldName] = searchFieldName === '_id' ? searchStr : `/${searchStr}/`;
-            result.push({ [searchFieldName]: searchFieldName === '_id' ? searchStr : `/${searchStr}/` });
-        }
-    }
-    return result.length === 0 ? {} :  { $or: result };
-}
-
-const createQueryExt = (searchQuery = {}, queryExt = {}) => {
-    if (!queryExt)
-        return searchQuery;
-    return { $and: [searchQuery, queryExt] };
-}
-
-const createQueryPaging = (fromPage, pageSize, sort) => {
-    let result = {};
-    if (fromPage !== undefined && pageSize !== undefined) {
-        result["skip"] = [fromPage * pageSize];
-        result["limit"] = [pageSize];
-    }
-    if (sort)
-        result["sort"] = [sort];
-    return result;
-}
-
-export const createFullQuery = ({ searchStr, searchFieldNames, queryExt = {} }, { fromPage, pageSize, sort } = {}) => {
-    return { q: JSON.stringify([createQueryExt(createQuery(searchStr, searchFieldNames), queryExt), createQueryPaging(fromPage, pageSize, sort)]) };
-}

+ 0 - 2
src/gql/index.js

@@ -1,2 +0,0 @@
-export { gqlGoodFind, gqlGoodFindOne } from './gqlGoods';
-export {createFullQuery} from './gqlUtils';

+ 1 - 1
src/reducers/authReducer.js

@@ -5,7 +5,7 @@ import { jwtDecode } from "../utills";
 import { createSlice } from "@reduxjs/toolkit";
 import { history } from "../App";
 import { UserEntity } from "../Entities";
-import { createFullQuery } from "../gql";
+import { createFullQuery } from "../utills";
 
 const getUsersSearchParams = (searchStr, queryExt) => (
     {

+ 7 - 2
src/reducers/categoryReducer.js

@@ -1,8 +1,7 @@
 import { createApi } from '@reduxjs/toolkit/query/react'
 import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query"
 import { gql } from "graphql-request";
-import { createFullQuery } from '../gql';
-//import { prepareHeaders } from "./index";
+import { createFullQuery } from '../utills';
 
 const getCategorySearchParams = (query, queryExt) => ({ searchStr: query, searchFieldNames: ["name"], queryExt });
 export const prepareHeaders = (headers, { getState }) => {
@@ -91,6 +90,12 @@ export const categoryApi = createApi({
                     ? [{ type: 'Category', _id: result.CategoryFindOne._id }, 'Category']
                     : ['Category'];
             },
+            transformResponse: (response) => {
+                return response;
+            },
+            transformErrorResponse: (response) => {
+                return response;
+            },
         }),
         saveCategory: builder.mutation({
             query: ({ category }) => (

+ 1 - 1
src/reducers/goodsReducer.js

@@ -1,7 +1,7 @@
 import { createApi } from '@reduxjs/toolkit/query/react'
 import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query"
 import { gql } from "graphql-request";
-import { createFullQuery } from '../gql';
+import { createFullQuery } from '../utills';
 
 export const prepareHeaders = (headers, { getState }) => {
     const token = getState().auth.token;

+ 0 - 1
src/reducers/index.js

@@ -1,4 +1,3 @@
-export { promiseReducer, actionPromise, actionFulfilled, actionPending, actionRejected } from "./promiseReducer";
 export { authApi, authSlice, authApi as loginApi, useUserFindQuery, actionAuthLogout, useGetUsersQuery, useGetUsersCountQuery, useSaveUserMutation, getCurrentUser, isCurrentUserAdmin } from './authReducer';
 export { cartSlice, actionAddGoodToCart, actionDeleteGoodFromCart, actionRestoreCart, actionClearCart, getCartItemsCount } from "./cartReducer";
 export { localStoredReducer, } from "./localStoredReducer";

+ 2 - 1
src/reducers/ordersReducer.js

@@ -1,7 +1,7 @@
 import { createApi } from '@reduxjs/toolkit/query/react'
 import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query"
 import { gql } from "graphql-request";
-import { createFullQuery } from '../gql';
+import { createFullQuery } from '../utills';
 
 const getOrderSearchParams = (query, queryExt) => ({ searchStr: query, searchFieldNames: ["_id"], queryExt });
 const prepareHeaders = (headers, { getState }) => {
@@ -11,6 +11,7 @@ const prepareHeaders = (headers, { getState }) => {
     }
     return headers;
 }
+
 const ordersApi = createApi({
     reducerPath: 'orders',
     baseQuery: graphqlRequestBaseQuery({

+ 0 - 44
src/reducers/promiseReducer.js

@@ -1,44 +0,0 @@
-import { createSlice } from "@reduxjs/toolkit"
-
-const createPromiseReducerSlice = name => createSlice({ //promiseReducer
-    name: name, //префикс типа наподобие AUTH_
-    initialState: {}, //state={} в параметрах
-    reducers: {
-        pending(state, { payload: { name } }) { //if (type === 'promise/pending')
-            state[name] = { status: 'PENDING' }
-        },
-        fulfilled(state, { payload: { name, payload } }) { //if (type === 'promise/fulfilled')
-            state[name] = { status: 'FULFILLED', payload }
-        },
-        rejected(state, { payload: { name, error } }) { //if (type === 'promise/rejected')
-            state[name] = { status: 'REJECTED', error }
-        },
-    }
-});
-
-const promiseReducerSlice = createPromiseReducerSlice('promise');
-
-const actionPromiseGeneric = (promiseReducerSlice, name, promise) =>
-    async dispatch => {
-        try {
-            dispatch(promiseReducerSlice.actions.pending({ name }))
-            let payload = await promise
-            if (payload && payload.data)
-                payload = Object.values(payload.data)[0];
-            dispatch(promiseReducerSlice.actions.fulfilled({ name, payload }))
-            return payload
-        }
-        catch (error) {
-            dispatch(promiseReducerSlice.actions.rejected({ name, error }))
-        }
-    }
-
-const actionPromise = (name, promise) => 
-    actionPromiseGeneric(promiseReducerSlice, name, promise);
-
-
-let promiseReducer = promiseReducerSlice.reducer;
-let actionPending = promiseReducerSlice.actions.pending;
-let actionFulfilled = promiseReducerSlice.actions.fulfilled;
-let actionRejected = promiseReducerSlice.actions.rejected;
-export { promiseReducer, actionPending, actionFulfilled, actionRejected, actionPromise, createPromiseReducerSlice, actionPromiseGeneric };

+ 0 - 61
src/utills/gql.js

@@ -1,61 +0,0 @@
-function jwtDecode(token) {                         // расщифровки токена авторизации
-    if (!token || typeof token != "string")
-        return undefined;
-    let tokenArr = token.split(".");
-    if (tokenArr.length !== 3)
-        return undefined;
-    try {
-        let tokenJsonStr = atob(tokenArr[1]);
-        let tokenJson = JSON.parse(tokenJsonStr);
-        return tokenJson;
-    }
-    catch (error) {
-        return undefined;
-    }
-}
-
-function getGql(url) {
-    return function gql(query, vars = undefined) {
-        try {
-            let fetchSettings =
-            {
-                method: "POST",
-                headers:
-                {
-                    "Content-Type": "application/json",
-                    "Accept": "application/json"
-                },
-                body: JSON.stringify(
-                    {
-                        query: query,
-                        variables: vars
-                    })
-            };
-            let authToken = window.localStorage.authToken;
-            if (authToken) {
-                fetchSettings.headers["Authorization"] = `Bearer ${authToken}`;
-            }
-            return fetch(url, fetchSettings)
-                .then(res => {
-                    try {
-                        if (!res.ok) {
-                            throw Error(res.statusText);
-                        }
-                        return res.json();
-                    }
-                    catch (error) {
-                        throw error;
-                    }
-
-                });
-        }
-        catch (error) {
-            throw error;
-        }
-    }
-}
-const gql = getGql("http://shop-roles.node.ed.asmer.org.ua/graphql");
-
-export { gql, jwtDecode }
-//export default gql;
-

+ 2 - 2
src/utills/index.js

@@ -1,2 +1,2 @@
-export {getFullImageUrl, findObjectIndexById, capitalize, fixBackendDataError} from './utils';
-export {gql, jwtDecode} from './gql';
+export {getFullImageUrl, findObjectIndexById, capitalize, fixBackendDataError, jwtDecode} from './utils';
+export {createFullQuery} from './gqlUtils';

+ 18 - 1
src/utills/utils.js

@@ -27,6 +27,23 @@ const fixBackendDataError = (result, propName) => {
     return undefined;
 }
 
-export { getFullImageUrl, findObjectIndexById, saveImage, capitalize, fixBackendDataError };
+function jwtDecode(token) {                         // расщифровки токена авторизации
+    if (!token || typeof token != "string")
+        return undefined;
+    let tokenArr = token.split(".");
+    if (tokenArr.length !== 3)
+        return undefined;
+    try {
+        let tokenJsonStr = atob(tokenArr[1]);
+        let tokenJson = JSON.parse(tokenJsonStr);
+        return tokenJson;
+    }
+    catch (error) {
+        return undefined;
+    }
+}
+
+
+export { getFullImageUrl, findObjectIndexById, saveImage, capitalize, fixBackendDataError, jwtDecode };