-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.go
70 lines (60 loc) · 1.85 KB
/
upload.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package cmd
import (
"encoding/json"
"fmt"
fc "github.com/caliagaa/ripfire/cmd/firebase_client"
"github.com/spf13/cobra"
"golang.org/x/net/context"
_ "google.golang.org/api/option"
"io/ioutil"
"log"
)
var (
documentJsonFileName string
collectionName string
documentName string
)
// uploadCmd represents the upload command
var uploadCmd = &cobra.Command{
Use: "upload",
Short: "Uploads a document based on JSON file for a collection to Firestore project",
Long: `Uploads a document based on JSON file for a collection to Firestore project`,
Run: func(cmd *cobra.Command, args []string) {
log.Println("Uploading to collection: ", collectionName)
uploadCollection(collectionName, documentJsonFileName, documentName)
},
}
func init() {
rootCmd.AddCommand(uploadCmd)
uploadCmd.Flags().StringVarP(&documentJsonFileName, "document", "d", "", "JSON file (as document) to upload")
uploadCmd.Flags().StringVarP(&documentName, "name", "n", "", "Document ID")
uploadCmd.Flags().StringVarP(&collectionName, "collection", "c", "", "Collection to upload")
uploadCmd.MarkFlagRequired("document")
uploadCmd.MarkFlagRequired("collection")
}
func uploadCollection(collectionName string, documentJsonFileName string, documentName string) {
ctx := context.Background()
client := fc.GetClient(ctx)
defer client.Close()
file, err0 := ioutil.ReadFile(documentJsonFileName)
if err0 != nil {
log.Fatalf("%v", err0)
return
}
jsonObject := make(map[string]interface{})
err1 := json.Unmarshal(file, &jsonObject)
if err1 != nil {
log.Fatalf("%v", err1)
return
}
fmt.Println(len(jsonObject))
if documentName == "" {
documentName = fmt.Sprintf("%v", jsonObject["code"])
}
_, err := client.Collection(collectionName).Doc(documentName).Set(ctx, jsonObject)
if err != nil {
log.Fatalf("Failed to upload document: %v", err)
return
}
log.Println("Document created")
}