func changeFeedHelper(cursor *r.Cursor, changeEventName string, send chan<- Message, stop <-chan bool) { change := make(chan r.ChangeResponse) cursor.Listen(change) for { eventName := "" var data interface{} select { case <-stop: cursor.Close() return case val := <-change: if val.NewValue != nil && val.OldValue == nil { eventName = changeEventName + " add" data = val.NewValue } else if val.NewValue == nil && val.OldValue != nil { eventName = changeEventName + " remove" data = val.OldValue } else if val.NewValue != nil && val.OldValue != nil { eventName = changeEventName + " edit" data = val.NewValue } send <- Message{eventName, data} } } }
func createSubscription(cursor *r.Cursor, client *Client, entityName string, stopKey int) { recordChan := make(chan r.ChangeResponse) cursor.Listen(recordChan) stopChan := client.NewStopChannel(stopKey) go func() { for { select { case <-stopChan: cursor.Close() return case change := <-recordChan: var command string var data interface{} if change.NewValue != nil && change.OldValue == nil { command = entityName + " add" data = change.NewValue } if change.NewValue == nil && change.OldValue != nil { command = entityName + " remove" data = change.OldValue fmt.Println("sent '" + entityName + " remove' msg") } if change.NewValue != nil && change.OldValue != nil { command = entityName + " edit" data = change.NewValue } client.send <- SocketMessage{command, data} fmt.Println("sent '"+command+"' msg ", data) } } }() }
func InitDB(dbName string) (session *r.Session, err error) { var cursor *r.Cursor session, err = r.Connect(r.ConnectOpts{ Address: os.Getenv("RETHINKDB_URL"), Database: dbName, MaxIdle: 10, Timeout: time.Second * 10, }) if err != nil { l.Println("Connect", err) return } cursor, err = r.DBList().Contains(dbName).Do(func(row r.Term) r.Term { return r.Branch( row.Eq(true), nil, r.DBCreate(dbName), ) }).Run(session) defer cursor.Close() for _, table := range tables { cursor, err = r.DB(dbName).TableList().Contains(table.name).Do(func(row r.Term) r.Term { return r.Branch( row.Eq(true), nil, r.DB(dbName).TableCreate(table.name, table.options), ) }).Run(session) defer cursor.Close() if err != nil { return } } return }