123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>25</title>
- </head>
- <body>
- <button id="A">A</button>
- <button id="B">B</button>
- <pre id="Cart"></pre>
- <script>
- function createStore(reducer) {
- let state = reducer(undefined, {});
- let cbs = [];
- function dispatch(action) {
- if (typeof action === "function") {
- return action(dispatch);
- }
- let newState = reducer(state, action);
- if (state !== newState) {
- state = newState;
- for (let cb of cbs) cb();
- }
- }
- return {
- getState() {
- return state;
- },
- dispatch,
- subscribe(cb) {
- cbs.push(cb);
- return () => {
- cbs = cbs.filter(
- (someElement) => someElement !== cb
- );
- };
- },
- };
- }
- function cartReducer(state = {}, { type, id, count }) {
- if (type === "CART_ADD") {
- return {
- ...state,
- [id]: count + (state[id] || 0),
- };
- }
- if (type === "CART_DELETE") {
- const { [id]: skip, ...newState } = state;
- return newState;
- }
- return state;
- }
- function promiseReducer(
- state = {},
- { type, status, payload, error, name }
- ) {
- if (type === "PROMISE") {
- console.log("3 reduser", name, status);
- return { ...state, [name]: { status, payload, error } };
- }
- return state;
- }
- const store = createStore(promiseReducer);
- store.subscribe(() => console.log(store.getState()));
- store.subscribe(() => {
- Cart.innerText += JSON.stringify(store.getState(), null, 4);
- console.log("4 subscribe");
- });
- const actionPromisePending = (name) => ({
- name,
- type: "PROMISE",
- status: "PENDING",
- });
- const actionPromiseResolved = (name, payload) => ({
- name,
- type: "PROMISE",
- status: "RESOLVED",
- payload,
- error: undefined,
- });
- const actionPromiseRejected = (name, error) => ({
- name,
- type: "PROMISE",
- status: "REJECTED",
- payload: undefined,
- error,
- });
- const delaySec = (sec) =>
- new Promise((ok) => setTimeout(() => ok(sec), sec * 1000));
- // store.dispatch(actionPromisePending('delay'))
- // delaySec(3).then(payload => store.dispatch(actionPromiseResolved('delay', payload)),
- // error => store.dispatch(actionPromiseRejected('delay', error))
- // );
- function actionPromise(name, promise) {
- return async (dispatch) => {
- console.log("2 action pending", name);
- dispatch(actionPromisePending(name));
- try {
- let payload = await promise;
- console.log("3 resolved");
- dispatch(actionPromiseResolved(name, payload));
- return payload;
- } catch (e) {
- console.log("3 rejected");
- dispatch(actionPromiseRejected(name, e));
- }
- };
- }
- console.log("1 start timer");
- store.dispatch(actionPromise("delay3", delaySec(3)));
- store.dispatch(actionPromise("delay5", delaySec(5)));
- const getGQL = (url) => (query, variables = {}) => {
- return fetch(url, {
- method: "POST",
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json",
- ...(localStorage.authToken
- ? {
- Authorization: `Bearer ${localStorage.authToken}`,
- }
- : {}),
- },
- body: JSON.stringify({ query, variables }),
- }).then((res) => res.json());
- };
- let gql = getGQL(
- "http://shop-roles.asmer.fs.a-level.com.ua/graphql"
- );
- function actionLogin(login, password) {
- return actionPromise(
- "login",
- gql(
- `query login($login:String, $password:String) {
- login(login:$login, password:$password)
- }`,
- { login, password }
- )
- );
- }
- // store.dispatch(actionLogin("qqq", "123")); // View событие
- function actionRegister(login, password) {
- return actionPromise(
- "register",
- gql(
- `mutation newUser($login: String, $password: String) {
- UserUpsert(user: {login: $login, password: $password}) {
- _id
- createdAt
- }
- }`,
- { login, password }
- )
- );
- }
- function actionRegAndLogin(login, password) {
- return async (dispatch) => {
- let regData = await dispatch(
- actionRegister(login, password)
- );
- if (regData.data.UserUpsert) {
- let logData = await dispatch(
- actionLogin(login, password)
- );
- console.log(logData);
- }
- };
- }
- store.dispatch(actionRegAndLogin("qqq10", "123"));
- // const actionCartAdd = (id, count = 1) => ({type:"CART_ADD", id, count});
- // const actionCartDelete = (id) => ({type:"CART_DELETE", id});
- // A.onclick = () => {store.dispatch(actionCartAdd('A'))}
- // B.onclick = () => {store.dispatch(actionCartAdd('B'))}
- // store.dispatch({type:"CART_ADD", id: "A", count: 3})
- // store.dispatch({type:"CART_ADD", id: "B", count: 4})
- // store.dispatch({type:"CART_ADD", id: "C", count: 5})
- // store.dispatch({type:"CART_DELETE", id: "B"})
- </script>
- </body>
- </html>
|