瀏覽代碼

HW<15> update

Vitalii Polishchuk 2 年之前
父節點
當前提交
3da089142e
共有 1 個文件被更改,包括 43 次插入10 次删除
  1. 43 10
      js/15-js-graphql/main.js

+ 43 - 10
js/15-js-graphql/main.js

@@ -1,19 +1,20 @@
 const getGQL = url => {
     return (query, variables) => {
-        fetch(url, {
+        return fetch(url, {
             method: 'POST',
             headers: {
-                "content-type": "application/json"
+                "content-type": "application/json",
+                ...(localStorage.authToken ? { Authorization: "Bearer " + localStorage.authToken } : {})
             },
-            body: JSON.stringify({ query, variables })
-        }).then(res => res.json()).then(data => console.log(data))
+            body: JSON.stringify({ query, variables }),
+        }).then(res => res.json())
     }
 }
 
 let gql = getGQL("http://shop-roles.asmer.fs.a-level.com.ua/graphql")
 
 
-let getId = (type, name) => {
+let getId = async (type, name) => {
     let t = type.toLowerCase();
     let query;
     if (t === "category") {
@@ -34,10 +35,11 @@ let getId = (type, name) => {
         "n": JSON.stringify([{ "name": name }])
     }
 
-    gql(query, qVariables)
+    let res = await gql(query, qVariables)
+    return res
 }
 
-let categoryById = id => {
+let categoryById = async (id) => {
     let query = `query fndcategory($id: String) {
         CategoryFind(query: $id){
           name goods{
@@ -52,10 +54,12 @@ let categoryById = id => {
         "id": JSON.stringify([{ "_id": id }])
     }
 
-    gql(query, qVariables)
+    let res = await gql(query, qVariables)
+    console.log(res)
+    return res
 }
 
-let goodById = id => {
+let goodById = async (id) => {
     let query = `query fndgood($id: String) {
         GoodFind(query: $id){
           name price images {
@@ -68,5 +72,34 @@ let goodById = id => {
         "id": JSON.stringify([{ "_id": id }])
     }
 
-    gql(query, qVariables)
+    let res = await gql(query, qVariables)
+    return res
 }
+
+let addProduct = async ({ name, price, description, imgSrc, categories }) => {
+    let query = `mutation addGood($product: GoodInput) {
+        GoodUpsert(good: $product){
+          _id
+        }
+      }`
+
+    let qVariables = {
+        "product": JSON.stringify([{ "name": name, "price": price, "description": description, "images": [{ "url": imgSrc }], "categories": [{ "_id": categories }] }])
+    }
+
+    let res = await gql(query, qVariables)
+    return res
+}
+
+let deleteProdact = async (id) => {
+    let query = `mutation goodDel($id: GoodInput) {
+        GoodDelete(good: $id)
+      }`
+
+    let qVariables = {
+        "id": JSON.stringify([{ "_id": id }])
+    }
+
+    let res = await gql(query, qVariables)
+    return res
+}