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

93 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

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