Skip to content

Instantly share code, notes, and snippets.

@chmelevskij
Last active June 6, 2019 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmelevskij/10cdbba9642e5e0bfdb50914ea2b33d9 to your computer and use it in GitHub Desktop.
Save chmelevskij/10cdbba9642e5e0bfdb50914ea2b33d9 to your computer and use it in GitHub Desktop.
AWS amplify bridge
/**
* Adapter to connect amplify hub and redux. Borrowed from:
* Thanks to https://github.com/richardzcode/Journal-AWS-Amplify-Tutorial/blob/master/step-08/journal/src/store/AmplifyBridge.js
*/
import { Auth, Hub, Logger } from 'aws-amplify';
import { Store } from 'redux';
const logger = new Logger('AmplifyBridge');
type AttributeArray = Array<{ Name: string; Value: any }>;
class AmplifyBridge {
private store: Store<any>;
constructor(store) {
logger.debug('Created bridge');
this.store = store;
Hub.listen('auth', this.checkUser);
this.checkUser(null); // first check
}
// Amplify Auth methods
public checkUser = capsule => {
logger.info('on Auth event', capsule);
Auth.currentAuthenticatedUser()
.then(this.checkUserSuccess)
.catch(this.checkUserError);
};
public loadUserInfo = user => {
Auth.currentUserInfo()
.then(info => this.loadUserInfoSuccess(user, info))
.catch(error => this.loadUserInfoError(user, error));
};
public loadProfile = user => {
Auth.userAttributes(user)
.then(this.loadProfileSuccess)
.catch(this.loadProfileError);
};
// Dispatching actions
public checkUserSuccess = user => {
logger.info('check user success', user);
this.loadUserInfo(user); // Defer store.dispatch to loadUserInfo
this.loadProfile(user);
};
public checkUserError = error => {
logger.info('check user error:', error);
this.store.dispatch({ type: 'login/logout' });
};
public loadUserInfoSuccess = (user, info) => {
logger.info('load user info success', user, info);
Object.assign(user, info);
this.store.dispatch({ type: 'user/saveCurrentInfo', payload: user });
};
public loadUserInfoError = (user, error) => {
logger.info('load user info error', error);
// this.store.dispatch({ type: '' })
};
public loadProfileSuccess = data => {
logger.info('load profile success', data);
const profile = this.translateAttributes(data);
this.store.dispatch({ type: 'user/saveCurrentProfile', payload: profile });
};
public loadProfileError = error => {
logger.info('load profile error', error);
// this.store.dispatch({ type: '' })
};
public translateAttributes = (data: AttributeArray): any => {
return data.reduce((acc, attr) => {
acc[attr.Name] = attr.Value;
return acc;
}, {});
};
}
export { logger as bridgeLogger };
export default AmplifyBridge;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment