Browse Source

metaplate checks: looks like it works

asmer 3 months ago
parent
commit
459a1d1e51
3 changed files with 160 additions and 101 deletions
  1. 155 99
      src/App.tsx
  2. 5 1
      src/lib/index.ts
  3. 0 1
      src/lib/router/index.tsx

+ 155 - 99
src/App.tsx

@@ -1,25 +1,21 @@
-import { useState, useEffect } from 'react'
-import reactLogo from './assets/react.svg'
-import viteLogo from '/vite.svg'
+import { useState, useEffect, Fragment } from 'react'
 import './App.css'
 import {createBrowserHistory} from 'history';
-import {Router} from 'react-router-dom'
-import {createQueryPub} from './lib/pub';
+import {Router, Link} from 'react-router-dom'
+import {createQueryPub, NamedRoute, NamedLink} from './lib';
+import {MetaPlate} from './lib';
 
-const history = createBrowserHistory()
-
-//console.log(createQueryPub)
-//
 
+const history = createBrowserHistory()
 
-//
-//
 const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2NjdmZjBkYTIyMzIxMjBjN2M4NzFmN2MiLCJsb2dpbiI6InRzdDE5IiwiYWNsIjpbIjY2N2ZmMGRhMjIzMjEyMGM3Yzg3MWY3YyIsInVzZXIiXX0sImlhdCI6MTcyMDI1OTEwN30.eDcInxQlskt32LjaCe5sdCcJ3B97BKYZtgUARxThYQM'
 
 console.log(JSON.parse(atob(token.split('.')[1])).sub.id)
 
+const shopUrl = 'http://shop-roles.node.ed.asmer.org.ua/'
+
 const gql = (query, variables={}) => 
-    fetch('http://shop-roles.node.ed.asmer.org.ua/graphql',{
+    fetch(shopUrl + 'graphql',{
         method: 'POST',
         headers: {
             'Content-Type': 'application/json',
@@ -32,112 +28,172 @@ const gql = (query, variables={}) =>
 const {queryPub, createQuery, withQueryFunc} = createQueryPub({
     queryFunc: gql,
     cacheTimeout: 500000,
-    //hidePendingOnRefresh: false,
 })
 
-
-//queryPub.subscribe(() => console.log(JSON.stringify(queryPub.queries.user, null, 4)))
-
-const {useGoodsQuery} = createQuery({promiseName: 'goods',
-                                     cacheTagsFunc: (payload) => payload.data.GoodFind.map(good => ({type: 'Good', id: good._id}))})
-
-//const {useUserQuery}  = createQuery({
-    //promiseName: 'user',
-    //args: [` 
-        //query user($query: String) {
-            //UserFindOne(query: $query){
-                //_id login nick
-            //}
-        //}
-    //`],
-    //cacheTagsFunc: ({data: {UserFindOne: {_id}}}) => ({_id, type: 'User'})
-//})
-//const userState = useUserQuery({query: JSON.stringify([{_id: '667ff0da2232120c7c871f7c'}])})
-
-//const {useUserQuery} = withQueryFunc(_id => gql(
-   //`query user($query: String) {
-        //UserFindOne(query: $query){
-            //_id login nick
-        //}
-    //}`,
-    //{query: JSON.stringify([{_id}])}
-//))({
-    //promiseName: 'user',
-    //cacheTagsFunc: ({data: {UserFindOne: {_id}}}) => ({_id, type: 'User'})
-//})
-
-
-const {useUserQuery}  = createQuery({
-    promiseName: 'user',
-    args: (_id) =>  [` 
-        query user($query: String) {
-            UserFindOne(query: $query){
-                _id login nick
+const {useCategoriesQuery} = createQuery({
+    promiseName: 'categories',
+    args: [`query MainCategories{
+              CategoryFind(query: "[{}]"){
+                _id name
+                  image{
+                    url
+                  }
+                goods{
+                _id
+                name description price images{
+                  url
+                }
+              }
+              subCategories{ name _id}
             }
         }
-    `, {query: JSON.stringify([{_id}])}],
-    cacheTagsFunc: ({data: {UserFindOne: {_id}}}) => [{_id, type: 'User'}]
+    `]
 })
 
-const {useUserMutation} = createQuery({
-    promiseName: 'user',
-    isMutation: true,
-    args: (_id, nick) => [
-        `mutation changeNick($_id:String, $nick:String){
-            UserUpsert(user:{_id:$_id, nick:$nick}){
-                _id nick
+const {useMainCategoriesQuery} = createQuery({
+    promiseName: 'mainCategories',
+    args: [`query MainCategories{
+              CategoryFind(query: "[{\\"parent\\":null}]"){
+                _id name
+                  image{
+                    url
+                  }
+                goods{
+                _id
+                name description price images{
+                  url
+                }
+              }
+              subCategories{ name _id}
             }
-        }`,
-        {_id, nick}],
-    cacheTagsFunc: ({data: {UserUpsert: {_id}}}) => [{_id, type: 'User'}]
+        }
+    `]
 })
 
-const EditNick = () => {
-    const [nick, setNick] = useState('')
-    const [update, {status, payload, error}] = useUserMutation()
-    console.log(status, payload, error)
-    return (
-        <div>
-            <input type='text' value={nick} onChange={e => setNick(e.target.value)} />
-            <button onClick={() => update('667ff0da2232120c7c871f7c', nick)}>Save</button>
-        </div>
-    )
-}
-
 
-function App() {
-    //const queryState = useGoodsQuery(`query {
-        //GoodFind(query: "[{}]"){
-            //name price _id
-        //}
-    //}`)
+const {query: categoryQuery} = createQuery({
+    promiseName: 'category',
+    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}])}]
+})
 
 
-    const userState = useUserQuery('667ff0da2232120c7c871f7c')
-    console.log(userState)
+//queryPub.subscribe(() => console.log(JSON.stringify(queryPub.queries.user, null, 4)))
+//
 
-    const [,setRandomState] = useState<number>()
 
-    useEffect(() => {
-        //setInterval(() => setRandomState(Math.random()), 1000)
-    },[])
 
-    //console.log(queryState)
+const Image = ({src}) => <img src={`${shopUrl}${src}`} style={{maxWidth: '50%'}}/>
+
+const Good = ({good, children}) =>
+good ? 
+<div className='Good'>
+    <h2>{good.name}</h2>
+    <p>{good.description}</p>
+    <money>{good.price}</money>
+    {children}
+</div>
+: <h3>null</h3>
+
+const Category = ({category:{name, _id}, children}) =>
+<div className='Category'>
+    <h1>{name}</h1>
+    {_id}
+    {children}
+</div>
+
+const Categories = ({children, data}) => 
+<div style={{border: '2px solid', paddingLeft: '20px'}}>
+    <h1>categories({data && data.length})</h1>
+    {children}
+</div>
+
+const Goods = ({children}) => 
+<div style={{border: '2px solid blue', paddingLeft: '10px'}}>
+    <h2>goods</h2>
+    {children}
+</div>
+
+const PageCategory = ({data}) => 
+    <MetaPlate data={data.payload.data.CategoryFindOne}>
+            <Category prop="category" keyDataKey="_id">
+                <Goods sourceDataKey="goods"> 
+                    <Good prop="good" keyDataKey="_id">
+                        <div sourceDataKey="images">
+                            <Image prop="src" sourceDataKey="url"/>
+                        </div>
+                    </Good>
+                </Goods>
+                <Categories sourceDataKey="subCategories" prop='data'>
+                    <Category prop="category" keyDataKey="_id" />
+                </Categories>
+            </Category>
+    </MetaPlate> 
+
+const LeftMenuItem = ({category:{_id,name}})=>
+//<li><NamedLink name='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.data.CategoryFind}>
+                    <Fragment>
+                        <LeftMenuItem prop="category" keyDataKey="_id"/>
+                    </Fragment>
+                </MetaPlate>}
+        </ul>
+    )
+}
 
-    //const {status, payload,cacheTags} = queryState
-    //console.log(JSON.stringify(cacheTags))
+function App() {
+    //const {payload} = useCategoriesQuery()
+    //console.log('update', performance.now())
+    //useEffect(() => console.log('effect',performance.now()), [payload])
     return (
         <Router history={history}>
-        <EditNick />
-        {userState.status === 'PENDING' && <h1>Loading</h1>}
-        {userState.status === 'FULFILLED' && userState.payload.data.UserFindOne.nick}
-
-
-
-        {/*status === 'PENDING' && <h1>Loading</h1>}
-        {status === 'FULFILLED' && payload.data.GoodFind.map(good => <h2 key={good._id}>{good.name}</h2>) */}
-
 
+            <LeftMenu />
+            <NamedRoute name="category" 
+                query={categoryQuery}
+                path="/category/:_id" 
+                component={PageCategory}/>
+
+
+
+            {/*payload && 
+            <MetaPlate data={payload.data.CategoryFind}>
+                <Categories prop='data'>
+                    <Category prop="category" keyDataKey="_id">
+                        <Goods sourceDataKey="goods"> 
+                            <Good prop="good" keyDataKey="_id">
+                                <div sourceDataKey="images">
+                                    <Image prop="src" sourceDataKey="url"/>
+                                </div>
+                            </Good>
+                        </Goods>
+                        <Categories sourceDataKey="subCategories" prop='data'>
+                            <Category prop="category" keyDataKey="_id" />
+                        </Categories>
+                    </Category>
+                </Categories>
+            </MetaPlate> */ }
         </Router>
     )
 }

+ 5 - 1
src/lib/index.ts

@@ -3,5 +3,9 @@ import createPub from './pub';
 export {createPub};
 
 export type { Pub } from  './pub'
-export { usePub } from  './pub'
+export { usePub, createQueryPub } from  './pub'
+
+
 export {NamedRoute, NamedLink, HashRoute, createPrivateRoute} from './router'
+import MetaPlate from './metaplate';
+export {MetaPlate, }

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

@@ -16,7 +16,6 @@ export const NamedRoute = ({name, routeName, query, pendingQueryComponent:P, err
         const [queryResult, setQueryResult] = useState()
         const [queryError, setQueryError] = useState()
         useEffect(() => {
-            console.log(props)
             if (query && typeof query === 'function'){
                 const querySyncResult = query(props.match.params, props, name)
                 if (querySyncResult && typeof querySyncResult.then === 'function'){