Skip to content

Commit 3a718c8

Browse files
committed
Add a new function deleteIfExists -> Bool
Closes #208
1 parent 8520a1b commit 3a718c8

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Sources/MeiliSearch/Indexes.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,24 @@ public struct Indexes {
230230
}
231231
}
232232

233+
/**
234+
Delete the index only if it exists.
235+
236+
- parameter completion: The completion closure used to notify when the server
237+
completes the delete request, it returns a `Bool` that is `true`
238+
If the request sucessfully deleted an existent index or `false` if a failure occured or the index do not exist.
239+
*/
240+
public func deleteIfExists(_ completion: @escaping (Bool) -> Void) {
241+
self.request.delete(api: "/indexes/\(self.uid)") { result in
242+
switch result {
243+
case .success:
244+
completion(true)
245+
default:
246+
completion(false)
247+
}
248+
}
249+
}
250+
233251
// MARK: Document
234252

235253
/**

Tests/MeiliSearchUnitTests/IndexesTests.swift

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,45 @@ class IndexesTests: XCTestCase {
277277
self.wait(for: [expectation], timeout: 10.0)
278278
}
279279

280+
func testDeleteIndexIfExists() {
281+
// Prepare the mock server
282+
session.pushEmpty(code: 204)
283+
284+
// Start the test with the mocked server
285+
let expectation = XCTestExpectation(description: "Delete Movies index")
286+
287+
self.index.deleteIfExists { result in
288+
if result {
289+
XCTAssertTrue(result)
290+
expectation.fulfill()
291+
} else {
292+
XCTFail("Failed to delete Movies index, it was not present on the server")
293+
}
294+
expectation.fulfill()
295+
}
296+
297+
self.wait(for: [expectation], timeout: 10.0)
298+
}
299+
300+
func testDeleteIndexIfExistsWhenIsnt() {
301+
// Prepare the mock server
302+
session.pushEmpty(code: 404)
303+
304+
// Start the test with the mocked server
305+
let expectation = XCTestExpectation(description: "Delete Movies index only if exists")
306+
307+
self.index.deleteIfExists { result in
308+
if !result {
309+
XCTAssertFalse(result)
310+
expectation.fulfill()
311+
} else {
312+
XCTFail("Deleting the index should have returned false as the index does not exist on the server")
313+
}
314+
expectation.fulfill()
315+
}
316+
317+
self.wait(for: [expectation], timeout: 10.0)
318+
}
280319
}
281320
// swiftlint:enable force_unwrapping
282321
// swiftlint:enable force_try

0 commit comments

Comments
 (0)