浏览代码

HW17 (without domEventPromise)

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

文件差异内容过多而无法显示
+ 574 - 0
js/17/HW17.js


+ 0 - 187
js/19/bolvanka.js

@@ -1,187 +0,0 @@
-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()

+ 0 - 269
js/19/graphql.js

@@ -1,269 +0,0 @@
-// 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)
-
-
-
-
-

+ 0 - 89
js/19/help requests.js

@@ -1,89 +0,0 @@
-/*Запрос на список корневых категорий
-Используем 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
-    }
-}
-

+ 0 - 43
js/19/index.html

@@ -1,43 +0,0 @@
-<!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>

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


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