Skip to content

Commit cc412f0

Browse files
committed
change request method and fix bugs
1 parent 6e7dcc4 commit cc412f0

File tree

2 files changed

+73
-40
lines changed

2 files changed

+73
-40
lines changed

src/commons/controlBar/ControlBarShareButton.tsx

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import ShareLinkState from 'src/features/playground/shareLinks/ShareLinkState';
88
import ControlButton from '../ControlButton';
99
import Constants from '../utils/Constants';
1010
import { showWarningMessage } from '../utils/notifications/NotificationsHelper';
11+
import { request } from '../utils/RequestHelper';
12+
import { RemoveLast } from '../utils/TypeHelper';
1113

1214
type ControlBarShareButtonProps = DispatchProps & StateProps;
1315

@@ -23,6 +25,7 @@ type StateProps = {
2325
key: string;
2426
isSicp?: boolean;
2527
programConfig: ShareLinkState;
28+
token: Tokens;
2629
};
2730

2831
type State = {
@@ -31,6 +34,20 @@ type State = {
3134
isSuccess: boolean;
3235
};
3336

37+
type ShareLinkRequestHelperParams = RemoveLast<Parameters<typeof request>>;
38+
39+
export type Tokens = {
40+
accessToken: string | undefined;
41+
refreshToken: string | undefined;
42+
};
43+
44+
export const requestToShareProgram = async (
45+
...[path, method, opts]: ShareLinkRequestHelperParams
46+
) => {
47+
const resp = await request(path, method, opts);
48+
return resp;
49+
};
50+
3451
export class ControlBarShareButton extends React.PureComponent<ControlBarShareButtonProps, State> {
3552
private shareInputElem: React.RefObject<HTMLInputElement>;
3653

@@ -96,7 +113,7 @@ export class ControlBarShareButton extends React.PureComponent<ControlBarShareBu
96113
label="Get Link"
97114
icon={IconNames.SHARE}
98115
// post request to backend, set keyword as return uuid
99-
onClick={this.fetchUUID}
116+
onClick={() => this.fetchUUID(this.props.token)}
100117
/>
101118
</div>
102119
) : (
@@ -159,30 +176,29 @@ export class ControlBarShareButton extends React.PureComponent<ControlBarShareBu
159176
}
160177
}
161178

162-
private fetchUUID() {
179+
private fetchUUID(tokens: Tokens) {
163180
const requestBody = {
164181
shared_program: {
165182
data: this.props.programConfig
166183
}
167184
};
168-
const fetchOpts: RequestInit = {
169-
method: 'POST',
170-
body: JSON.stringify(requestBody),
171-
headers: {
172-
'Content-Type': 'application/json'
185+
186+
const getProgramUrl = async () => {
187+
const resp = await requestToShareProgram(`shared_programs`, 'POST', {
188+
body: requestBody,
189+
...tokens
190+
});
191+
if (!resp) {
192+
return showWarningMessage('Fail to generate url!');
173193
}
194+
const respJson = await resp.json();
195+
this.setState({
196+
keyword: `${window.location.host}/playground/share/` + respJson.uuid
197+
});
198+
this.setState({ isLoading: true, isSuccess: true });
199+
return;
174200
};
175-
fetch(`${Constants.backendUrl}/api/shared_programs`, fetchOpts)
176-
.then(res => {
177-
return res.json();
178-
})
179-
.then(resp => {
180-
this.setState({
181-
// seems like there's no frontend url env variable, should be replaced by frontend server accordingly
182-
keyword: `http://localhost:8000/playground/share/` + resp.uuid
183-
});
184-
this.setState({ isLoading: true, isSuccess: true });
185-
})
186-
.catch(err => showWarningMessage('Fail to generate url! Error: ' + err));
201+
202+
getProgramUrl();
187203
}
188204
}

src/pages/playground/Playground.tsx

Lines changed: 38 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import makeHtmlDisplayTabFrom from 'src/commons/sideContent/content/SideContentH
3535
import { changeSideContentHeight } from 'src/commons/sideContent/SideContentActions';
3636
import { useSideContent } from 'src/commons/sideContent/SideContentHelper';
3737
import { useResponsive, useTypedSelector } from 'src/commons/utils/Hooks';
38+
import { showWarningMessage } from 'src/commons/utils/notifications/NotificationsHelper';
3839
import { convertParamToBoolean, convertParamToInt } from 'src/commons/utils/ParamParseHelper';
3940
import { IParsedQuery, parseQuery } from 'src/commons/utils/QueryHelper';
4041
import {
@@ -109,7 +110,10 @@ import { ControlBarEvalButton } from '../../commons/controlBar/ControlBarEvalBut
109110
import { ControlBarExecutionTime } from '../../commons/controlBar/ControlBarExecutionTime';
110111
import { ControlBarGoogleDriveButtons } from '../../commons/controlBar/ControlBarGoogleDriveButtons';
111112
import { ControlBarSessionButtons } from '../../commons/controlBar/ControlBarSessionButton';
112-
import { ControlBarShareButton } from '../../commons/controlBar/ControlBarShareButton';
113+
import {
114+
ControlBarShareButton,
115+
requestToShareProgram
116+
} from '../../commons/controlBar/ControlBarShareButton';
113117
import { ControlBarStepLimit } from '../../commons/controlBar/ControlBarStepLimit';
114118
import { ControlBarToggleFolderModeButton } from '../../commons/controlBar/ControlBarToggleFolderModeButton';
115119
import { ControlBarGitHubButtons } from '../../commons/controlBar/github/ControlBarGitHubButtons';
@@ -440,25 +444,34 @@ const Playground: React.FC<PlaygroundProps> = props => {
440444
}, [editorSessionId]);
441445

442446
const hash = isSicpEditor ? props.initialEditorValueHash : location.hash;
443-
const { uuid } = useParams<string>();
447+
const { uuid } = useParams<{ uuid: string }>();
448+
const config = useUrlEncoder();
449+
const tokens = useTypedSelector((state: OverallState) => ({
450+
accessToken: state.session.accessToken,
451+
refreshToken: state.session.refreshToken
452+
}));
444453

445454
const handleURL = useCallback(
446-
(uuid: string | undefined) => {
455+
async (uuid: string | undefined) => {
447456
if (uuid !== undefined) {
448-
fetch(`${Constants.backendUrl}/api/shared_programs/${uuid}`)
449-
.then(response => response.json())
450-
.then(resp => {
451-
const res: ShareLinkState = new ShareLinkStateDecoder(resp).decodeWith(
452-
new JsonDecoderDelegate()
453-
);
454-
resetConfig(
455-
res,
456-
{ handleChangeExecTime, handleChapterSelect },
457-
workspaceLocation,
458-
dispatch,
459-
fileSystem
460-
);
461-
});
457+
const resp = await requestToShareProgram(`shared_programs/${uuid}`, 'GET', {
458+
...tokens
459+
});
460+
if (!resp) {
461+
return showWarningMessage('Invalid share program link! ');
462+
}
463+
const respJson = await resp.json();
464+
const res: ShareLinkState = new ShareLinkStateDecoder(respJson).decodeWith(
465+
new JsonDecoderDelegate()
466+
);
467+
resetConfig(
468+
res,
469+
{ handleChangeExecTime, handleChapterSelect },
470+
workspaceLocation,
471+
dispatch,
472+
fileSystem
473+
);
474+
return;
462475
} else {
463476
const config = new ShareLinkStateDecoder(location.hash).decodeWith(
464477
new UrlParamsDecoderDelegate()
@@ -470,15 +483,20 @@ const Playground: React.FC<PlaygroundProps> = props => {
470483
dispatch,
471484
fileSystem
472485
);
486+
return;
473487
}
474488
},
489+
// disabled eslint here since tokens are checked separately, checking single object cause infinite rerender.
490+
// eslint-disable-next-line
475491
[
476492
dispatch,
477493
fileSystem,
478494
handleChangeExecTime,
479495
handleChapterSelect,
480496
location.hash,
481-
workspaceLocation
497+
workspaceLocation,
498+
tokens.accessToken,
499+
tokens.refreshToken
482500
]
483501
);
484502

@@ -819,8 +837,6 @@ const Playground: React.FC<PlaygroundProps> = props => {
819837
]
820838
);
821839

822-
const config = useUrlEncoder();
823-
824840
const shareButton = useMemo(() => {
825841
const qs = isSicpEditor ? Links.playground + '#' + props.initialEditorValueHash : queryString;
826842
return (
@@ -830,12 +846,13 @@ const Playground: React.FC<PlaygroundProps> = props => {
830846
handleUpdateShortURL={s => dispatch(updateShortURL(s))}
831847
queryString={qs}
832848
programConfig={config}
849+
token={tokens}
833850
shortURL={shortURL}
834851
isSicp={isSicpEditor}
835852
key="share"
836853
/>
837854
);
838-
}, [dispatch, isSicpEditor, props.initialEditorValueHash, queryString, shortURL, config]);
855+
}, [dispatch, isSicpEditor, props.initialEditorValueHash, queryString, shortURL, config, tokens]);
839856

840857
const toggleFolderModeButton = useMemo(() => {
841858
return (

0 commit comments

Comments
 (0)