Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions mongodbatlas/indexes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package mongodbatlas

import (
"context"
"fmt"
"net/http"
)

const indexesPath = "groups/%s/clusters/%s/index"

// IndexesService is an interface for interfacing with the clusters indexes
// endpoints of the MongoDB Atlas API.
// See more: https://docs.atlas.mongodb.com/reference/api/indexes/
type IndexesService interface {
Create(context.Context, string, string, *IndexConfiguration) (*Response, error)
}

// IndexesServiceOp handles communication with the Cluster related methods
// of the MongoDB Atlas API
type IndexesServiceOp struct {
Client RequestDoer
}

var _ IndexesService = &IndexesServiceOp{}

// IndexConfiguration represents a new index requests for a given database and collection.
type IndexConfiguration struct {
DB string `json:"db"` // DB the database of the index
Collection string `json:"collection"` // Collection the collection of the index
Keys []map[string]string `json:"keys"` // Keys array of keys to index and their type, sorting of keys is important for an index
Options *IndexOptions `json:"options,omitempty"` // Options MongoDB index options
Collation *CollationOptions `json:"collation,omitempty"` // Collation Mongo collation index options
}

// IndexOptions, represents mdb index options
// See: https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options
type IndexOptions struct {
Background bool `json:"background,omitempty"`
PartialFilterExpression *map[string]interface{} `json:"partialFilterExpression,omitempty"`
StorageEngine *map[string]interface{} `json:"storageEngine,omitempty"`
Weights *map[string]int `json:"weights,omitempty"`
DefaultLanguage string `json:"default_language,omitempty"`
LanguageOverride string `json:"language_override,omitempty"`
TextIndexVersion int `json:"textIndexVersion,omitempty"`
TwodsphereIndexVersion int `json:"2dsphereIndexVersion,omitempty"`
Bits int `json:"bits,omitempty"`
Unique bool `json:"unique,omitempty"`
Sparse bool `json:"sparse,omitempty"`
GeoMin int `json:"min,omitempty"`
GeoMax int `json:"max,omitempty"`
BucketSize int `json:"bucketSize,omitempty"`
Name string `json:"name,omitempty"`
ExpireAfterSeconds int `json:"expireAfterSeconds,omitempty"`
}

// CollationOptions represents options for collation indexes
// See: https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#option-for-collation
type CollationOptions struct {
Locale string `json:"locale,omitempty"`
CaseLevel bool `json:"caseLevel,omitempty"`
CaseFirst string `json:"caseFirst,omitempty"`
Strength int `json:"strength,omitempty"`
NumericOrdering bool `json:"numericOrdering,omitempty"`
Alternate string `json:"alternate,omitempty"`
MaxVariable string `json:"maxVariable,omitempty"`
Normalization bool `json:"normalization,omitempty"`
Backwards bool `json:"backwards,omitempty"`
}

// Create creates a request for a rolling index creation for the project associated to {GROUP-ID} and the {CLUSTER-NAME}.
// See more: https://docs.atlas.mongodb.com/reference/api/rolling-index-create-one/
func (s *IndexesServiceOp) Create(ctx context.Context, groupID string, clusterName string, createReq *IndexConfiguration) (*Response, error) {
if groupID == "" {
return nil, NewArgError("groupID", "must be set")
}
if clusterName == "" {
return nil, NewArgError("clusterName", "must be set")
}
if createReq == nil {
return nil, NewArgError("createReq", "must be set")
}

path := fmt.Sprintf(indexesPath, groupID, clusterName)

req, err := s.Client.NewRequest(ctx, http.MethodPost, path, createReq)
if err != nil {
return nil, err
}

resp, err := s.Client.Do(ctx, req, nil)

return resp, err
}
61 changes: 61 additions & 0 deletions mongodbatlas/indexes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package mongodbatlas

import (
"encoding/json"
"fmt"
"net/http"
"testing"

"github.com/go-test/deep"
)

func TestIndexesServiceOp_Create(t *testing.T) {
setup()
defer teardown()

groupID := "1"
clusterName := "appData"

createRequest := &IndexConfiguration{
DB: "test",
Collection: "test",
Keys: []map[string]string{
{
"name": "1",
},
},
Options: &IndexOptions{
Unique: true,
},
}
mux.HandleFunc(fmt.Sprintf("/groups/%s/clusters/%s/index", groupID, clusterName), func(w http.ResponseWriter, r *http.Request) {
testMethod(t, r, http.MethodPost)
expected := map[string]interface{}{
"db": "test",
"collection": "test",
"keys": []interface{}{map[string]interface{}{
"name": "1",
}},
"options": map[string]interface{}{
"unique": true,
},
}

var v map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
t.Fatalf("decode json: %v", err)
}

if diff := deep.Equal(v, expected); diff != nil {
t.Errorf("Clusters.Update Request Body = %v", diff)
}
fmt.Fprint(w, "{}")
})

_, err := client.Indexes.Create(ctx, groupID, clusterName, createRequest)

if err != nil {
t.Fatalf("Indexes.Create returned error: %v", err)
}
}
2 changes: 2 additions & 0 deletions mongodbatlas/mongodbatlas.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ type Client struct {
ProcessDisks ProcessDisksService
ProcessDiskMeasurements ProcessDiskMeasurementsService
ProcessDatabases ProcessDatabasesService
Indexes IndexesService

onRequestCompleted RequestCompletionCallback
}
Expand Down Expand Up @@ -193,6 +194,7 @@ func NewClient(httpClient *http.Client) *Client {
c.ProcessDisks = &ProcessDisksServiceOp{Client: c}
c.ProcessDiskMeasurements = &ProcessDiskMeasurementsServiceOp{Client: c}
c.ProcessDatabases = &ProcessDatabasesServiceOp{Client: c}
c.Indexes = &IndexesServiceOp{Client: c}

return c
}
Expand Down