Пример #1
0
// GetAll fetches all operation from BoltDB storage.
func GetAll() (result []Operation) {
	view(func(k, v []byte) {
		op := &Operation{}
		boltdb.DecodeValue(v, op, cfg.DataEncoding)
		result = append(result, *op)
	})
	return
}
Пример #2
0
// FetchByDate attempts to fetch all operations, which are operated by user with
// username (or all users if username = "") and in time bounds beetween dateFrom and dateTo dates.
func FetchByDate(dateFrom, dateTo, username string) ([]Operation, error) {
	result := []Operation{}

	db, err := bolt.Open(cfg.BoltDB, dbMode, nil)
	if err != nil {
		return result, err
	}
	defer db.Close()

	//halper func for parsing date and handling errors
	parseTime := func(source string) (time.Time, error) {
		t, err := time.Parse(TimeLayout, source)
		if err != nil {
			return t, err
		}
		return t, nil
	}

	from, err := parseTime(dateFrom)
	if err != nil {
		return result, err
	}

	to, err := parseTime(dateTo)
	if err != nil {
		return result, err
	}

	now, err := parseTime(time.Now().Format(TimeLayout))
	if err != nil {
		return result, err
	}

	if to.Equal(now) {
		to = time.Now()
	} else {
		to = to.Add(24 * time.Hour)
	}

	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(cfg.BucketForOperations))
		c := b.Cursor()
		for k, v := c.Seek([]byte(from.String())); k != nil && bytes.Compare(k, []byte(to.String())) <= 0; k, v = c.Next() {
			//check username
			if username != "" && !bytes.HasSuffix(k, []byte(username)) {
				continue
			}

			op := &Operation{}
			boltdb.DecodeValue(v, op, cfg.DataEncoding)
			result = append(result, *op)
		}
		return nil
	})

	return result, nil
}