浏览代码

HW19 (module)

Volddemar4ik 2 年之前
父节点
当前提交
24bb24499e
共有 7 个文件被更改,包括 1724 次插入0 次删除
  1. 15 0
      js/17/HW17.js
  2. 187 0
      js/19 (module)/bolvanka.js
  3. 269 0
      js/19 (module)/graphql.js
  4. 89 0
      js/19 (module)/help requests.js
  5. 43 0
      js/19 (module)/index.html
  6. 849 0
      js/19 (module)/magic.js
  7. 272 0
      js/19 (module)/redusers.js

+ 15 - 0
js/17/HW17.js

@@ -570,4 +570,19 @@
 //      по событию зарезолвить промис отдав в качестве результата объект события
 //      убрать обработчик с DOM - элемента, используя removeEventListener.
 {
+    function domEventPromise(element, nameOfEvent) {
+        function executor(resolve) {
+            function event(param) {
+                element.disabled = true;
+                element.removeEventListener(nameOfEvent, event);
+                setTimeout(() => resolve(param), 3000);
+            }
+            element.disabled = false;
+            element.addEventListener(nameOfEvent, event)
+        }
+        return new Promise(executor);
+    }
+
+
+
 }

+ 187 - 0
js/19 (module)/bolvanka.js

@@ -0,0 +1,187 @@
+function createStore(reducer) {
+    let state = reducer(undefined, {}) //стартовая инициализация состояния, запуск редьюсера со state === undefined
+    let cbs = []                     //массив подписчиков
+
+    const getState = () => state            //функция, возвращающая переменную из замыкания
+    const subscribe = cb => (cbs.push(cb),   //запоминаем подписчиков в массиве
+        () => cbs = cbs.filter(c => c !== cb)) //возвращаем функцию unsubscribe, которая удаляет подписчика из списка
+
+    const dispatch = action => {
+        if (typeof action === 'function') { //если action - не объект, а функция
+            return action(dispatch, getState) //запускаем эту функцию и даем ей dispatch и getState для работы
+        }
+        const newState = reducer(state, action) //пробуем запустить редьюсер
+        if (newState !== state) { //проверяем, смог ли редьюсер обработать action
+            state = newState //если смог, то обновляем state 
+            for (let cb of cbs) cb(state) //и запускаем подписчиков
+        }
+    }
+
+    return {
+        getState, //добавление функции getState в результирующий объект
+        dispatch,
+        subscribe //добавление subscribe в объект
+    }
+}
+
+function combineReducers(reducers) {
+    function totalReducer(state = {}, action) {
+        const newTotalState = {}
+        for (const [reducerName, reducer] of Object.entries(reducers)) {
+            const newSubState = reducer(state[reducerName], action)
+            if (newSubState !== state[reducerName]) {
+                newTotalState[reducerName] = newSubState
+            }
+        }
+        if (Object.keys(newTotalState).length) {
+            return { ...state, ...newTotalState }
+        }
+        return state
+    }
+
+    return totalReducer
+}
+
+const reducers = {
+    promise: promiseReducer, //допилить много имен для многих промисо
+    //auth: authReducer,     //часть предыдущего ДЗ
+    //cart: cartReducer,     //часть предыдущего ДЗ
+}
+
+const totalReducer = combineReducers(reducers)
+
+
+function promiseReducer(state = {}, { type, status, payload, error }) {
+    if (type === 'PROMISE') {
+        //имена добавить
+        return { status, payload, error }
+    }
+    return state
+}
+
+
+
+
+//имена добавить
+const actionPending = () => ({ type: 'PROMISE', status: 'PENDING' })
+const actionFulfilled = payload => ({ type: 'PROMISE', status: 'FULFILLED', payload })
+const actionRejected = error => ({ type: 'PROMISE', status: 'REJECTED', error })
+
+//имена добавить
+const actionPromise = promise =>
+    async dispatch => {
+        dispatch(actionPending()) //сигнализируем redux, что промис начался
+        try {
+            const payload = await promise //ожидаем промиса
+            dispatch(actionFulfilled(payload)) //сигнализируем redux, что промис успешно выполнен
+            return payload //в месте запуска store.dispatch с этим thunk можно так же получить результат промиса
+        }
+        catch (error) {
+            dispatch(actionRejected(error)) //в случае ошибки - сигнализируем redux, что промис несложился
+        }
+    }
+
+
+
+
+const store = createStore(totalReducer) //не забудьте combineReducers если он у вас уже есть
+store.subscribe(() => console.log(store.getState()))
+
+const drawPeople = (state) => {
+    const [, route] = location.hash.split('/')
+    if (route !== 'people') return
+
+    const { status, payload, error } = store.getState().promise//.имя другое
+    if (status === 'PENDING') {
+        main.innerHTML = `<img src='https://cdn.dribbble.com/users/63485/screenshots/1309731/infinite-gif-preloader.gif' />`
+    }
+    if (status === 'FULFILLED') {
+        const { name, mass, eye_color, films } = payload
+        main.innerHTML = `<h1>${name}</h1>
+                         <section>ЖЫРНОСТЬ: ${mass}кг</section>
+                         <section style="color: ${eye_color}">Цвет глаз</section>
+                         `
+        for (const filmUrl of films) {
+            const filmId = filmUrl.split('/films/')[1].slice(0, -1)
+            main.innerHTML += `<a href="#/films/${filmId}">Фильм №${filmId}</a>`
+        }
+    }
+}
+
+store.subscribe(drawPeople)
+
+store.subscribe(() => {
+    const [, route] = location.hash.split('/')
+    if (route !== 'films') return
+
+    const { status, payload, error } = store.getState().promise//.имя одно
+    if (status === 'PENDING') {
+        main.innerHTML = `<img src='https://cdn.dribbble.com/users/63485/screenshots/1309731/infinite-gif-preloader.gif' />`
+    }
+    if (status === 'FULFILLED') {
+        const { title, opening_crawl, characters } = payload
+        main.innerHTML = `<h1>${title}</h1>
+                         <p>${opening_crawl}</p>
+                         `
+        for (const peopleUrl of characters) {
+            const peopleId = peopleUrl.split('/people/')[1].slice(0, -1)
+            main.innerHTML += `<a href="#/people/${peopleId}">Герой №${peopleId}</a>`
+        }
+    }
+})
+
+const actionGetPeople = id =>  //имя другое
+    actionPromise(fetch(`https://swapi.dev/api/people/${id}`).then(res => res.json()))
+
+const actionGetFilm = id =>
+    actionPromise(fetch(`https://swapi.dev/api/films/${id}`).then(res => res.json()))
+
+const actionSomePeople = () =>
+    actionPromise(fetch(`https://swapi.dev/api/people/`).then(res => res.json()))
+
+store.dispatch(actionSomePeople())
+
+store.subscribe(() => {
+    const { status, payload, error } = store.getState().promise//.имя третье
+    if (status === 'FULFILLED' && payload.results) {
+        aside.innerHTML = ''
+        for (const { url: peopleUrl, name } of payload.results) {
+            const peopleId = peopleUrl.split('/people/')[1].slice(0, -1)
+            aside.innerHTML += `<a href="#/people/${peopleId}">${name}</a>`
+        }
+    }
+})
+
+window.onhashchange = () => {
+    const [, route, _id] = location.hash.split('/')
+
+    const routes = {
+        people() {
+            console.log('People', _id)
+            store.dispatch(actionGetPeople(_id))
+        },
+        films() {
+            store.dispatch(actionGetFilm(_id))
+        },
+        //category() {
+        //store.dispatch(actionCategoryById(_id))
+        //},
+        //good(){
+        ////тут был store.dispatch goodById
+        //console.log('good', _id)
+        //},
+        login() {
+            console.log('А ТУТ ЩА ДОЛЖНА БЫТЬ ФОРМА ЛОГИНА')
+            //нарисовать форму логина, которая по нажатию кнопки Login делает store.dispatch(actionFullLogin(login, password))
+        },
+        //register(){
+        ////нарисовать форму регистрации, которая по нажатию кнопки Login делает store.dispatch(actionFullRegister(login, password))
+        //},
+    }
+
+    if (route in routes) {
+        routes[route]()
+    }
+}
+
+window.onhashchange()

+ 269 - 0
js/19 (module)/graphql.js

@@ -0,0 +1,269 @@
+// getGql - фунция GraphQL запросов для всех запросов ниже!
+function getGql(endpoint) {
+
+    let headers = {
+        'Content-Type': 'application/json;charset=utf-8',
+        'Accept': 'application/json',
+    }
+    if ('authToken' in localStorage) {
+        headers.Authorization = 'Bearer ' + localStorage.authToken
+    }
+
+    return async function gql(query, variables = {}) {
+        let result = await fetch(endpoint, {
+            method: 'POST',
+            headers,
+            body: JSON.stringify({
+                query,
+                variables
+            })
+        }).then(res => res.json())
+
+        if (('errors' in result) && !('data' in result)) {
+            throw new Error(JSON.stringify(result.errors))
+        }
+
+        result = Object.values(result.data)[0]
+
+        return result
+    }
+}
+const gql = getGql('http://shop-roles.node.ed.asmer.org.ua/graphql') // скармливаем урл для запросов
+
+
+
+// ==============================================================
+// Запрос на список корневых категорий
+
+
+// запрос на самом сервере
+// query CategoryFind{
+//     CategoryFind(query: "[{\"parent\": null}]"){
+//     _id name
+//     }
+// }
+
+let findCategory = `query baseCategory($searchVariablesCategory: String){
+        CategoryFind(query: $searchVariablesCategory){
+            _id name parent {
+                _id
+                name
+            }
+        }
+    }`
+
+let variables = {
+    searchVariablesCategory: JSON.stringify([{ parent: null }])
+}
+
+// тест
+gql(findCategory, variables).then(console.log)
+
+
+
+// ===============================================================
+// Запрос для получения одной категории с товарами и картинками
+
+
+// запрос на самом сервере
+// query categoryFindOne($q: String,) {
+//         CategoryFindOne(query: $q){
+//       _id name parent{
+//             _id name
+//             } 
+//         goods{
+//         _id name  description price 
+//         images{
+//                     url
+//                 }
+//             }
+//       subCategories{
+//         _id name
+//             }
+//         }
+//     }
+
+let findOneCategory = `query categoryFindOne($searchVariablesCategoryOne: String,) {
+        CategoryFindOne(query: $searchVariablesCategoryOne){
+      _id name parent{
+            _id name
+            } 
+        goods{
+        _id name  description price 
+        images{
+                    url
+                }
+            }
+      subCategories{
+        _id name
+            }
+        }
+    }`
+
+let variables = {
+    searchVariablesCategoryOne: JSON.stringify([{ _id: "6262ca7dbf8b206433f5b3d1" }])
+}
+
+// тест
+gql(findOneCategory, variables).then(console.log)
+
+
+
+// ======================================================
+// Запрос на получение товара с описанием и картинками
+
+// запрос на сервере
+//   query oneGoodWithImages($q2: String) {
+//         GoodFindOne(query: $q2){
+//         _id name price description images {
+//                 url
+//             }
+//         }
+//     }
+
+
+let findGoodWithImage = `query oneGoodWithImages($searchVariablesGoodOne: String) {
+        GoodFindOne(query: $searchVariablesGoodOne){
+        _id name price description images {
+                url
+            }
+        }
+    }
+`
+
+let variables = {
+    searchVariablesGoodOne: JSON.stringify([{ _id: "62c9472cb74e1f5f2ec1a0d3" }])
+}
+
+// тест
+gql(findGoodWithImage, variables).then(console.log)
+
+
+
+// ===================================================================
+// Запрос на регистрацию - работает, если не залогинен пользователь
+
+
+// запрос на сервере
+// mutation registration($loginReg: String, $passwordReg: String){
+//     UserUpsert(user: {
+//         login: $loginReg, password: $passwordReg
+//     }){
+//     _id createdAt
+//     }
+// }
+
+let registration = `  mutation registration($loginReg:String,$passwordReg:String ){
+  UserUpsert(user:{
+    login:$loginReg, password:$passwordReg
+  }){
+    _id createdAt
+  }
+}`
+
+let variables = {
+    loginReg: "abababa",
+    passwordReg: "123123"
+}
+
+// тест
+gql(registration, variables).then(console.log)
+
+
+
+// =======================================================
+// Запрос на логин
+
+// на сервере
+// query login($login: String, $password: String){
+//         login(login: $login, password: $password)
+//     }
+
+let checkLogin = `query login($login: String, $password: String){
+        login(login: $login, password: $password)
+    }
+`
+
+let variables = {
+    login: "abababa",
+    password: "123123"
+}
+
+// тест
+gql(checkLogin, variables).then(console.log)
+
+
+
+// ===============================================================================
+// Запрос истории заказов - нужно учитывать, что работает только, если вместе с заголовком отправить JWT-token от пользователя
+
+// запрос на сервере
+//        query order{
+//         OrderFind(query: "[{}]"){
+//       _id total orderGoods{
+//         good {
+//                     _id
+//                     name
+//                     price
+//                 }
+//             }
+//         }
+//     }
+
+let orderFind = `query order ($order: String){
+        OrderFind(query: $order){
+      _id total orderGoods{
+        good {
+                    _id
+                    name
+                    price
+                }
+            }
+        }
+    }
+`
+
+let variables = {
+    order: JSON.stringify([{}])
+}
+
+// тест
+gql(orderFind, variables).then(console.log)
+
+
+
+// ==========================================================================
+// Запрос оформления заказа - еще нужно добавить запрос на очистку корзины
+
+// запрос на сервере
+//  mutation myOrder($createOrder: OrderInput){
+//     OrderUpsert(order: $createOrder) {
+//     orderGoods{
+//       count good{
+//                 _id
+//             }
+//         }
+//     }
+// }
+
+let orderCreate = `mutation myOrder($createOrder: OrderInput){
+    OrderUpsert(order: $createOrder) {
+    orderGoods{
+      count good{
+                _id
+            }
+        }
+    }
+}`
+
+let variables = {
+    createOrder: JSON.stringify({ orderGoods: { count: 2, good: { _id: "62c9472cb74e1f5f2ec1a0d2" } } })
+}
+
+// тест
+gql(orderCreate, variables).then(console.log)
+
+
+
+
+

+ 89 - 0
js/19 (module)/help requests.js

@@ -0,0 +1,89 @@
+/*Запрос на список корневых категорий
+Используем CategoryFind, однако в параметре query используем поиск по полю parent, которое должно быть равно null. (у корневых категорий нет родителя)*/
+{
+    let findCategory = `query baseCategory($searchNullparent: String){
+        CategoryFind(query: $searchNullparent){
+            _id name parent {
+                _id
+                name
+            }
+        }
+    }`
+
+    let variables = {
+        searchNullparent: JSON.stringify([{ parent: null }])
+    }
+
+
+
+    const gql = getGql('http://shop-roles.node.ed.asmer.org.ua/graphql')
+
+    gql(findCategory, variables).then(console.log)
+}
+
+
+
+
+
+
+// getGql - полностью готова
+{
+    function getGql(endpoint) {
+
+        let headers = {
+            'Content-Type': 'application/json;charset=utf-8',
+            'Accept': 'application/json',
+        }
+        if ('authToken' in localStorage) {
+            headers.Authorization = 'Bearer ' + localStorage.authToken
+        }
+
+        return async function gql(query, variables = {}) {
+            let result = await fetch(endpoint, {
+                method: 'POST',
+                headers,
+                body: JSON.stringify({
+                    query,
+                    variables
+                })
+            }).then(res => res.json())
+
+            if (('errors' in result) && !('data' in result)) {
+                throw new Error(JSON.stringify(result.errors))
+            }
+
+            result = Object.values(result.data)[0]
+
+            return result
+        }
+    }
+}
+
+
+
+
+
+
+
+// localStoredReducer
+{
+    function localStoredReducer(originalReducer, localStorageKey) {
+        function wrapper(state, action) {
+            if (!state) {
+                try {
+                    return JSON.parse(localStorage[localStorageKey])
+                }
+                catch (error) {
+
+                }
+            }
+            const newState = originalReducer(state, action)
+            localStorage[localStoredReducer] = JSON.stringify(newState)
+
+            return newState
+        }
+
+        return wrapper
+    }
+}
+

+ 43 - 0
js/19 (module)/index.html

@@ -0,0 +1,43 @@
+<!DOCTYPE HTML>
+<html>
+
+<head>
+    <title>GQL</title>
+    <meta charset='utf8' />
+    <style>
+        #mainContainer {
+            display: flex;
+        }
+
+        #aside {
+            width: 30%;
+        }
+
+        #aside>a {
+            display: block;
+        }
+
+        header {
+            min-height: 100px;
+            background-color: #AAA;
+        }
+    </style>
+</head>
+
+<body>
+    <header>
+        <div id='cartIcon'>5</div>
+    </header>
+    <div id='mainContainer'>
+        <aside id='aside'>
+            Категории
+            Сюда надо воткнуть список корневых категорий интернет-магазина
+        </aside>
+        <main id='main'>
+            Контент
+        </main>
+    </div>
+    <script src='bolvanka.js'></script>
+</body>
+
+</html>

文件差异内容过多而无法显示
+ 849 - 0
js/19 (module)/magic.js


文件差异内容过多而无法显示
+ 272 - 0
js/19 (module)/redusers.js