list.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package db
  15. import (
  16. "yunion.io/x/jsonutils"
  17. )
  18. type CustomizeListFilterFunc func(item jsonutils.JSONObject) (bool, error)
  19. type CustomizeListFilters struct {
  20. filters []CustomizeListFilterFunc
  21. }
  22. func NewCustomizeListFilters() *CustomizeListFilters {
  23. return &CustomizeListFilters{
  24. filters: []CustomizeListFilterFunc{},
  25. }
  26. }
  27. func (f *CustomizeListFilters) Append(funcs ...CustomizeListFilterFunc) *CustomizeListFilters {
  28. f.filters = append(f.filters, funcs...)
  29. return f
  30. }
  31. func (f CustomizeListFilters) Len() int {
  32. return len(f.filters)
  33. }
  34. func (f CustomizeListFilters) IsEmpty() bool {
  35. return f.Len() == 0
  36. }
  37. func (f CustomizeListFilters) DoApply(objs []jsonutils.JSONObject) ([]jsonutils.JSONObject, error) {
  38. filteredObjs := []jsonutils.JSONObject{}
  39. for _, obj := range objs {
  40. ok, err := f.singleApply(obj)
  41. if err != nil {
  42. return nil, err
  43. }
  44. if ok {
  45. filteredObjs = append(filteredObjs, obj)
  46. }
  47. }
  48. return filteredObjs, nil
  49. }
  50. func (f CustomizeListFilters) singleApply(obj jsonutils.JSONObject) (bool, error) {
  51. if f.IsEmpty() {
  52. return true, nil
  53. }
  54. for _, filter := range f.filters {
  55. ok, err := filter(obj)
  56. if err != nil {
  57. return false, err
  58. }
  59. if !ok {
  60. return false, nil
  61. }
  62. }
  63. return true, nil
  64. }