// getSort transform a resource.Lookup into a Mongo sort list. // If the sort list is empty, fallback to _id. func getSort(l *resource.Lookup) []string { ln := len(l.Sort()) if ln == 0 { return []string{"_id"} } s := make([]string, ln) for i, sort := range l.Sort() { if len(sort) > 0 && sort[0] == '-' { s[i] = "-" + getField(sort[1:]) } else { s[i] = getField(sort) } } return s }
// Find items from memory matching the provided lookup func (m *MemoryHandler) Find(ctx context.Context, lookup *resource.Lookup, page, perPage int) (list *resource.ItemList, err error) { m.RLock() defer m.RUnlock() err = handleWithLatency(m.Latency, ctx, func() error { items := []*resource.Item{} // Apply filter for _, id := range m.ids { item, _, err := m.fetch(id) if err != nil { return err } if !lookup.Filter().Match(item.Payload) { continue } items = append(items, item) } // Apply sort if len(lookup.Sort()) > 0 { s := sortableItems{lookup.Sort(), items} sort.Sort(s) } // Apply pagination total := len(items) start := (page - 1) * perPage end := total if perPage > 0 { end = start + perPage if start > total-1 { start = 0 end = 0 } else if end > total-1 { end = total } } list = &resource.ItemList{total, page, items[start:end]} return nil }) return list, err }