Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

build: migrate to SDK-V2 #200

Merged
merged 12 commits into from
Nov 4, 2024
20 changes: 13 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"audit-fix": "HUSKY_SKIP_HOOKS=1 dev-tools npm-audit-fix --production --team-reviewers dx",
"prepare": "./scripts/install_husky.sh",
"pre-commit": "lint-staged",
"pre-push": "npm run test"
"pre-push": "npm run test",
"clean": "rm -rf dist"
},
"repository": {
"type": "git",
Expand All @@ -34,7 +35,7 @@
"dependencies": {
"@fluentui/react-northstar": "^0.50.0",
"@hapi/joi": "^17.1.1",
"@microsoft/teams-js": "^1.11.0",
"@microsoft/teams-js": "^2.19.0",
"@newrelic/pino-enricher": "^1.1.1",
"@sentry/browser": "^5.22.3",
"@sentry/node": "^5.22.3",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect } from "react";
import { useMutation } from "react-query";
import * as microsoftTeams from "@microsoft/teams-js";
import { app, pages } from "@microsoft/teams-js";

import { requester, url } from "../../../lib";
import { Resource, WebhookEventType } from "../../../constants";
Expand Down Expand Up @@ -61,13 +61,14 @@ export const useConfigurationCreate = ({

useEffect(() => {
if (isInitialized) {
microsoftTeams.getContext(({
channelId,
channelName,
tid: tenantId
}) => {
microsoftTeams.settings.getSettings(settings => {
microsoftTeams.settings.registerOnSaveHandler(async saveEvent => {
app.getContext().then(({

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing important but, should we also update to async, await style to improve readability ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since we're using it inside useEffect this version seems to provide a better readability to me. you can see the alternatives here: https://devtrium.com/posts/async-functions-useeffect

channel,
user
}: app.Context) => {
const { displayName: channelName, id: channelId } = channel ?? {};
const { tenant: { id: tenantId } = { id: undefined } } = user ?? {};
pages.getConfig().then(settings => {
pages.config.registerOnSaveHandler(async saveEvent => {
if (tenantId === undefined ||
channelId === undefined ||
channelName === undefined ||
Expand Down Expand Up @@ -99,17 +100,17 @@ export const useConfigurationCreate = ({
}
});

microsoftTeams.settings.setSettings({
await pages.config.setConfig({
entityId: configurationId,
configName: resource.name,
suggestedDisplayName: resource.name,
contentUrl: decodeURI(`${window.location.origin}${url.getHomeUrl({
id: configurationId,
resourceName: resource.name,
resourceType: resource.type,
channel: "{channelName}",
theme: "{theme}"
})}`)
} as microsoftTeams.settings.Settings);
});

saveEvent.notifySuccess();
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useQuery } from "react-query";
import { INTERNAL_SERVER_ERROR, UNAUTHORIZED } from "http-status-codes";
import * as microsoftTeams from "@microsoft/teams-js";
import { app } from "@microsoft/teams-js";

import { requester } from "../../../lib";
import { Project, Styleguide } from "../../../constants";
Expand All @@ -25,8 +25,13 @@ interface UseWorkspacesResultParams {
onStyleguidesSuccess: (styleguides: Styleguide[]) => void;
}

const getChannelId = (): Promise<string> => new Promise(resolve => {
microsoftTeams.getContext(({ channelId }) => resolve(channelId as string));
const getChannelId = (): Promise<string> => new Promise((resolve, reject) => {
app.getContext().then(({ channel }) => {
if (channel) {
resolve(channel.id);
}
reject(new Error("Channel is not defined"));
});
});

export const useResources = ({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect } from "react";
import * as microsoftTeams from "@microsoft/teams-js";
import { pages } from "@microsoft/teams-js";

import { Resource, resourceBasedEvents, WebhookEventType } from "../../../constants";

Expand All @@ -24,7 +24,7 @@ export const useValidate = (params: UseValidateParams): void => {
const valid = isValid(params);
useEffect(() => {
if (params.enabled) {
microsoftTeams.settings.setValidityState(valid);
pages.config.setValidityState(valid);
}
}, [valid, params.enabled]);
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect } from "react";
import { useMutation } from "react-query";
import * as microsoftTeams from "@microsoft/teams-js";
import { pages } from "@microsoft/teams-js";

import { requester } from "../../../lib";

Expand All @@ -14,7 +14,7 @@ export const useConfigurationDelete = ({ configurationId, isInitialized }: UseCo

useEffect(() => {
if (isInitialized) {
microsoftTeams.settings.registerOnRemoveHandler(async removeEvent => {
pages.config.registerOnRemoveHandler(async removeEvent => {
try {
await deleteConfiguration(configurationId);
removeEvent.notifySuccess();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect } from "react";
import { useMutation } from "react-query";
import * as microsoftTeams from "@microsoft/teams-js";
import { app, pages } from "@microsoft/teams-js";

import { requester, url } from "../../../lib";
import { Resource, WebhookEventType } from "../../../constants";
Expand Down Expand Up @@ -61,12 +61,13 @@ export const useConfigurationUpdate = ({

useEffect(() => {
if (isInitialized) {
microsoftTeams.getContext(({
channelId,
channelName,
tid: tenantId
app.getContext().then(({
channel,
user
}) => {
microsoftTeams.settings.registerOnSaveHandler(async saveEvent => {
const { id: channelId, displayName: channelName } = channel ?? {};
const { tenant: { id: tenantId } = { id: undefined } } = user ?? {};
pages.config.registerOnSaveHandler(async saveEvent => {
if (tenantId === undefined ||
channelId === undefined ||
channelName === undefined ||
Expand All @@ -90,17 +91,17 @@ export const useConfigurationUpdate = ({
}
});

microsoftTeams.settings.setSettings({
await pages.config.setConfig({
entityId: configurationId,
configName: resource.name,
suggestedDisplayName: resource.name,
contentUrl: decodeURI(`${window.location.origin}${url.getHomeUrl({
id: configurationId,
resourceName: resource.name,
resourceType: resource.type,
channel: "{channelName}",
theme: "{theme}"
})}`)
} as microsoftTeams.settings.Settings);
});

saveEvent.notifySuccess();
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect } from "react";
import * as microsoftTeams from "@microsoft/teams-js";
import { pages } from "@microsoft/teams-js";
import { Resource, resourceBasedEvents, WebhookEventType } from "../../../constants";

interface UseValidateParams {
Expand Down Expand Up @@ -30,7 +30,7 @@ export const useValidate = (params: UseValidateParams): void => {
const valid = isValid(params);
useEffect(() => {
if (params.enabled) {
microsoftTeams.settings.setValidityState(valid);
pages.config.setValidityState(valid);
}
}, [valid, params.enabled]);
};
50 changes: 38 additions & 12 deletions src/client/containers/LoginContainer/LoginContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import React, { FunctionComponent } from "react";
import React, { FunctionComponent, useState } from "react";

import { useInitialize } from "../../hooks";
import { useLogin } from "./hooks";
import { authentication } from "@microsoft/teams-js";
import { Login } from "./components";
import { Loader } from "@fluentui/react-northstar";
import { useRouter } from "next/router";
import { url, requester, storage } from "../../lib";

const errorToText = (error?: string): string => {
switch (error) {
case "CancelledByUser":
case "access_denied":
return "You need to authorize Microsoft Teams app to connect your Zeplin projects and styleguides.";
default:
return "Authorization failed due to an API related connectivity issue. Please retry logging in.";
}
};

export const LoginContainer: FunctionComponent = () => {
const {
query: {
Expand All @@ -20,15 +30,30 @@ export const LoginContainer: FunctionComponent = () => {
} = useRouter();

const { isInitializeLoading } = useInitialize();
const [login, { loginError }] = useLogin({
onSuccess: async (code?: string) => {
try {
const { accessToken, refreshToken } = await requester.createAuthToken(String(code));
storage.setAccessToken(accessToken);
storage.setRefreshToken(refreshToken);
} catch (err) {
// TODO: log to sentry
const [loginError, setLoginError] = useState<string | undefined>();

async function authenticate() {
try {
const code = await authentication.authenticate({
height: 476,
url: "/api/auth/authorize"
});
return code;
} catch (err) {
setLoginError(errorToText((err as unknown as Error).message));
}
}

async function login() {
try {
const code = await authenticate();
if (!code) {
throw Error("Authentication code is missing");
}
const { accessToken, refreshToken } = await requester.createAuthToken(String(code));
storage.setAccessToken(accessToken);
storage.setRefreshToken(refreshToken);

replace(id
? url.getConfigurationUpdateUrl({
channel: channel as string,
Expand All @@ -38,12 +63,13 @@ export const LoginContainer: FunctionComponent = () => {
theme: theme as string
})
: url.getConfigurationCreateUrl({

channel: channel as string,
theme: theme as string
}));
} catch (err) {
// TODO: log to sentry
}
});
}

if (isInitializeLoading) {
return <Loader styles={{ height: "100vh" }} />;
Expand Down
1 change: 0 additions & 1 deletion src/client/containers/LoginContainer/hooks/index.ts

This file was deleted.

39 changes: 0 additions & 39 deletions src/client/containers/LoginContainer/hooks/useLogin.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { FunctionComponent, useEffect } from "react";
import { useRouter } from "next/router";
import * as microsoftTeams from "@microsoft/teams-js";
import { app, authentication } from "@microsoft/teams-js";
import { Loader } from "@fluentui/react-northstar";

export const ZeplinAuthEndContainer: FunctionComponent = () => {
Expand All @@ -12,13 +12,13 @@ export const ZeplinAuthEndContainer: FunctionComponent = () => {
} = useRouter();

useEffect(() => {
microsoftTeams.initialize(() => {
app.initialize().then(() => {
if (error) {
microsoftTeams.authentication.notifyFailure(String(error));
authentication.notifyFailure(String(error));
return;
}

microsoftTeams.authentication.notifySuccess(code as string);
authentication.notifySuccess(code as string);
});
}, []);

Expand Down
6 changes: 3 additions & 3 deletions src/client/hooks/useInitialize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import * as microsoftTeams from "@microsoft/teams-js";
import { app } from "@microsoft/teams-js";

interface UseInitializeParams {
onSuccess?: () => void;
Expand All @@ -12,8 +12,8 @@ interface UseInitializeResult {
export const useInitialize = ({ onSuccess }: UseInitializeParams = {}): UseInitializeResult => {
const [isInitializeLoading, setIsInitializeLoading] = useState(true);
useEffect(() => {
microsoftTeams.initialize(() => {
microsoftTeams.appInitialization.notifySuccess();
app.initialize().then(() => {
app.notifySuccess();
setIsInitializeLoading(false);
onSuccess?.();
});
Expand Down
Loading
Loading