let gql = (url, query, variables={}) =>
    fetch(url, {
        method: 'POST',
        headers:{
            Accept: 'application/json',
            "Content-Type": 'application/json'
        },
        body: JSON.stringify({query, variables})
    }).then(res => res.json())

// используя функцию gql, понаделать функций с параметрами для разных запросов: категории, категория по id с товарами, товар по id с картинками и описанием, логин, регистрация.
//     например:
let idd = 123456
// `\\"_id\\":\\"${id}\\"`
console.log(JSON.parse("[{\"_id\":\"123456\"}]"))
const url = 'http://shop-roles.node.ed.asmer.org.ua/graphql'
const gqlCategoriesList = () => {
    return gql(url, `query cats{
    CategoryFind(query: "[{}]"){
    _id, name,
  }
}`, {}
    )
}

const gqlRegister = (login, password) => {
    return gql(url, `mutation register($login: String, $password: String){
    UserUpsert(user: {login: $login, password: $password}){
        _id, login, createdAt
    }
}`, {login, password})
}

const gqlLogin = (login, password) =>
    gql(url,
        `query login($login:String, $password: String){
                login(login:$login, password: $password)
        }`, {login, password})

const gqlCategories = () => {
    return gql(url,
        ` query categories{
                            CategoryFind(query:"[{}]"){
                            _id name goods {
                                _id
                                name
                                price
                                description
                                }
                          }
                     }`
        );
}
const productSearchById = (id) => {
    let jsn = JSON.stringify({_id: id})
    return gql(
        url,
        `query searchById{
        GoodFind(query: ${JSON.stringify(`[${jsn}]`)}){
            name description images {
                _id
                createdAt
                text
                url
                originalFileName
            }
        }
    }`,
    );
};

(async function callAll() {
    console.log(await gqlCategoriesList());
    console.log(await gqlRegister("Vlada Simonova", "123456"));
    console.log(await gqlLogin("Vlada Simonova", "123456"));
    console.log(await gqlCategories());
    console.log(await productSearchById("62c9472cb74e1f5f2ec1a0d3"));
})();



