File size: 2,273 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { flat } from '../../../utils/flat/index.js'
import { Action, ActionResponse, ActionQueryParameters } from '../action.interface.js'
import { RecordJSON } from '../../../frontend/interfaces/index.js'
import Filter from '../../utils/filter/filter.js'

/**
 * @implements Action
 * @category Actions
 * @module SearchAction
 * @description
 * Used to search particular record based on "title" property. It is used by
 * select fields with autocomplete.
 * Uses {@link ShowAction} component to render form
 * @private
 */
export const SearchAction: Action<SearchActionResponse> = {
  name: 'search',
  isVisible: false,
  actionType: 'resource',
  /**
   * Search records by query string.
   *
   * To invoke this action use {@link ApiClient#resourceAction}
   * @memberof module:SearchAction
   *
   * @return  {Promise<SearchResponse>}  populated record
   * @implements ActionHandler
   */
  handler: async (request, response, context) => {
    const { currentAdmin, resource } = context
    const { query } = request

    const decorated = resource.decorate()
    const titlePropertyName = request.query?.searchProperty ?? decorated.titleProperty().name()

    const {
      sortBy = decorated.options?.sort?.sortBy || titlePropertyName,
      direction = decorated.options?.sort?.direction || 'asc',
      filters: customFilters = {},
      perPage = 50,
      page = 1,
    } = flat.unflatten(query || {}) as ActionQueryParameters

    const queryString = request.params && request.params.query
    const queryFilter = queryString ? { [titlePropertyName]: queryString } : {}
    const filters = {
      ...customFilters,
      ...queryFilter,
    }
    const filter = new Filter(filters, resource)

    const records = await resource.find(filter, {
      limit: perPage,
      offset: (page - 1) * perPage,
      sort: {
        sortBy,
        direction,
      },
    }, context)

    return {
      records: records.map((record) => record.toJSON(currentAdmin)),
    }
  },
}

export default SearchAction

/**
 * Response of a [Search]{@link ApiController#search} action in the API
 * @memberof module:SearchAction
 * @alias SearchResponse
 */
export type SearchActionResponse = ActionResponse & {
  /**
   * List of records
   */
  records: Array<RecordJSON>;
}