Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: refactored useFacet composable #587

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/composables/src/composables/useFacet/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// @depracated - moved to theme

import { SearchData } from '../../types';

const buildBreadcrumbsList = (rootCat, bc) => {
Expand Down
5 changes: 5 additions & 0 deletions packages/composables/src/composables/useFacet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ const constructSortObject = (sortData: string) => {
return baseData.length > 0 ? Object.fromEntries([baseData]) : {};
};

/**
* @deprecated since version <version?>
*
* @see <add docs link>
*/
const factoryParams = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
search: async (context: Context, params: ComposableFunctionArgs<FacetSearchResult<any>>) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/theme/components/AppHeader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,6 @@ import {
categoryGetters,
useCart,
useCategorySearch,
useFacet,
wishlistGetters,
} from '@vue-storefront/magento';
import {
Expand All @@ -197,6 +196,7 @@ import {
useUiState,
useWishlist,
useUser,
useFacet,
} from '~/composables';
import StoreSwitcher from '~/components/StoreSwitcher.vue';

Expand Down Expand Up @@ -224,7 +224,7 @@ export default defineComponent({
result: searchResult,
search: productsSearch,
// loading: productsLoading,
} = useFacet('AppHeader:Products');
} = useFacet();
const {
result: categories,
search: categoriesSearch,
Expand Down
1 change: 1 addition & 0 deletions packages/theme/composables/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { default as useWishlist } from './useWishlist';
export { default as useUser } from './useUser';
export { default as useForgotPassword } from './useForgotPassword';
export { default as useCategory } from './useCategory';
export { default as useFacet } from './useFacet';
76 changes: 76 additions & 0 deletions packages/theme/composables/useFacet/_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { SearchData } from './useFacet';

const buildBreadcrumbsList = (rootCat, bc) => {
const newBc = [...bc, {
text: rootCat.name,
link: rootCat.slug,
}];
return rootCat.parent ? buildBreadcrumbsList(rootCat.parent, newBc) : newBc;
};

export const buildBreadcrumbs = (rootCat) => buildBreadcrumbsList(rootCat, [])
.reverse()
.reduce(
(prev, curr, index) => ([
...prev,
{
...curr,
link: `${prev[index - 1]?.link || ''}/${curr.link}`,
}]),
[],
);

const filterFacets = (criteria) => (f) => (criteria ? criteria.includes(f.attribute_code) : true);

const getFacetTypeByCode = (code) => {
if (code === 'type_of_stones') {
return 'radio';
}
return 'checkbox';
};

const createFacetsFromOptions = (facets, filters, facet) => {
const options = facet.options || [];
const selectedList = filters && filters[facet.attribute_code] ? filters[facet.attribute_code] : [];
return options
.map(({
label,
value,
count,
}) => ({
type: getFacetTypeByCode(facet.attribute_code),
id: label,
attrName: label,
value,
selected: selectedList.includes(value),
count,
}));
};

export const reduceForFacets = (facets, filters) => (prev, curr) => ([
...prev,
...createFacetsFromOptions(facets, filters, curr),
]);

export const reduceForGroupedFacets = (facets, filters) => (prev, curr) => ([
...prev,
{
id: curr.attribute_code,
label: curr.label,
options: createFacetsFromOptions(facets, filters, curr),
count: null,
},
]);

export const buildFacets = (searchData: SearchData, reduceFn, criteria?: string[]) => {
if (!searchData.data) {
return [];
}

const {
data: { availableFilters: facets },
input: { filters },
} = searchData;

return facets?.filter(filterFacets(criteria)).reduce(reduceFn(facets, filters), []);
};
136 changes: 136 additions & 0 deletions packages/theme/composables/useFacet/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { Ref, ref, useContext } from '@nuxtjs/composition-api';
import {
AgnosticFacetSearchParams, ComposableFunctionArgs, Logger, ProductsSearchParams } from '@vue-storefront/core';
import { FacetSearchResult, UseFacet, UseFacetErrors} from './useFacet';
import { GetProductSearchParams } from '@vue-storefront/magento-api/src/types/API';

const availableSortingOptions = [
{
label: 'Sort: Default',
value: '',
},
{
label: 'Sort: Name A-Z',
value: 'name_ASC',
},
{
label: 'Sort: Name Z-A',
value: 'name_DESC',
},
{
label: 'Sort: Price from low to high',
value: 'price_ASC',
}, {
label: 'Sort: Price from high to low',
value: 'price_DESC',
},
];

const constructFilterObject = (inputFilters: Object) => {
const filter = {};

Object.keys(inputFilters).forEach((key) => {
if (key === 'price') {
const price = { from: 0, to: 0 };
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const flatPrices = inputFilters[key].flatMap((inputFilter) => inputFilter.split('_').map((str) => Number.parseFloat(str))).sort((a, b) => a - b);

[price.from] = flatPrices;
price.to = flatPrices[flatPrices.length - 1];

filter[key] = price;
} else if (typeof inputFilters[key] === 'string') {
filter[key] = { in: [inputFilters[key]] };
} else {
filter[key] = { in: inputFilters[key] };
}
});

return filter;
};

const constructSortObject = (sortData: string) => {
const baseData = sortData.split(/_/gi);

return baseData.length > 0 ? Object.fromEntries([baseData]) : {};
};

export const useFacet = (): UseFacet => {
const { app } = useContext();
const loading: Ref<boolean> = ref(false);
const result: Ref<FacetSearchResult<any>> = ref({ data: null, input: null });
const error: Ref<UseFacetErrors> = ref({
search: null,
});

const search = async (params?: ComposableFunctionArgs<AgnosticFacetSearchParams>) => {
Logger.debug('useFacet/search', params);

result.value.input = params;
try {
loading.value = true;

const itemsPerPage = (params.itemsPerPage) ? params.itemsPerPage : 20;
const inputFilters = (params.filters) ? params.filters : {};
const categoryId = (params.categoryId) ? {
category_uid: {
...(Array.isArray(params.categoryId)
? { in: params.categoryId }
: { eq: params.categoryId }),
},
} : {};

const productParams: ProductsSearchParams = {
filter: {
...categoryId,
...constructFilterObject({
...inputFilters,
}),
},
perPage: itemsPerPage,
offset: (params.page - 1) * itemsPerPage,
page: params.page,
search: (params.term) ? params.term : '',
sort: constructSortObject(params.sort || ''),
};

const productSearchParams: GetProductSearchParams = {
pageSize: productParams.perPage,
search: productParams.search,
filter: productParams.filter,
sort: productParams.sort,
currentPage: productParams.page,
};

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const { data } = await app.context.$vsf.$magento.api.products(productSearchParams, params?.customQuery || { products: 'products' });

Logger.debug('[Result]:', { data });

result.value.data = {
items: data?.products?.items || [],
total: data?.products?.total_count,
availableFilters: data?.products?.aggregations,
category: { id: params.categoryId },
availableSortingOptions,
perPageOptions: [10, 20, 50],
itemsPerPage,
};
error.value.search = null;
} catch (err) {
error.value.search = err;
Logger.error(`useFacet/search`, err);
} finally {
loading.value = false;
}
};

return {
result,
loading,
error,
search,
};
};

export default useFacet;
23 changes: 23 additions & 0 deletions packages/theme/composables/useFacet/useFacet.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { AgnosticFacetSearchParams, ComposableFunctionArgs} from '@vue-storefront/core';
import { Ref } from '@nuxtjs/composition-api';
// @ts-ignore
import { FacetResultsData } from '@vue-storefront/magento/types';

export interface FacetSearchResult<S> {
data: S;
input: AgnosticFacetSearchParams;
}

export interface UseFacetErrors {
search: Error;
}


export type SearchData = FacetSearchResult<FacetResultsData>;

export interface UseFacet {
result: Ref<FacetSearchResult<FacetResultsData>>;
loading: Ref<boolean>;
search: (params?: ComposableFunctionArgs<AgnosticFacetSearchParams>) => Promise<void>;
error: Ref<UseFacetErrors>;
}
5 changes: 2 additions & 3 deletions packages/theme/pages/Category.vue
Original file line number Diff line number Diff line change
Expand Up @@ -425,13 +425,12 @@ import {
categoryGetters,
facetGetters,
productGetters,
useFacet,
} from '@vue-storefront/magento';
import { onSSR, useVSFContext } from '@vue-storefront/core';
import { useCache, CacheTagPrefix } from '@vue-storefront/cache';
import { useUrlResolver } from '~/composables/useUrlResolver.ts';
import {
useUiHelpers, useUiState, useImage, useWishlist, useUser, useCategory,
useUiHelpers, useUiState, useImage, useWishlist, useUser, useCategory, useFacet
} from '~/composables';
import cacheControl from '~/helpers/cacheControl';
import { useAddToCart } from '~/helpers/cart/addToCart';
Expand Down Expand Up @@ -484,7 +483,7 @@ export default defineComponent({
const {
result,
search,
} = useFacet(`facetId:${path}`);
} = useFacet();
const { toggleFilterSidebar } = useUiState();
const {
categories,
Expand Down