diff --git a/lib/src/client.dart b/lib/src/client.dart index 784698d1..932e86aa 100644 --- a/lib/src/client.dart +++ b/lib/src/client.dart @@ -24,4 +24,12 @@ abstract class MeiliSearchClient { /// Finds index by matching [uid]. If index is not exists tries to create a /// new index. Future getOrCreateIndex(String uid, {String primaryKey}); + + /// Return health of the MeiliSearch server. + /// Throws an error if containing details if MeiliSearch can't process your request. + Future> health(); + + /// Get health of the MeiliSearch server. + /// Return true or false. + Future isHealthy(); } diff --git a/lib/src/client_impl.dart b/lib/src/client_impl.dart index 85cca236..62df7c1d 100644 --- a/lib/src/client_impl.dart +++ b/lib/src/client_impl.dart @@ -62,4 +62,21 @@ class MeiliSearchClientImpl implements MeiliSearchClient { return await createIndex(uid, primaryKey: primaryKey); } } + + @override + Future> health() async { + final response = await http.getMethod>('/health'); + + return response.data; + } + + @override + Future isHealthy() async { + try { + await health(); + } on Exception catch (_) { + return false; + } + return true; + } } diff --git a/test/health_test.dart b/test/health_test.dart new file mode 100644 index 00000000..d812118f --- /dev/null +++ b/test/health_test.dart @@ -0,0 +1,31 @@ +import 'package:test/test.dart'; + +import 'utils/client.dart'; + +void main() { + group('Health', () { + setUpClient(); + + test('of the server when the url is valid', () async { + var health = await client.health(); + expect(health, {'status': 'available'}); + }); + + test('of the server when the url is valid with isHealthy', () async { + var health = await client.isHealthy(); + expect(health, true); + }); + }); + group('Health Fail', () { + setUpClientWithWrongUrl(); + + test('when the url is not valid', () async { + expect(client.health(), throwsException); + }); + + test('when the url is not valid with isHealthy', () async { + var health = await client.isHealthy(); + expect(health, false); + }); + }); +} diff --git a/test/utils/client.dart b/test/utils/client.dart index ed2d862a..04500194 100644 --- a/test/utils/client.dart +++ b/test/utils/client.dart @@ -48,6 +48,16 @@ Future setUpHttp() async { }); } +Future setUpClientWithWrongUrl() async { + setUp(() { + var server = 'http://wrongurl:1234'; + + print('Using wrong url server on $server for running tests.'); + + client = MeiliSearchClient(server, 'masterKey'); + }); +} + String randomUid([String prefix = 'index']) { return '${prefix}_${random.nextInt(9999)}'; }