connect method
Implementation
Future<void> connect({
required String api,
required String anonToken,
required List<String> authAttrs,
required String appId,
bool? debug,
String? cacheKey,
}) async {
_config = NawahConfig(
api: api,
anonToken: anonToken,
authAttrs: authAttrs,
appId: appId,
debug: debug ?? false,
cacheKey: cacheKey ?? 'NAWAH',
);
// Confirm api points to Nawah application
http.Response? response = null;
try {
response = await http.get(Uri.parse(api));
} catch (err) {
NawahDI.get<INawahLogger>()?.error(
this,
'Connecting to Nawah App failed with following condition: $err',
);
throw ConnectionException();
}
final isSuccessResponse = response.statusCode == 200;
bool isNawahApp = true;
try {
final res = jsonDecode(response.body);
isNawahApp = res['args']?['powered_by'] == 'Nawah';
} on FormatException catch (_) {
isNawahApp = false;
} on TypeError catch (_) {
isNawahApp = false;
}
if (!isSuccessResponse || !isNawahApp) {
NawahDI.get<INawahLogger>()?.error(
this,
'Connecting to Nawah App failed with following condition:',
);
NawahDI.get<INawahLogger>()?.error(
this,
'isSuccessResponse: $isSuccessResponse',
);
NawahDI.get<INawahLogger>()?.error(
this,
'isNawahApp: $isNawahApp',
);
NawahDI.get<INawahLogger>()?.error(
this,
'Response statusCode, body: ${response.statusCode}, ${response.body}',
);
throw ConnectionException();
}
_onConnStateChange(ConnState.connected);
this.addEventListener(NawahListenerKey.message, (res) => res['args']['session'] != null, (_, res) {
NawahDI.get<INawahLogger>()?.log(this, 'Response has session object');
if (res['args']['session']['_id'] == 'f00000000000000000000012') {
if (this.authState == AuthState.authed) {
session = null;
this._onAuthStateChange(AuthState.notAuthed);
}
clearCacheSession();
NawahDI.get<INawahLogger>()?.log(this, 'Session is null');
} else {
setCacheSession(res['args']['session']);
session = res['args']['session'];
_onAuthStateChange(AuthState.authed);
NawahDI.get<INawahLogger>()?.log(this, 'Session updated');
}
});
}