Skip to content

Commit 29468c2

Browse files
fix(indexing): replaceAllObjects blocked if called for non-existent index (#699)
1 parent dce3e44 commit 29468c2

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

algolia/search/index_objects.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,29 @@ func (i *Index) browserForObjects(params searchParams, opts ...interface{}) func
344344
// prevent issues, one may want to pass the opt.Safe(true) option. Note that
345345
// passing this option will make the method blocking.
346346
func (i *Index) ReplaceAllObjects(objects interface{}, opts ...interface{}) (g *wait.Group, err error) {
347+
safe := iopt.ExtractSafe(opts...).Get()
348+
349+
exists, err := i.Exists()
350+
if err != nil {
351+
err = fmt.Errorf("cannot check if the index exists: %v", err)
352+
return
353+
}
354+
355+
if !exists {
356+
resSaveObjects, e := i.SaveObjects(objects, opts...)
357+
if e != nil {
358+
err = fmt.Errorf("cannot save objects to the index: %v", e)
359+
return
360+
}
361+
if safe {
362+
if e := resSaveObjects.Wait(); e != nil {
363+
err = fmt.Errorf("error while waiting for saving objects to the index: %v", e)
364+
return
365+
}
366+
}
367+
return
368+
}
369+
347370
tmpIndex := i.client.InitIndex(fmt.Sprintf(
348371
"%s_tmp_%d",
349372
i.name,
@@ -359,7 +382,6 @@ func (i *Index) ReplaceAllObjects(objects interface{}, opts ...interface{}) (g *
359382
}()
360383

361384
g = wait.NewGroup()
362-
safe := iopt.ExtractSafe(opts...).Get()
363385
optsWithScopes := opt.InsertOrReplaceOption(opts, opt.Scopes("rules", "settings", "synonyms"))
364386

365387
resCopyIndex, err := i.client.CopyIndex(i.name, tmpIndex.name, optsWithScopes...)

cts/index/replacing_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,17 @@ func TestReplacing(t *testing.T) {
107107
require.NoError(t, err)
108108
}
109109
}
110+
111+
func TestReplacingNonExistentIndex(t *testing.T) {
112+
t.Parallel()
113+
_, index, _ := cts.InitSearchClient1AndIndex(t)
114+
115+
_, err := index.ReplaceAllObjects([]map[string]string{{"objectID": "one"}, {"objectID": "two"}}, opt.Safe(true))
116+
require.NoError(t, err)
117+
118+
err = index.GetObject("one", nil)
119+
require.NoError(t, err)
120+
121+
err = index.GetObject("two", nil)
122+
require.NoError(t, err)
123+
}

0 commit comments

Comments
 (0)