Browse Source

basic query routes sample

asmer 1 month ago
parent
commit
64434034ce
5 changed files with 101 additions and 33 deletions
  1. 88 24
      src/App.tsx
  2. 1 1
      src/lib/index.ts
  3. 4 1
      src/lib/pub/query/index.ts
  4. 6 6
      src/lib/queryRoute/index.tsx
  5. 2 1
      src/lib/router/index.tsx

+ 88 - 24
src/App.tsx

@@ -5,12 +5,17 @@ import {Router, Link} from 'react-router-dom'
 import {createQueryPub, NamedRoute, NamedLink, usePub} from './lib';
 import {MetaPlate} from './lib';
 
+import {createQueryRoutes} from './lib';
+
+/*
+  CREATE QUERY ROUTE HUGE CONFIGURATION SAMPLE/TEST
+ */
 
 const history = createBrowserHistory()
 
 const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2NjdmZjBkYTIyMzIxMjBjN2M4NzFmN2MiLCJsb2dpbiI6InRzdDE5IiwiYWNsIjpbIjY2N2ZmMGRhMjIzMjEyMGM3Yzg3MWY3YyIsInVzZXIiXX0sImlhdCI6MTcyMDI1OTEwN30.eDcInxQlskt32LjaCe5sdCcJ3B97BKYZtgUARxThYQM'
 
-console.log(JSON.parse(atob(token.split('.')[1])).sub.id)
+//console.log(JSON.parse(atob(token.split('.')[1])).sub.id)
 
 const shopUrl = 'http://shop-roles.node.ed.asmer.org.ua/'
 
@@ -32,6 +37,31 @@ const gql = (query, variables={}) =>
         return Object.values(result.data)[0]
     })
 
+const LeftMenu = ({data}) => {
+    return (
+        <ul>
+                <MetaPlate data={data}>
+                    <>
+                        <LeftMenuItem prop="category" keyDataKey="_id"/>
+                    </>
+                </MetaPlate>
+        </ul>
+    )
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 const {queryPub, createQuery, withQueryFunc} = createQueryPub({
     queryFunc: gql,
     cacheTimeout: 5000,
@@ -107,9 +137,9 @@ const {query: categoryQuery, useCategoryQuery} = createQuery({
 const Image = ({src}) => <img src={`${shopUrl}${src}`} style={{maxWidth: '50%'}}/>
 
 const Good = ({good, children}) => {
-    useEffect(() => {
-        console.log('good mount', good.name)
-    },[])
+    //useEffect(() => {
+        //console.log('good mount', good.name)
+    //},[])
     return (
         good ? 
             <div className='Good'>
@@ -171,20 +201,59 @@ const PageCategory = ({data}) => {
 const LeftMenuItem = ({category:{_id,name}})=>
 <li><NamedLink routeName='category' params={{_id}}>{name}</NamedLink></li>
 //<li><Link  to={`/category/${_id}`}>{name}</Link></li>
+//
+//
 
-const LeftMenu = () => {
-    const {payload} = useMainCategoriesQuery()
-    return (
-        <ul>
-            {payload && 
-                <MetaPlate data={payload}>
-                    <>
-                        <LeftMenuItem prop="category" keyDataKey="_id"/>
-                    </>
-                </MetaPlate>}
-        </ul>
-    )
-}
+
+const queryRouteResult = createQueryRoutes({
+    query: gql,
+    Pending: () => <h1>Loading...</h1>,
+    //cacheTimeout: 5000,
+    queryRoutes: {
+        index: {
+            path: '/',
+            args: [`query MainCategories{
+                      CategoryFind(query: "[{\\"parent\\":null}]"){
+                        _id name
+                          image{
+                            url 
+                          }
+                        goods{
+                        _id
+                        name description price images{
+                          url
+                        }
+                      }
+                      subCategories{ name _id}
+                    }
+                }
+            `],
+            component: LeftMenu,
+        },
+        category: {
+            path: '/category/:_id',
+            args: ({_id}) => [`query categoryById($query:String){
+                      CategoryFindOne(query: $query){
+                        _id name
+                          image{
+                            url
+                          }
+                        goods{
+                        _id
+                        name description price images{
+                          url
+                        }
+                      }
+                      subCategories{ name _id}
+                    }
+                }
+            `, {query: JSON.stringify([{_id}])}],
+            component: PageCategory
+        }
+    }
+})
+
+const { AllRoutes } = queryRouteResult
 
 function App() {
     //const {payload} = useCategoriesQuery()
@@ -193,13 +262,8 @@ function App() {
     return (
         <Router history={history}>
 
-            <LeftMenu />
-            <NamedRoute name="category" 
-                query={categoryQuery}
-                path="/category/:_id" 
-                errorQueryComponent={({error}) => <h1><pre>{error.message}</pre></h1>}
-                pendingQueryComponent={() => <h1>Loading</h1>}
-                component={PageCategory}/>
+            <AllRoutes />
+
 
 
 

+ 1 - 1
src/lib/index.ts

@@ -9,6 +9,6 @@ export { usePub, createQueryPub } from  './pub'
 export {NamedRoute, NamedLink, HashRoute, createPrivateRoute} from './router'
 import MetaPlate from './metaplate';
 export { MetaPlate }
-export { createQueryRoute } from './queryRoute'; 
+export { createQueryRoutes } from './queryRoute'; 
 
 

+ 4 - 1
src/lib/pub/query/index.ts

@@ -34,7 +34,10 @@ export default (options:CreateQueryPubOptions) => {
     const queryPub = createPub({queries: {}, mutations: {}})
     const currentPromises = {queries: {}, mutations: {}}
 
-    options = {...defaultOptions, ...options}
+    options.cacheTimeout                ||= defaultOptions.cacheTimeout
+    options.hidePendingOnRefresh        ||= defaultOptions.hidePendingOnRefresh
+    options.avoidRepeatInProgress       ||= defaultOptions.avoidRepeatInProgress
+    options.forceRefreshAfterTimeout    ||= defaultOptions.forceRefreshAfterTimeout
 
     /*
      * function to remember basic transport function (like fetch or gql) in closure for further usage

+ 6 - 6
src/lib/queryRoute/index.tsx

@@ -1,4 +1,4 @@
-import { ComponentType } from 'react';
+import { ComponentType, Fragment } from 'react';
 import { GetUserRolesFunc, NamedRoute, NamedLink, createPrivateRoute } from '../router';
 import { Pub } from '../pub';
 import { createQueryPub } from '../pub';
@@ -138,10 +138,10 @@ export const createQueryRoutes = (options:CreateQueryRoutesOptions):CreateQueryR
 
     const queryRoutesResults:QueryRoutesResults = {};
 
-    for (const {name, queryRoute} of Object.entries(options.queryRoutes)){
-        const {path, args, component, Pending, Error:ErrorComponent, errorQueryComponentErrorProp:errorProp, componentQueryResultProp:resultProp, path, cacheTagsFunc, roles, fallback, isMutation} = queryRoute
+    for (const [name, queryRoute] of Object.entries(options.queryRoutes)){
+        const {path, args, component, Pending, Error:ErrorComponent, errorQueryComponentErrorProp:errorProp, componentQueryResultProp:resultProp, cacheTagsFunc, roles, fallback, isMutation} = queryRoute
 
-        const camelCaseName = name[1].toUpperCase() + name.slice(1)
+        const camelCaseName = name[0].toUpperCase() + name.slice(1)
 
         let queryRouteResult:QueryRouteResult = {}
 
@@ -205,13 +205,13 @@ export const createQueryRoutes = (options:CreateQueryRoutesOptions):CreateQueryR
         }
 
 
-        queryRoutesResults[name] = queryRoutesResult
+        queryRoutesResults[name] = queryRouteResult
     }
 
     const AllRoutes = () => 
         (
             <>
-                {Object.values(queryRoutesResults).map(({Route}) => <Route />)}
+                {Object.entries(queryRoutesResults).map(([key,{Route}]) => <Route key={key}/>)}
             </>
         )
 

+ 2 - 1
src/lib/router/index.tsx

@@ -19,9 +19,10 @@ export const NamedRoute = ({name, routeName, query, pendingQueryComponent:P, err
         useEffect(() => {
             if (query && typeof query === 'function'){
                 if (typeof query.getQueryPubBranch === 'function'){ //if it's queryPub query function
-                    query(props.match.params, props, name)
+                    query(props.match.params/*, props, name*/)
                     const [queryPub, key] = query.getQueryPubBranch(props.match.params)
                     queryPubUnsubscribeRef.current = queryPub.subscribe(() => {
+                        //console.log(queryPub, key, queryPub[key])
                         const {status, payload, error} = queryPub[key];
                         ({
                             PENDING(){