Browse Source

HW<16> done

Vitalii Polishchuk 3 years ago
parent
commit
961d5340a4
1 changed files with 128 additions and 0 deletions
  1. 128 0
      js/16-js-graphql/main.js

+ 128 - 0
js/16-js-graphql/main.js

@@ -0,0 +1,128 @@
+const getGQL = url => {
+  return (query, variables) => {
+    return fetch(url, {
+      method: 'POST',
+      headers: {
+        "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")
+
+//функция для регистрации
+let reg = async (login, password) => {
+  let query = `mutation reg($l: String, $p: String) {
+        UserUpsert(user:  {
+            login: $l,
+            password: $p
+          } ) {
+            _id
+          }
+      }`
+
+  let qVariables = {
+    "l": login,
+    "p": password
+  }
+
+  let res = await gql(query, qVariables)
+  return res
+}
+
+//функция для логина
+let log = async (login, password) => {
+  let query = `query log($l: String, $p: String) {
+        login(login: $l, password: $p)
+      }`
+
+  let qVariables = {
+    "l": login,
+    "p": password
+  }
+
+  let token = await gql(query, qVariables)
+  console.log(token)
+  localStorage.authToken = token.data.login
+}
+
+//функция для отправки заказа. Принимает объект вида:{_id1: количество, _id2: количество}
+let newOrder = async (obj) => {
+  let option = Object.entries(obj);
+  let orderGoods = [];
+
+  for (let key of option) {
+    let i = {
+      "count": key[1],
+      "good": { "_id": key[0] }
+    }
+    orderGoods.push(i);
+  }
+
+  let query = `mutation sndOrder($order: OrderInput) {
+     OrderUpsert(order: $order) {
+       _id createdAt total
+     }
+   }`
+
+  let qVariables = {
+    "order": {
+      "orderGoods": orderGoods
+    }
+  }
+
+  let res = await gql(query, qVariables)
+  console.log(res)
+  return res
+}
+
+//функция для получения всех заказов
+let getOrders = async () => {
+  let query = `query ordersfnd {
+    OrderFind(query: "[{}]"){
+      _id total owner{
+        _id
+      }
+      orderGoods{
+        good{
+          _id
+          name
+        }
+        count total
+      }
+    }
+  }`
+
+  let res = await gql(query)
+  console.log(res)
+  return res
+}
+
+//функция для получения одного заказа по _id
+let orderById = async (id) => {
+  let query = `query orderfnd($id: String){
+    OrderFind(query: $id){
+      createdAt total owner{
+        _id
+      }
+      orderGoods{
+        good{
+          _id
+          name
+        }
+        count total
+      } 
+    }
+  }`
+
+  let qVariables = {
+    "id": JSON.stringify([{ "_id": id }])
+  }
+
+  let res = await gql(query, qVariables)
+  console.log(res)
+  return res
+}