Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sschottler/1c8139ae43c1b7a58550523030816c43 to your computer and use it in GitHub Desktop.
Save sschottler/1c8139ae43c1b7a58550523030816c43 to your computer and use it in GitHub Desktop.
import { NativeModules, Platform } from 'react-native';
import { Consumer } from '../models';
// declare a type for the native module explicitly and assign to that variable:
const AuthenticationServiceNativeModule: AuthenticationServiceNativeModule =
NativeModules.AuthenticationService;
// all common methods that have same signature between IOS/Android:
interface AuthenticationServiceNativeModule {
initialize(awsdkBundleId: string, awsdkUrl: string, awsdkKey: string): Promise<string>;
authenticateConsumer(userName: string, password: string): Promise<Consumer>;
}
// if we have android-specific calls, we extend interface and cast later:
interface AndroidAuthenticationService extends AuthenticationServiceNativeModule {
androidOnlyCall(): Promise<string>;
}
// if we have ios-specific calls, we extend interface and cast later:
// TypeScript Rule complains if you start interface with "I"
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
interface IOSAuthenticationService extends AuthenticationServiceNativeModule {
iosOnlyCall(): Promise<string>;
}
export interface AuthenticationService extends AuthenticationServiceNativeModule {
platformAgnosticMethod(): Promise<string>;
}
// re-export strongly-typed interface with conditional platform logic encapsulated:
export const AuthenticationService: AuthenticationService = {
// spread native module methods at top level:
...AuthenticationServiceNativeModule,
// encapsulate conditional platform logic here so callers don't have to know this:
platformAgnosticMethod() {
if (Platform.OS === 'ios') {
// cast to the android service interface and make call:
return (AuthenticationServiceNativeModule as IOSAuthenticationService).iosOnlyCall();
} else {
// cast to the ios service interface and make call:
return (AuthenticationServiceNativeModule as AndroidAuthenticationService).androidOnlyCall();
}
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment