github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/lib/search.go (about)

     1  package lib
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/qri-io/qri/base/params"
     7  	qhttp "github.com/qri-io/qri/lib/http"
     8  	"github.com/qri-io/qri/registry"
     9  	"github.com/qri-io/qri/registry/regclient"
    10  	"github.com/qri-io/qri/repo"
    11  )
    12  
    13  // SearchMethods groups together methods for search
    14  type SearchMethods struct {
    15  	d dispatcher
    16  }
    17  
    18  // Name returns the name of this method group
    19  func (m SearchMethods) Name() string {
    20  	return "search"
    21  }
    22  
    23  // Attributes defines attributes for each method
    24  func (m SearchMethods) Attributes() map[string]AttributeSet {
    25  	return map[string]AttributeSet{
    26  		"search": {Endpoint: qhttp.AESearch, HTTPVerb: "POST"},
    27  	}
    28  }
    29  
    30  // SearchParams defines paremeters for the search Method
    31  type SearchParams struct {
    32  	params.List
    33  	Query string `json:"q"`
    34  }
    35  
    36  // SetNonZeroDefaults sets a default limit and offset
    37  func (p *SearchParams) SetNonZeroDefaults() {
    38  	if p.Offset < 0 {
    39  		p.Offset = 0
    40  	}
    41  	if p.Limit <= 0 {
    42  		p.Limit = params.DefaultListLimit
    43  	}
    44  }
    45  
    46  // Search queries for items on qri related to given parameters
    47  func (m SearchMethods) Search(ctx context.Context, p *SearchParams) ([]registry.SearchResult, error) {
    48  	got, _, err := m.d.Dispatch(ctx, dispatchMethodName(m, "search"), p)
    49  	if res, ok := got.([]registry.SearchResult); ok {
    50  		return res, err
    51  	}
    52  	return nil, dispatchReturnError(got, err)
    53  }
    54  
    55  // Implementations for FSI methods follow
    56  
    57  // searchImpl holds the method implementations for search
    58  type searchImpl struct{}
    59  
    60  // Search queries for items on qri related to given parameters
    61  func (searchImpl) Search(scope scope, p *SearchParams) ([]registry.SearchResult, error) {
    62  	client := scope.RegistryClient()
    63  	if client == nil {
    64  		return nil, repo.ErrNoRegistry
    65  	}
    66  	params := &regclient.SearchParams{
    67  		Query:  p.Query,
    68  		Limit:  p.Limit,
    69  		Offset: p.Offset,
    70  	}
    71  
    72  	regResults, err := client.Search(scope.Context(), params)
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  	return regResults, nil
    77  }