mealie/frontend/composables/recipes/use-recipe-search.ts
Jacob Corn e1d3a247c7
feat: random sort option for front page (#2363)
* Add hook for random sorting

* Add random sorting to front page

* Add multiple tests for random sorting.

* Be extra sure that all recipes are returned.

* Too stable random. seed doesn't reach backend.

* add timestamp to useRecipeSearch

* Update randomization tests for timestamp seeding

* ruff cleanup

* pass timestamp separately in getAll

* remove debugging log items

* remove timestamp from address bar

* remove defaults from backend timestamps

* timestamp should be optional

* fix edge case: query without timestamp

* similar edge case: no timestamp in pagination

* ruff :/

* better edge case handling

* stabilize random search test w/more recipes

* better pagination seeding

* update pagination seed test

* remove redundant random/seed check

* Test for api routes to random sorting.

* please the typing gods

* hack to make query parameters throw correct exc

* ruff

* fix validator message typo

* black reformatting

---------

Co-authored-by: Hayden <64056131+hay-kot@users.noreply.github.com>
2023-05-29 16:56:20 -08:00

71 lines
1.5 KiB
TypeScript

import { Ref, ref } from "@nuxtjs/composition-api";
import { watchDebounced } from "@vueuse/core";
import { UserApi } from "~/lib/api";
import { Recipe } from "~/lib/api/types/recipe";
export interface UseRecipeSearchReturn {
query: Ref<string>;
error: Ref<string>;
loading: Ref<boolean>;
data: Ref<Recipe[]>;
trigger(): Promise<void>;
}
/**
* `useRecipeSearch` constructs a basic reactive search query
* that when `query` is changed, will search for recipes based
* on the query. Useful for searchable list views. For advanced
* search, use the `useRecipeQuery` composable.
*/
export function useRecipeSearch(api: UserApi): UseRecipeSearchReturn {
const query = ref("");
const error = ref("");
const loading = ref(false);
const recipes = ref<Recipe[]>([]);
async function searchRecipes(term: string) {
loading.value = true;
const { data, error } = await api.recipes.search({
search: term,
page: 1,
orderBy: "name",
orderDirection: "asc",
perPage: 20,
_searchSeed: Date.now().toString(),
});
if (error) {
console.error(error);
loading.value = false;
recipes.value = [];
return;
}
if (data) {
recipes.value = data.items;
}
loading.value = false;
}
watchDebounced(
() => query.value,
async (term: string) => {
await searchRecipes(term);
},
{ debounce: 500 }
);
async function trigger() {
await searchRecipes(query.value);
}
return {
query,
error,
loading,
data: recipes,
trigger,
};
}