-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (71 loc) · 1.93 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type airtableRecord struct {
Id string `json:"id"`
Fields map[string]interface{} `json:"fields"`
}
type airtableObjectsResponse struct {
Records []airtableRecord
}
func main() {
records := FetchRecords()
PostRecords(*records)
}
func FetchRecords() *airtableObjectsResponse {
airtableApiKey := os.Getenv("AIRTABLE_API_KEY")
airtableTableName := os.Getenv("AIRTABLE_TABLE_NAME")
airtableWorspaceId := os.Getenv("AIRTABLE_WORKSPACE_ID")
airtableUrl := fmt.Sprintf("https://api.airtable.com/v0/%s/%s?api_key=", airtableWorspaceId, airtableTableName)
authedAirtableUrl := airtableUrl + airtableApiKey
res, err := http.Get(authedAirtableUrl)
if err != nil {
log.Fatal(err)
}
objects := new(airtableObjectsResponse)
err = json.NewDecoder(res.Body).Decode(objects)
defer res.Body.Close()
if err != nil {
log.Fatal(err)
}
return objects
}
func PostRecords(objects airtableObjectsResponse) {
algoliaApiKey := os.Getenv("ALGOLIA_API_KEY")
algoliaAppId := os.Getenv("ALGOLIA_APP_ID")
algoliaIndexName := os.Getenv("ALGOLIA_INDEX_NAME")
for _, object := range objects.Records {
alogoliaUrl := fmt.Sprintf("https://%s.algolia.net/1/indexes/%s/%s", algoliaAppId, algoliaIndexName, object.Id)
headers := map[string]string{
"X-Algolia-API-Key": algoliaApiKey,
"X-Algolia-Application-Id": algoliaAppId,
}
objectData, err := json.Marshal(object.Fields)
if err != nil {
log.Fatal(err)
}
fmt.Printf("PUTing %s", object.Id)
putRequest(alogoliaUrl, bytes.NewReader(objectData), headers)
}
}
func putRequest(url string, data io.Reader, headers map[string]string) {
client := &http.Client{}
req, err := http.NewRequest(http.MethodPut, url, data)
for key, value := range headers {
req.Header.Set(key, value)
}
if err != nil {
log.Fatal(err)
}
_, err = client.Do(req)
if err != nil {
log.Fatal(err)
}
}