示例#1
0
// Write writes the item to the store. It constructs the key using the i.Key()
// and prefixes it with the type of struct. When the key is empty, it assigns
// a unique universal id(UUID) using the SetKey method of the Item
func (s *Store) Write(i store.Item) error {
	c := s.pool.Get()
	defer c.Close()

	value := reflect.ValueOf(i).Elem()

	ri := &Item{
		prefix: s.typeName(value),
		data:   make(map[string]interface{}),
	}

	// Use the Items id if set or generate
	// a new UUID
	ri.key = i.Key()
	if len(ri.key) == 0 {
		ri.key = uuid.New()
	}
	i.SetKey(ri.key)

	// convert the item to redis item
	if err := marshall(i, value, ri); err != nil {
		return err
	}

	for key, val := range ri.data {
		if err := c.Send("HSET", ri.Key(), key, val); err != nil {
			return err
		}
		c.Flush()
	}

	return nil
}
示例#2
0
// Delete deletes the item from the store. It constructs the key using i.Key().
// When the key is empty, it returns a store.ErrEmptyKey error. When the key
// does not exist, it returns a store.ErrKeyNotFound error.
func (s *Redis) Delete(i store.Item) error {
	c := s.pool.Get()
	defer c.Close()

	value := reflect.ValueOf(i).Elem()

	ri := &item{
		prefix: s.typeName(value),
	}

	ri.key = i.Key()
	if len(ri.key) == 0 {
		return store.ErrEmptyKey
	}

	count, err := driver.Int(c.Do("DEL", ri.Key()))
	if err != nil {
		return err
	}
	if count == 0 {
		return store.ErrKeyNotFound
	}

	return nil
}
示例#3
0
// Read reads the item from redis store and copies the values to item
// It Returns store.ErrKeyNotFound when no values are found for the key provided
// and store.ErrKeyMissing when key is not provided. Unmarshalling id done using
// driver provided redis.ScanStruct
func (s *Store) Read(i store.Item) error {
	c := s.pool.Get()
	defer c.Close()

	value := reflect.ValueOf(i).Elem()
	if len(i.Key()) == 0 {
		return store.ErrEmptyKey
	}
	ri := &Item{
		key:    i.Key(),
		prefix: value.Type().Name(),
	}
	reply, err := driver.Values(c.Do("HGETALL", ri.Key()))
	if err != nil {
		return err
	}
	if len(reply) == 0 {
		return store.ErrKeyNotFound
	}
	if err := driver.ScanStruct(reply, i); err != nil {
		return err
	}
	return nil
}