Skip to content

Commit

Permalink
refactor: simplify document creation
Browse files Browse the repository at this point in the history
  • Loading branch information
Muni10 committed Jan 25, 2024
1 parent a4033d4 commit f29f0c5
Showing 1 changed file with 7 additions and 20 deletions.
27 changes: 7 additions & 20 deletions internal/opensearch/opensearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,49 +14,36 @@ import (

func Handler(ctx context.Context, client *opensearch.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, _ *http.Request) {
// Create index contests
indexName := "contests"
indexCreateRequest := opensearchapi.CreateRequest{
Index: indexName,
}
rs, err := indexCreateRequest.Do(ctx, client)
if err != nil && rs.StatusCode == 400 {
log.Info("Index already exists")
} else {
_, err = client.Indices.Create(indexName)
if err != nil {
http.Error(w, fmt.Sprintf("create index: %v", err), http.StatusInternalServerError)
return
}
log.Info("Successfully created index")
}
// Create document
epoch := fmt.Sprintf("%d", time.Now().UnixNano())
document := strings.NewReader(`{ "Application": "contests" }`)
documentCreateRequest := opensearchapi.CreateRequest{
indexRequest := opensearchapi.IndexRequest{
Index: indexName,
DocumentID: epoch,
Body: document,
}
rs, err = documentCreateRequest.Do(ctx, client)

rs, err := indexRequest.Do(ctx, client)
if err != nil {
http.Error(w, fmt.Sprintf("create document: %v", err), http.StatusInternalServerError)
return
}
log.Info("Successfully wrote document to opensearch: %v", rs)
defer rs.Body.Close()
log.Info("Successfully created document to opensearch: %v", rs)

// Retrieving same document
getRequest := opensearchapi.GetRequest{
Index: indexName,
DocumentID: epoch,
}

rs, err = getRequest.Do(ctx, client)
if err != nil {
http.Error(w, fmt.Sprintf("get document: %v", err), http.StatusInternalServerError)
return
}

log.Info("Successfully read document from opensearch: %v", rs)

w.WriteHeader(http.StatusOK)
}
}

0 comments on commit f29f0c5

Please sign in to comment.