pager.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package pagination
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "reflect"
  7. "strings"
  8. "devel.mephi.ru/iacherepanov/openstack-gophercloud"
  9. )
  10. var (
  11. // ErrPageNotAvailable is returned from a Pager when a next or previous page is requested, but does not exist.
  12. ErrPageNotAvailable = errors.New("The requested page does not exist.")
  13. )
  14. // Page must be satisfied by the result type of any resource collection.
  15. // It allows clients to interact with the resource uniformly, regardless of whether or not or how it's paginated.
  16. // Generally, rather than implementing this interface directly, implementors should embed one of the concrete PageBase structs,
  17. // instead.
  18. // Depending on the pagination strategy of a particular resource, there may be an additional subinterface that the result type
  19. // will need to implement.
  20. type Page interface {
  21. // NextPageURL generates the URL for the page of data that follows this collection.
  22. // Return "" if no such page exists.
  23. NextPageURL() (string, error)
  24. // IsEmpty returns true if this Page has no items in it.
  25. IsEmpty() (bool, error)
  26. // GetBody returns the Page Body. This is used in the `AllPages` method.
  27. GetBody() interface{}
  28. }
  29. // Pager knows how to advance through a specific resource collection, one page at a time.
  30. type Pager struct {
  31. client *gophercloud.ServiceClient
  32. initialURL string
  33. createPage func(r PageResult) Page
  34. Err error
  35. // Headers supplies additional HTTP headers to populate on each paged request.
  36. Headers map[string]string
  37. }
  38. // NewPager constructs a manually-configured pager.
  39. // Supply the URL for the first page, a function that requests a specific page given a URL, and a function that counts a page.
  40. func NewPager(client *gophercloud.ServiceClient, initialURL string, createPage func(r PageResult) Page) Pager {
  41. return Pager{
  42. client: client,
  43. initialURL: initialURL,
  44. createPage: createPage,
  45. }
  46. }
  47. // WithPageCreator returns a new Pager that substitutes a different page creation function. This is
  48. // useful for overriding List functions in delegation.
  49. func (p Pager) WithPageCreator(createPage func(r PageResult) Page) Pager {
  50. return Pager{
  51. client: p.client,
  52. initialURL: p.initialURL,
  53. createPage: createPage,
  54. }
  55. }
  56. func (p Pager) fetchNextPage(url string) (Page, error) {
  57. resp, err := Request(p.client, p.Headers, url)
  58. if err != nil {
  59. return nil, err
  60. }
  61. remembered, err := PageResultFrom(resp)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return p.createPage(remembered), nil
  66. }
  67. // EachPage iterates over each page returned by a Pager, yielding one at a time to a handler function.
  68. // Return "false" from the handler to prematurely stop iterating.
  69. func (p Pager) EachPage(handler func(Page) (bool, error)) error {
  70. if p.Err != nil {
  71. return p.Err
  72. }
  73. currentURL := p.initialURL
  74. for {
  75. currentPage, err := p.fetchNextPage(currentURL)
  76. if err != nil {
  77. return err
  78. }
  79. empty, err := currentPage.IsEmpty()
  80. if err != nil {
  81. return err
  82. }
  83. if empty {
  84. return nil
  85. }
  86. ok, err := handler(currentPage)
  87. if err != nil {
  88. return err
  89. }
  90. if !ok {
  91. return nil
  92. }
  93. currentURL, err = currentPage.NextPageURL()
  94. if err != nil {
  95. return err
  96. }
  97. if currentURL == "" {
  98. return nil
  99. }
  100. }
  101. }
  102. // AllPages returns all the pages from a `List` operation in a single page,
  103. // allowing the user to retrieve all the pages at once.
  104. func (p Pager) AllPages() (Page, error) {
  105. // pagesSlice holds all the pages until they get converted into as Page Body.
  106. var pagesSlice []interface{}
  107. // body will contain the final concatenated Page body.
  108. var body reflect.Value
  109. // Grab a test page to ascertain the page body type.
  110. testPage, err := p.fetchNextPage(p.initialURL)
  111. if err != nil {
  112. return nil, err
  113. }
  114. // Store the page type so we can use reflection to create a new mega-page of
  115. // that type.
  116. pageType := reflect.TypeOf(testPage)
  117. // if it's a single page, just return the testPage (first page)
  118. if _, found := pageType.FieldByName("SinglePageBase"); found {
  119. return testPage, nil
  120. }
  121. // Switch on the page body type. Recognized types are `map[string]interface{}`,
  122. // `[]byte`, and `[]interface{}`.
  123. switch pb := testPage.GetBody().(type) {
  124. case map[string]interface{}:
  125. // key is the map key for the page body if the body type is `map[string]interface{}`.
  126. var key string
  127. // Iterate over the pages to concatenate the bodies.
  128. err = p.EachPage(func(page Page) (bool, error) {
  129. b := page.GetBody().(map[string]interface{})
  130. for k, v := range b {
  131. // If it's a linked page, we don't want the `links`, we want the other one.
  132. if !strings.HasSuffix(k, "links") {
  133. // check the field's type. we only want []interface{} (which is really []map[string]interface{})
  134. switch vt := v.(type) {
  135. case []interface{}:
  136. key = k
  137. pagesSlice = append(pagesSlice, vt...)
  138. }
  139. }
  140. }
  141. return true, nil
  142. })
  143. if err != nil {
  144. return nil, err
  145. }
  146. // Set body to value of type `map[string]interface{}`
  147. body = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(key), reflect.TypeOf(pagesSlice)))
  148. body.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(pagesSlice))
  149. case []byte:
  150. // Iterate over the pages to concatenate the bodies.
  151. err = p.EachPage(func(page Page) (bool, error) {
  152. b := page.GetBody().([]byte)
  153. pagesSlice = append(pagesSlice, b)
  154. // seperate pages with a comma
  155. pagesSlice = append(pagesSlice, []byte{10})
  156. return true, nil
  157. })
  158. if err != nil {
  159. return nil, err
  160. }
  161. if len(pagesSlice) > 0 {
  162. // Remove the trailing comma.
  163. pagesSlice = pagesSlice[:len(pagesSlice)-1]
  164. }
  165. var b []byte
  166. // Combine the slice of slices in to a single slice.
  167. for _, slice := range pagesSlice {
  168. b = append(b, slice.([]byte)...)
  169. }
  170. // Set body to value of type `bytes`.
  171. body = reflect.New(reflect.TypeOf(b)).Elem()
  172. body.SetBytes(b)
  173. case []interface{}:
  174. // Iterate over the pages to concatenate the bodies.
  175. err = p.EachPage(func(page Page) (bool, error) {
  176. b := page.GetBody().([]interface{})
  177. pagesSlice = append(pagesSlice, b...)
  178. return true, nil
  179. })
  180. if err != nil {
  181. return nil, err
  182. }
  183. // Set body to value of type `[]interface{}`
  184. body = reflect.MakeSlice(reflect.TypeOf(pagesSlice), len(pagesSlice), len(pagesSlice))
  185. for i, s := range pagesSlice {
  186. body.Index(i).Set(reflect.ValueOf(s))
  187. }
  188. default:
  189. err := gophercloud.ErrUnexpectedType{}
  190. err.Expected = "map[string]interface{}/[]byte/[]interface{}"
  191. err.Actual = fmt.Sprintf("%T", pb)
  192. return nil, err
  193. }
  194. // Each `Extract*` function is expecting a specific type of page coming back,
  195. // otherwise the type assertion in those functions will fail. pageType is needed
  196. // to create a type in this method that has the same type that the `Extract*`
  197. // function is expecting and set the Body of that object to the concatenated
  198. // pages.
  199. page := reflect.New(pageType)
  200. // Set the page body to be the concatenated pages.
  201. page.Elem().FieldByName("Body").Set(body)
  202. // Set any additional headers that were pass along. The `objectstorage` pacakge,
  203. // for example, passes a Content-Type header.
  204. h := make(http.Header)
  205. for k, v := range p.Headers {
  206. h.Add(k, v)
  207. }
  208. page.Elem().FieldByName("Header").Set(reflect.ValueOf(h))
  209. // Type assert the page to a Page interface so that the type assertion in the
  210. // `Extract*` methods will work.
  211. return page.Elem().Interface().(Page), err
  212. }