accounts-frontend/packages/app/components/dev/apps/actions.ts

88 lines
2.1 KiB
TypeScript
Raw Normal View History

2019-12-07 16:58:52 +05:30
import { Dispatch } from 'redux';
import { OauthAppResponse } from 'app/services/api/oauth';
import oauth from 'app/services/api/oauth';
import { User } from 'app/components/user';
2019-12-07 16:58:52 +05:30
import { Apps } from './reducer';
2018-05-05 12:12:21 +05:30
type SetAvailableAction = {
2019-12-07 16:58:52 +05:30
type: 'apps:setAvailable';
payload: Array<OauthAppResponse>;
};
2019-12-07 16:58:52 +05:30
type DeleteAppAction = { type: 'apps:deleteApp'; payload: string };
type AddAppAction = { type: 'apps:addApp'; payload: OauthAppResponse };
2018-05-05 12:12:21 +05:30
export type Action = SetAvailableAction | DeleteAppAction | AddAppAction;
export function setAppsList(apps: Array<OauthAppResponse>): SetAvailableAction {
return {
type: 'apps:setAvailable',
payload: apps,
};
}
export function getApp(
state: { apps: Apps },
clientId: string,
2019-12-07 16:58:52 +05:30
): OauthAppResponse | null {
return state.apps.available.find(app => app.clientId === clientId) || null;
}
export function fetchApp(clientId: string) {
return async (dispatch: Dispatch<any>): Promise<void> => {
const app = await oauth.getApp(clientId);
2018-05-05 12:12:21 +05:30
dispatch(addApp(app));
};
2018-05-05 12:12:21 +05:30
}
2018-05-05 12:12:21 +05:30
function addApp(app: OauthAppResponse): AddAppAction {
return {
type: 'apps:addApp',
payload: app,
};
}
export function fetchAvailableApps() {
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);
dispatch(setAppsList(apps));
};
}
export function deleteApp(clientId: string) {
return async (dispatch: Dispatch<any>): Promise<void> => {
await oauth.delete(clientId);
dispatch(createDeleteAppAction(clientId));
};
2018-05-05 12:12:21 +05:30
}
function createDeleteAppAction(clientId: string): DeleteAppAction {
return {
type: 'apps:deleteApp',
payload: clientId,
};
}
export function resetApp(clientId: string, resetSecret: boolean) {
return async (dispatch: Dispatch<any>): Promise<void> => {
const { data: app } = await oauth.reset(clientId, resetSecret);
if (resetSecret) {
dispatch(addApp(app));
}
};
}