fix: creation and deletion

This commit is contained in:
Apoorv Mishra committed 2023-07-04 18:57:42 +05:30
1 parent cc24c2f569
commit fa33516f1a
10 files changed
+140 -228

No files matched your search

+5 -1
View File
@@ -7,6 +7,8 @@ type RequestResponse<T> = {
error: unknown;
/** Whether the request is currently in progress. */
loading: boolean;
/** Whether the request has successfully completed */
loaded: boolean;
/** Function to start the request. */
request: () => Promise<T | undefined>;
};
@@ -22,6 +24,7 @@ export default function useRequest<T = unknown>(
): RequestResponse<T> {
const [data, setData] = React.useState<T>();
const [loading, setLoading] = React.useState<boolean>(false);
const [loaded, setLoaded] = React.useState<boolean>(false);
const [error, setError] = React.useState();
const request = React.useCallback(async () => {
@@ -29,6 +32,7 @@ export default function useRequest<T = unknown>(
try {
const response = await requestFn();
setData(response);
setLoaded(true);
return response;
} catch (err) {
setError(err);
@@ -39,5 +43,5 @@ export default function useRequest<T = unknown>(
return undefined;
}, [requestFn]);
return { data, loading, error, request };
return { data, loading, loaded, error, request };
}
-2
View File
@@ -16,8 +16,6 @@ class Integration<T = unknown> extends BaseModel {
collectionId: string;
authToken?: string | null;
@Field
@observable
events: string[];
+9 -1
View File
@@ -1,5 +1,5 @@
import { filter } from "lodash";
import { computed } from "mobx";
import { action, computed } from "mobx";
import { IntegrationService } from "@shared/types";
import naturalSort from "@shared/utils/naturalSort";
import BaseStore from "~/stores/BaseStore";
@@ -22,6 +22,14 @@ class IntegrationsStore extends BaseStore<Integration> {
service: IntegrationService.Slack,
});
}
@action
async create(
params: Partial<Integration & { authToken?: string | null }>,
options?: Record<string, string | boolean | number | undefined>
) {
return super.create(params, options);
}
}
export default IntegrationsStore;
+86 -62
View File
@@ -8,21 +8,37 @@ import Integration from "~/models/Integration";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
import Input from "~/components/Input";
import LoadingIndicator from "~/components/LoadingIndicator";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
import SlackIcon from "./Icon";
import IframelyIcon from "./Icon";
import SettingRow from "./components/SettingRow";
type FormData = {
url: string;
authToken: string;
baseUrl: string;
apiKey: string;
};
function Iframely() {
const { integrations } = useStores();
const { t } = useTranslation();
const { showToast } = useToasts();
const [disconnecting, setDisconnecting] = React.useState<boolean>(false);
const { loading, loaded, request } = useRequest(() =>
integrations.fetchPage({
type: IntegrationType.Embed,
})
);
React.useEffect(() => {
if (!loaded && !loading) {
void request();
}
}, [loaded, loading, request]);
const integration = find(integrations.orderedData, {
type: IntegrationType.Embed,
@@ -36,49 +52,22 @@ function Iframely() {
formState,
} = useForm<FormData>({
mode: "all",
defaultValues: {
url: integration?.settings.url,
authToken:
integration && integration.authToken
? integration.authToken
: undefined,
},
});
React.useEffect(() => {
void integrations.fetchPage({
type: IntegrationType.Embed,
});
}, [integrations]);
React.useEffect(() => {
reset({
url: integration?.settings.url,
authToken:
integration && integration.authToken
? integration.authToken
: undefined,
});
}, [integration, reset]);
const handleSubmit = React.useCallback(
async (data: FormData) => {
try {
if (data.url) {
await integrations.save({
id: integration?.id,
if (data.baseUrl) {
await integrations.create({
type: IntegrationType.Embed,
service: IntegrationService.Iframely,
authToken: data.authToken ? data.authToken : null,
settings: data.url
authToken: data.apiKey ? data.apiKey : null,
settings: data.baseUrl
? {
url: data.url,
url: data.baseUrl,
}
: undefined,
});
} else {
await integration?.delete();
}
showToast(t("Settings saved"), {
@@ -93,35 +82,70 @@ function Iframely() {
[integrations, integration, t, showToast]
);
return (
<Scene title={t("Iframely")} icon={<SlackIcon />}>
<Heading>{t("Iframely")}</Heading>
const disconnect = React.useCallback(async () => {
setDisconnecting(true);
try {
await integration?.delete();
showToast(t("Integration disconnected"), {
type: "success",
});
reset();
} catch (err) {
showToast(err.message, {
type: "error",
});
} finally {
setDisconnecting(false);
}
}, [integration]);
<form onSubmit={formHandleSubmit(handleSubmit)}>
<SettingRow
label={t("Iframely url")}
name="iframelyUrl"
description={t("Add your Iframely url here.")}
border={false}
>
<Input
placeholder="https://iframe.ly"
pattern="https?://.*"
{...register("url")}
/>
</SettingRow>
<SettingRow
label={t("Iframely key")}
name="key"
description={t("Add your Iframely key here.")}
border={false}
>
<Input placeholder="x-xxxx-xxxx-xxxx" {...register("authToken")} />
</SettingRow>
<Button type="submit" disabled={formState.isSubmitting}>
{formState.isSubmitting ? `${t("Saving")}…` : t("Save")}
if (!loaded) {
return null;
}
return loading ? (
<LoadingIndicator />
) : (
<Scene title={t("Iframely")} icon={<IframelyIcon />}>
<Heading>{t("Iframely")}</Heading>
<Text type="secondary">
{t("Get rich previews of links in documents")}
</Text>
{!integration ? (
<form onSubmit={formHandleSubmit(handleSubmit)}>
<SettingRow
label={t("Deployment url")}
name="url"
description={t(
"Optionally add your self-hosted Iframely installation url here or leave blank to use the cloud hosted Iframely."
)}
border={false}
>
<Input
placeholder="https://iframe.ly"
pattern="https?://.*"
{...register("baseUrl")}
/>
</SettingRow>
<SettingRow
label={t("API key")}
name="key"
description={t(
"Add your Iframely API key to enable previewing of links."
)}
border={false}
>
<Input {...register("apiKey")} />
</SettingRow>
<Button type="submit" disabled={formState.isSubmitting}>
{formState.isSubmitting ? `${t("Saving")}…` : t("Save")}
</Button>
</form>
) : (
<Button onClick={disconnect} disabled={disconnecting}>
{disconnecting ? `${t("Disconnecting")}…` : t("Disconnect")}
</Button>
</form>
)}
</Scene>
);
}
+21 -28
View File
@@ -4,7 +4,7 @@ import {
IntegrationSettings,
IntegrationType,
} from "@shared/types";
import { User, Integration, IntegrationAuthentication } from "@server/models";
import { User, Integration } from "@server/models";
import { UserCreatableIntegrationService } from "@server/models/Integration";
type Props = {
@@ -30,7 +30,7 @@ export default async function integrationCreator({
events,
transaction,
}: Props) {
let integration = await Integration.create(
return Integration.create(
{
userId: user.id,
teamId: user.teamId,
@@ -39,32 +39,25 @@ export default async function integrationCreator({
collectionId,
events,
type,
authentication: token
? {
userId: user.id,
teamId: user.teamId,
service,
scopes: authScopes,
token,
}
: undefined,
},
{ transaction }
{
include: token
? [
{
association: "authentication",
},
]
: undefined,
transaction,
}
);
let authentication: IntegrationAuthentication | undefined;
if (token) {
authentication = await IntegrationAuthentication.create(
{
userId: user.id,
teamId: user.teamId,
integrationId: integration.id,
service,
scopes: authScopes,
token,
},
{ transaction }
);
integration.authenticationId = authentication.id;
await integration.save({ transaction });
}
integration = (await Integration.scope("withAuthentication").findByPk(
integration.id,
{ transaction }
)) as Integration<unknown>;
return integration;
}
@@ -1,66 +0,0 @@
"use strict";
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.addColumn(
"authentications",
"integrationId",
{
type: Sequelize.UUID,
allowNull: true,
onDelete: "cascade",
unique: true,
references: {
model: "integrations",
},
},
{ transaction }
);
const integrations = await queryInterface.sequelize.query(
`SELECT id, "authenticationId" FROM integrations where "authenticationId" is not null`,
{
type: queryInterface.sequelize.QueryTypes.SELECT,
transaction,
}
);
for (const integration of integrations) {
await queryInterface.sequelize.query(
`UPDATE authentications SET "integrationId" = :integrationId WHERE id = :authenticationId and "integrationId" is null`,
{
type: queryInterface.sequelize.QueryTypes.UPDATE,
replacements: {
integrationId: integration.id,
authenticationId: integration.authenticationId,
},
transaction,
}
);
}
await queryInterface.sequelize.query(
`DELETE from authentications WHERE "integrationId" is null`,
{
type: queryInterface.sequelize.QueryTypes.DELETE,
transaction,
}
);
await queryInterface.changeColumn(
"authentications",
"integrationId",
{
type: Sequelize.UUID,
allowNull: false,
},
{ transaction }
);
});
},
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn("authentications", "integrationId");
},
};
@@ -1,50 +0,0 @@
"use strict";
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.removeConstraint(
"integrations",
"integrations_authenticationId_fkey",
{ transaction }
);
await queryInterface.changeColumn(
"integrations",
"authenticationId",
{
type: Sequelize.UUID,
allowNull: true,
unique: true,
onDelete: "SET NULL",
references: {
model: "authentications",
},
},
{ transaction }
);
});
},
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.transaction(async (transaction) => {
await queryInterface.removeConstraint(
"integrations",
"integrations_authenticationId_fkey",
{ transaction }
);
await queryInterface.changeColumn(
"integrations",
"authenticationId",
{
type: Sequelize.UUID,
allowNull: true,
onDelete: "CASCADE",
references: {
model: "authentications",
},
},
{ transaction }
);
});
},
};
@@ -4,11 +4,8 @@ import {
ForeignKey,
BelongsTo,
Column,
Unique,
AllowNull,
} from "sequelize-typescript";
import { IntegrationService } from "@shared/types";
import Integration from "./Integration";
import Team from "./Team";
import User from "./User";
import IdModel from "./base/IdModel";
@@ -52,15 +49,6 @@ class IntegrationAuthentication extends IdModel {
@ForeignKey(() => Team)
@Column(DataType.UUID)
teamId: string;
@BelongsTo(() => Integration, "integrationId")
integration: Integration;
@ForeignKey(() => Integration)
@Unique
@AllowNull(false)
@Column(DataType.UUID)
integrationId: string;
}
export default IntegrationAuthentication;
+11 -1
View File
@@ -5,7 +5,7 @@ import integrationUpdater from "@server/commands/integrationUpdater";
import auth from "@server/middlewares/authentication";
import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate";
import { Event, Integration } from "@server/models";
import { Event, Integration, IntegrationAuthentication } from "@server/models";
import { authorize } from "@server/policies";
import { presentIntegration } from "@server/presenters";
import { APIContext } from "@server/types";
@@ -122,6 +122,16 @@ router.post(
authorize(user, "delete", integration);
await integration.destroy({ transaction });
// also remove the corresponding authentication if it exists
if (integration.authenticationId) {
await IntegrationAuthentication.destroy({
where: {
id: integration.authenticationId,
},
transaction,
});
}
await Event.create(
{
name: "integrations.delete",
+8 -5
View File
@@ -861,17 +861,20 @@
"This month": "This month",
"Last month": "Last month",
"This year": "This year",
"Integration disconnected": "Integration disconnected",
"Iframely": "Iframely",
"Iframely url": "Iframely url",
"Add your Iframely url here.": "Add your Iframely url here.",
"Iframely key": "Iframely key",
"Add your Iframely key here.": "Add your Iframely key here.",
"Get rich previews of links in documents": "Get rich previews of links in documents",
"Deployment url": "Deployment url",
"Optionally add your self-hosted Iframely installation url here or leave blank to use the cloud hosted Iframely.": "Optionally add your self-hosted Iframely installation url here or leave blank to use the cloud hosted Iframely.",
"API key": "API key",
"Add your Iframely API key to enable previewing of links.": "Add your Iframely API key to enable previewing of links.",
"Disconnecting": "Disconnecting",
"Disconnect": "Disconnect",
"Add to Slack": "Add to Slack",
"document published": "document published",
"document updated": "document updated",
"Posting to the <em>{{ channelName }}</em> channel on": "Posting to the <em>{{ channelName }}</em> channel on",
"These events should be posted to Slack": "These events should be posted to Slack",
"Disconnect": "Disconnect",
"Whoops, you need to accept the permissions in Slack to connect {{appName}} to your team. Try again?": "Whoops, you need to accept the permissions in Slack to connect {{appName}} to your team. Try again?",
"Something went wrong while authenticating your request. Please try logging in again?": "Something went wrong while authenticating your request. Please try logging in again?",
"Get rich previews of {{ appName }} links shared in Slack and use the <em>{{ command }}</em> slash command to search for documents without leaving your chat.": "Get rich previews of {{ appName }} links shared in Slack and use the <em>{{ command }}</em> slash command to search for documents without leaving your chat.",