pagination.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. )
  7. // Paginator keeps track of pagination configuration for an API operation.
  8. type Paginator struct {
  9. InputTokens interface{} `json:"input_token"`
  10. OutputTokens interface{} `json:"output_token"`
  11. LimitKey string `json:"limit_key"`
  12. MoreResults string `json:"more_results"`
  13. }
  14. // InputTokensString returns output tokens formatted as a list
  15. func (p *Paginator) InputTokensString() string {
  16. str := p.InputTokens.([]string)
  17. return fmt.Sprintf("%#v", str)
  18. }
  19. // OutputTokensString returns output tokens formatted as a list
  20. func (p *Paginator) OutputTokensString() string {
  21. str := p.OutputTokens.([]string)
  22. return fmt.Sprintf("%#v", str)
  23. }
  24. // used for unmarshaling from the paginators JSON file
  25. type paginationDefinitions struct {
  26. *API
  27. Pagination map[string]Paginator
  28. }
  29. // AttachPaginators attaches pagination configuration from filename to the API.
  30. func (a *API) AttachPaginators(filename string) {
  31. p := paginationDefinitions{API: a}
  32. f, err := os.Open(filename)
  33. defer f.Close()
  34. if err != nil {
  35. panic(err)
  36. }
  37. err = json.NewDecoder(f).Decode(&p)
  38. if err != nil {
  39. panic(err)
  40. }
  41. p.setup()
  42. }
  43. // setup runs post-processing on the paginator configuration.
  44. func (p *paginationDefinitions) setup() {
  45. for n, e := range p.Pagination {
  46. if e.InputTokens == nil || e.OutputTokens == nil {
  47. continue
  48. }
  49. paginator := e
  50. switch t := paginator.InputTokens.(type) {
  51. case string:
  52. paginator.InputTokens = []string{t}
  53. case []interface{}:
  54. toks := []string{}
  55. for _, e := range t {
  56. s := e.(string)
  57. toks = append(toks, s)
  58. }
  59. paginator.InputTokens = toks
  60. }
  61. switch t := paginator.OutputTokens.(type) {
  62. case string:
  63. paginator.OutputTokens = []string{t}
  64. case []interface{}:
  65. toks := []string{}
  66. for _, e := range t {
  67. s := e.(string)
  68. toks = append(toks, s)
  69. }
  70. paginator.OutputTokens = toks
  71. }
  72. if o, ok := p.Operations[n]; ok {
  73. o.Paginator = &paginator
  74. } else {
  75. panic("unknown operation for paginator " + n)
  76. }
  77. }
  78. }