Skip to content

Commit

Permalink
if status = 401 then we'll try to renew the token
Browse files Browse the repository at this point in the history
  • Loading branch information
jibon57 committed Oct 15, 2024
1 parent f01f19d commit 42a8339
Show file tree
Hide file tree
Showing 12 changed files with 200 additions and 81 deletions.
78 changes: 39 additions & 39 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,45 @@ const tsEslint = require('typescript-eslint');
const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');

module.exports = tsEslint.config(
{ ignores: ['dist'] },
{
extends: [
js.configs.recommended,
...tsEslint.configs.recommended,
eslintPluginPrettierRecommended,
],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parser: tsEslint.parser,
parserOptions: {
projectService: true,
tsconfigRootDir: __dirname,
},
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'@typescript-eslint/no-explicit-any': 'off',
'react-refresh/only-export-components': 'warn',
'prettier/prettier': [
'error',
{
'singleQuote': true,
'semi': true,
'tabWidth': 2,
'bracketSpacing': true,
'trailingComma': 'all',
'arrowParens': 'always',
'endOfLine': 'auto',
{ignores: ['dist']},
{
extends: [
js.configs.recommended,
...tsEslint.configs.recommended,
eslintPluginPrettierRecommended,
],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parser: tsEslint.parser,
parserOptions: {
projectService: true,
tsconfigRootDir: __dirname,
},
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'@typescript-eslint/no-explicit-any': 'off',
'react-refresh/only-export-components': 'warn',
'prettier/prettier': [
'error',
{
'singleQuote': true,
'semi': true,
'tabWidth': 2,
'bracketSpacing': true,
'trailingComma': 'all',
'arrowParens': 'always',
'endOfLine': 'auto',
},
],
},
],
},
},
);
3 changes: 1 addition & 2 deletions src/components/app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ const App = () => {
) {
setLoading(true);
} else if (roomConnectionStatus === 're-connecting') {
//eslint-disable-next-line
// @ts-ignore
// @ts-expect-error this won't be an error
toastId.current = toast.loading(
t('notifications.room-disconnected-reconnecting'),
{
Expand Down
5 changes: 2 additions & 3 deletions src/components/breakout-room/form/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,9 @@ const FromElems = () => {
setUsers(tmp);
}, [participants, users]);

// if room number decrease then we'll reset otherwise user will be missing
// if room number decreases then we'll reset otherwise user will be missing
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// @ts-expect-error has default value
if (totalRooms === preTotalRooms || totalRooms > preTotalRooms) {
return;
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/external-media-player/video-js/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore

// @ts-expect-error won't be a problem
import { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js';
import { DataMsgBodyType } from 'plugnmeet-protocol-js';

Expand Down
4 changes: 2 additions & 2 deletions src/components/external-media-player/video-js/player.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore

// @ts-expect-error won't be a problem
import videojs, { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js';
import 'video.js/dist/video-js.css';

Expand Down
58 changes: 47 additions & 11 deletions src/helpers/api/plugNmeetAPI.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import axios, { ResponseType } from 'axios';
import { CommonResponseSchema } from 'plugnmeet-protocol-js';
import axios, { AxiosError, ResponseType } from 'axios';
import {
CommonResponseSchema,
NatsMsgClientToServerEvents,
NatsMsgClientToServerSchema,
} from 'plugnmeet-protocol-js';
import { create, toBinary } from '@bufbuild/protobuf';

import { getAccessToken } from '../utils';
import { store } from '../../store';
import { getNatsConn } from '../nats';

const API = axios.create({
baseURL: (window as any).PLUG_N_MEET_SERVER_URL + '/api',
Expand All @@ -19,6 +24,21 @@ const getToken = () => {
return getAccessToken();
};

export const requestToRenewPnmToken = async () => {
const token = getToken();
if (token) {
const conn = getNatsConn();
if (conn) {
await conn.sendMessageToSystemWorker(
create(NatsMsgClientToServerSchema, {
event: NatsMsgClientToServerEvents.REQ_RENEW_PNM_TOKEN,
msg: token,
}),
);
}
}
};

const sendAPIRequest = async (
path: string,
body: any,
Expand All @@ -39,18 +59,34 @@ const sendAPIRequest = async (
});
return res.data;
} catch (e: any) {
console.error(e.message);
const err = e as AxiosError;
console.error(err.message);

// if status = 401 then we'll try to renew token
// so that next try will not be failing because of the expired token
if (err.status === 401) {
console.info(`Got status: ${err.status}, trying to renew token.`);
requestToRenewPnmToken().then();
}
const output = {
status: false,
msg: err.code + ': ' + err.message,
};

// @ts-expect-error we'll check if the value is undefined
if (typeof err.response?.data?.msg !== 'undefined') {
// @ts-expect-error we checked if the value is undefined
output.msg = err.response?.data?.msg.replace(
'go-jose/go-jose/jwt',
err.response.statusText,
);
}

if (!json_encode) {
const res = create(CommonResponseSchema, {
status: false,
msg: e.code + ': ' + e.message,
});
const res = create(CommonResponseSchema, output);
return toBinary(CommonResponseSchema, res);
} else {
return {
status: false,
msg: e.code + ': ' + e.message,
};
return output;
}
}
};
Expand Down
7 changes: 3 additions & 4 deletions src/helpers/hooks/useResumableFilesUpload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ const useResumableFilesUpload = ({
type: 'error',
});
},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore

// @ts-expect-error actually value exist
maxFileSize: maxFileSize ? Number(maxFileSize) * 1000000 : undefined,
maxFileSizeErrorCallback() {
toast(t('notifications.max-file-size-exceeds'), {
Expand Down Expand Up @@ -128,8 +128,7 @@ const useResumableFilesUpload = ({
});

r.on('uploadStart', function () {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// @ts-expect-error this value exists
toastId.current = toast(
t('right-panel.uploading-file', {
fileName,
Expand Down
15 changes: 5 additions & 10 deletions src/helpers/nats/ConnectNats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,7 @@ export default class ConnectNats {
const consumer = await this._js.consumers.get(this._roomId, consumerName);
const sub = await consumer.consume();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// @ts-expect-error not a error
for await (const m of sub) {
try {
const payload = fromBinary(NatsMsgServerToClientSchema, m.data);
Expand All @@ -429,8 +428,7 @@ export default class ConnectNats {
const consumer = await this._js.consumers.get(this._roomId, consumerName);
const sub = await consumer.consume();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// @ts-expect-error not a error
for await (const m of sub) {
try {
const payload = fromBinary(NatsMsgServerToClientSchema, m.data);
Expand All @@ -457,8 +455,7 @@ export default class ConnectNats {
const consumer = await this._js.consumers.get(this._roomId, consumerName);
const sub = await consumer.consume();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// @ts-expect-error not a error
for await (const m of sub) {
try {
const payload = fromBinary(ChatMessageSchema, m.data);
Expand Down Expand Up @@ -497,8 +494,7 @@ export default class ConnectNats {
}
};

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// @ts-expect-error not a error
for await (const m of sub) {
try {
await processData(m);
Expand Down Expand Up @@ -534,8 +530,7 @@ export default class ConnectNats {
await this.handleDataMsg.handleMessage(payload);
};

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// @ts-expect-error not a error
for await (const m of sub) {
try {
await processData(m);
Expand Down
4 changes: 2 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import App from './components/app';
import Loading from './components/extra-pages/Loading';

const container = document.getElementById('plugNmeet-app');
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore

// @ts-expect-error not a error
const root = createRoot(container);
root.render(
<React.StrictMode>
Expand Down
39 changes: 36 additions & 3 deletions src/store/services/breakoutRoomApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@ import {
} from 'plugnmeet-protocol-js';
import { fromBinary, toBinary, toJson } from '@bufbuild/protobuf';

import { requestToRenewPnmToken } from '../../helpers/api/plugNmeetAPI';

export const breakoutRoomApi = createApi({
reducerPath: 'breakoutRoomApi',
baseQuery: fetchBaseQuery({
baseUrl: (window as any).PLUG_N_MEET_SERVER_URL + '/api/breakoutRoom',
prepareHeaders: (headers, api) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// @ts-expect-error not a error
const token = api.getState().session.token;
headers.append('Authorization', token);
headers.append('Content-Type', 'application/protobuf');
return headers;
},
}),
Expand All @@ -42,6 +42,17 @@ export const breakoutRoomApi = createApi({
},
};
},
transformErrorResponse: (response) => {
if (
// @ts-expect-error this value exists
typeof response.originalStatus !== 'undefined' &&
// @ts-expect-error this value exists
response.originalStatus === 401
) {
console.info(`Got status: 401, trying to renew token.`);
requestToRenewPnmToken().then();
}
},
providesTags: ['List'],
}),
createBreakoutRooms: builder.mutation<
Expand All @@ -60,6 +71,17 @@ export const breakoutRoomApi = createApi({
},
};
},
transformErrorResponse: (response) => {
if (
// @ts-expect-error this value exists
typeof response.originalStatus !== 'undefined' &&
// @ts-expect-error this value exists
response.originalStatus === 401
) {
console.info(`Got status: 401, trying to renew token.`);
requestToRenewPnmToken().then();
}
},
invalidatesTags: ['List'],
}),
increaseDuration: builder.mutation<
Expand Down Expand Up @@ -122,6 +144,17 @@ export const breakoutRoomApi = createApi({
},
};
},
transformErrorResponse: (response) => {
if (
// @ts-expect-error this value exists
typeof response.originalStatus !== 'undefined' &&
// @ts-expect-error this value exists
response.originalStatus === 401
) {
console.info(`Got status: 401, trying to renew token.`);
requestToRenewPnmToken().then();
}
},
providesTags: ['My_Rooms'],
}),
endSingleRoom: builder.mutation<BreakoutRoomRes, EndBreakoutRoomReq>({
Expand Down
Loading

0 comments on commit 42a8339

Please sign in to comment.