如果它是空的,如何从graphQL查询中删除变量?

时间:2019-09-17 10:30:20

标签: reactjs ecmascript-6 graphql

如果变量SearchQuery的值是一个空字符串,并且在模板文字中包含此逻辑,如何将其忽略?

代码:

var query = `query RunSearch($searchQuery: String, $mType: MediaType, $filterMethod:[MediaSort], $season:MediaSeason){
  Page(perPage:10, page: 1){
    pageInfo {
      total
      currentPage
      lastPage
      hasNextPage
      perPage
    }

    media(type: $mType, search: $searchQuery, sort:$filterMethod, season:$season){
    title{
    english
  }
    format,
    description(asHtml:true),
    averageScore,
    studios(isMain:true) {
      nodes {
        name
      }
    },
    coverImage {
      large
      color
    },
    genres
  }
  }

}`;

1 个答案:

答案 0 :(得分:1)

您可以使用使用模板字符串的函数来构建查询。 您可以添加更多变量或控件以满足您的需求。

const myvars = {
 searchQuery : "",
 mType : "pdf",
 filterMethod : "asc",
 season : ""
}


const buildQuery = (vars) => {
let sq = vars.searchQuery == "" ? "" : "$searchQuery: String,"
let mt = vars.mType == "" ? "" : "$mType: MediaType,"
let fm = vars.filterMethod == "" ? "" : "$filterMethod: [MediaSort],"
let ss =  vars.season == "" ? "" : "$season:MediaSeason"
var query = `query RunSearch(${sq} ${mt} ${fm} ${ss}){
  Page(perPage:10, page: 1){
    pageInfo {
      total
      currentPage
      lastPage
      hasNextPage
      perPage
    }

    media(type: $mType, search: $searchQuery, sort:$filterMethod, season:$season){
    title{
    english
  }
    format,
    description(asHtml:true),
    averageScore,
    studios(isMain:true) {
      nodes {
        name
      }
    },
    coverImage {
      large
      color
    },
    genres
  }
  }

}`;
return query;
}

let myquery = buildQuery(myvars);
console.log(myquery)