refactor: rewrite useAppConfig with RQ

This commit is contained in:
Rıdvan Akca
2024-03-07 18:13:18 +03:00
parent bd5aedd83f
commit 63b9943203
9 changed files with 72 additions and 71 deletions

View File

@@ -1,17 +0,0 @@
import AppConfig from '../../models/app-config.js';
const getAppConfig = async (_parent, params, context) => {
context.currentUser.can('create', 'Connection');
const appConfig = await AppConfig.query()
.withGraphFetched({
appAuthClients: true,
})
.findOne({
key: params.key,
});
return appConfig;
};
export default getAppConfig;

View File

@@ -1,7 +1,6 @@
import getApp from './queries/get-app.js'; import getApp from './queries/get-app.js';
import getAppAuthClient from './queries/get-app-auth-client.ee.js'; import getAppAuthClient from './queries/get-app-auth-client.ee.js';
import getAppAuthClients from './queries/get-app-auth-clients.ee.js'; import getAppAuthClients from './queries/get-app-auth-clients.ee.js';
import getAppConfig from './queries/get-app-config.ee.js';
import getBillingAndUsage from './queries/get-billing-and-usage.ee.js'; import getBillingAndUsage from './queries/get-billing-and-usage.ee.js';
import getConfig from './queries/get-config.ee.js'; import getConfig from './queries/get-config.ee.js';
import getConnectedApps from './queries/get-connected-apps.js'; import getConnectedApps from './queries/get-connected-apps.js';
@@ -35,7 +34,6 @@ const queryResolvers = {
getApp, getApp,
getAppAuthClient, getAppAuthClient,
getAppAuthClients, getAppAuthClients,
getAppConfig,
getBillingAndUsage, getBillingAndUsage,
getConfig, getConfig,
getConnectedApps, getConnectedApps,

View File

@@ -1,6 +1,5 @@
type Query { type Query {
getApp(key: String!): App getApp(key: String!): App
getAppConfig(key: String!): AppConfig
getAppAuthClient(id: String!): AppAuthClient getAppAuthClient(id: String!): AppAuthClient
getAppAuthClients(appKey: String!, active: Boolean): [AppAuthClient] getAppAuthClients(appKey: String!, active: Boolean): [AppAuthClient]
getConnectedApps(name: String): [App] getConnectedApps(name: String): [App]

View File

@@ -14,7 +14,9 @@ function AdminApplicationCreateAuthClient(props) {
const { appKey, onClose } = props; const { appKey, onClose } = props;
const { data: auth } = useAppAuth(appKey); const { data: auth } = useAppAuth(appKey);
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const { appConfig, loading: loadingAppConfig } = useAppConfig(appKey);
const { data: appConfig, isLoading: isAppConfigLoading } =
useAppConfig(appKey);
const [ const [
createAppConfig, createAppConfig,
@@ -33,7 +35,7 @@ function AdminApplicationCreateAuthClient(props) {
}); });
const submitHandler = async (values) => { const submitHandler = async (values) => {
let appConfigId = appConfig?.id; let appConfigId = appConfig?.data?.id;
if (!appConfigId) { if (!appConfigId) {
const { data: appConfigData } = await createAppConfig({ const { data: appConfigData } = await createAppConfig({
@@ -51,6 +53,7 @@ function AdminApplicationCreateAuthClient(props) {
} }
const { name, active, ...formattedAuthDefaults } = values; const { name, active, ...formattedAuthDefaults } = values;
await createAppAuthClient({ await createAppAuthClient({
variables: { variables: {
input: { input: {
@@ -97,7 +100,7 @@ function AdminApplicationCreateAuthClient(props) {
onClose={onClose} onClose={onClose}
error={createAppConfigError || createAppAuthClientError} error={createAppConfigError || createAppAuthClientError}
title={formatMessage('createAuthClient.title')} title={formatMessage('createAuthClient.title')}
loading={loadingAppConfig} loading={isAppConfigLoading}
submitHandler={submitHandler} submitHandler={submitHandler}
authFields={auth?.data?.fields} authFields={auth?.data?.fields}
submitting={loadingCreateAppConfig || loadingCreateAppAuthClient} submitting={loadingCreateAppConfig || loadingCreateAppAuthClient}

View File

@@ -7,6 +7,7 @@ import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack'; import Stack from '@mui/material/Stack';
import LoadingButton from '@mui/lab/LoadingButton'; import LoadingButton from '@mui/lab/LoadingButton';
import { useMutation } from '@apollo/client'; import { useMutation } from '@apollo/client';
import { CREATE_APP_CONFIG } from 'graphql/mutations/create-app-config'; import { CREATE_APP_CONFIG } from 'graphql/mutations/create-app-config';
import { UPDATE_APP_CONFIG } from 'graphql/mutations/update-app-config'; import { UPDATE_APP_CONFIG } from 'graphql/mutations/update-app-config';
import Form from 'components/Form'; import Form from 'components/Form';
@@ -14,24 +15,28 @@ import { Switch } from './style';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar'; import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
function AdminApplicationSettings(props) { function AdminApplicationSettings(props) {
const { appConfig, loading } = useAppConfig(props.appKey); const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar();
const { data: appConfig, isLoading: loading } = useAppConfig(props.appKey);
const [createAppConfig, { loading: loadingCreateAppConfig }] = useMutation( const [createAppConfig, { loading: loadingCreateAppConfig }] = useMutation(
CREATE_APP_CONFIG, CREATE_APP_CONFIG,
{ {
refetchQueries: ['GetAppConfig'], refetchQueries: ['GetAppConfig'],
}, },
); );
const [updateAppConfig, { loading: loadingUpdateAppConfig }] = useMutation( const [updateAppConfig, { loading: loadingUpdateAppConfig }] = useMutation(
UPDATE_APP_CONFIG, UPDATE_APP_CONFIG,
{ {
refetchQueries: ['GetAppConfig'], refetchQueries: ['GetAppConfig'],
}, },
); );
const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar();
const handleSubmit = async (values) => { const handleSubmit = async (values) => {
try { try {
if (!appConfig) { if (!appConfig.data) {
await createAppConfig({ await createAppConfig({
variables: { variables: {
input: { key: props.appKey, ...values }, input: { key: props.appKey, ...values },
@@ -40,10 +45,11 @@ function AdminApplicationSettings(props) {
} else { } else {
await updateAppConfig({ await updateAppConfig({
variables: { variables: {
input: { id: appConfig.id, ...values }, input: { id: appConfig.data.id, ...values },
}, },
}); });
} }
enqueueSnackbar(formatMessage('adminAppsSettings.successfullySaved'), { enqueueSnackbar(formatMessage('adminAppsSettings.successfullySaved'), {
variant: 'success', variant: 'success',
SnackbarProps: { SnackbarProps: {
@@ -54,13 +60,14 @@ function AdminApplicationSettings(props) {
throw new Error('Failed while saving!'); throw new Error('Failed while saving!');
} }
}; };
const defaultValues = useMemo( const defaultValues = useMemo(
() => ({ () => ({
allowCustomConnection: appConfig?.allowCustomConnection || false, allowCustomConnection: appConfig?.data?.allowCustomConnection || false,
shared: appConfig?.shared || false, shared: appConfig?.data?.shared || false,
disabled: appConfig?.disabled || false, disabled: appConfig?.data?.disabled || false,
}), }),
[appConfig], [appConfig?.data],
); );
return ( return (
<Form <Form

View File

@@ -6,6 +6,7 @@ import Collapse from '@mui/material/Collapse';
import ListItem from '@mui/material/ListItem'; import ListItem from '@mui/material/ListItem';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import * as React from 'react'; import * as React from 'react';
import AddAppConnection from 'components/AddAppConnection'; import AddAppConnection from 'components/AddAppConnection';
import AppAuthClientsDialog from 'components/AppAuthClientsDialog/index.ee'; import AppAuthClientsDialog from 'components/AppAuthClientsDialog/index.ee';
import FlowSubstepTitle from 'components/FlowSubstepTitle'; import FlowSubstepTitle from 'components/FlowSubstepTitle';
@@ -46,18 +47,22 @@ function ChooseConnectionSubstep(props) {
const { connection, appKey } = step; const { connection, appKey } = step;
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const editorContext = React.useContext(EditorContext); const editorContext = React.useContext(EditorContext);
const { authenticate } = useAuthenticateApp({
appKey: application.key,
useShared: true,
});
const [showAddConnectionDialog, setShowAddConnectionDialog] = const [showAddConnectionDialog, setShowAddConnectionDialog] =
React.useState(false); React.useState(false);
const [showAddSharedConnectionDialog, setShowAddSharedConnectionDialog] = const [showAddSharedConnectionDialog, setShowAddSharedConnectionDialog] =
React.useState(false); React.useState(false);
const { authenticate } = useAuthenticateApp({
appKey: application.key,
useShared: true,
});
const { data, loading, refetch } = useQuery(GET_APP_CONNECTIONS, { const { data, loading, refetch } = useQuery(GET_APP_CONNECTIONS, {
variables: { key: appKey }, variables: { key: appKey },
}); });
const { appConfig } = useAppConfig(application.key);
const { data: appConfig } = useAppConfig(application.key);
// TODO: show detailed error when connection test/verification fails // TODO: show detailed error when connection test/verification fails
const [ const [
testConnection, testConnection,
@@ -67,6 +72,7 @@ function ChooseConnectionSubstep(props) {
id: connection?.id, id: connection?.id,
}, },
}); });
React.useEffect(() => { React.useEffect(() => {
if (connection?.id) { if (connection?.id) {
testConnection({ testConnection({
@@ -77,32 +83,38 @@ function ChooseConnectionSubstep(props) {
} }
// intentionally no dependencies for initial test // intentionally no dependencies for initial test
}, []); }, []);
const connectionOptions = React.useMemo(() => { const connectionOptions = React.useMemo(() => {
const appWithConnections = data?.getApp; const appWithConnections = data?.getApp;
const options = const options =
appWithConnections?.connections?.map((connection) => appWithConnections?.connections?.map((connection) =>
optionGenerator(connection), optionGenerator(connection),
) || []; ) || [];
if (!appConfig || appConfig.canCustomConnect) {
if (!appConfig?.data || appConfig?.data?.canCustomConnect) {
options.push({ options.push({
label: formatMessage('chooseConnectionSubstep.addNewConnection'), label: formatMessage('chooseConnectionSubstep.addNewConnection'),
value: ADD_CONNECTION_VALUE, value: ADD_CONNECTION_VALUE,
}); });
} }
if (appConfig?.canConnect) {
if (appConfig?.data?.canConnect) {
options.push({ options.push({
label: formatMessage('chooseConnectionSubstep.addNewSharedConnection'), label: formatMessage('chooseConnectionSubstep.addNewSharedConnection'),
value: ADD_SHARED_CONNECTION_VALUE, value: ADD_SHARED_CONNECTION_VALUE,
}); });
} }
return options; return options;
}, [data, formatMessage, appConfig]); }, [data, formatMessage, appConfig?.data]);
const handleClientClick = async (appAuthClientId) => { const handleClientClick = async (appAuthClientId) => {
try { try {
const response = await authenticate?.({ const response = await authenticate?.({
appAuthClientId, appAuthClientId,
}); });
const connectionId = response?.createConnection.id; const connectionId = response?.createConnection.id;
if (connectionId) { if (connectionId) {
await refetch(); await refetch();
onChange({ onChange({
@@ -120,11 +132,14 @@ function ChooseConnectionSubstep(props) {
setShowAddSharedConnectionDialog(false); setShowAddSharedConnectionDialog(false);
} }
}; };
const { name } = substep; const { name } = substep;
const handleAddConnectionClose = React.useCallback( const handleAddConnectionClose = React.useCallback(
async (response) => { async (response) => {
setShowAddConnectionDialog(false); setShowAddConnectionDialog(false);
const connectionId = response?.createConnection.id; const connectionId = response?.createConnection.id;
if (connectionId) { if (connectionId) {
await refetch(); await refetch();
onChange({ onChange({
@@ -146,14 +161,17 @@ function ChooseConnectionSubstep(props) {
const typedSelectedOption = selectedOption; const typedSelectedOption = selectedOption;
const option = typedSelectedOption; const option = typedSelectedOption;
const connectionId = option?.value; const connectionId = option?.value;
if (connectionId === ADD_CONNECTION_VALUE) { if (connectionId === ADD_CONNECTION_VALUE) {
setShowAddConnectionDialog(true); setShowAddConnectionDialog(true);
return; return;
} }
if (connectionId === ADD_SHARED_CONNECTION_VALUE) { if (connectionId === ADD_SHARED_CONNECTION_VALUE) {
setShowAddSharedConnectionDialog(true); setShowAddSharedConnectionDialog(true);
return; return;
} }
if (connectionId !== step.connection?.id) { if (connectionId !== step.connection?.id) {
onChange({ onChange({
step: { step: {
@@ -168,6 +186,7 @@ function ChooseConnectionSubstep(props) {
}, },
[step, onChange], [step, onChange],
); );
React.useEffect(() => { React.useEffect(() => {
if (step.connection?.id) { if (step.connection?.id) {
retestConnection({ retestConnection({
@@ -175,6 +194,7 @@ function ChooseConnectionSubstep(props) {
}); });
} }
}, [step.connection?.id, retestConnection]); }, [step.connection?.id, retestConnection]);
const onToggle = expanded ? onCollapse : onExpand; const onToggle = expanded ? onCollapse : onExpand;
return ( return (

View File

@@ -1,14 +0,0 @@
import { gql } from '@apollo/client';
export const GET_APP_CONFIG = gql`
query GetAppConfig($key: String!) {
getAppConfig(key: $key) {
id
key
allowCustomConnection
canConnect
canCustomConnect
shared
disabled
}
}
`;

View File

@@ -1,13 +1,17 @@
import { useQuery } from '@apollo/client'; import { useQuery } from '@tanstack/react-query';
import { GET_APP_CONFIG } from 'graphql/queries/get-app-config.ee'; import api from 'helpers/api';
export default function useAppConfig(key) {
const { data, loading } = useQuery(GET_APP_CONFIG, { export default function useAppConfig(appKey) {
variables: { key }, const query = useQuery({
context: { autoSnackbar: false }, queryKey: ['appConfig', appKey],
queryFn: async ({ payload, signal }) => {
const { data } = await api.get(`/v1/app-configs/${appKey}`, {
signal,
});
return data;
},
}); });
const appConfig = data?.getAppConfig;
return { return query;
appConfig,
loading,
};
} }

View File

@@ -66,13 +66,14 @@ export default function Application() {
const connectionOptions = React.useMemo(() => { const connectionOptions = React.useMemo(() => {
const shouldHaveCustomConnection = const shouldHaveCustomConnection =
appConfig?.canConnect && appConfig?.canCustomConnect; appConfig?.data?.canConnect && appConfig?.data?.canCustomConnect;
const options = [ const options = [
{ {
label: formatMessage('app.addConnection'), label: formatMessage('app.addConnection'),
key: 'addConnection', key: 'addConnection',
'data-test': 'add-connection-button', 'data-test': 'add-connection-button',
to: URLS.APP_ADD_CONNECTION(appKey, appConfig?.canConnect), to: URLS.APP_ADD_CONNECTION(appKey, appConfig?.data?.canConnect),
}, },
]; ];
@@ -86,7 +87,7 @@ export default function Application() {
} }
return options; return options;
}, [appKey, appConfig]); }, [appKey, appConfig?.data]);
if (loading) return null; if (loading) return null;
@@ -135,9 +136,9 @@ export default function Application() {
element={ element={
<SplitButton <SplitButton
disabled={ disabled={
appConfig && appConfig?.data &&
!appConfig?.canConnect && !appConfig?.data?.canConnect &&
!appConfig?.canCustomConnect !appConfig?.data?.canCustomConnect
} }
options={connectionOptions} options={connectionOptions}
/> />