accounts-frontend/src/components/dev/apps/actions.js

78 lines
2.1 KiB
JavaScript
Raw Normal View History

// @flow
import type { Dispatch } from 'redux';
import type { OauthAppResponse } from 'services/api/oauth';
import type { User } from 'components/user';
2018-05-05 12:12:21 +05:30
import oauth from 'services/api/oauth';
2018-05-05 12:12:21 +05:30
import type { Apps } from './reducer';
type SetAvailableAction = { type: 'apps:setAvailable', payload: Array<OauthAppResponse> };
type DeleteAppAction = { type: 'apps:deleteApp', payload: string };
type AddAppAction = { type: 'apps:addApp', payload: OauthAppResponse };
export type Action = SetAvailableAction | DeleteAppAction | AddAppAction;
export function setAppsList(apps: Array<OauthAppResponse>): SetAvailableAction {
return {
2018-05-05 12:12:21 +05:30
type: 'apps:setAvailable',
payload: apps,
};
}
export function getApp(state: {apps: Apps}, clientId: string): ?OauthAppResponse {
return state.apps.available.find((app) => app.clientId === clientId) || null;
}
export function fetchApp(clientId: string) {
2018-05-05 12:12:21 +05:30
return async (dispatch: Dispatch<any>): Promise<void> => {
const app = await oauth.getApp(clientId);
dispatch(addApp(app));
};
}
2018-05-05 12:12:21 +05:30
function addApp(app: OauthAppResponse): AddAppAction {
return {
type: 'apps:addApp',
payload: app
};
}
export function fetchAvailableApps() {
2018-05-05 12:12:21 +05:30
return async (dispatch: Dispatch<any>, getState: () => {user: User}): Promise<void> => {
const { id } = getState().user;
if (!id) {
dispatch(setAppsList([]));
return;
}
const apps = await oauth.getAppsByUser(id);
2018-05-05 12:12:21 +05:30
dispatch(setAppsList(apps));
};
}
export function deleteApp(clientId: string) {
2018-05-05 12:12:21 +05:30
return async (dispatch: Dispatch<any>): Promise<void> => {
await oauth.delete(clientId);
2018-05-05 12:12:21 +05:30
dispatch(createDeleteAppAction(clientId));
};
}
function createDeleteAppAction(clientId: string): DeleteAppAction {
return {
type: 'apps:deleteApp',
payload: clientId
};
}
export function resetApp(clientId: string, resetSecret: bool) {
2018-05-05 12:12:21 +05:30
return async (dispatch: Dispatch<any>): Promise<void> => {
const { data: app } = await oauth.reset(clientId, resetSecret);
2018-05-05 12:12:21 +05:30
if (resetSecret) {
dispatch(addApp(app));
}
};
}