aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/RecipePreviewsStore.ts
blob: f851f3203c9a4790030e6a42154ab2c1aedb0604 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { action, computed, makeObservable, observable } from 'mobx';

import type { Stores } from '../@types/stores.types';
import type { Actions } from '../actions/lib/actions';
import type { ApiInterface } from '../api';
import type Recipe from '../models/Recipe';

import type RecipePreview from '../models/RecipePreview';
import CachedRequest from './lib/CachedRequest';
import Request from './lib/Request';
import TypedStore from './lib/TypedStore';

export default class RecipePreviewsStore extends TypedStore {
  @observable allRecipePreviewsRequest = new CachedRequest(
    this.api.recipePreviews,
    'all',
  );

  @observable featuredRecipePreviewsRequest = new CachedRequest(
    this.api.recipePreviews,
    'featured',
  );

  @observable searchRecipePreviewsRequest = new Request(
    this.api.recipePreviews,
    'search',
  );

  constructor(stores: Stores, api: ApiInterface, actions: Actions) {
    super(stores, api, actions);

    makeObservable(this);

    // Register action handlers
    this.actions.recipePreview.search.listen(this._search.bind(this));
  }

  async setup(): Promise<void> {
    // Not implemented
  }

  @computed get all(): RecipePreview[] {
    return this.allRecipePreviewsRequest.execute().result || [];
  }

  @computed get featured(): RecipePreview[] {
    return this.featuredRecipePreviewsRequest.execute().result || [];
  }

  @computed get searchResults(): RecipePreview[] {
    return this.searchRecipePreviewsRequest.result || [];
  }

  @computed get dev(): Recipe[] {
    return this.stores.recipes.all.filter(r => r.local);
  }

  // Actions
  @action _search({ needle }): void {
    if (needle !== '') {
      this.searchRecipePreviewsRequest.execute(needle);
    }
  }
}