const getGQL = url =>
    (query, variables = {}) => fetch(url, {
        
        method: 'POST',
        headers: {
          ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} : {}),
          "Content-Type": "application/json",
        },
        body: JSON.stringify({query, variables})
            
    }).then(res => res.json())
      .then(data => { console.log(data);
        if (data.errors && !data.data)
            throw new Error(JSON.stringify(data.errors))
        return data.data[Object.keys(data.data)[0]]
    })

const gql = getGQL('http://shop-roles.asmer.fs.a-level.com.ua/graphql');

const autoriz = () =>
  gql(`query autoriz ($login:String, $password:String){
    login(login:$login, password:$password)
    }`,
    {
      "login": "vika",
      "password": "2021"
    })

   
async function autorization () {
  let token = await autoriz();
  localStorage.setItem ("authToken", token);
}

autorization();


let _id = "5dcad1316d09c45440d14d07";

async function orderGood (_id) {
  const oderUpsert = await gql(`mutation order{
    OrderUpsert(order:{
      orderGoods:[
        {count:3, good:{_id: "${_id}"}
        }
      ]
    }) {
      total _id 
    }}
  `)   
}
orderGood(_id);

let _idOderUpsert = "61a9f1c8c750c12ba6ba41d9";

async function orderById (_id) {
   await gql(`query order($q1:String) {
        OrderFindOne(query:$q1){
            _id total, 
        }
    }`, {"q1": JSON.stringify([{_id}])})
}
orderById(_idOderUpsert);

async function catById(_){
  let category = await gql(`query category {
    CategoryFind(query:"[{}]"){
       _id 
    }
  }`);
  const oneCategory = category[1]._id; console.log(oneCategory)
  await gql(`query catByOne ($query:String){
    CategoryFindOne(query:$query){
      name goods{
        _id name
      }
    }
  }`, {"query": JSON.stringify([{_id :oneCategory}])})
}

catById();

const goodId = "5dc87cb90e36db246e3049b0";
const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua';

async function getImageGood (_id) {
  const data = await gql(`query imageFind($image:String){
    ImageFind(query: $image){
     url good {
      _id name
      }
    }
   }`, {
    "image": JSON.stringify([{_id}])
   })
   
  document.body.innerHTML =`<img src= "${backURL}/${data[0].url}" alt="альтернативный текст" />`
}

getImageGood(goodId);




                                       