import actionPromise from "./actionPromise";
import {gql} from "./";



let toRegexp = (str) => {
    str = str.replace(/ +/g, " ").trim();
    str = "/" + str.split(" ").join("|") + "/";
    return str;
  };
  
  let toQuery = (str, fields = ["name", "description"]) => {
    str = toRegexp(str);
    let arr = fields.map((s) => {
        //console.log(s, typeof s);
        return { [s]: str };
    });
    return { $or: arr };
  };
  

function actionSearch(queryString) {

    return actionPromise('search', gql(
      `query goods($query: String) {
        GoodFind(query: $query)  {
          name, price,
          images{url}, _id
          categories {
            _id
            createdAt
            name
          }
        }
      }`, {query: JSON.stringify([toQuery(queryString)])}))
  }
  
export {toRegexp, toQuery, actionSearch};