func (m *DB) putMapItem(tx *bolt.Tx, mi common.MapItem) error { // extract key and value bytes. k := mi.Key() if k == nil { // all MapItems must have own EndnodeAddress. return common.ErrNoEndnodeAddress } v, err := m.marshalMapItem(mi) if err != nil { return err } // put an item into core bucket. items := tx.Bucket([]byte(boltItemBucket)) items.Put(k, v) // get pendings bucket. pendings := tx.Bucket([]byte(boltPendingBucket)) // put it to cloud bucket if CloudAddress is available. ck := mi.CloudKey() if ck != nil { if pendings.Get(k) != nil { if err := pendings.Delete(k); err != nil { return err } } cloud := tx.Bucket([]byte(boltCloudBucket)) return cloud.Put(ck, k) } // otherwise put it to pendings bucket. if pendings.Get(k) == nil { return pendings.Put(k, k) } return nil }
// UpdateCloud updates CloudAddress field of a end-node. func (m *DB) UpdateCloud(ea common.EndnodeAddress, ca common.CloudAddress) (common.MapItem, error) { var item common.MapItem err := m.db.Update(func(tx *bolt.Tx) (err error) { item, err = m.getMapItem(tx, []byte(ea.IDString())) if err != nil { return err } item.CloudAddress = &ca return m.putMapItem(tx, item) }) if err != nil { return common.MapItem{}, err } return item, nil }
// UpsertEndnodeProperties updates or inserts a end-node with thing properties. func (m *DB) UpsertEndnodeProperties(ea common.EndnodeAddress, data []byte) (common.MapItem, error) { var item common.MapItem err := m.db.Update(func(tx *bolt.Tx) (err error) { item, err = m.getMapItem(tx, []byte(ea.IDString())) if err != nil { if err != common.ErrUnknownEndnode { return err } item = common.MapItem{ EndnodeAddress: &ea, } } item.ThingProperties = data return m.putMapItem(tx, item) }) if err != nil { return common.MapItem{}, err } return item, nil }
// UpdateEndnode updates EndnodeAddress for an existing end-node. func (m *DB) UpdateEndnode(newEA common.EndnodeAddress, caddr common.CloudAddress) (common.MapItem, error) { var item common.MapItem err := m.db.Update(func(tx *bolt.Tx) (err error) { //find mapItem with cloud address item, err = m.FindByCloudAddress(caddr) if err != nil { return err } //delete mapItem from bucket err = m.deleteMapItem(tx, item.Key()) if err != nil { return err } //insert mapItem with new endnode address item.EndnodeAddress = &newEA return m.putMapItem(tx, item) }) if err != nil { return common.MapItem{}, err } return item, nil }