Created
July 6, 2017 06:06
-
-
Save tleyden/49e4b50256103af2c69051cc24db0afb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"encoding/json" | |
"github.com/flimzy/kivik" | |
_ "github.com/flimzy/kivik/driver/couchdb" // The CouchDB driver | |
"os" | |
"log" | |
) | |
type Params struct { | |
Username string | |
Password string | |
Host string | |
DbName string | |
Doc map[string]interface{} | |
DocId string | |
} | |
func main() { | |
ctx := context.TODO() | |
params := discoverParams() | |
dataSourceName := fmt.Sprintf( | |
"http://%s:%s@%s", | |
params.Username, | |
params.Password, | |
params.Host, | |
) | |
client, err := kivik.New(ctx, "couch", dataSourceName) | |
if err != nil { | |
panic(err) | |
} | |
db, err := client.DB(ctx, params.DbName) | |
if err != nil { | |
panic(err) | |
} | |
// Cas loop where we get the latest rev of the doc | |
for { | |
fetchedDocRow, err := db.Get(ctx, params.DocId) | |
if err != nil { | |
// Assume this will be the first rev of the doc, so do nothing in this case | |
} else { | |
// Got an existing doc, update the doc being inserted to be based on this rev | |
// we had a valid previous rev | |
fetchedDoc := map[string]interface{}{} | |
scanDocErr := fetchedDocRow.ScanDoc(&fetchedDoc) | |
if scanDocErr != nil { | |
panic(fmt.Sprintf("Could not read doc into map")) | |
} | |
revRaw, ok := fetchedDoc["_rev"] | |
if !ok { | |
panic(fmt.Sprintf("Doc does not have _rev field")) | |
} | |
rev := revRaw.(string) | |
params.Doc["_rev"] = rev | |
} | |
log.Printf("Going to put doc: %+v", params.Doc) | |
rev, err := db.Put(context.TODO(), params.DocId, params.Doc) | |
if err != nil { | |
// TODO: this should write to stderr rather than stdout | |
log.Printf("Error putting doc, assuming to be 409 cas error. Actual err: %v", err) | |
continue | |
} | |
fmt.Printf("%s inserted with revision %s\n", params.DocId, rev) | |
break | |
} | |
// TODO: do a get on the doc and write it to stdout | |
// remove all other debugging | |
} | |
func discoverParams() (params Params) { | |
// native actions receive one argument, the JSON object as a string | |
arg := os.Args[1] | |
// unmarshal the string to a JSON object | |
json.Unmarshal([]byte(arg), ¶ms) | |
return params | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment