github.com/mmatczuk/gohan@v0.0.0-20170206152520-30e45d9bdb69/db/pagination/pagination.go (about) 1 // Copyright (C) 2015 NTT Innovation Institute, Inc. 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 12 // implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 package pagination 17 18 import ( 19 "fmt" 20 "net/url" 21 "strconv" 22 23 "github.com/cloudwan/gohan/schema" 24 ) 25 26 const ( 27 //ASC ascending order 28 ASC = "asc" 29 //DESC descending order 30 DESC = "desc" 31 32 defaultSortKey = "id" 33 defaultSortOrder = ASC 34 ) 35 36 //Paginator stores pagination data 37 type Paginator struct { 38 Key string 39 Order string 40 Limit uint64 41 Offset uint64 42 } 43 44 //NewPaginator create Paginator 45 func NewPaginator(s *schema.Schema, key, order string, limit, offset uint64) (*Paginator, error) { 46 if key == "" { 47 key = defaultSortKey 48 } 49 if order == "" { 50 order = defaultSortOrder 51 } 52 if order != ASC && order != DESC { 53 return nil, fmt.Errorf("Unknown sort order %s", order) 54 } 55 if s != nil { 56 found := false 57 for _, p := range s.Properties { 58 if p.ID == key { 59 found = true 60 break 61 } 62 } 63 if !found { 64 return nil, fmt.Errorf("Schema %s has no property %s which can used as sorting key", s.ID, key) 65 } 66 } 67 return &Paginator{ 68 Key: key, 69 Order: order, 70 Limit: limit, 71 Offset: offset, 72 }, nil 73 } 74 75 //FromURLQuery create Paginator from Query params 76 func FromURLQuery(s *schema.Schema, values url.Values) (pg *Paginator, err error) { 77 sortKey := values.Get("sort_key") 78 sortOrder := values.Get("sort_order") 79 var limit uint64 80 var offset uint64 81 82 if l := values.Get("limit"); l != "" { 83 limit, err = strconv.ParseUint(l, 10, 64) 84 } 85 if err != nil { 86 return 87 } 88 89 if o := values.Get("offset"); o != "" { 90 offset, err = strconv.ParseUint(o, 10, 64) 91 } 92 if err != nil { 93 return 94 } 95 return NewPaginator(s, sortKey, sortOrder, limit, offset) 96 }