DEV Community

Ice Calee
Ice Calee

Posted on

Append method with URLSearchParams

Just for the sake of learning and not to forget,
I am sharing this chunk of code of the implementation of Append method with URLSearchParams.

async getCategoryMains() {
    const params = Object.assign(this.search, {
      size: this.options.itemsPerPage,
      page: this.options.page,
      categoryType: "VIDEO",
      appPublishId: [1,2]
    });
    const response = await getAllCategoryMains(params);
    if (response.status === 200) {
      this.categoryMainData = response.data
      this.categoryMainCount = Number(response.headers["x-total-count"]);
      this.handleSetCategoryMainId();
    }
  }
Enter fullscreen mode Exit fullscreen mode

Api code

export const getAllCategoryMains = async (search) => {
  const params = new URLSearchParams();
  params.append('page', String(search.page - 1));
  params.append('size', search.size);

  getSearchParams(params, search);
  // @ts-ignore
  const response = await Vue.axios.get(
    `/${env}/contents/api/category-mains?sort=id,desc`,
    {
      params,
      headers: {
        Authorization: "Bearer " + session.get("access_token"),
      },
    }
  );
  if (response && response.status === 200) {
    return response;
  }
  return response;
};


const getSearchParams = (params: any, search: any) => {
  if (search.sort) {
    params.append("sort",search.sort);
  }
  if (search.appPublishId !== "" && search.appPublishId !== undefined) {
    if(typeof search.appPublishId != 'number'){
      search.appPublishId.forEach(id => {
        params.append("appPublishId.in", id);
      })
    }
    else {
      params.append("appPublishId.equals",search.appPublishId)
    }
  }
  if (typeof search.name ==='string' && search.name !== "") {
    params.append("name.contains",search.name);
  }
  if (typeof search.activated ==='string' && search.activated !== "") {
    params.append("activated.equals",search.activated);
  }
  if (typeof search.categoryType ==='string' && search.categoryType !== "") {
    params.append("categoryType.in",search.categoryType);
  }
  if (typeof search.category ==='string' && search.category !== "") {
    params.append("tagId.in", search.category);
  }
};
Enter fullscreen mode Exit fullscreen mode

I'm a junior frontend developer with 5 months of work experience, so if you know any better suggestions for rewriting this code please leave comments.

Top comments (0)