|
| 1 | +import { |
| 2 | + PageSizeAccessor, |
| 3 | + PaginationAccessor, |
| 4 | + SearchkitComponent, |
| 5 | + SearchkitComponentProps, |
| 6 | +} from 'searchkit'; |
| 7 | +import { ModuleCode } from 'types/modules'; |
| 8 | + |
| 9 | +export type RandomPickerProps = { |
| 10 | + getRandomModuleCode: () => Promise<ModuleCode>; |
| 11 | +}; |
| 12 | + |
| 13 | +interface SearchkitRandomPickerProps extends SearchkitComponentProps { |
| 14 | + buttonComponent: React.ElementType<RandomPickerProps>; |
| 15 | +} |
| 16 | + |
| 17 | +type State = Record<string, never>; |
| 18 | + |
| 19 | +export default class RandomPicker extends SearchkitComponent<SearchkitRandomPickerProps, State> { |
| 20 | + paginationAccessor() { |
| 21 | + return this.accessor as PaginationAccessor; |
| 22 | + } |
| 23 | + |
| 24 | + // eslint-disable-next-line class-methods-use-this |
| 25 | + override defineAccessor() { |
| 26 | + return new PaginationAccessor('p'); |
| 27 | + } |
| 28 | + |
| 29 | + getRandomModuleCode = async (): Promise<ModuleCode> => { |
| 30 | + const sizeAccessor = this.searchkit.getAccessorByType(PageSizeAccessor) as PageSizeAccessor; |
| 31 | + const totalPages = Math.ceil(this.searchkit.getHitsCount() / sizeAccessor.getSize()); |
| 32 | + const randomPage = Math.floor(Math.random() * totalPages); |
| 33 | + |
| 34 | + this.paginationAccessor().state = this.paginationAccessor().state.setValue(randomPage); |
| 35 | + const { hits } = (await this.searchkit.performSearch()).results.hits; |
| 36 | + const randomHit = hits[Math.floor(Math.random() * hits.length)]; |
| 37 | + /* eslint-disable no-underscore-dangle */ |
| 38 | + return randomHit._source.moduleCode; |
| 39 | + }; |
| 40 | + |
| 41 | + override render() { |
| 42 | + const { buttonComponent: Button } = this.props; |
| 43 | + return <Button getRandomModuleCode={this.getRandomModuleCode} />; |
| 44 | + } |
| 45 | +} |
0 commit comments