From cd9c2f76f1ee2ddcc97a50f8c13b7d6af1035f8c Mon Sep 17 00:00:00 2001 From: Ganesan Chandran Date: Sun, 25 Aug 2024 12:06:41 +0530 Subject: [PATCH] feat: encrypted environment and bulk export (#28) --- .editorconfig | 28 + .eslintrc.json | 2 +- .github/ISSUE_TEMPLATE/bug_report.md | 7 +- .github/PULL_REQUEST_TEMPLATE.md | 2 +- .github/workflows/package.yaml | 27 + .github/workflows/publish.yaml | 27 + .npmrc | 2 + CHANGELOG.md | 26 +- LICENSE | 2 +- README.md | 8 +- dictionary.txt | 1 + package-lock.json | 32 +- package.json | 122 +- src/extension.ts | 193 +- src/fetch-client-ui/App.css | 82 +- src/fetch-client-ui/App.test.tsx | 8 +- src/fetch-client-ui/App.tsx | 101 +- .../components/Collection/AddTo/addTo.tsx | 454 ++-- .../AttachVariable/attachVariable.tsx | 232 +- .../Collection/BulkExport/bulkExport.tsx | 172 ++ .../Collection/BulkExport/style.css | 75 + .../components/Collection/CopyTo/copyTo.tsx | 282 +- .../components/Collection/RunAll/helper.ts | 176 +- .../components/Collection/RunAll/runAll.tsx | 1433 +++++----- .../Collection/RunAll/runAllSettings.tsx | 104 +- .../Settings/CollectionSettings.tsx | 274 +- .../components/Collection/consts.ts | 4 +- .../components/Collection/helper.ts | 44 +- .../components/Collection/style.css | 545 ++-- .../Common/Autocomplete/Autocomplete.tsx | 258 +- .../components/Common/Autocomplete/style.css | 34 +- .../components/Common/CodeGenerator/consts.ts | 126 +- .../components/Common/CodeGenerator/index.tsx | 405 +-- .../components/Common/CodeGenerator/style.css | 32 +- .../components/Common/Consts/sysVariables.ts | 150 +- .../Common/Editor/EditorProvider.tsx | 227 +- .../components/Common/Editor/index.tsx | 52 +- .../components/Common/Editor/style.css | 46 +- .../components/Common/Modal/index.tsx | 15 + .../components/Common/Modal/style.css | 65 + .../components/Common/NotesEditor/index.tsx | 82 +- .../components/Common/NotesEditor/style.css | 42 +- .../components/Common/Table/ResponseTable.tsx | 94 +- .../components/Common/Table/Table.tsx | 462 ++-- .../components/Common/Table/style.css | 88 +- .../components/Common/Table/types.ts | 134 +- .../Common/TextEditor/TextEditor.tsx | 478 ++-- .../components/Common/TextEditor/style.css | 22 +- .../Common/TypesGenerator/consts.ts | 26 +- .../Common/TypesGenerator/index.tsx | 154 +- .../components/Common/Viewer/HTMLViewer.tsx | 12 +- .../components/Common/Viewer/JSONViewer.tsx | 56 +- .../components/Common/Viewer/XMLViewer.tsx | 78 +- .../components/Common/Viewer/style.css | 30 +- .../components/Common/Viewer/types.ts | 6 +- .../components/Common/helper.ts | 78 +- .../components/Common/icons.tsx | 28 +- .../components/Common/vscodeAPI.ts | 4 +- .../components/Cookies/index.tsx | 251 +- .../components/Cookies/redux/actions.ts | 12 +- .../components/Cookies/redux/index.ts | 4 +- .../components/Cookies/redux/reducer.ts | 40 +- .../components/Cookies/redux/types.ts | 26 +- .../components/Cookies/style.css | 33 +- src/fetch-client-ui/components/Curl/helper.ts | 44 +- src/fetch-client-ui/components/Curl/index.tsx | 522 ++-- src/fetch-client-ui/components/Curl/style.css | 82 +- .../components/ErrorLog/ErrorLog.tsx | 35 +- .../components/ErrorLog/style.css | 30 +- .../components/MainUI/index.tsx | 832 +++--- .../components/MainUI/redux/actions.ts | 64 +- .../components/MainUI/redux/index.ts | 4 +- .../components/MainUI/redux/reducer.ts | 90 +- .../components/MainUI/redux/types.ts | 54 +- .../components/MainUI/style.css | 154 +- .../OptionsPanel/OptionTab/index.tsx | 74 +- .../OptionsPanel/Options/Auth/OAuth/index.tsx | 572 ++-- .../OptionsPanel/Options/Auth/OAuth/style.css | 56 +- .../OptionsPanel/Options/Auth/aws/index.tsx | 198 +- .../OptionsPanel/Options/Auth/aws/style.css | 30 +- .../OptionsPanel/Options/Auth/consts.ts | 42 +- .../OptionsPanel/Options/Auth/index.tsx | 862 +++--- .../OptionsPanel/Options/Auth/style.css | 178 +- .../Options/Body/Binary/consts.ts | 152 +- .../Options/Body/Binary/index.tsx | 250 +- .../Options/Body/Binary/style.css | 92 +- .../Options/Body/FormData/index.tsx | 234 +- .../Options/Body/GraphQL/index.tsx | 92 +- .../Options/Body/GraphQL/style.css | 38 +- .../OptionsPanel/Options/Body/None/index.tsx | 14 +- .../OptionsPanel/Options/Body/None/style.css | 10 +- .../OptionsPanel/Options/Body/Raw/Raw.tsx | 36 +- .../OptionsPanel/Options/Body/Raw/style.css | 8 +- .../Options/Body/UrlEncoded/index.tsx | 148 +- .../OptionsPanel/Options/Body/consts.ts | 20 +- .../OptionsPanel/Options/Body/index.tsx | 154 +- .../OptionsPanel/Options/Body/style.css | 84 +- .../OptionsPanel/Options/GraphQL/index.tsx | 92 +- .../OptionsPanel/Options/GraphQL/style.css | 38 +- .../OptionsPanel/Options/Headers/index.tsx | 196 +- .../Options/Headers/parentHeaders.tsx | 10 +- .../Options/Headers/requestHeaders.tsx | 44 +- .../OptionsPanel/Options/PostFetch/index.tsx | 42 +- .../OptionsPanel/Options/PreFetch/consts.ts | 70 +- .../OptionsPanel/Options/PreFetch/index.tsx | 142 +- .../Options/PreFetch/preRequest.tsx | 450 +-- .../OptionsPanel/Options/PreFetch/style.css | 76 +- .../Options/QueryParams/index.tsx | 118 +- .../OptionsPanel/Options/Settings/index.tsx | 237 +- .../OptionsPanel/Options/Settings/style.css | 52 +- .../RequestUI/OptionsPanel/Options/helper.ts | 4 +- .../RequestUI/OptionsPanel/consts.ts | 16 +- .../RequestUI/OptionsPanel/index.tsx | 64 +- .../RequestUI/OptionsPanel/style.css | 66 +- .../RequestUI/RequestPanel/common.ts | 22 +- .../RequestUI/RequestPanel/consts.ts | 16 +- .../RequestUI/RequestPanel/index.tsx | 417 ++- .../RequestUI/RequestPanel/style.css | 116 +- .../components/RequestUI/redux/actions.ts | 388 +-- .../components/RequestUI/redux/colReducer.ts | 78 +- .../components/RequestUI/redux/index.ts | 6 +- .../components/RequestUI/redux/reducer.ts | 778 +++--- .../RequestUI/redux/reqSettingsReducer.ts | 46 +- .../components/RequestUI/redux/types.ts | 416 +-- .../OptionsPanel/OptionTab/index.tsx | 386 ++- .../OptionsPanel/OptionTab/style.css | 64 +- .../ResponseUI/OptionsPanel/OptionTab/util.ts | 42 +- .../OptionsPanel/Options/Cookies/index.tsx | 50 +- .../OptionsPanel/Options/Cookies/style.css | 6 + .../OptionsPanel/Options/Headers/index.tsx | 40 +- .../OptionsPanel/Options/Headers/style.css | 8 +- .../OptionsPanel/Options/Response/consts.ts | 10 +- .../OptionsPanel/Options/Response/index.tsx | 431 ++- .../OptionsPanel/Options/Response/style.css | 260 +- .../ResponseUI/ResponsePanel/consts.ts | 16 +- .../ResponseUI/ResponsePanel/index.tsx | 89 +- .../ResponseUI/ResponsePanel/style.css | 38 +- .../components/ResponseUI/redux/actions.ts | 70 +- .../components/ResponseUI/redux/index.ts | 5 +- .../components/ResponseUI/redux/reducer.ts | 120 +- .../components/ResponseUI/redux/types.ts | 78 +- .../components/SideBar/Collection/index.tsx | 1218 +++++---- .../components/SideBar/Collection/style.css | 140 +- .../components/SideBar/History/index.tsx | 404 +-- .../components/SideBar/History/style.css | 26 +- .../components/SideBar/Variables/index.tsx | 365 +-- .../components/SideBar/Variables/style.css | 6 +- .../components/SideBar/index.tsx | 611 +++-- .../components/SideBar/redux/actions.ts | 328 +-- .../components/SideBar/redux/index.ts | 4 +- .../components/SideBar/redux/reducer.ts | 592 ++-- .../components/SideBar/redux/types.ts | 298 +- .../components/SideBar/style.css | 314 +-- .../components/SideBar/util.ts | 104 +- .../components/TestUI/TestPanel/consts.ts | 224 +- .../components/TestUI/TestPanel/helper.ts | 508 ++-- .../components/TestUI/TestPanel/index.tsx | 374 +-- .../components/TestUI/TestPanel/style.css | 44 +- .../components/TestUI/TestResult/index.tsx | 176 +- .../components/TestUI/TestResult/style.css | 110 +- .../components/Variables/index.tsx | 364 +-- .../components/Variables/redux/actions.ts | 48 +- .../components/Variables/redux/index.ts | 4 +- .../components/Variables/redux/reducer.ts | 100 +- .../components/Variables/redux/types.ts | 42 +- .../components/Variables/resToVar.tsx | 318 +-- .../components/Variables/style.css | 124 +- src/fetch-client-ui/index.css | 82 +- src/fetch-client-ui/index.tsx | 14 +- src/fetch-client-ui/reducer/combineReducer.ts | 40 +- src/fetch-client-ui/reportWebVitals.ts | 18 +- src/fetch-client-ui/store/appStore.ts | 2 +- .../store/stateAndRouterProvider.tsx | 12 +- src/fetch-client-ui/store/types.ts | 4 +- src/utils/LocalStorageService.ts | 22 +- src/utils/PreFetchRunner.ts | 216 +- src/utils/PubSub.ts | 100 +- src/utils/configuration.ts | 338 +-- src/utils/crypto/fc-crypto.ts | 53 + src/utils/crypto/index.ts | 6 + src/utils/crypto/types.ts | 12 + src/utils/curlToRequest.ts | 586 ++-- src/utils/db/collectionDBUtil.ts | 1886 ++++++------- src/utils/db/constants.ts | 12 +- src/utils/db/cookieDBUtil.ts | 163 +- src/utils/db/dbPaths.ts | 10 +- src/utils/db/dbUtil.ts | 296 +- src/utils/db/getExtDbPath.ts | 22 +- src/utils/db/historyDBUtil.ts | 224 +- src/utils/db/mainDBUtil.ts | 797 +++--- src/utils/db/transferDBConfig.ts | 86 +- src/utils/db/varDBUtil.ts | 847 +++--- src/utils/fetchUtil.ts | 630 ++--- src/utils/helper.ts | 528 ++-- .../fetchClient/fetchClientImporter_1_0.ts | 150 +- .../importers/postman/postmanImporter_2_1.ts | 906 ++++--- .../importers/postman/postman_2_1.types.ts | 880 +++--- .../postman/postman_2_1.variable_types.ts | 18 +- .../thunderClientImporter_1_2.ts | 780 +++--- .../thunderClient_1_2.variable_types.ts | 18 +- .../thunderClient/thunderClient_1_2_types.ts | 140 +- src/utils/logger/constants.ts | 2 +- src/utils/logger/logger.ts | 24 +- src/utils/logger/requestLog.ts | 96 +- src/utils/logger/vsCodeLogger.ts | 110 +- src/utils/ui/addToCollectionUIProvider.tsx | 232 +- src/utils/ui/bulkExportUIProvider.tsx | 66 + src/utils/ui/cookieUIProvider.tsx | 107 +- src/utils/ui/curlUIProvider.tsx | 144 +- src/utils/ui/errorLogUIProvider.tsx | 110 +- src/utils/ui/helper.ts | 155 +- src/utils/ui/mainUIProvider.tsx | 622 ++--- src/utils/ui/sideBarUIProvider.tsx | 616 ++--- src/utils/ui/variableUIProvider.tsx | 105 +- .../fetchClientCollectionValidator.ts | 2412 ++++++++--------- .../fetchClientVariableValidator.ts | 214 +- src/utils/vscodeConfig.ts | 126 +- tsconfig.json | 15 +- vsc-extension-quickstart.md | 4 +- webpack.config.js | 238 +- 220 files changed, 21145 insertions(+), 20080 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/workflows/package.yaml create mode 100644 .github/workflows/publish.yaml create mode 100644 .npmrc create mode 100644 src/fetch-client-ui/components/Collection/BulkExport/bulkExport.tsx create mode 100644 src/fetch-client-ui/components/Collection/BulkExport/style.css create mode 100644 src/fetch-client-ui/components/Common/Modal/index.tsx create mode 100644 src/fetch-client-ui/components/Common/Modal/style.css create mode 100644 src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/style.css create mode 100644 src/utils/crypto/fc-crypto.ts create mode 100644 src/utils/crypto/index.ts create mode 100644 src/utils/crypto/types.ts create mode 100644 src/utils/ui/bulkExportUIProvider.tsx diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a29c175 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,28 @@ +root = true + +[*] +end_of_line = lf +indent_size = 2 +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{yml,yaml,yml.tpl}] +indent_size = 2 +indent_style = space + +[*.md] +indent_style = space +indent_size = 2 + +[*.json] +indent_size = 2 +indent_style = space + +[.husky/_/husky.sh] +charset = unset +end_of_line = unset +insert_final_newline = unset +trim_trailing_whitespace = unset +indent_style = unset +indent_size = unset diff --git a/.eslintrc.json b/.eslintrc.json index 5351a58..2d06b25 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -23,4 +23,4 @@ "*.config.js", "**/*.js" ] -} \ No newline at end of file +} diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index aeb4c1a..7fbf8b5 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -24,9 +24,10 @@ A clear and concise description of what you expected to happen. If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - - OS: [e.g. Windows] - - Fetch Client Version [e.g. 1.0.0] - - VS Code Version [e.g. 1.65.0] + - OS: [e.g. Windows] + - Fetch Client Version [e.g. 1.0.0] + - VS Code Version [e.g. 1.65.0] + - Node Version [e.g. 18.0.0] **Additional context** Add any other context about the problem here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 69d59ca..7c75582 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -25,4 +25,4 @@ Please include a summary of the changes and context. List any dependencies that - [ ] I have made corresponding changes to the documentation -**Linked Issue** : [#Issue_Number](Issue_Link) \ No newline at end of file +**Linked Issue** : [#Issue_Number](Issue_Link) diff --git a/.github/workflows/package.yaml b/.github/workflows/package.yaml new file mode 100644 index 0000000..71be11b --- /dev/null +++ b/.github/workflows/package.yaml @@ -0,0 +1,27 @@ +name: Deploy Extension + +on: + workflow_dispatch: + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Use Node + uses: actions/setup-node@v4 + with: + node-version: 18.x + + - name: Install the Dependencies + run: npm install + + - name: Install vsce + run: npm install -g @vscode/vsce + + - name: Package the Extension + run: vsce package diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml new file mode 100644 index 0000000..a2b4f33 --- /dev/null +++ b/.github/workflows/publish.yaml @@ -0,0 +1,27 @@ +name: Deploy Extension + +on: + workflow_dispatch: + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Use Node + uses: actions/setup-node@v4 + with: + node-version: 18.x + + - name: Install the Dependencies + run: npm install + + - name: Install vsce + run: npm install -g @vscode/vsce + + - name: Publish the Extension + run: vsce publish -p ${{ secrets.VSCE_TOKEN }} diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..d6268b4 --- /dev/null +++ b/.npmrc @@ -0,0 +1,2 @@ +${USER_NAME}:registry=https://npm.pkg.github.com +//npm.pkg.github.com/:_authToken=${NPM_TOKEN} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f0db72..09f78c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ All notable changes to the "Fetch Client" extension will be documented in this file. +## v1.7.0 - September, 2024 +### 🎉 New Features +- `Encrypted` environment variables. Variables are stored in the encrypted format. +- New settings are added for the encrypted environment and encryption in exporting the variables. +- Bulk export option added in the collections and variables. +- Bulk import for the collections and variables. +- Variables are hided in the variable screen. + +### 🐛 Bug Fixes +- Cookie name is not parsed correctly. +- "Manage Cookie" button is added in the cookie section in Response panel. + +### 🔗 Miscellaneous +- Added menu options for raise the requests/issues and write a review about `Fetch Client` +- GitHub action added for build vsix package and publish the extension. + +### Requirements +- Minimum required version of **VSCode** is `v1.75.0` +- Minimum **Node** version is `18.20.3` + ## v1.6.0 - August, 2024 ### 🎉 New Features - Added menu for directly run the requests @@ -117,7 +137,7 @@ All notable changes to the "Fetch Client" extension will be documented in this f - Folder added to the Collection. - Set environment variable from json response, headers and cookies. - Support AWS Signature auth type. -- Support Cookies and Manage cookies feature ([#1](https://github.com/Ganesan-Chandran/vscode-fetch-client/issues/1)) added. +- Support Cookies and Manage cookies feature ([#1](https://github.com/Ganesan-Chandran/vscode-fetch-client/issues/1)) added. - Support Copy and Paste the item between Collection/Folder. - Support Variables highlight ([#3](https://github.com/Ganesan-Chandran/vscode-fetch-client/issues/3)). - New test case options (Length and Type) are added. @@ -146,8 +166,8 @@ All notable changes to the "Fetch Client" extension will be documented in this f - Generate code snippet for various languages. - Save response and test results as File. - Export/Import the Fetch Client's collections and environment variables. -- Add documentation/feedback for each request. +- Add documentation/feedback for each request. ### 🐛 Bug Fixes -\- \ No newline at end of file +\- diff --git a/LICENSE b/LICENSE index 7a9aad1..faf7d91 100644 --- a/LICENSE +++ b/LICENSE @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/README.md b/README.md index 92c3b0e..7d2c6bc 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,11 @@ Fetch Client is Visual Studio Code extension which is used to test the Rest API. * Various post body which are Form, Form-Encoded, Raw (Json, Plain Text, XML), Binary File and GraphQL. * Syntax highlight for Response data. * Tree view for JSON and XML responses and HTML preview for HTML responses. -* History, Collection, Environment Variable is supported. +* History, Collection, `Encrypted` Environment Variable is supported. * Test the API request and response data without any scripts/code. * Generate code snippet for various languages. * Save response and test results as File. -* Export/Import the Fetch Client/Postman/Thunder Client's collections and environment variables. +* Bulk Export/Import the Fetch Client/Postman/Thunder Client's collections and environment variables. * Add documentation/feedback for each request. * Set the environment variable data from the response. * Manage the Cookies. @@ -390,7 +390,7 @@ Fetch client provides the quick access of History, collection and Environment va

Import Curl Menu -
+
Import Curl
Import Curl Request @@ -498,7 +498,7 @@ DO NOT ENTER/EDIT MANUALLY in the below settings. Configuration will be done aut

- Fetch Client settings + Fetch Client settings
## 🚀 Tech Stack diff --git a/dictionary.txt b/dictionary.txt index 28703f1..3211aa8 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -43,3 +43,4 @@ UI url VSCode vscode-fetch-client +vsix diff --git a/package-lock.json b/package-lock.json index a9c41a9..fa43f27 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,14 +1,15 @@ { "name": "fetch-client", - "version": "1.6.0", + "version": "1.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "fetch-client", - "version": "1.6.0", + "version": "1.7.0", "license": "MIT", "dependencies": { + "@ganesan-chandran/fetch-client-crypto": "^1.0.1", "aws4": "^1.11.0", "axios": "^0.26.1", "form-data": "^4.0.0", @@ -45,6 +46,7 @@ "buffer": "^6.0.3", "cross-env": "^7.0.3", "draft-js": "^0.11.7", + "editorconfig-checker": "^5.1.8", "eslint": "^8.57.0", "fast-xml-parser": "^4.0.7", "glob": "^7.2.0", @@ -2389,6 +2391,15 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@ganesan-chandran/fetch-client-crypto": { + "version": "1.0.1", + "resolved": "https://npm.pkg.github.com/download/@ganesan-chandran/fetch-client-crypto/1.0.1/78cdfe791639f2cf817a7ab2bcd28130ab7c80b3", + "integrity": "sha512-8cKGZRAiALOXizTa2ESt4GBTjiqcobxsLogngJ9j5Yh3hoJhPMn3pAN9XTWk889N5Ma1Mk7wvIfG10bBXyTUSQ==", + "license": "MIT", + "engines": { + "node": ">=18.20.3" + } + }, "node_modules/@humanwhocodes/config-array": { "version": "0.11.14", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", @@ -9109,6 +9120,23 @@ "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "dev": true }, + "node_modules/editorconfig-checker": { + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/editorconfig-checker/-/editorconfig-checker-5.1.8.tgz", + "integrity": "sha512-GM/qCbXA8GajSqqjXiWZN49i0nizQV5PjkVKIwWB9rtsm/pztjnBC+4dts5wW2KdrP2zyMPEltWHtWQwoCadqg==", + "dev": true, + "bin": { + "ec": "dist/index.js", + "editorconfig-checker": "dist/index.js" + }, + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "type": "buymeacoffee", + "url": "https://www.buymeacoffee.com/mstruebing" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", diff --git a/package.json b/package.json index 10abb71..5665045 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "fetch-client", "displayName": "Fetch Client", "description": "Rest API Client for VS Code which is used to test your API's within VS Code.", - "version": "1.6.0", + "version": "1.7.0", "publisher": "GanesanChandran", "author": { "name": "Ganesan Chandran " @@ -57,6 +57,7 @@ "onCommand:fetch-client.openSettings", "onCommand:fetch-client.openErrorLog", "onCommand:fetch-client.curlRequest", + "onCommand:fetch-client.bulkExport", "onStartupFinished" ], "main": "./dist/extension.js", @@ -76,30 +77,40 @@ }, { "command": "fetch-client.manageCookies", - "title": "Manage Cookies", + "title": "🌐 Manage Cookies", "category": "Fetch Client" }, { "command": "fetch-client.openSettings", - "title": "Fetch Client Settings", + "title": "⚙️ Fetch Client Settings", "category": "Fetch Client" }, { "command": "fetch-client.openErrorLog", - "title": "View Error Log", + "title": "🔍 View Error Log", "category": "Fetch Client" }, - { - "command": "fetch-client.reloadData", - "title": "Reload", - "icon": "$(refresh)", - "category": "Fetch Client" - }, - { - "command": "fetch-client.documentation", - "title": "Documentation", - "category": "Fetch Client" - } + { + "command": "fetch-client.reloadData", + "title": "Reload", + "icon": "$(refresh)", + "category": "Fetch Client" + }, + { + "command": "fetch-client.documentation", + "title": "📄 Documentation", + "category": "Fetch Client" + }, + { + "command": "fetch-client.raiseRequest", + "title": "✅ Raise Requests/Issues", + "category": "Fetch Client" + }, + { + "command": "fetch-client.feedback", + "title": "⭐ Write a Review", + "category": "Fetch Client" + } ], "viewsContainers": { "activitybar": [ @@ -248,6 +259,20 @@ "scope": "resource", "markdownDescription": "Workspace location (**`Do not edit manually. Configuration will be done automatically. Manual editing may lead to data loss.`**)", "order": 13 + }, + "fetch-client.encryptedVariables": { + "type": "boolean", + "default": false, + "scope": "resource", + "markdownDescription": "Encrypt the environment variable values in the local store.", + "order": 14 + }, + "fetch-client.encryptedVariablesInExport": { + "type": "boolean", + "default": true, + "scope": "resource", + "markdownDescription": "Encrypt the environment variable values during export.", + "order": 15 } } } @@ -270,15 +295,25 @@ "group": "group2@2" }, { - "command": "fetch-client.reloadData", - "when": "view == fetch-client.sideBar", + "command": "fetch-client.reloadData", + "when": "view == fetch-client.sideBar", "group": "navigation" - }, - { - "command": "fetch-client.documentation", - "group": "group2@3", - "when": "view == fetch-client.sideBar" - } + }, + { + "command": "fetch-client.documentation", + "group": "group2@3", + "when": "view == fetch-client.sideBar" + }, + { + "command": "fetch-client.raiseRequest", + "group": "group3@1", + "when": "view == fetch-client.sideBar" + }, + { + "command": "fetch-client.feedback", + "group": "group3@2", + "when": "view == fetch-client.sideBar" + } ], "commandPalette": [ { @@ -293,14 +328,22 @@ "command": "fetch-client.openErrorLog", "when": "false" }, - { - "command": "fetch-client.reloadData", - "when": "false" - }, - { - "command": "fetch-client.documentation", - "when": "false" - } + { + "command": "fetch-client.reloadData", + "when": "false" + }, + { + "command": "fetch-client.documentation", + "when": "false" + }, + { + "command": "fetch-client.raiseRequest", + "when": "false" + }, + { + "command": "fetch-client.feedback", + "when": "false" + } ] } }, @@ -312,8 +355,7 @@ "compile-tests": "tsc -p ./", "watch-tests": "tsc -watch -p ./", "pretest": "npm run compile-tests && npm run compile && npm run lint", - "lint-check": "eslint src --ext .ts,.tsx", - "lint-fix": "eslint src --ext .ts,.tsx --fix", + "lint-check": "editorconfig-checker", "md-lint": "markdownlint *.md ./**/*.md ./**/**/*.md --ignore node_modules --ignore CHANGELOG.md", "md-lint-fix": "markdownlint *.md ./**/*.md ./**/**/*.md --ignore node_modules --ignore CHANGELOG.md --fix", "md-spellcheck": "spellchecker -f *.md ./**/*.md -d dictionary.txt --language en-GB", @@ -345,11 +387,15 @@ "buffer": "^6.0.3", "cross-env": "^7.0.3", "draft-js": "^0.11.7", + "editorconfig-checker": "^5.1.8", "eslint": "^8.57.0", "fast-xml-parser": "^4.0.7", "glob": "^7.2.0", "httpsnippet": "^2.0.0", + "jest": "^29.7.0", "lokijs": "^1.5.12", + "markdownlint": "^0.34.0", + "markdownlint-cli": "^0.41.0", "mini-css-extract-plugin": "^2.6.0", "mocha": "^9.2.2", "monaco-editor": "^0.33.0", @@ -364,6 +410,7 @@ "redux": "^4.1.2", "redux-thunk": "^2.4.1", "source-map-loader": "^3.0.1", + "spellchecker-cli": "^6.2.0", "stream": "0.0.2", "stream-browserify": "^3.0.0", "terser-webpack-plugin": "^5.3.1", @@ -375,16 +422,13 @@ "web-vitals": "^2.1.4", "webpack": "^5.66.0", "webpack-bundle-analyzer": "^4.5.0", - "webpack-cli": "^4.9.2", - "markdownlint": "^0.34.0", - "markdownlint-cli": "^0.41.0", - "spellchecker-cli": "^6.2.0", - "jest": "^29.7.0" + "webpack-cli": "^4.9.2" }, "dependencies": { + "@ganesan-chandran/fetch-client-crypto": "^1.0.1", "aws4": "^1.11.0", "axios": "^0.26.1", - "form-data": "^4.0.0", + "form-data": "^4.0.0", "moment-mini": "^2.29.4", "quicktype-core": "^6.1.0", "react": "^17.0.2", diff --git a/src/extension.ts b/src/extension.ts index 4800a99..7da222c 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -20,7 +20,9 @@ import { getExtDbPath, setGlobalStorageUri } from './utils/db/getExtDbPath'; import { transferDbConfig } from './utils/db/transferDBConfig'; import { GetAllCollections } from './utils/db/collectionDBUtil'; import { GetAllHistory } from './utils/db/historyDBUtil'; -import { GetAllVariable } from './utils/db/varDBUtil'; +import { GetAllVariable, UpdateToDecryptedVariables, UpdateToEncryptedVariables } from './utils/db/varDBUtil'; +import { getVariableEncryptionFCConfiguration, setVariableEncryptionConfiguration } from './utils/vscodeConfig'; +import { BulkExportProviderUI } from './utils/ui/bulkExportUIProvider'; export var pubSub: PubSub; export var vsCodeLogger: VSCodeLogger; @@ -30,121 +32,144 @@ var extPath = ""; var extensionUri: vscode.Uri; export function OpenExistingItem(id?: string, name?: string, colId?: string, folderId?: string, varId?: string, type?: string, newTab?: boolean) { - WebAppPanel.createOrShow(extensionUri, id, (name && name.length > 15 ? name.substring(0, 15) + "..." : name), colId, varId, type, folderId, newTab); + WebAppPanel.createOrShow(extensionUri, id, (name && name.length > 15 ? name.substring(0, 15) + "..." : name), colId, varId, type, folderId, newTab); } export function OpenAddToColUI(id: string) { - vscode.commands.executeCommand("fetch-client.addToCol", id, "", "", "addtocol"); + vscode.commands.executeCommand("fetch-client.addToCol", id, "", "", "addtocol"); } export function OpenVariableUI(id?: string, type?: string) { - vscode.commands.executeCommand("fetch-client.newVar", id, type); + vscode.commands.executeCommand("fetch-client.newVar", id, type); } export function OpenCopyToColUI(id: string, name: string) { - vscode.commands.executeCommand("fetch-client.addToCol", id, "", name, "copytocol"); + vscode.commands.executeCommand("fetch-client.addToCol", id, "", name, "copytocol"); } export function OpenAttachVariableUI(id: string, name: string) { - vscode.commands.executeCommand("fetch-client.addToCol", id, "", name, "attachcol"); + vscode.commands.executeCommand("fetch-client.addToCol", id, "", name, "attachcol"); } export function OpenRunAllUI(colId: string, folderId: string, name: string, varId: string) { - vscode.commands.executeCommand("fetch-client.addToCol", colId, folderId, name, "runall", varId); + vscode.commands.executeCommand("fetch-client.addToCol", colId, folderId, name, "runall", varId); } export function OpenCookieUI(id?: string) { - vscode.commands.executeCommand("fetch-client.manageCookies", id); + vscode.commands.executeCommand("fetch-client.manageCookies", id); } export function OpenCurlUI() { - vscode.commands.executeCommand("fetch-client.curlRequest"); + vscode.commands.executeCommand("fetch-client.curlRequest"); +} + +export function OpenBulkExportUI(type: string) { + vscode.commands.executeCommand("fetch-client.bulkExport", type); } export function OpenColSettings(colId: string, folderId: string, name: string, type: string, varId: string) { - vscode.commands.executeCommand("fetch-client.addToCol", colId, folderId, name, "colsettings@:@" + type, varId); + vscode.commands.executeCommand("fetch-client.addToCol", colId, folderId, name, "colsettings@:@" + type, varId); } export function activate(context: vscode.ExtensionContext) { - setGlobalStorageUri(context.globalStorageUri.fsPath); - extPath = getExtDbPath(); - extensionUri = context.extensionUri; - - pubSub = new PubSub(); - vsCodeLogger = new VSCodeLogger(); - - if (!fs.existsSync(extPath)) { - fs.mkdirSync(extPath, { recursive: true }); - } - - if (!fs.existsSync(historyDBPath())) { - CreateHistoryDB(); - } - - if (!fs.existsSync(mainDBPath())) { - CreateMainDB(); - } - - if (!fs.existsSync(collectionDBPath())) { - CreateCollectionDB(); - } - - if (!fs.existsSync(variableDBPath())) { - CreateVariableDB(); - } - - if (!fs.existsSync(cookieDBPath())) { - CreateCookieDB(); - } - - if (!fs.existsSync(path.resolve(extPath, logPath))) { - createLogFile(); - } - - storageManager = new LocalStorageService(context.workspaceState); - - vscode.window.onDidChangeActiveColorTheme((e: vscode.ColorTheme) => { - if (pubSub) { - pubSub.publish({ messageType: pubSubTypes.themeChanged }); - } - }); - - sideBarProvider = new SideBarProvider(context.extensionUri); - context.subscriptions.push(vscode.window.registerWebviewViewProvider(SideBarProvider.viewType, sideBarProvider)); - context.subscriptions.push(vscode.commands.registerCommand('fetch-client.newRequest', () => { WebAppPanel.createOrShow(context.extensionUri); })); - context.subscriptions.push(AddToColUI(context.extensionUri)); - context.subscriptions.push(VariableUI(context.extensionUri)); - context.subscriptions.push(CookieUI(context.extensionUri)); - context.subscriptions.push(vscode.commands.registerCommand('fetch-client.openSettings', () => { - vscode.commands.executeCommand('workbench.action.openSettings', 'Fetch Client'); - })); - context.subscriptions.push(ErrorLogUI(context.extensionUri)); - context.subscriptions.push(CurlProviderUI(context.extensionUri)); - - context.subscriptions.push( - vscode.workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("fetch-client.saveToWorkspace")) { - transferDbConfig(); - } - }) - ); - - context.subscriptions.push(vscode.commands.registerCommand('fetch-client.reloadData', () => { - GetAllCollections(sideBarProvider?.view?.webview); - GetAllHistory(sideBarProvider?.view); - GetAllVariable(sideBarProvider?.view?.webview); - })); - - context.subscriptions.push(vscode.commands.registerCommand('fetch-client.documentation', () => { - vscode.env.openExternal(vscode.Uri.parse('https://github.com/Ganesan-Chandran/vscode-fetch-client/wiki')); - })); + setGlobalStorageUri(context.globalStorageUri.fsPath); + setVariableEncryptionConfiguration(getVariableEncryptionFCConfiguration()); + + extPath = getExtDbPath(); + extensionUri = context.extensionUri; + + pubSub = new PubSub(); + vsCodeLogger = new VSCodeLogger(); + + if (!fs.existsSync(extPath)) { + fs.mkdirSync(extPath, { recursive: true }); + } + + if (!fs.existsSync(historyDBPath())) { + CreateHistoryDB(); + } + + if (!fs.existsSync(mainDBPath())) { + CreateMainDB(); + } + + if (!fs.existsSync(collectionDBPath())) { + CreateCollectionDB(); + } + + if (!fs.existsSync(variableDBPath())) { + CreateVariableDB(); + } + + if (!fs.existsSync(cookieDBPath())) { + CreateCookieDB(); + } + + if (!fs.existsSync(path.resolve(extPath, logPath))) { + createLogFile(); + } + + storageManager = new LocalStorageService(context.workspaceState); + + vscode.window.onDidChangeActiveColorTheme((_e: vscode.ColorTheme) => { + if (pubSub) { + pubSub.publish({ messageType: pubSubTypes.themeChanged }); + } + }); + + sideBarProvider = new SideBarProvider(context.extensionUri); + context.subscriptions.push(vscode.window.registerWebviewViewProvider(SideBarProvider.viewType, sideBarProvider)); + context.subscriptions.push(vscode.commands.registerCommand('fetch-client.newRequest', () => { WebAppPanel.createOrShow(context.extensionUri); })); + context.subscriptions.push(AddToColUI(context.extensionUri)); + context.subscriptions.push(VariableUI(context.extensionUri)); + context.subscriptions.push(CookieUI(context.extensionUri)); + context.subscriptions.push(vscode.commands.registerCommand('fetch-client.openSettings', () => { + vscode.commands.executeCommand('workbench.action.openSettings', 'Fetch Client'); + })); + context.subscriptions.push(ErrorLogUI(context.extensionUri)); + context.subscriptions.push(CurlProviderUI(context.extensionUri)); + context.subscriptions.push(BulkExportProviderUI(context.extensionUri)); + + context.subscriptions.push( + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("fetch-client.saveToWorkspace")) { + transferDbConfig(); + } else if (e.affectsConfiguration("fetch-client.encryptedVariables")) { + if (getVariableEncryptionFCConfiguration()) { + UpdateToEncryptedVariables(); + setVariableEncryptionConfiguration(true); + } else { + UpdateToDecryptedVariables(); + setVariableEncryptionConfiguration(false); + } + } + }) + ); + + context.subscriptions.push(vscode.commands.registerCommand('fetch-client.reloadData', () => { + GetAllCollections(sideBarProvider?.view?.webview); + GetAllHistory(sideBarProvider?.view); + GetAllVariable(sideBarProvider?.view?.webview); + })); + + context.subscriptions.push(vscode.commands.registerCommand('fetch-client.documentation', () => { + vscode.env.openExternal(vscode.Uri.parse('https://github.com/Ganesan-Chandran/vscode-fetch-client/wiki')); + })); + + context.subscriptions.push(vscode.commands.registerCommand('fetch-client.raiseRequest', () => { + vscode.env.openExternal(vscode.Uri.parse('https://github.com/Ganesan-Chandran/vscode-fetch-client/issues')); + })); + + context.subscriptions.push(vscode.commands.registerCommand('fetch-client.feedback', () => { + vscode.env.openExternal(vscode.Uri.parse('https://marketplace.visualstudio.com/items?itemName=GanesanChandran.fetch-client&ssr=false#review-details')); + })); } export function getStorageManager(): LocalStorageService { - return storageManager; + return storageManager; } export function deactivate() { - pubSub.clear(); + pubSub.clear(); } diff --git a/src/fetch-client-ui/App.css b/src/fetch-client-ui/App.css index 3dc622c..6015ae7 100644 --- a/src/fetch-client-ui/App.css +++ b/src/fetch-client-ui/App.css @@ -1,90 +1,90 @@ html, body, #root { - height: 100%; + height: 100%; } .app { - height: 100%; + height: 100%; } body { - background-color: var(--background-color); - color : var(--text-color); - border-color : var(--border-color); - font-family : var(--font-family); - padding : 0; + background-color: var(--background-color); + color : var(--text-color); + border-color : var(--border-color); + font-family : var(--font-family); + padding : 0; } hr { - border : none; - height : 1px; - background: #5e5e5e; + border : none; + height : 1px; + background: #5e5e5e; } .error-text-box { - width : 90%; - height : 350px; - resize : none; - background-color: var(--background-color); - color : var(--text-color); - border-color : var(--border-color); - outline : none; + width : 90%; + height : 350px; + resize : none; + background-color: var(--background-color); + color : var(--text-color); + border-color : var(--border-color); + outline : none; } .error-header-text-box, .error-something-text-box { - width : 90%; - height : 50px; - resize : none; - background-color: transparent; - color : red; - border-color : transparent; - outline : none; + width : 90%; + height : 50px; + resize : none; + background-color: transparent; + color : red; + border-color : transparent; + outline : none; } .error-something-text-box { - color: white !important; + color: white !important; } .error-text-box:focus, .error-header-text-box:focus, .error-something-text-box:focus { - outline: none; + outline: none; } .error-panel { - padding : 20px; - text-align: center; + padding : 20px; + text-align: center; } .error-text-panel { - width: 100%; + width: 100%; } .issue-raise-button-panel { - width : 90%; - text-align : center; - padding-top: 10px; + width : 90%; + text-align : center; + padding-top: 10px; } .issue-raise-button { - appearance : button; - width : fit-content !important; - text-decoration: none; + appearance : button; + width : fit-content !important; + text-decoration: none; } .issue-raise-button:hover { - background-color: var(--button-hover-color); - color : var(--text-color); - text-decoration : none; + background-color: var(--button-hover-color); + color : var(--text-color); + text-decoration : none; } .issue-raise-button:focus { - outline: none; + outline: none; } .body-full-screen { - overflow : hidden; - transform: none !important; + overflow : hidden; + transform: none !important; } diff --git a/src/fetch-client-ui/App.test.tsx b/src/fetch-client-ui/App.test.tsx index 2a68616..4797556 100644 --- a/src/fetch-client-ui/App.test.tsx +++ b/src/fetch-client-ui/App.test.tsx @@ -1,9 +1,9 @@ -import React from 'react'; import { render, screen } from '@testing-library/react'; +import React from 'react'; import App from './App'; test('renders learn react link', () => { - render(); - const linkElement = screen.getByText(/learn react/i); - expect(linkElement).toBeInTheDocument(); + render(); + const linkElement = screen.getByText(/learn react/i); + expect(linkElement).toBeInTheDocument(); }); diff --git a/src/fetch-client-ui/App.tsx b/src/fetch-client-ui/App.tsx index 800a130..a845109 100644 --- a/src/fetch-client-ui/App.tsx +++ b/src/fetch-client-ui/App.tsx @@ -13,64 +13,67 @@ const CollectionSettings = React.lazy(() => import('./components/Collection/Sett const RunAll = React.lazy(() => import('./components/Collection/RunAll/runAll')); const ErrorLog = React.lazy(() => import('./components/ErrorLog/ErrorLog')); const CurlUI = React.lazy(() => import('./components/Curl')); +const BulkExportUI = React.lazy(() => import('./components/Collection/BulkExport/bulkExport')); function ErrorFallback({ error }) { - const errorData = " Name : " + error.name + "\n\n" + " Message : " + error.message + "\n\n" + " Stack : " + error.stack; + const errorData = " Name : " + error.name + "\n\n" + " Message : " + error.message + "\n\n" + " Stack : " + error.stack; - return ( -
- - -
- -
- -
- ); + return ( +
+ + +
+ +
+ +
+ ); } const App = () => { - return ( -
- - loading...
}> - {renderUI()} - - -
- ); + return ( +
+ + loading...
}> + {renderUI()} + + + + ); }; function renderUI() { - if (document.title === 'sideBar') { - return ; - } else if (document.title.includes('addtocol')) { - return ; - } else if (document.title.includes('copytocol')) { - return ; - } else if (document.title.includes('newvar')) { - return ; - } else if (document.title.includes('attachcol')) { - return ; - } else if (document.title.includes('runall')) { - return ; - } else if (document.title.includes('colsettings')) { - return ; - } else if (document.title.includes('curlreq')) { - return ; - } else if (document.title.includes('managecookies')) { - return ; - } else if (document.title.includes('errorlog')) { - return ; - } else { - return ; - } + if (document.title === 'sideBar') { + return ; + } else if (document.title.includes('addtocol')) { + return ; + } else if (document.title.includes('copytocol')) { + return ; + } else if (document.title.includes('newvar')) { + return ; + } else if (document.title.includes('attachcol')) { + return ; + } else if (document.title.includes('runall')) { + return ; + } else if (document.title.includes('colsettings')) { + return ; + } else if (document.title.includes('curlreq')) { + return ; + } else if (document.title.includes('managecookies')) { + return ; + } else if (document.title.includes('errorlog')) { + return ; + } else if (document.title.includes('bulkexport')) { + return ; + } else { + return ; + } } export default App; diff --git a/src/fetch-client-ui/components/Collection/AddTo/addTo.tsx b/src/fetch-client-ui/components/Collection/AddTo/addTo.tsx index e7eda14..e131c34 100644 --- a/src/fetch-client-ui/components/Collection/AddTo/addTo.tsx +++ b/src/fetch-client-ui/components/Collection/AddTo/addTo.tsx @@ -11,255 +11,255 @@ import "../style.css"; const AddToCollection = () => { - const [errors, setErrors] = useState({ - "colSelect": "", - "colName": "", - "folderName": "" - }); + const [errors, setErrors] = useState({ + "colSelect": "", + "colName": "", + "folderName": "" + }); - const [selectedCollection, selSelectedCollection] = useState(""); - const [colName, setColName] = useState(""); - const [collections, setCollections] = useState([]); + const [selectedCollection, selSelectedCollection] = useState(""); + const [colName, setColName] = useState(""); + const [collections, setCollections] = useState([]); - const [history, setHistory] = useState(); - const [isDone, setDone] = useState(false); + const [history, setHistory] = useState(); + const [isDone, setDone] = useState(false); - const [selectedFolder, setSelectedFolder] = useState(""); - const [folderName, setFolderName] = useState(""); - const [folders, setFolders] = useState([]); - const [currentFolders, setCurrentFolders] = useState([]); + const [selectedFolder, setSelectedFolder] = useState(""); + const [folderName, setFolderName] = useState(""); + const [folders, setFolders] = useState([]); + const [currentFolders, setCurrentFolders] = useState([]); - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { - let colNames = [{ name: "Select", value: "", disabled: true }]; - colNames = [...colNames, ...event.data.collectionNames]; - colNames.push({ name: "----------------------", value: "-1", disabled: true }); - colNames.push({ name: "Create New", value: "0", disabled: false }); - setCollections(colNames); - setFolders(event.data.folderNames); - } else if (event.data && event.data.type === responseTypes.getHistoryItemResponse) { - setHistory(event.data.history[0] as IHistory); - } else if (event.data && event.data.type === responseTypes.addToCollectionsResponse) { - setDone(true); - } - }); + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { + let colNames = [{ name: "Select", value: "", disabled: true }]; + colNames = [...colNames, ...event.data.collectionNames]; + colNames.push({ name: "----------------------", value: "-1", disabled: true }); + colNames.push({ name: "Create New", value: "0", disabled: false }); + setCollections(colNames); + setFolders(event.data.folderNames); + } else if (event.data && event.data.type === responseTypes.getHistoryItemResponse) { + setHistory(event.data.history[0] as IHistory); + } else if (event.data && event.data.type === responseTypes.addToCollectionsResponse) { + setDone(true); + } + }); - vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }); - let id = document.title.split("@:@")[1]; - vscode.postMessage({ type: requestTypes.getHistoryItemRequest, data: id }); - }, []); + vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }); + let id = document.title.split("@:@")[1]; + vscode.postMessage({ type: requestTypes.getHistoryItemRequest, data: id }); + }, []); - const onSelect = (event: React.ChangeEvent) => { - selSelectedCollection(event.target.value); - setColName(""); + const onSelect = (event: React.ChangeEvent) => { + selSelectedCollection(event.target.value); + setColName(""); - let folderNames = [{ colId: "", name: "Select", value: "", disabled: true }]; - folderNames = [...folderNames, ...folders.filter(item => item.colId === event.target.value)]; - folderNames.push({ colId: "-1", name: "----------------------", value: "-1", disabled: true }); - folderNames.push({ colId: "0", name: "Create New", value: "0", disabled: false }); + let folderNames = [{ colId: "", name: "Select", value: "", disabled: true }]; + folderNames = [...folderNames, ...folders.filter(item => item.colId === event.target.value)]; + folderNames.push({ colId: "-1", name: "----------------------", value: "-1", disabled: true }); + folderNames.push({ colId: "0", name: "Create New", value: "0", disabled: false }); - setCurrentFolders(folderNames); - setSelectedFolder(""); - setFolderName(""); + setCurrentFolders(folderNames); + setSelectedFolder(""); + setFolderName(""); - setErrors({ - ...errors, "colSelect": "", - "colName": "", - "folderName": "" - }); - }; + setErrors({ + ...errors, "colSelect": "", + "colName": "", + "folderName": "" + }); + }; - const onSelectFolder = (event: React.ChangeEvent) => { - setErrors({ ...errors, "folderName": "" }); - setSelectedFolder(event.target.value); - setFolderName(""); - }; + const onSelectFolder = (event: React.ChangeEvent) => { + setErrors({ ...errors, "folderName": "" }); + setSelectedFolder(event.target.value); + setFolderName(""); + }; - function handleValidation() { - if (selectedCollection === "") { - setErrors({ ...errors, "colSelect": "Please select/create the collection" }); - return false; - } + function handleValidation() { + if (selectedCollection === "") { + setErrors({ ...errors, "colSelect": "Please select/create the collection" }); + return false; + } - if (selectedCollection === "0") { - if (!colName) { - setErrors({ ...errors, "colName": "Cannot be empty" }); - return false; - } - if (colName.toUpperCase().trim() === "DEFAULT") { - setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); - return false; - } - } + if (selectedCollection === "0") { + if (!colName) { + setErrors({ ...errors, "colName": "Cannot be empty" }); + return false; + } + if (colName.toUpperCase().trim() === "DEFAULT") { + setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); + return false; + } + } - if (selectedFolder === "0") { - if (!folderName) { - setErrors({ ...errors, "folderName": "Cannot be empty" }); - return false; - } - } + if (selectedFolder === "0") { + if (!folderName) { + setErrors({ ...errors, "folderName": "Cannot be empty" }); + return false; + } + } - return true; - } + return true; + } - function onSubmitClick() { + function onSubmitClick() { - if (handleValidation()) { - let folder: IFolder; + if (handleValidation()) { + let folder: IFolder; - if (selectedFolder) { - folder = { - id: selectedFolder === "0" ? uuidv4() : selectedFolder, - name: selectedFolder === "0" ? folderName : "", - createdTime: formatDate(), - type: "folder", - data: [history], - settings: InitialSettings - }; - } + if (selectedFolder) { + folder = { + id: selectedFolder === "0" ? uuidv4() : selectedFolder, + name: selectedFolder === "0" ? folderName : "", + createdTime: formatDate(), + type: "folder", + data: [history], + settings: InitialSettings + }; + } - let collection: ICollections = { - id: selectedCollection === "0" ? uuidv4() : selectedCollection, - createdTime: formatDate(), - name: selectedCollection === "0" ? colName : "", - data: folder ? [folder] : [history], - variableId: "", - settings: InitialSettings - }; + let collection: ICollections = { + id: selectedCollection === "0" ? uuidv4() : selectedCollection, + createdTime: formatDate(), + name: selectedCollection === "0" ? colName : "", + data: folder ? [folder] : [history], + variableId: "", + settings: InitialSettings + }; - vscode.postMessage({ type: requestTypes.addToCollectionsRequest, data: { col: collection, hasFolder: folder ? true : false, isNewFolder : selectedFolder === "0" ? true : false} }); - } - } + vscode.postMessage({ type: requestTypes.addToCollectionsRequest, data: { col: collection, hasFolder: folder ? true : false, isNewFolder : selectedFolder === "0" ? true : false} }); + } + } - function onNameChange(e: any) { - setColName(e.target.value); - setErrors({ ...errors, "colName": (e.target.value ? (e.target.value.toUpperCase().trim() === "DEFAULT" ? "Collection name should not be 'Default'" : "") : "Cannot be empty") }); - } + function onNameChange(e: any) { + setColName(e.target.value); + setErrors({ ...errors, "colName": (e.target.value ? (e.target.value.toUpperCase().trim() === "DEFAULT" ? "Collection name should not be 'Default'" : "") : "Cannot be empty") }); + } - function onFolderNameChange(e: any) { - setFolderName(e.target.value); - setErrors({ ...errors, "folderName": (e.target.value ? "" : "Cannot be empty") }); - } + function onFolderNameChange(e: any) { + setFolderName(e.target.value); + setErrors({ ...errors, "folderName": (e.target.value ? "" : "Cannot be empty") }); + } - return ( - history && history.name ? -
-
Add To Collection
-
- - - - - - - - - - - - - - - {selectedCollection === "0" ? - - - : null} - {selectedCollection ? - - - : null} - {selectedFolder === "0" ? - - - : null} - -
- History Name : - - -
- Request Details : - -
{history.method.toUpperCase()}
-
{history.url?.length > 50 ? history.url.substring(0, 50) + "..." : history.url}
-
{formatDate(history.createdTime)}
-
- Collection : - - -
- Collection Name : - - -
- Folder : - - -
- Folder Name : - - -
-
- -
-
- {isDone && (History item has added to Collection successfully)} -
-
-
- : - <> - ); + return ( + history && history.name ? +
+
✅ Add To Collection
+
+ + + + + + + + + + + + + + + {selectedCollection === "0" ? + + + : null} + {selectedCollection ? + + + : null} + {selectedFolder === "0" ? + + + : null} + +
+ History Name : + + +
+ Request Details : + +
{history.method.toUpperCase()}
+
{history.url?.length > 50 ? history.url.substring(0, 50) + "..." : history.url}
+
{formatDate(history.createdTime)}
+
+ Collection : + + +
+ Collection Name : + + +
+ Folder : + + +
+ Folder Name : + + +
+
+ +
+
+ {isDone && (History item has added to Collection successfully)} +
+
+
+ : + <> + ); }; -export default AddToCollection; \ No newline at end of file +export default AddToCollection; diff --git a/src/fetch-client-ui/components/Collection/AttachVariable/attachVariable.tsx b/src/fetch-client-ui/components/Collection/AttachVariable/attachVariable.tsx index cc4f122..77787a3 100644 --- a/src/fetch-client-ui/components/Collection/AttachVariable/attachVariable.tsx +++ b/src/fetch-client-ui/components/Collection/AttachVariable/attachVariable.tsx @@ -6,132 +6,132 @@ import { IVariable } from "../../SideBar/redux/types"; import "../style.css"; const AttachVariable = () => { - const [colName, setColName] = useState(""); - const [colId, setColId] = useState(""); - const [names, setNames] = useState([]); - const [selectedVarId, setVarId] = useState(""); + const [colName, setColName] = useState(""); + const [colId, setColId] = useState(""); + const [names, setNames] = useState([]); + const [selectedVarId, setVarId] = useState(""); - const [errors, setErrors] = useState({}); - const [isDone, setDone] = useState(false); + const [errors, setErrors] = useState({}); + const [isDone, setDone] = useState(false); - useEffect(() => { - const id = document.title.split("@:@")[1]; - setColId(id); - const name = document.title.split("@:@")[3]; - setColName(name); + useEffect(() => { + const id = document.title.split("@:@")[1]; + setColId(id); + const name = document.title.split("@:@")[3]; + setColName(name); - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getAllVariableResponse) { - let vars = event.data.variable as IVariable[]; - let varNames = [{ name: "Select", value: "", disabled: true }]; + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getAllVariableResponse) { + let vars = event.data.variable as IVariable[]; + let varNames = [{ name: "Select", value: "", disabled: true }]; - var ids = vars.reduce((ids, item, index) => { - if (index !== 0) { - ids.push({ name: item.name, value: item.id, disabled: false }); - } - return ids; - }, []); + var ids = vars.reduce((ids, item, index) => { + if (index !== 0) { + ids.push({ name: item.name, value: item.id, disabled: false }); + } + return ids; + }, []); - varNames = [...varNames, ...ids]; - setNames(varNames); - } else if (event.data && event.data.type === responseTypes.attachVariableResponse) { - setDone(true); - } - }); + varNames = [...varNames, ...ids]; + setNames(varNames); + } else if (event.data && event.data.type === responseTypes.attachVariableResponse) { + setDone(true); + } + }); - vscode.postMessage({ type: requestTypes.getAllVariableRequest }); - }, []); + vscode.postMessage({ type: requestTypes.getAllVariableRequest }); + }, []); - const onSelect = (event: React.ChangeEvent) => { - setErrors({ ...errors, "varId": "" }); - setVarId(event.target.value); - }; + const onSelect = (event: React.ChangeEvent) => { + setErrors({ ...errors, "varId": "" }); + setVarId(event.target.value); + }; - function handleValidation() { - if (selectedVarId === "") { - setErrors({ ...errors, "varId": "Please select the variable" }); - return false; - } + function handleValidation() { + if (selectedVarId === "") { + setErrors({ ...errors, "varId": "Please select the variable" }); + return false; + } - return true; - } + return true; + } - function onSubmitClick() { - if (handleValidation()) { - vscode.postMessage({ type: requestTypes.attachVariableRequest, data: { colId: colId, varId: selectedVarId } }); - } - } + function onSubmitClick() { + if (handleValidation()) { + vscode.postMessage({ type: requestTypes.attachVariableRequest, data: { colId: colId, varId: selectedVarId } }); + } + } - return ( - colId ? -
-
Attach Variable
-
- - - - - - - - - - - - - - - -
- Selected Collection - - -
- Variable - - -
- - {errors["varId"] &&
{errors["varId"]}
} -
-
- -
-
- {isDone && ({`Collection '${colName}' is attached to variable successfully`})} -
-
-
- : - <> - ); + return ( + colId ? +
+
🔗 Attach Variable
+
+ + + + + + + + + + + + + + + +
+ Selected Collection + + +
+ Variable + + +
+ + {errors["varId"] &&
{errors["varId"]}
} +
+
+ +
+
+ {isDone && ({`Collection '${colName}' is attached to variable successfully`})} +
+
+
+ : + <> + ); }; -export default AttachVariable; \ No newline at end of file +export default AttachVariable; diff --git a/src/fetch-client-ui/components/Collection/BulkExport/bulkExport.tsx b/src/fetch-client-ui/components/Collection/BulkExport/bulkExport.tsx new file mode 100644 index 0000000..1192bf2 --- /dev/null +++ b/src/fetch-client-ui/components/Collection/BulkExport/bulkExport.tsx @@ -0,0 +1,172 @@ +import React, { useEffect, useState } from "react"; +import { requestTypes, responseTypes } from "../../../../utils/configuration"; +import { Modal } from "../../Common/Modal"; +import vscode from "../../Common/vscodeAPI"; +import { IVariable } from "../../SideBar/redux/types"; +import "./style.css"; + +const BulkExport = () => { + + const [collectionNames, setCollectionNames] = useState([]); + const [selectedIds, setSelectedIds] = useState([]); + const [filePath, setFilePath] = useState(""); + const [loading, setLoading] = useState(true); + const [showModal, setShowModal] = useState(false); + const [isDone, setDone] = useState(false); + const [type, setType] = useState("col"); + + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getAllCollectionNamesResponse) { + setCollectionNames(event.data.collectionNames); + setLoading(false); + } else if (event.data && event.data.type === responseTypes.getAllVariableResponse) { + let vars = event.data.variable as IVariable[]; + var varNames = vars.reduce((ids, item, index) => { + if (index !== 0) { + ids.push({ name: item.name, value: item.id, disabled: false }); + } + return ids; + }, []); + setCollectionNames(varNames); + setLoading(false); + } else if (event.data && event.data.type === responseTypes.selectPathResponse) { + setFilePath(event.data.path); + } else if (event.data && event.data.type === responseTypes.bulkColExportResponse) { + setShowModal(false); + setDone(true); + } + }); + + let type = document.title.split("@:@")[1]; + setType(type); + + if (type === "col") { + vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "bulkexport" }); + } else { + vscode.postMessage({ type: requestTypes.getAllVariableRequest }); + } + }, []); + + const handleCheckboxChange = (event) => { + const checkedId = event.target.value; + if (event.target.checked) { + if (checkedId === "0") { + let all: any[] = ["0"]; + collectionNames.forEach(item => { all.push(item.value); }); + setSelectedIds(all); + } else { + setSelectedIds([...selectedIds, checkedId]); + } + } else { + if (checkedId === "0") { + setSelectedIds([]); + } + else { + setSelectedIds(selectedIds.filter(id => id !== checkedId && id !== "0")); + } + } + }; + + function onSubmitClick() { + setShowModal(true); + vscode.postMessage({ type: requestTypes.bulkColExportRequest, data: { cols: selectedIds.filter(id => id !== "0"), path: filePath, type: type } }); + } + + const onSelectFile = (evt: any) => { + overrideEventDefaults(evt); + vscode.postMessage({ type: requestTypes.selectPathRequest }); + }; + + const overrideEventDefaults = + (event: Event | React.DragEvent | React.ChangeEvent): void => { + event.preventDefault(); + event.stopPropagation(); + }; + + return ( +
+ +

Exporting the {type === "col" ? "collections..." : "variables..."}

+
+ { + loading === true ? + <> +
+
{"Loading...."}
+ + : + <> +
Bulk Export
+
+ { + collectionNames?.length > 0 ? + <> +
+
{type === "col" ? "Collections :" : "Variables :"}
+
+ +
+ + { + collectionNames.map((col) => ( + + )) + } +
+
+
+
+ +
+
Path :
+
+ +
{filePath}
+
+
+
+
+
+
+ +
+ {isDone && ({type === "col" ? "Collections " : "Variables"} are exported successfully)} +
+
+
+
+ + : + <> + + } +
+ + } +
+ ); +}; + +export default BulkExport; diff --git a/src/fetch-client-ui/components/Collection/BulkExport/style.css b/src/fetch-client-ui/components/Collection/BulkExport/style.css new file mode 100644 index 0000000..c288f26 --- /dev/null +++ b/src/fetch-client-ui/components/Collection/BulkExport/style.css @@ -0,0 +1,75 @@ +.bulk-export-title { + font-size: 17px; + margin-bottom: 15px; +} + +.bulk-export-list-container { + display: flex; + flex-direction: column; + gap: 10px; + overflow-y: scroll; + height: 250px; + padding-bottom: 15px; + width: 100%; + border: 1px solid; +} + +.bulk-panel { + padding-left: 10%; + padding-top: 20px; +} + +.bulk-list { + padding-top: 2.5px; + padding-bottom: 2.5px; + padding-left: 5px; +} + +/* container */ +.responsive-three-column-grid { + display: block; +} + +/* columns */ +.responsive-three-column-grid>* { + padding: 1rem; +} + +/* tablet breakpoint */ +@media (min-width:768px) { + .responsive-three-column-grid { + display: grid; + grid-auto-rows: 1fr; + grid-template-columns: 0.3fr 1fr 1fr; + } + + .bulk-text-title{ + text-align: right !important; + } +} + +.bulk-path-select-panel { + display: flex; +} + +.bulk-path-btn { + width: 75px; + height: 30px; +} + +.bulk-filename-text { + color: var(--text-color); + font-size: var(--font-size); + margin-left: 10px; + width: calc(100% - 85px); +} + +.bulk-message-panel { + margin : 0 auto; + padding-top: 15px; + text-align : center; +} + +.bulk-text-title{ + text-align: left; +} diff --git a/src/fetch-client-ui/components/Collection/CopyTo/copyTo.tsx b/src/fetch-client-ui/components/Collection/CopyTo/copyTo.tsx index a0792d7..4995a0d 100644 --- a/src/fetch-client-ui/components/Collection/CopyTo/copyTo.tsx +++ b/src/fetch-client-ui/components/Collection/CopyTo/copyTo.tsx @@ -7,156 +7,156 @@ import "../style.css"; const CopyTo = () => { - const [sourceColName, setSourceColName] = useState(""); - const [sourceColId, setSourceColId] = useState(""); - const [destColId, setDestColId] = useState(""); - const [destColName, setDestColName] = useState(""); - const [collectionNames, setCollectionNames] = useState([]); + const [sourceColName, setSourceColName] = useState(""); + const [sourceColId, setSourceColId] = useState(""); + const [destColId, setDestColId] = useState(""); + const [destColName, setDestColName] = useState(""); + const [collectionNames, setCollectionNames] = useState([]); - const [errors, setErrors] = useState({}); - const [isDone, setDone] = useState(false); + const [errors, setErrors] = useState({}); + const [isDone, setDone] = useState(false); - useEffect(() => { - const id = document.title.split("@:@")[1]; - setSourceColId(id); - const name = document.title.split("@:@")[3]; - setSourceColName(name); + useEffect(() => { + const id = document.title.split("@:@")[1]; + setSourceColId(id); + const name = document.title.split("@:@")[3]; + setSourceColName(name); - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getAllCollectionNamesResponse) { - let findIndex: number = -1; - let names = event.data.collectionNames; - let colNames = [{ name: "Select", value: "", disabled: true }]; - let found = names.some(function (item: any, index: number) { findIndex = index; return item.value === id; }); - if (found) { - names.splice(findIndex, 1); - } - colNames = [...colNames, ...names]; - colNames.push({ name: "----------------------", value: "-1", disabled: true }); - colNames.push({ name: "Create New", value: "0", disabled: false }); - setCollectionNames(colNames); - } else if (event.data && event.data.type === responseTypes.copyToCollectionsResponse) { - setDone(true); - } - }); + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getAllCollectionNamesResponse) { + let findIndex: number = -1; + let names = event.data.collectionNames; + let colNames = [{ name: "Select", value: "", disabled: true }]; + let found = names.some(function (item: any, index: number) { findIndex = index; return item.value === id; }); + if (found) { + names.splice(findIndex, 1); + } + colNames = [...colNames, ...names]; + colNames.push({ name: "----------------------", value: "-1", disabled: true }); + colNames.push({ name: "Create New", value: "0", disabled: false }); + setCollectionNames(colNames); + } else if (event.data && event.data.type === responseTypes.copyToCollectionsResponse) { + setDone(true); + } + }); - vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "copytocol" }); - }, []); + vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "copytocol" }); + }, []); - const onSelect = (event: React.ChangeEvent) => { - setErrors({ ...errors, "colName": "" }); - setDestColId(event.target.value); - }; + const onSelect = (event: React.ChangeEvent) => { + setErrors({ ...errors, "colName": "" }); + setDestColId(event.target.value); + }; - function handleValidation() { - if (destColId === "") { - setErrors({ ...errors, "colName": "Please select/create the collection" }); - return false; - } - if (destColId === "0") { - if (!destColName) { - setErrors({ ...errors, "colName": "Cannot be empty" }); - return false; - } - if (destColName.toUpperCase().trim() === "DEFAULT") { - setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); - return false; - } - return true; - } - return true; - } + function handleValidation() { + if (destColId === "") { + setErrors({ ...errors, "colName": "Please select/create the collection" }); + return false; + } + if (destColId === "0") { + if (!destColName) { + setErrors({ ...errors, "colName": "Cannot be empty" }); + return false; + } + if (destColName.toUpperCase().trim() === "DEFAULT") { + setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); + return false; + } + return true; + } + return true; + } - function onSubmitClick() { - if (handleValidation()) { - vscode.postMessage({ type: requestTypes.copyToCollectionsRequest, data: { sourceId: sourceColId, distId: destColId === "0" ? uuidv4() : destColId, name: destColId === "0" ? destColName : "" } }); - } - } + function onSubmitClick() { + if (handleValidation()) { + vscode.postMessage({ type: requestTypes.copyToCollectionsRequest, data: { sourceId: sourceColId, distId: destColId === "0" ? uuidv4() : destColId, name: destColId === "0" ? destColName : "" } }); + } + } - function onNameChange(e: any) { - setDestColName(e.target.value); - setErrors({ ...errors, "colName": (e.target.value ? (e.target.value.toUpperCase().trim() === "DEFAULT" ? "Collection name should not be 'Default'" : "") : "Cannot be empty") }); - } + function onNameChange(e: any) { + setDestColName(e.target.value); + setErrors({ ...errors, "colName": (e.target.value ? (e.target.value.toUpperCase().trim() === "DEFAULT" ? "Collection name should not be 'Default'" : "") : "Cannot be empty") }); + } - return ( - sourceColName ? -
-
Copy Collection To
-
- - - - - - - - - - - {destColId === "0" && ( - - - )} - {errors["colName"] && - - - } - -
- Selected Collection : - - -
- Copy To : - - -
- New Collection Name : - - -
- -
{errors["colName"]}
-
-
- -
-
- {isDone && (Collection items are copied successfully)} -
-
-
- : - <> - ); + return ( + sourceColName ? +
+
📑 Copy Collection To
+
+ + + + + + + + + + + {destColId === "0" && ( + + + )} + {errors["colName"] && + + + } + +
+ Selected Collection : + + +
+ Copy To : + + +
+ New Collection Name : + + +
+ +
{errors["colName"]}
+
+
+ +
+
+ {isDone && (Collection items are copied successfully)} +
+
+
+ : + <> + ); }; -export default CopyTo; \ No newline at end of file +export default CopyTo; diff --git a/src/fetch-client-ui/components/Collection/RunAll/helper.ts b/src/fetch-client-ui/components/Collection/RunAll/helper.ts index 0fd047f..074a890 100644 --- a/src/fetch-client-ui/components/Collection/RunAll/helper.ts +++ b/src/fetch-client-ui/components/Collection/RunAll/helper.ts @@ -5,113 +5,113 @@ import { IReponseModel } from "../../ResponseUI/redux/types"; import { IVariable } from "../../SideBar/redux/types"; export function exportJson( - req: IRequestModel[], - selectedReq: boolean[], - res: IReponseModel[][], - sourceColName: string, - selectedVariable: IVariable, - totalIterations: number + req: IRequestModel[], + selectedReq: boolean[], + res: IReponseModel[][], + sourceColName: string, + selectedVariable: IVariable, + totalIterations: number ): any { - let iteration: any[] = []; - for (let i = 0; i < totalIterations; i++) { - let iterationData: any[] = []; - req.forEach((item, index) => { - if (selectedReq[index]) { - iterationData.push({ - request: { - id: item.id, - url: item.url, - name: item.name, - createdTime: item.createdTime, - method: item.method.toUpperCase(), - notes: item.notes - }, - response: res[i] && res[i][index] ? { - status: res[i][index].response.status, - statusText: res[i][index].response.statusText, - duration: getResponseDuration(res, i, index), - size: getResponseSize(res, i, index) - } : "[]", - tests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.map((itm) => { - return { - testCase: itm.test, - actualValue: itm.actualValue, - result: itm.result - }; - }) : "[]", - totalTests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.length : 0, - passedTests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === true).length : 0, - failedTests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === false).length : 0, - }); - } - }); + let iteration: any[] = []; + for (let i = 0; i < totalIterations; i++) { + let iterationData: any[] = []; + req.forEach((item, index) => { + if (selectedReq[index]) { + iterationData.push({ + request: { + id: item.id, + url: item.url, + name: item.name, + createdTime: item.createdTime, + method: item.method.toUpperCase(), + notes: item.notes + }, + response: res[i] && res[i][index] ? { + status: res[i][index].response.status, + statusText: res[i][index].response.statusText, + duration: getResponseDuration(res, i, index), + size: getResponseSize(res, i, index) + } : "[]", + tests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.map((itm) => { + return { + testCase: itm.test, + actualValue: itm.actualValue, + result: itm.result + }; + }) : "[]", + totalTests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.length : 0, + passedTests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === true).length : 0, + failedTests: res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === false).length : 0, + }); + } + }); - let totalRequests = selectedReq.filter(item => item === true).length; - let passedCount = passedRequestsCount(res[i]); + let totalRequests = selectedReq.filter(item => item === true).length; + let passedCount = passedRequestsCount(res[i]); - let iterationInfo = { - iteration: i + 1, - totalRequests: totalRequests, - passedRequests: passedCount, - failedRequests: totalRequests - passedCount, - iterationData: iterationData - }; - iteration.push(iterationInfo); - } + let iterationInfo = { + iteration: i + 1, + totalRequests: totalRequests, + passedRequests: passedCount, + failedRequests: totalRequests - passedCount, + iterationData: iterationData + }; + iteration.push(iterationInfo); + } - let exportData = { - app: "Fetch Client", - collectionName: sourceColName, - version: "1.0", - exportedDate: formatDate(), - variableName: selectedVariable.name, - totalIterations: totalIterations, - iterations: iteration - }; + let exportData = { + app: "Fetch Client", + collectionName: sourceColName, + version: "1.0", + exportedDate: formatDate(), + variableName: selectedVariable.name, + totalIterations: totalIterations, + iterations: iteration + }; - return exportData; + return exportData; } export function exportCSV( - req: IRequestModel[], - selectedReq: boolean[], - res: IReponseModel[][], - sourceColName: string, - selectedVariable: IVariable, - totalIterations: number + req: IRequestModel[], + selectedReq: boolean[], + res: IReponseModel[][], + sourceColName: string, + selectedVariable: IVariable, + totalIterations: number ): string { - let data = `app,Fetch Client\ncollectionName,${sourceColName}\nversion,1.0\nexportedDate,${formatDate()}\nvariableName,${selectedVariable.name}\ntotalIterations,${totalIterations}\n\n`; + let data = `app,Fetch Client\ncollectionName,${sourceColName}\nversion,1.0\nexportedDate,${formatDate()}\nvariableName,${selectedVariable.name}\ntotalIterations,${totalIterations}\n\n`; - for (let i = 0; i < totalIterations; i++) { - data = data + `iteration,${i + 1}\n`; - data = data + `Id,Url,Name,Method,Status,Status Text,Duration,Size,Total Tests,Total Passed,Total Failed\n`; - req.forEach((item, index) => { - if (selectedReq[index]) { - data = data + `${item.id},${item.url},${item.name},${item.method.toUpperCase()},${res[i] && res[i][index] ? res[i][index].response.status : ""},${res[i] && res[i][index] ? res[i][index].response.statusText : ""},${getResponseDuration(res, i, index)},${getResponseSize(res, i, index)},${res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.length : 0},${res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === true).length : 0},${res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === false).length : 0}\n`; - } - }); - data = data + "\n"; - } + for (let i = 0; i < totalIterations; i++) { + data = data + `iteration,${i + 1}\n`; + data = data + `Id,Url,Name,Method,Status,Status Text,Duration,Size,Total Tests,Total Passed,Total Failed\n`; + req.forEach((item, index) => { + if (selectedReq[index]) { + data = data + `${item.id},${item.url},${item.name},${item.method.toUpperCase()},${res[i] && res[i][index] ? res[i][index].response.status : ""},${res[i] && res[i][index] ? res[i][index].response.statusText : ""},${getResponseDuration(res, i, index)},${getResponseSize(res, i, index)},${res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.length : 0},${res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === true).length : 0},${res[i] && res[i][index] && res[i][index].testResults ? res[i][index].testResults.filter(re => re.result === false).length : 0}\n`; + } + }); + data = data + "\n"; + } - return data; + return data; } function passedRequestsCount(res: IReponseModel[]) { - let count = 0; - for (let i = 0; i < res?.length; i++) { - if (res[i]?.response?.status >= 200 && res[i]?.response?.status < 205) { - count++; - } - } + let count = 0; + for (let i = 0; i < res?.length; i++) { + if (res[i]?.response?.status >= 200 && res[i]?.response?.status < 205) { + count++; + } + } - return count; + return count; } function getResponseDuration(res: IReponseModel[][], selectedIteration: number, index: number) { - return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.isError ? "0 ms" : GetResponseTime(res[selectedIteration][index].response.duration) : ""; + return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.isError ? "0 ms" : GetResponseTime(res[selectedIteration][index].response.duration) : ""; } function getResponseSize(res: IReponseModel[][], selectedIteration: number, index: number) { - return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.size ? FormatBytes(parseInt(res[selectedIteration][index].response.size)) : "" : ""; -} \ No newline at end of file + return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.size ? FormatBytes(parseInt(res[selectedIteration][index].response.size)) : "" : ""; +} diff --git a/src/fetch-client-ui/components/Collection/RunAll/runAll.tsx b/src/fetch-client-ui/components/Collection/RunAll/runAll.tsx index 90406c6..3198c10 100644 --- a/src/fetch-client-ui/components/Collection/RunAll/runAll.tsx +++ b/src/fetch-client-ui/components/Collection/RunAll/runAll.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from "react"; import { requestTypes, responseTypes } from "../../../../utils/configuration"; import vscode from "../../Common/vscodeAPI"; import { IRequestModel } from "../../RequestUI/redux/types"; -import { FormatBytes, GetResponseTime } from "../../ResponseUI/OptionsPanel/OptionTab/util"; +import { GetResponseTime } from "../../ResponseUI/OptionsPanel/OptionTab/util"; import { IReponseModel } from "../../ResponseUI/redux/types"; import { ISettings, IVariable } from "../../SideBar/redux/types"; import { getMethodClassName } from "../../SideBar/util"; @@ -13,727 +13,714 @@ import { RunAllSettings } from "./runAllSettings"; const RunAll = () => { - const [sourceColName, setSourceColName] = useState(""); - const [processing, setProcessing] = useState(false); - const [start, setStart] = useState(false); - const [done, setDone] = useState(false); - const [varId, setVarId] = useState(""); - const [colId, setColId] = useState(""); - const [folderId, setFolderId] = useState(""); - const [itemPaths, setItemPaths] = useState(null); - - const [loading, _setLoading] = useState(false); - const refLoading = useRef(loading); - const setLoading = (data: boolean) => { - refLoading.current = data; - _setLoading(refLoading.current); - }; - - const [req, _setReq] = useState([]); - const refReq = useRef(req); - const setReq = (data: IRequestModel[]) => { - refReq.current = data; - _setReq(refReq.current); - }; - - const [parentSettings, _setParentSettings] = useState(); - const refParentSettings = useRef(parentSettings); - const setParentSettings = (data: ISettings) => { - refParentSettings.current = data; - _setParentSettings(refParentSettings.current); - }; - - const [selectedVariable, _setSelectedVariable] = useState(); - const refSelectedVariable = useRef(selectedVariable); - const setSelectedVariable = (data: IVariable) => { - refSelectedVariable.current = data; - _setSelectedVariable(refSelectedVariable.current); - }; - - const [curIndex, _setCurIndex] = useState(0); - const refCurIndex = useRef(curIndex); - const setCurIndex = (data: number) => { - refCurIndex.current = data; - _setCurIndex(refCurIndex.current); - }; - - const [res, _setRes] = useState([[]]); - const refRes = useRef(res); - const setRes = (data: IReponseModel[][]) => { - refRes.current = data; - _setRes(refRes.current); - }; - - const [selectedReq, _setSelectedReq] = useState([]); - const refSelectedReq = useRef(selectedReq); - const setSelectedReq = (data: boolean[]) => { - refSelectedReq.current = data; - _setSelectedReq(refSelectedReq.current); - }; - - const [selectedTab, setSelectedTab] = useState("Runner"); - const [selectedOption, setSelectedOption] = useState(1); - - const [totalIteration, setTotalIteration] = useState(1); - const [requestDelay, setRequsetDelay] = useState(0); - const [iterationDelay, setIterationDelay] = useState(0); - - const [processIteration, _setProcessIteration] = useState(0); - const refProcessIteration = useRef(processIteration); - const setProcessIteration = (data: number) => { - refProcessIteration.current = data; - _setProcessIteration(refProcessIteration.current); - }; - - const [selectedIteration, setSelectedIteration] = useState(0); - - const [cancelled, setCancelled] = useState(false); - - useEffect(() => { - const colId = document.title.split("@:@")[1]; - const folderId = document.title.split("@:@")[2]; - const name = document.title.split("@:@")[3]; - const varId = document.title.split("@:@")[4]; - - setSourceColName(name.trim()); - setVarId(varId?.trim()); - setFolderId(folderId?.trim()); - setColId(colId?.trim()); - - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getCollectionsByIdResponse) { - setReq((event.data.collections as IRequestModel[])); - setItemPaths(event.data.paths); - } else if (event.data && event.data.type === responseTypes.apiResponse) { - setResponse(event.data); - setProcessing(false); - } else if (event.data && event.data.type === responseTypes.getVariableItemResponse) { - setSelectedVariable(event.data.data[0] as IVariable); - } else if (event.data && event.data.type === responseTypes.multipleApiResponse) { - if (event.data.output && event.data.output.length > 0) { - event.data.output.forEach((item, index: number) => { - let enabledIndex: number; - if (index === 0) { - enabledIndex = refSelectedReq.current.findIndex(item => item === true); - } else { - enabledIndex = getNextIndex(refCurIndex.current, refSelectedReq.current); - } - - setCurIndex(enabledIndex); - setResponse(item.value); - }); - setProcessing(false); - } - } else if (event.data && event.data.type === responseTypes.getParentSettingsResponse) { - setParentSettings(event.data.settings as ISettings); - setLoading(false); - } - }); - - vscode.postMessage({ type: requestTypes.getVariableItemRequest, data: { id: varId, isGlobal: varId ? false : true } }); - vscode.postMessage({ type: requestTypes.getCollectionsByIdRequest, data: { colId: colId, folderId: folderId, type: name.trim().includes("\\") ? "fol" : "col" } }); - setLoading(true); - }, []); - - function setResponse(data: any) { - let local = [...refRes.current]; - let newRes: IReponseModel = { - response: data.response, - headers: data.headers, - cookies: data.cookies - }; - if (refReq.current[refCurIndex.current].tests.length - 1 > 0) { - newRes.testResults = executeTests(refReq.current[refCurIndex.current].tests, newRes, refSelectedVariable.current.data); - } else { - newRes.testResults = []; - } - - if (refReq.current[refCurIndex.current].setvar.length - 1 > 0) { - let variable = setVariable(refSelectedVariable.current, refReq.current[refCurIndex.current].setvar, newRes); - setSelectedVariable(variable); - } - - if (!local[refProcessIteration.current]) { - local.push([]); - } - - local[refProcessIteration.current][refCurIndex.current] = newRes; - - if (refCurIndex.current === refReq.current.length - 1) { - vscode.postMessage({ type: requestTypes.updateVariableRequest, data: refSelectedVariable.current }); - } - setRes(local); - } - - function onSubmitClick() { - setStart(true); - setProcessing(true); - if (selectedOption === 1) { - sequentialRun(); - } else { - parallelRun(); - } - } - - function onCancelClick() { - setProcessing(false); - setStart(false); - setDone(true); - setCancelled(true); - } - - function sequentialRun() { - let enabledIndex = selectedReq.findIndex(item => item === true); - if (enabledIndex !== -1) { - setCurIndex(enabledIndex); - let id = itemPaths[req[enabledIndex].id].split(";")[1]; - if (id === colId) { - id = ""; - } - setProcessing(true); - vscode.postMessage({ type: requestTypes.apiRequest, data: { settings: parentSettings, reqData: req[enabledIndex], variableData: selectedVariable, colId: colId, folderId: id } }); - } - } - - function parallelRun() { - const { selectedRequest, selectedPaths } = getAllSelectedRequest(); - vscode.postMessage({ type: requestTypes.multipleApiRequest, data: { reqData: selectedRequest, variableData: selectedVariable ? selectedVariable.data : null, colId: colId, itemPaths: selectedPaths } }); - } - - function getAllSelectedRequest(): { selectedRequest: IRequestModel[], selectedPaths: any[] } { - let enabledIndex = selectedReq.findIndex(item => item === true); - if (enabledIndex === -1) { - return; - } - - let selectedRequest: IRequestModel[] = []; - let selectedPaths = []; - for (let i = 0; i < selectedReq.length; i++) { - if (selectedReq[i]) { - selectedRequest.push(req[i]); - selectedPaths.push(itemPaths[i]); - } - } - - return { selectedRequest: selectedRequest, selectedPaths: selectedPaths }; - } - - function getNextIndex(currentInex: number, selectedReq: boolean[]) { - for (let i = currentInex + 1; i < selectedReq.length; i++) { - if (selectedReq[i]) { - return i; - } - } - - return -1; - } - - function nextParallelCall() { - const { selectedRequest, selectedPaths } = getAllSelectedRequest(); - setProcessing(true); - setProcessIteration(processIteration + 1); - vscode.postMessage({ type: requestTypes.multipleApiRequest, data: { reqData: selectedRequest, variableData: selectedVariable ? selectedVariable.data : null, colId: colId, itemPaths: selectedPaths } }); - } - - useEffect(() => { - if (!start) { - return; - } - - if (selectedOption === 2) { - if (res[processIteration].length === req.length && (processIteration + 1) < totalIteration) { - setTimeout(nextParallelCall, iterationDelay); - } - - if ((processIteration + 1) >= totalIteration) { - setStart(false); - setDone(true); - } - - return; - } else { - if (res[processIteration].length - 1 === curIndex) { - if (req.length - 1 > curIndex) { - let enabledIndex = getNextIndex(curIndex, selectedReq); - if (enabledIndex !== -1) { - let id = itemPaths[req[enabledIndex].id].split(";")[1]; - if (id === colId) { - id = ""; - } - setTimeout(() => { - setProcessing(true); - vscode.postMessage({ type: requestTypes.apiRequest, data: { reqData: req[enabledIndex], variableData: selectedVariable, colId: colId, folderId: id, settings: parentSettings } }); - setCurIndex(enabledIndex); - }, requestDelay); - - } else { - setStart(false); - setDone(true); - } - } else { - - if ((processIteration + 1) < totalIteration) { - setProcessIteration(processIteration + 1); - setTimeout(sequentialRun, iterationDelay); - return; - } - - setStart(false); - setDone(true); - } - } else { - setStart(false); - } - } - }, [res]); - - useEffect(() => { - if (req && req.length > 0 && selectedReq.length === 0) { - let selected = []; - req.forEach(() => { - selected.push(true); - }); - - setSelectedReq(selected); - } - }, [req]); - - function getResponseStatus(index: number) { - if (cancelled) { - if ((processIteration + 1) < totalIteration && selectedIteration > processIteration && selectedReq[index]) { - return "CANCELLED"; - } - - if (!(res[selectedIteration] && res[selectedIteration][index]) && selectedReq[index]) { - return "CANCELLED"; - } - - } - return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index].response.isError ? "ERROR" : (res[selectedIteration][index].response.status === 0 ? "" : (res[selectedIteration][index].response.status + " " + res[selectedIteration][index].response.statusText)) : ""; - } - - function getResponseDuration(index: number) { - if (cancelled) { - if ((processIteration + 1) < totalIteration && selectedIteration > processIteration && selectedReq[index]) { - return "CANCELLED"; - } - - if (!(res[selectedIteration] && res[selectedIteration][index]) && selectedReq[index]) { - return "CANCELLED"; - } - - } - return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.isError ? "0 ms" : GetResponseTime(res[selectedIteration][index].response.duration) : ""; - } - - function getResponseSize(index: number) { - if (cancelled) { - if ((processIteration + 1) < totalIteration && selectedIteration > processIteration && selectedReq[index]) { - return "CANCELLED"; - } - - if (!(res[selectedIteration] && res[selectedIteration][index]) && selectedReq[index]) { - return "CANCELLED"; - } - } - return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.size ? FormatBytes(parseInt(res[selectedIteration][index].response.size)) : "" : ""; - } - - function getStatusClassName(index: number): string { - if (cancelled) { - if (((processIteration + 1) < totalIteration) && (selectedIteration > processIteration)) { - return "runall-status-error"; - } - - if (!(res[selectedIteration] && res[selectedIteration][index])) { - return "runall-status-error"; - } - } - - if (!res[selectedIteration][index] || (selectedOption === 2 && processing)) { - return "runall-status-normal"; - } - - if (res[selectedIteration][index].response.isError) { - return "runall-status-error"; - } - - if (res[selectedIteration][index].response.status <= 399) { - return "runall-status-success"; - } - - return "runall-status-error"; - } - - function getClassName(index: number): string { - if (cancelled) { - if ((processIteration + 1) < totalIteration && selectedIteration > processIteration) { - return "runall-status-error"; - } - - if (!(res[selectedIteration] && res[selectedIteration][index])) { - return "runall-status-error"; - } - } - - if (!res[selectedIteration][index] || (processing && selectedOption === 2)) { - return "runall-status-normal"; - } - - if (res[selectedIteration][index].response.isError) { - return "runall-status-error"; - } - - return "runall-status-success"; - } - - function onRowClick(index: number) { - if (res[selectedIteration] && res[selectedIteration][index]) { - vscode.postMessage({ type: requestTypes.openRunRequest, data: { reqData: req[index], resData: res[selectedIteration][index], id: req[index].id, varId: varId, colId: colId, folderId: folderId } }); - } - } - - function onClickExportJson(e: any) { - e.preventDefault(); - let exportData = exportJson(req, selectedReq, res, sourceColName, selectedVariable, totalIteration); - vscode.postMessage({ type: requestTypes.exportRunTestJsonRequest, data: exportData, name: sourceColName }); - } - - function onClickExportCSV(e: any) { - e.preventDefault(); - let data = exportCSV(req, selectedReq, res, sourceColName, selectedVariable, totalIteration); - vscode.postMessage({ type: requestTypes.exportRunTestCSVRequest, data: data, name: sourceColName }); - } - - function getTestClassName(index: number) { - let total = refReq.current[index].tests.length - 1; - - if (!selectedReq[index]) { - return "runall-test-disabled"; - } - - if (total === 0) { - return "runall-test-normal"; - } - - if (res[index]) { - let pass = res[selectedIteration][index].testResults?.filter(item => item.result === true).length; - - if (total === pass) { - return "runall-test-pass"; - } - return "runall-test-fail"; - } else { - return "runall-test-normal"; - } - } - - function getTestResult(index: number) { - let total = refReq.current[index].tests.length - 1; - if (total === 0) { - return "No Tests"; - } - if (res[index]) { - let pass = res[selectedIteration][index].testResults?.filter(item => item.result === true).length; - return `${pass} / ${total}`; - } - return `${0}/${total}`; - } - - function onSelectChange(e: any, index: number) { - let localReq = [...selectedReq]; - localReq[index] = !localReq[index]; - setSelectedReq(localReq); - } - - function onSelect(e: any, index: number) { - e.preventDefault(); - e.stopPropagation(); - let localReq = [...req]; - var element = localReq[index]; - localReq.splice(index, 1); - localReq.splice(e.target.value, 0, element); - - - let localSelectedReq = [...selectedReq]; - var eleReq = localSelectedReq[index]; - localSelectedReq.splice(index, 1); - localSelectedReq.splice(e.target.value, 0, eleReq); - - - setReq(localReq); - setSelectedReq(localSelectedReq); - } - - function isDisabled() { - if (selectedReq) { - return selectedReq.filter(item => item === true).length === 0 ? true : false; - } - - return true; - } - - function onSelectedTab(tab: string) { - setSelectedTab(tab); - } - - function renderHeader() { - return ( - <> -
- {sourceColName.includes("\\") ? "Collection \\ Folder :" : "Collection :"} - {sourceColName} - {"Attached Variable :"} - {selectedVariable ? selectedVariable.name : "-"} -
- {getTabRender()} - - ); - } - - function getTabRender() { - return ( -
- {["Runner", "Settings"].map((tab) => { - return ( - - ); - })} -
- ); - } - - function renderBody() { - return ( -
- { - selectedTab === "Runner" - ? - renderRunAllTable() - : - renderSettings() - } -
- ); - } - - function setDelayValue(e: any) { - if (e.target.validity.valid) { - setRequsetDelay(e.target.value); - } - } - - function setDelayValueBlur(e: any) { - if (e.target.validity.valid) { - setRequsetDelay(e.target.value === "" ? 0 : (e.target.value > 300000 ? 300000 : e.target.value)); - } - } - - function setIterationValue(e: any) { - if (e.target.validity.valid) { - setTotalIteration(e.target.value); - if (e.target.value < 2) { - setIterationDelay(0); - } - } - } - - function setIterationValueBlur(e: any) { - if (e.target.validity.valid) { - setTotalIteration(e.target.value === "" || e.target.value === 0 ? 1 : (e.target.value > 10 ? 10 : e.target.value)); - if (e.target.value === "" || e.target.value < 2) { - setIterationDelay(0); - } - } - } - - function setIterationDelayValue(e: any) { - if (e.target.validity.valid) { - setIterationDelay(e.target.value); - } - } - - function setIterationDelayValueBlur(e: any) { - if (e.target.validity.valid) { - setIterationDelay(e.target.value === "" ? 0 : (e.target.value > 300000 ? 300000 : e.target.value)); - } - } - - function renderSettings() { - return ( - - ); - } - - function onPrevClick(value: number) { - if (value >= 0) { - setSelectedIteration(value); - } - } - - function onNextClick(value: number) { - if (value < totalIteration) { - setSelectedIteration(value); - } - } - - function renderRunAllTable() { - return ( - <> -
- - {(start || done) && } - {!start && !done && } -
-
- - - - -
-
- - - - - - - - - - - {selectedOption === 1 && } - - - - { - req.map((item, index) => { - return onRowClick(index)} className={selectedReq[index] ? "runall-enabled" : "runall-disabled"} > - - - - - - - - {selectedOption === 1 && } - ; - }) - } - -
PathMethodNameStatusDurationTests (Pass / Total)Order
- onSelectChange(e, index)} - /> - - {itemPaths ? itemPaths[item.id].split(";")[0] : ""} - - {item.method.toUpperCase()} - - {item.name} - - {(selectedOption === 1 && curIndex === index && processing) || (selectedOption === 2 && processing && selectedReq[index]) ? "loading..." : getResponseStatus(index)} - - {(selectedOption === 1 && curIndex === index && processing) || (selectedOption === 2 && processing && selectedReq[index]) ? "loading..." : getResponseDuration(index)} - - {(selectedOption === 1 && curIndex === index && processing) || (selectedOption === 2 && processing && selectedReq[index]) ? "loading..." : getTestResult(index)} - - -
-
- - ); - } - - function renderButton() { - return ( - <> - { - selectedTab === "Runner" ? -
- - -
- - {!isDisabled() && done &&
- JSON - CSV -
} -
-
- : - <> - } - - ); - } - - return ( -
-
Run Collection
-
- {renderHeader()} - { - loading === true ? - <> -
-
{"Loading...."}
- - : - <> - {renderBody()} - {renderButton()} - - } -
-
- ); + const [sourceColName, setSourceColName] = useState(""); + const [processing, setProcessing] = useState(false); + const [start, setStart] = useState(false); + const [done, setDone] = useState(false); + const [varId, setVarId] = useState(""); + const [colId, setColId] = useState(""); + const [folderId, setFolderId] = useState(""); + const [itemPaths, setItemPaths] = useState(null); + + const [loading, _setLoading] = useState(false); + const refLoading = useRef(loading); + const setLoading = (data: boolean) => { + refLoading.current = data; + _setLoading(refLoading.current); + }; + + const [req, _setReq] = useState([]); + const refReq = useRef(req); + const setReq = (data: IRequestModel[]) => { + refReq.current = data; + _setReq(refReq.current); + }; + + const [parentSettings, _setParentSettings] = useState(); + const refParentSettings = useRef(parentSettings); + const setParentSettings = (data: ISettings) => { + refParentSettings.current = data; + _setParentSettings(refParentSettings.current); + }; + + const [selectedVariable, _setSelectedVariable] = useState(); + const refSelectedVariable = useRef(selectedVariable); + const setSelectedVariable = (data: IVariable) => { + refSelectedVariable.current = data; + _setSelectedVariable(refSelectedVariable.current); + }; + + const [curIndex, _setCurIndex] = useState(0); + const refCurIndex = useRef(curIndex); + const setCurIndex = (data: number) => { + refCurIndex.current = data; + _setCurIndex(refCurIndex.current); + }; + + const [res, _setRes] = useState([[]]); + const refRes = useRef(res); + const setRes = (data: IReponseModel[][]) => { + refRes.current = data; + _setRes(refRes.current); + }; + + const [selectedReq, _setSelectedReq] = useState([]); + const refSelectedReq = useRef(selectedReq); + const setSelectedReq = (data: boolean[]) => { + refSelectedReq.current = data; + _setSelectedReq(refSelectedReq.current); + }; + + const [selectedTab, setSelectedTab] = useState("Runner"); + const [selectedOption, setSelectedOption] = useState(1); + + const [totalIteration, setTotalIteration] = useState(1); + const [requestDelay, setRequsetDelay] = useState(0); + const [iterationDelay, setIterationDelay] = useState(0); + + const [processIteration, _setProcessIteration] = useState(0); + const refProcessIteration = useRef(processIteration); + const setProcessIteration = (data: number) => { + refProcessIteration.current = data; + _setProcessIteration(refProcessIteration.current); + }; + + const [selectedIteration, setSelectedIteration] = useState(0); + + const [cancelled, setCancelled] = useState(false); + + useEffect(() => { + const colId = document.title.split("@:@")[1]; + const folderId = document.title.split("@:@")[2]; + const name = document.title.split("@:@")[3]; + const varId = document.title.split("@:@")[4]; + + setSourceColName(name.trim()); + setVarId(varId?.trim()); + setFolderId(folderId?.trim()); + setColId(colId?.trim()); + + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getCollectionsByIdResponse) { + setReq((event.data.collections as IRequestModel[])); + setItemPaths(event.data.paths); + } else if (event.data && event.data.type === responseTypes.apiResponse) { + setResponse(event.data); + setProcessing(false); + } else if (event.data && event.data.type === responseTypes.getVariableItemResponse) { + setSelectedVariable(event.data.data[0] as IVariable); + } else if (event.data && event.data.type === responseTypes.multipleApiResponse) { + if (event.data.output && event.data.output.length > 0) { + event.data.output.forEach((item, index: number) => { + let enabledIndex: number; + if (index === 0) { + enabledIndex = refSelectedReq.current.findIndex(item => item === true); + } else { + enabledIndex = getNextIndex(refCurIndex.current, refSelectedReq.current); + } + + setCurIndex(enabledIndex); + setResponse(item.value); + }); + setProcessing(false); + } + } else if (event.data && event.data.type === responseTypes.getParentSettingsResponse) { + setParentSettings(event.data.settings as ISettings); + setLoading(false); + } + }); + + vscode.postMessage({ type: requestTypes.getVariableItemRequest, data: { id: varId, isGlobal: varId ? false : true } }); + vscode.postMessage({ type: requestTypes.getCollectionsByIdRequest, data: { colId: colId, folderId: folderId, type: name.trim().includes("\\") ? "fol" : "col" } }); + setLoading(true); + }, []); + + function setResponse(data: any) { + let local = [...refRes.current]; + let newRes: IReponseModel = { + response: data.response, + headers: data.headers, + cookies: data.cookies + }; + if (refReq.current[refCurIndex.current].tests.length - 1 > 0) { + newRes.testResults = executeTests(refReq.current[refCurIndex.current].tests, newRes, refSelectedVariable.current.data); + } else { + newRes.testResults = []; + } + + if (refReq.current[refCurIndex.current].setvar.length - 1 > 0) { + let variable = setVariable(refSelectedVariable.current, refReq.current[refCurIndex.current].setvar, newRes); + setSelectedVariable(variable); + } + + if (!local[refProcessIteration.current]) { + local.push([]); + } + + local[refProcessIteration.current][refCurIndex.current] = newRes; + + if (refCurIndex.current === refReq.current.length - 1) { + vscode.postMessage({ type: requestTypes.updateVariableRequest, data: refSelectedVariable.current }); + } + setRes(local); + } + + function onSubmitClick() { + setStart(true); + setProcessing(true); + if (selectedOption === 1) { + sequentialRun(); + } else { + parallelRun(); + } + } + + function onCancelClick() { + setProcessing(false); + setStart(false); + setDone(true); + setCancelled(true); + } + + function sequentialRun() { + let enabledIndex = selectedReq.findIndex(item => item === true); + if (enabledIndex !== -1) { + setCurIndex(enabledIndex); + let id = itemPaths[req[enabledIndex].id].split(";")[1]; + if (id === colId) { + id = ""; + } + setProcessing(true); + vscode.postMessage({ type: requestTypes.apiRequest, data: { settings: parentSettings, reqData: req[enabledIndex], variableData: selectedVariable, colId: colId, folderId: id } }); + } + } + + function parallelRun() { + const { selectedRequest, selectedPaths } = getAllSelectedRequest(); + vscode.postMessage({ type: requestTypes.multipleApiRequest, data: { reqData: selectedRequest, variableData: selectedVariable ? selectedVariable.data : null, colId: colId, itemPaths: selectedPaths } }); + } + + function getAllSelectedRequest(): { selectedRequest: IRequestModel[], selectedPaths: any[] } { + let enabledIndex = selectedReq.findIndex(item => item === true); + if (enabledIndex === -1) { + return null; + } + + let selectedRequest: IRequestModel[] = []; + let selectedPaths = []; + for (let i = 0; i < selectedReq.length; i++) { + if (selectedReq[i]) { + selectedRequest.push(req[i]); + selectedPaths.push(itemPaths[i]); + } + } + + return { selectedRequest: selectedRequest, selectedPaths: selectedPaths }; + } + + function getNextIndex(currentInex: number, selectedReq: boolean[]) { + for (let i = currentInex + 1; i < selectedReq.length; i++) { + if (selectedReq[i]) { + return i; + } + } + + return -1; + } + + function nextParallelCall() { + const { selectedRequest, selectedPaths } = getAllSelectedRequest(); + setProcessing(true); + setProcessIteration(processIteration + 1); + vscode.postMessage({ type: requestTypes.multipleApiRequest, data: { reqData: selectedRequest, variableData: selectedVariable ? selectedVariable.data : null, colId: colId, itemPaths: selectedPaths } }); + } + + useEffect(() => { + if (!start) { + return; + } + + if (selectedOption === 2) { + if (res[processIteration].length === req.length && (processIteration + 1) < totalIteration) { + setTimeout(nextParallelCall, iterationDelay); + } + + if ((processIteration + 1) >= totalIteration) { + setStart(false); + setDone(true); + } + + return; + } else { + if (res[processIteration].length - 1 === curIndex) { + if (req.length - 1 > curIndex) { + let enabledIndex = getNextIndex(curIndex, selectedReq); + if (enabledIndex !== -1) { + let id = itemPaths[req[enabledIndex].id].split(";")[1]; + if (id === colId) { + id = ""; + } + setTimeout(() => { + setProcessing(true); + vscode.postMessage({ type: requestTypes.apiRequest, data: { reqData: req[enabledIndex], variableData: selectedVariable, colId: colId, folderId: id, settings: parentSettings } }); + setCurIndex(enabledIndex); + }, requestDelay); + + } else { + setStart(false); + setDone(true); + } + } else { + + if ((processIteration + 1) < totalIteration) { + setProcessIteration(processIteration + 1); + setTimeout(sequentialRun, iterationDelay); + return; + } + + setStart(false); + setDone(true); + } + } else { + setStart(false); + } + } + }, [res]); + + useEffect(() => { + if (req && req.length > 0 && selectedReq.length === 0) { + let selected = []; + req.forEach(() => { + selected.push(true); + }); + + setSelectedReq(selected); + } + }, [req]); + + function getResponseStatus(index: number) { + if (cancelled) { + if ((processIteration + 1) < totalIteration && selectedIteration > processIteration && selectedReq[index]) { + return "CANCELLED"; + } + + if (!(res[selectedIteration] && res[selectedIteration][index]) && selectedReq[index]) { + return "CANCELLED"; + } + + } + return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index].response.isError ? "ERROR" : (res[selectedIteration][index].response.status === 0 ? "" : (res[selectedIteration][index].response.status + " " + res[selectedIteration][index].response.statusText)) : ""; + } + + function getResponseDuration(index: number) { + if (cancelled) { + if ((processIteration + 1) < totalIteration && selectedIteration > processIteration && selectedReq[index]) { + return "CANCELLED"; + } + + if (!(res[selectedIteration] && res[selectedIteration][index]) && selectedReq[index]) { + return "CANCELLED"; + } + + } + return res[selectedIteration] && res[selectedIteration][index] ? res[selectedIteration][index]?.response.isError ? "0 ms" : GetResponseTime(res[selectedIteration][index].response.duration) : ""; + } + + function getStatusClassName(index: number): string { + if (cancelled) { + if (((processIteration + 1) < totalIteration) && (selectedIteration > processIteration)) { + return "runall-status-error"; + } + + if (!(res[selectedIteration] && res[selectedIteration][index])) { + return "runall-status-error"; + } + } + + if (!res[selectedIteration][index] || (selectedOption === 2 && processing)) { + return "runall-status-normal"; + } + + if (res[selectedIteration][index].response.isError) { + return "runall-status-error"; + } + + if (res[selectedIteration][index].response.status <= 399) { + return "runall-status-success"; + } + + return "runall-status-error"; + } + + function getClassName(index: number): string { + if (cancelled) { + if ((processIteration + 1) < totalIteration && selectedIteration > processIteration) { + return "runall-status-error"; + } + + if (!(res[selectedIteration] && res[selectedIteration][index])) { + return "runall-status-error"; + } + } + + if (!res[selectedIteration][index] || (processing && selectedOption === 2)) { + return "runall-status-normal"; + } + + if (res[selectedIteration][index].response.isError) { + return "runall-status-error"; + } + + return "runall-status-success"; + } + + function onRowClick(index: number) { + if (res[selectedIteration] && res[selectedIteration][index]) { + vscode.postMessage({ type: requestTypes.openRunRequest, data: { reqData: req[index], resData: res[selectedIteration][index], id: req[index].id, varId: varId, colId: colId, folderId: folderId } }); + } + } + + function onClickExportJson(e: any) { + e.preventDefault(); + let exportData = exportJson(req, selectedReq, res, sourceColName, selectedVariable, totalIteration); + vscode.postMessage({ type: requestTypes.exportRunTestJsonRequest, data: exportData, name: sourceColName }); + } + + function onClickExportCSV(e: any) { + e.preventDefault(); + let data = exportCSV(req, selectedReq, res, sourceColName, selectedVariable, totalIteration); + vscode.postMessage({ type: requestTypes.exportRunTestCSVRequest, data: data, name: sourceColName }); + } + + function getTestClassName(index: number) { + let total = refReq.current[index].tests.length - 1; + + if (!selectedReq[index]) { + return "runall-test-disabled"; + } + + if (total === 0) { + return "runall-test-normal"; + } + + if (res[index]) { + let pass = res[selectedIteration][index].testResults?.filter(item => item.result === true).length; + + if (total === pass) { + return "runall-test-pass"; + } + return "runall-test-fail"; + } else { + return "runall-test-normal"; + } + } + + function getTestResult(index: number) { + let total = refReq.current[index].tests.length - 1; + if (total === 0) { + return "No Tests"; + } + if (res[index]) { + let pass = res[selectedIteration][index].testResults?.filter(item => item.result === true).length; + return `${pass} / ${total}`; + } + return `${0}/${total}`; + } + + function onSelectChange(_e: any, index: number) { + let localReq = [...selectedReq]; + localReq[index] = !localReq[index]; + setSelectedReq(localReq); + } + + function onSelect(e: any, index: number) { + e.preventDefault(); + e.stopPropagation(); + let localReq = [...req]; + var element = localReq[index]; + localReq.splice(index, 1); + localReq.splice(e.target.value, 0, element); + + + let localSelectedReq = [...selectedReq]; + var eleReq = localSelectedReq[index]; + localSelectedReq.splice(index, 1); + localSelectedReq.splice(e.target.value, 0, eleReq); + + + setReq(localReq); + setSelectedReq(localSelectedReq); + } + + function isDisabled() { + if (selectedReq) { + return selectedReq.filter(item => item === true).length === 0 ? true : false; + } + + return true; + } + + function onSelectedTab(tab: string) { + setSelectedTab(tab); + } + + function renderHeader() { + return ( + <> +
+ {sourceColName.includes("\\") ? "Collection \\ Folder :" : "Collection :"} + {sourceColName} + {"Attached Variable :"} + {selectedVariable ? selectedVariable.name : "-"} +
+ {getTabRender()} + + ); + } + + function getTabRender() { + return ( +
+ {["Runner", "Settings"].map((tab) => { + return ( + + ); + })} +
+ ); + } + + function renderBody() { + return ( +
+ { + selectedTab === "Runner" + ? + renderRunAllTable() + : + renderSettings() + } +
+ ); + } + + function setDelayValue(e: any) { + if (e.target.validity.valid) { + setRequsetDelay(e.target.value); + } + } + + function setDelayValueBlur(e: any) { + if (e.target.validity.valid) { + setRequsetDelay(e.target.value === "" ? 0 : (e.target.value > 300000 ? 300000 : e.target.value)); + } + } + + function setIterationValue(e: any) { + if (e.target.validity.valid) { + setTotalIteration(e.target.value); + if (e.target.value < 2) { + setIterationDelay(0); + } + } + } + + function setIterationValueBlur(e: any) { + if (e.target.validity.valid) { + setTotalIteration(e.target.value === "" || e.target.value === 0 ? 1 : (e.target.value > 10 ? 10 : e.target.value)); + if (e.target.value === "" || e.target.value < 2) { + setIterationDelay(0); + } + } + } + + function setIterationDelayValue(e: any) { + if (e.target.validity.valid) { + setIterationDelay(e.target.value); + } + } + + function setIterationDelayValueBlur(e: any) { + if (e.target.validity.valid) { + setIterationDelay(e.target.value === "" ? 0 : (e.target.value > 300000 ? 300000 : e.target.value)); + } + } + + function renderSettings() { + return ( + + ); + } + + function onPrevClick(value: number) { + if (value >= 0) { + setSelectedIteration(value); + } + } + + function onNextClick(value: number) { + if (value < totalIteration) { + setSelectedIteration(value); + } + } + + function renderRunAllTable() { + return ( + <> +
+ + {(start || done) && } + {!start && !done && } +
+
+ + + + +
+
+ + + + + + + + + + + {selectedOption === 1 && } + + + + { + req.map((item, index) => { + return onRowClick(index)} className={selectedReq[index] ? "runall-enabled" : "runall-disabled"} > + + + + + + + + {selectedOption === 1 && } + ; + }) + } + +
PathMethodNameStatusDurationTests (Pass / Total)Order
+ onSelectChange(e, index)} + /> + + {itemPaths ? itemPaths[item.id].split(";")[0] : ""} + + {item.method.toUpperCase()} + + {item.name} + + {(selectedOption === 1 && curIndex === index && processing) || (selectedOption === 2 && processing && selectedReq[index]) ? "loading..." : getResponseStatus(index)} + + {(selectedOption === 1 && curIndex === index && processing) || (selectedOption === 2 && processing && selectedReq[index]) ? "loading..." : getResponseDuration(index)} + + {(selectedOption === 1 && curIndex === index && processing) || (selectedOption === 2 && processing && selectedReq[index]) ? "loading..." : getTestResult(index)} + + +
+
+ + ); + } + + function renderButton() { + return ( + <> + { + selectedTab === "Runner" ? +
+ + +
+ + {!isDisabled() && done &&
+ JSON + CSV +
} +
+
+ : + <> + } + + ); + } + + return ( +
+
🔁 Run Collection
+
+ {renderHeader()} + { + loading === true ? + <> +
+
{"Loading...."}
+ + : + <> + {renderBody()} + {renderButton()} + + } +
+
+ ); }; -export default RunAll; \ No newline at end of file +export default RunAll; diff --git a/src/fetch-client-ui/components/Collection/RunAll/runAllSettings.tsx b/src/fetch-client-ui/components/Collection/RunAll/runAllSettings.tsx index 28849d4..106fb6c 100644 --- a/src/fetch-client-ui/components/Collection/RunAll/runAllSettings.tsx +++ b/src/fetch-client-ui/components/Collection/RunAll/runAllSettings.tsx @@ -3,56 +3,56 @@ import "../style.css"; export const RunAllSettings = (props: any) => { - const { selectedOption, iteration, iterationDelay, delay } = props; - const { setSelectedOption, setIterationValue, setIterationDelayValue, setDelayValue, setIterationValueBlur, setDelayValueBlur, setIterationDelayValueBlur } = props; + const { selectedOption, iteration, iterationDelay, delay } = props; + const { setSelectedOption, setIterationValue, setIterationDelayValue, setDelayValue, setIterationValueBlur, setDelayValueBlur, setIterationDelayValueBlur } = props; - return ( - <> -
- setSelectedOption(1)} - /> Sequential Run - setSelectedOption(2)} - /> Parallel Run -
-
- - - -
-
- - - -
- {selectedOption !== 2 &&
- - - -
} - {selectedOption === 2 &&
} - - ); -}; \ No newline at end of file + return ( + <> +
+ setSelectedOption(1)} + /> Sequential Run + setSelectedOption(2)} + /> Parallel Run +
+
+ + + +
+
+ + + +
+ {selectedOption !== 2 &&
+ + + +
} + {selectedOption === 2 &&
} + + ); +}; diff --git a/src/fetch-client-ui/components/Collection/Settings/CollectionSettings.tsx b/src/fetch-client-ui/components/Collection/Settings/CollectionSettings.tsx index b6959e0..808db39 100644 --- a/src/fetch-client-ui/components/Collection/Settings/CollectionSettings.tsx +++ b/src/fetch-client-ui/components/Collection/Settings/CollectionSettings.tsx @@ -17,154 +17,154 @@ import "../style.css"; const CollectionSettings = () => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const { auth, preFetch, headers } = useSelector((state: IRootState) => state.requestData); + const { auth, preFetch, headers } = useSelector((state: IRootState) => state.requestData); - const [tabOptions] = useState(["Headers", "Authorization", "PreRequest"]); - const [selectedTab, setSelectedTab] = useState("Headers"); - const [type, setType] = useState(SettingsType.Collection); - const [colId, setColId] = useState(""); - const [folderId, setFolderId] = useState(""); - const [name, setName] = useState(""); - const [loading, setLoading] = useState(true); - const [isDone, setDone] = useState(false); - const [variableItem, setVariableItem] = useState(null); + const [tabOptions] = useState(["Headers", "Authorization", "PreRequest"]); + const [selectedTab, setSelectedTab] = useState("Headers"); + const [type, setType] = useState(SettingsType.Collection); + const [colId, setColId] = useState(""); + const [folderId, setFolderId] = useState(""); + const [name, setName] = useState(""); + const [loading, setLoading] = useState(true); + const [isDone, setDone] = useState(false); + const [variableItem, setVariableItem] = useState(null); - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getColSettingsResponse) { - let settings: ISettings; - if (event.data && event.data.data.settings) { - settings = event.data.data.settings; - } - else { - settings = InitialSettings; - if (type === SettingsType.Folder) { - settings.auth.authType = "inherit"; - } - } - dispatch(Actions.SetRequestAuthAction(settings.auth)); - settings.preFetch && dispatch(Actions.SetPreFetchAction(settings.preFetch)); - settings.headers && dispatch(Actions.SetRequestHeadersAction(settings.headers)); - } else if (event.data && event.data.type === responseTypes.saveColSettingsResponse) { - setDone(true); - } else if (event.data && event.data.type === responseTypes.getVariableItemResponse) { - setVariableItem(event.data.data[0] as IVariable); - } if (event.data && event.data.type === responseTypes.tokenResponse) { - let tokenResponse: IResponse = event.data.response as IResponse; - if (!tokenResponse.isError && tokenResponse.status === 200) { - const responseData = JSON.parse(tokenResponse.responseData); - let tokenName = auth.oauth.tokenName ? auth.oauth.tokenName : "access_token"; - dispatch(Actions.SetOAuthTokenAction(responseData[tokenName] ? responseData[tokenName] : "")); - } - } else if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { - let col: ICollection[] = event.data.collectionNames?.map((item: { value: any; name: any; }) => { - return { - id: item.value, - name: item.name - }; - }); - col.unshift({ id: "", name: "select" }); - dispatch(Actions.SetCollectionListAction(col)); - } - }); + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getColSettingsResponse) { + let settings: ISettings; + if (event.data && event.data.data.settings) { + settings = event.data.data.settings; + } + else { + settings = InitialSettings; + if (type === SettingsType.Folder) { + settings.auth.authType = "inherit"; + } + } + dispatch(Actions.SetRequestAuthAction(settings.auth)); + settings.preFetch && dispatch(Actions.SetPreFetchAction(settings.preFetch)); + settings.headers && dispatch(Actions.SetRequestHeadersAction(settings.headers)); + } else if (event.data && event.data.type === responseTypes.saveColSettingsResponse) { + setDone(true); + } else if (event.data && event.data.type === responseTypes.getVariableItemResponse) { + setVariableItem(event.data.data[0] as IVariable); + } if (event.data && event.data.type === responseTypes.tokenResponse) { + let tokenResponse: IResponse = event.data.response as IResponse; + if (!tokenResponse.isError && tokenResponse.status === 200) { + const responseData = JSON.parse(tokenResponse.responseData); + let tokenName = auth.oauth.tokenName ? auth.oauth.tokenName : "access_token"; + dispatch(Actions.SetOAuthTokenAction(responseData[tokenName] ? responseData[tokenName] : "")); + } + } else if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { + let col: ICollection[] = event.data.collectionNames?.map((item: { value: any; name: any; }) => { + return { + id: item.value, + name: item.name + }; + }); + col.unshift({ id: "", name: "select" }); + dispatch(Actions.SetCollectionListAction(col)); + } + }); - let splitData = document.title.split("@:@"); - const type = splitData[1]; - const colId = splitData[2]; - const folderId = splitData[3]; - const name = splitData[4]; - const varId = splitData[5]; - setType(type); - setColId(colId); - setFolderId(folderId); - setName(name); + let splitData = document.title.split("@:@"); + const type = splitData[1]; + const colId = splitData[2]; + const folderId = splitData[3]; + const name = splitData[4]; + const varId = splitData[5]; + setType(type); + setColId(colId); + setFolderId(folderId); + setName(name); - vscode.postMessage({ type: requestTypes.getVariableItemRequest, data: { id: varId, isGlobal: (varId !== "undefined" && varId !== undefined && varId !== "") ? false : true } }); - vscode.postMessage({ type: requestTypes.getColSettingsRequest, data: { colId: colId, folderId: folderId } }); - vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }); - }, []); + vscode.postMessage({ type: requestTypes.getVariableItemRequest, data: { id: varId, isGlobal: (varId !== "undefined" && varId !== undefined && varId !== "") ? false : true } }); + vscode.postMessage({ type: requestTypes.getColSettingsRequest, data: { colId: colId, folderId: folderId } }); + vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }); + }, []); - useEffect(() => { - if (variableItem && headers) { - setLoading(false); - } - }, [variableItem, headers]); + useEffect(() => { + if (variableItem && headers) { + setLoading(false); + } + }, [variableItem, headers]); - function onSelectedTab(tab: string) { - setSelectedTab(tab); - } + function onSelectedTab(tab: string) { + setSelectedTab(tab); + } - function getBody() { - return ( -
- {selectedTab === "Authorization" && variableItem && } - {selectedTab === "PreRequest" && } - {selectedTab === "Headers" && variableItem && } -
- ); - } + function getBody() { + return ( +
+ {selectedTab === "Authorization" && variableItem && } + {selectedTab === "PreRequest" && } + {selectedTab === "Headers" && variableItem && } +
+ ); + } - function getTabRender() { - return ( - tabOptions.map((tab) => { - return ( - - ); - }) - ); - } + function getTabRender() { + return ( + tabOptions.map((tab) => { + return ( + + ); + }) + ); + } - function onSubmitClick() { - let settings: ISettings = { - auth: { ...auth }, - preFetch: { ...preFetch }, - headers: [...headers] - }; + function onSubmitClick() { + let settings: ISettings = { + auth: { ...auth }, + preFetch: { ...preFetch }, + headers: [...headers] + }; - vscode.postMessage({ type: requestTypes.saveColSettingsRequest, data: { colId: colId, folderId: folderId, settings: settings } }); - } + vscode.postMessage({ type: requestTypes.saveColSettingsRequest, data: { colId: colId, folderId: folderId, settings: settings } }); + } - return ( -
-
{type} Settings
-
- {type} : - {name} -
-
- { - getTabRender() - } -
- { - loading ? - <> -
-
{"Loading...."}
- - : -
- { - getBody() - } -
- -
-
- {isDone && (Settings are updated successfully)} -
-
- } -
- ); + return ( +
+
⚙️ {type} Settings
+
+ {type} : + {name} +
+
+ { + getTabRender() + } +
+ { + loading ? + <> +
+
{"Loading...."}
+ + : +
+ { + getBody() + } +
+ +
+
+ {isDone && (Settings are updated successfully)} +
+
+ } +
+ ); }; -export default CollectionSettings; \ No newline at end of file +export default CollectionSettings; diff --git a/src/fetch-client-ui/components/Collection/consts.ts b/src/fetch-client-ui/components/Collection/consts.ts index 1d55c65..02218b7 100644 --- a/src/fetch-client-ui/components/Collection/consts.ts +++ b/src/fetch-client-ui/components/Collection/consts.ts @@ -1,4 +1,4 @@ export const SettingsType = { - Folder: "Folder", - Collection: "Collection" + Folder: "Folder", + Collection: "Collection" }; diff --git a/src/fetch-client-ui/components/Collection/helper.ts b/src/fetch-client-ui/components/Collection/helper.ts index 2eafffe..2e723f1 100644 --- a/src/fetch-client-ui/components/Collection/helper.ts +++ b/src/fetch-client-ui/components/Collection/helper.ts @@ -1,26 +1,26 @@ export function HandleColSelectionValidation(selectedCollection: string, colName: string, selectedFolder: string, folderName: string, errors: any, setErrors: any) { - if (selectedCollection === "") { - setErrors({ ...errors, "colSelect": "Please select/create the collection" }); - return false; - } + if (selectedCollection === "") { + setErrors({ ...errors, "colSelect": "Please select/create the collection" }); + return false; + } - if (selectedCollection === "0") { - if (!colName) { - setErrors({ ...errors, "colName": "Cannot be empty" }); - return false; - } - if (colName.toUpperCase().trim() === "DEFAULT") { - setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); - return false; - } - } + if (selectedCollection === "0") { + if (!colName) { + setErrors({ ...errors, "colName": "Cannot be empty" }); + return false; + } + if (colName.toUpperCase().trim() === "DEFAULT") { + setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); + return false; + } + } - if (selectedFolder === "0") { - if (!folderName) { - setErrors({ ...errors, "folderName": "Cannot be empty" }); - return false; - } - } + if (selectedFolder === "0") { + if (!folderName) { + setErrors({ ...errors, "folderName": "Cannot be empty" }); + return false; + } + } - return true; -} \ No newline at end of file + return true; +} diff --git a/src/fetch-client-ui/components/Collection/style.css b/src/fetch-client-ui/components/Collection/style.css index d23db2a..fad9063 100644 --- a/src/fetch-client-ui/components/Collection/style.css +++ b/src/fetch-client-ui/components/Collection/style.css @@ -1,29 +1,29 @@ .tab-menu { - padding : 10px; - background-color: transparent; - color : var(--text-color); - border : 0; - cursor : pointer; - margin-left : 10px; + padding : 10px; + background-color: transparent; + color : var(--text-color); + border : 0; + cursor : pointer; + margin-left : 10px; } .addto-header { - font-style : normal; - font-size : x-large; - padding-top: 30px; - text-align : center; + font-style : normal; + font-size : x-large; + padding-top: 20px; + text-align : center; } .addto-body { - padding-top: 50px; + padding-top: 50px; } .addto-body-settings { - padding-top: 15px; + padding-top: 15px; } .center { - margin: 0 auto; + margin: 0 auto; } .addto-table thead, @@ -31,575 +31,576 @@ .addto-table th, .addto-table tr, .addto-table td { - border: none !important; + border: none !important; } .addto-table { - width: 50%; + width: 50%; } .addto-table tr { - height: 60px; + height: 60px; } .addto-table td, .addto-table tr { - display: flex; + display: flex; } .addto-table tr:hover { - background-color: transparent !important; + background-color: transparent !important; } .block-display { - display: block !important; + display: block !important; } .col-1-size { - width: 250px; + width: 250px; } .col-2-size { - width: 100%; + width: 100%; } .details-col { - display : grid !important; - text-align: left !important; + display : grid !important; + text-align: left !important; } .details-row { - height: 130px !important; + height: 130px !important; } .button-panel { - text-align: center; + text-align: center; } .addto-label { - font-weight : 500; - color : var(--text-color); - padding-right: 20px; + font-weight : 500; + color : var(--text-color); + padding-right: 20px; } .addto-text { - color : var(--text-color); - font-size : 14px; - border : 1px solid var(--border-color); - background-color: transparent; - outline : 0; - height : 25px; - width : 100%; - padding : 5px 10px; + color : var(--text-color); + font-size : 14px; + border : 1px solid var(--border-color); + background-color: transparent; + outline : 0; + height : 25px; + width : 100%; + padding : 5px 10px; } .addto-text:focus { - outline: none; + outline: none; } .required-value { - border: 1px solid var(--required-color) !important; + border: 1px solid var(--required-color) !important; } .addto-select { - background-color: var(--background-color); - box-sizing : border-box; - color : var(--text-color); - font-size : small; - outline : none; - padding : 10px; - width : 100%; + background-color: var(--background-color); + box-sizing : border-box; + color : var(--text-color); + font-size : small; + outline : none; + padding : 10px; + width : 100%; } .addto-select:focus { - outline: none; + outline: none; } .addto-select:required:invalid { - color: var(--input-unchecked); + color: var(--input-unchecked); } .addto-select option[value=""][disabled] { - display: none; + display: none; } .addto-select option { - color : var(--text-color) !important; - background: var(--background-color) !important; + color : var(--text-color) !important; + background: var(--background-color) !important; } .col-2-size select { - height: 37px; + height: 37px; } .disabled { - color: var(--input-unchecked); + color: var(--input-unchecked); } .success-message { - color : #2fb12f !important;; - font-size: medium; + color : #2fb12f !important;; + font-size: medium; } .message-panel { - width : 50%; - margin : 0 auto; - padding-top: 15px; - text-align : center; + width : 50%; + margin : 0 auto; + padding-top: 15px; + text-align : center; } .addto-text:disabled, .addto-text[disabled], .addto-text:disabled:hover, .addto-text[disabled]:hover { - background-color: var(--list-hover-background-color); - cursor : not-allowed; + background-color: var(--list-hover-background-color); + cursor : not-allowed; } .error-select { - border: 1px solid red !important; + border: 1px solid red !important; } .runall-panel { - overflow: hidden; - height : 100%; + overflow: hidden; + height : 100%; } .runall-header { - font-style : normal; - font-size : x-large; - padding-top: 5px; - text-align : center; + font-style : normal; + font-size : x-large; + padding-top: 10px; + padding-bottom: 10px; + text-align : center; } .runall-body { - height: calc(100% - 70px); + height: calc(100% - 90px); } .runall-tbl { - width : 100%; - table-layout : fixed; - border-collapse: collapse; - text-align : center; + width : 100%; + table-layout : fixed; + border-collapse: collapse; + text-align : center; } .runall-tbl-panel { - margin-top : 20px; - width : 100%; - padding-left : 10px; - padding-right: 10px; - box-sizing : border-box; - overflow : auto; - max-height : calc(100% - 30px); + margin-top : 20px; + width : 100%; + padding-left : 10px; + padding-right: 10px; + box-sizing : border-box; + overflow : auto; + max-height : calc(100% - 30px); } .runall-tbl tbody, .runall-tbl td { - border : var(--border-size) solid var(--border-color); - border-top: none !important; + border : var(--border-size) solid var(--border-color); + border-top: none !important; } .runall-tbl th { - padding : 7px; - background-color: var(--list-hover-background-color); + padding : 7px; + background-color: var(--list-hover-background-color); } .runall-tbl>tbody>tr:first-child>td { - border-top : none !important; - border-right: var(--border-size) solid var(--border-color) !important; - border-left : var(--border-size) solid var(--border-color) !important; + border-top : none !important; + border-right: var(--border-size) solid var(--border-color) !important; + border-left : var(--border-size) solid var(--border-color) !important; } .runall-tbl-panel thead th { - position : sticky; - top : 0; - z-index : 1; - border-top : none !important; - border-bottom: none !important; - border-right : var(--border-size) solid var(--border-color) !important; - border-left : var(--border-size) solid var(--border-color) !important; - box-shadow : inset 0 1px 0 var(--border-color), inset 0 -1px 0 var(--border-color); - box-shadow : inset 0 1px 0 var(--border-color), inset 0 -1px 0 var(--border-color); + position : sticky; + top : 0; + z-index : 1; + border-top : none !important; + border-bottom: none !important; + border-right : var(--border-size) solid var(--border-color) !important; + border-left : var(--border-size) solid var(--border-color) !important; + box-shadow : inset 0 1px 0 var(--border-color), inset 0 -1px 0 var(--border-color); + box-shadow : inset 0 1px 0 var(--border-color), inset 0 -1px 0 var(--border-color); } .runall-tbl td { - padding: 10px; + padding: 10px; } .runall-col-name { - margin-left : 20px; - position : relative; - padding-bottom: 15px; + margin-left : 20px; + position : relative; + padding-bottom: 15px; } .runall-col-last-row { - padding-bottom: 0; + padding-bottom: 0; } .runall-method-label, .method-label { - width : 60px; - text-align : center; - height : 25px; - border-radius: 5px; - font-weight : bold; + width : 60px; + text-align : center; + height : 25px; + border-radius: 5px; + font-weight : bold; } .runall-method-label { - color: var(--text-color); + color: var(--text-color); } .method-label { - padding: 5px 5px 0; + padding: 5px 5px 0; } .runall-method-label { - padding: 3px; + padding: 3px; } .runall-col-0 { - width: 5%; + width: 5%; } .runall-col-1 { - width: 10%; + width: 10%; } .runall-col-2 { - width: 30%; + width: 30%; } .runall-col-5 { - width : 10%; - padding-left : 5px !important; - padding-right: 5px !important; + width : 10%; + padding-left : 5px !important; + padding-right: 5px !important; } .runall-label { - color : inherit; - word-break: break-word; + color : inherit; + word-break: break-word; } .runall-btn-panel { - margin-top: 15px; - text-align: center; + margin-top: 15px; + text-align: center; } .runall-btn { - width: fit-content; - margin-right: 10px; - height : 30px; - padding : 5px !important; + width: fit-content; + margin-right: 10px; + height : 30px; + padding : 5px !important; } .runall-cancel-btn { - width: 100px !important; + width: 100px !important; } .runall-status-success { - color : #4bb543; - font-weight: bolder; + color : #4bb543; + font-weight: bolder; } .runall-status-error { - color : #ea5b5b !important; - font-weight: bolder; + color : #ea5b5b !important; + font-weight: bolder; } .runall-tbl tbody { - cursor: pointer; + cursor: pointer; } /* Style The Dropdown Button */ .runall-dropbtn { - margin-right: 10px; - height : 30px; - padding : 5px !important; - width : max-content; + margin-right: 10px; + height : 30px; + padding : 5px !important; + width : max-content; } .runall-dropdown { - position: relative; - display : inline-block; + position: relative; + display : inline-block; } .runall-dropdown-content { - display : none; - position : fixed; - width : 125px; - min-width : 100px; - overflow : auto; - box-shadow : 10px 8px 16px 0 rgba(0, 0, 0, 0.4); - color : var(--text-color); - background-color: var(--background-color); - border : 1px solid var(--border-color); - z-index : 1; - position : absolute; - bottom : 100%; + display : none; + position : fixed; + width : 125px; + min-width : 100px; + overflow : auto; + box-shadow : 10px 8px 16px 0 rgba(0, 0, 0, 0.4); + color : var(--text-color); + background-color: var(--background-color); + border : 1px solid var(--border-color); + z-index : 1; + position : absolute; + bottom : 100%; } .runall-dropdown-content a { - padding : 5px 10px; - text-decoration : none; - cursor : pointer; - background-color: var(--background-color); - color : var(--text-color); - outline : none; - border : 3px solid transparent; - border-radius : 0; - text-align : left; - display : block; + padding : 5px 10px; + text-decoration : none; + cursor : pointer; + background-color: var(--background-color); + color : var(--text-color); + outline : none; + border : 3px solid transparent; + border-radius : 0; + text-align : left; + display : block; } .runall-dropdown-content a:hover { - background-color: var(--button-hover-color); - color : var(--button-text-color); + background-color: var(--button-hover-color); + color : var(--button-text-color); } .runall-test-normal, .runall-test-pass, .runall-test-fail, .runall-test-disabled { - color : #fff; - display : inline-block; - padding : 2px 8px; - font-weight : 500; - border-radius: 3px; - width : 100%; - word-break : break-word; - box-sizing : border-box; - font-size : 12px; + color : #fff; + display : inline-block; + padding : 2px 8px; + font-weight : 500; + border-radius: 3px; + width : 100%; + word-break : break-word; + box-sizing : border-box; + font-size : 12px; } .runall-test-normal { - background-color: #555; + background-color: #555; } .runall-test-pass { - background-color: green; + background-color: green; } .runall-test-fail { - background-color: red; + background-color: red; } .runall-test-disabled { - background-color: transparent; - color : var(--input-unchecked) !important; + background-color: transparent; + color : var(--input-unchecked) !important; } .addto-text:disabled, .addto-text[disabled], .addto-text:disabled:hover, .addto-text[disabled]:hover { - background-color: var(--list-hover-background-color); - cursor : not-allowed; + background-color: var(--list-hover-background-color); + cursor : not-allowed; } .runall-dropdown:hover .runall-dropdown-content { - display: block !important; + display: block !important; } .a-disabled { - pointer-events: none; - opacity : 0.7; + pointer-events: none; + opacity : 0.7; } .col-settings-panel-tabs { - display : flex; - justify-content: start; - border-bottom : 1px solid #555; + display : flex; + justify-content: start; + border-bottom : 1px solid #555; } .col-settings-panel { - height : calc(100% - 150px); - width : 98%; - display: block; - padding: 10px; + height : calc(100% - 150px); + width : 98%; + display: block; + padding: 10px; } .col-settings-header { - font-style : normal; - font-size : x-large; - padding-top: 10px; - text-align : center; + font-style : normal; + font-size : x-large; + padding-top: 10px; + text-align : center; } .col-settings-name-panel { - padding : 10px 210px 20px 10px; - font-size: medium; + padding : 10px 210px 20px 10px; + font-size: medium; } .col-settings-body { - font-size : var(--font-size); - max-height : calc(100% - 60px); - overflow : auto; - padding-top: 10px; - padding-bottom: 10px; + font-size : var(--font-size); + max-height : calc(100% - 60px); + overflow : auto; + padding-top: 10px; + padding-bottom: 10px; } .addto-title-label { - color : var(--text-color); - padding-right: 20px; + color : var(--text-color); + padding-right: 20px; } .submit-button { - background-color: var(--button-background-color); - border : 0; - border-radius : 3px; - color : var(--button-text-color); - cursor : pointer; - display : inline-block; - font-weight : bold; - outline : none; - width : 75px; - height : 30px; + background-color: var(--button-background-color); + border : 0; + border-radius : 3px; + color : var(--button-text-color); + cursor : pointer; + display : inline-block; + font-weight : bold; + outline : none; + width : 75px; + height : 30px; } .submit-button:disabled, .submit-button[disabled] { - background-color: #ccc; - color : #666; - cursor : not-allowed; + background-color: #ccc; + color : #666; + cursor : not-allowed; } .order-btn-panel { - display: flex; + display: flex; } .order-btn { - background-color: transparent; - outline : none; - border : 0; - color : var(--button-text-color); - font-size : large; - cursor : pointer; + background-color: transparent; + outline : none; + border : 0; + color : var(--button-text-color); + font-size : large; + cursor : pointer; } .runall-order-select { - background-color: transparent; - color : var(--button-text-color); - width : 95%; - font-size : large + background-color: transparent; + color : var(--button-text-color); + width : 95%; + font-size : large } select.runall-order-select option { - background-color: var(--background-color); - color : var(--button-text-color); + background-color: var(--background-color); + color : var(--button-text-color); } .runall-disabled { - color: var(--input-unchecked) !important; + color: var(--input-unchecked) !important; } .runall-enabled { - color: var(--text-color) !important; + color: var(--text-color) !important; } .runall-btn:disabled, .runall-btn[disabled], .runall-dropbtn:disabled, .runall-dropbtn[disabled] { - background-color: #ccc; - color : #666; - cursor : not-allowed; + background-color: #ccc; + color : #666; + cursor : not-allowed; } .runall-order-select:disabled, .runall-order-select[disabled] { - color: var(--input-unchecked) !important; + color: var(--input-unchecked) !important; } .runall-tab-items-panel { - max-height: calc(100% - 95px); - overflow-y: auto; - overflow-x: hidden; - cursor : pointer; + max-height: calc(100% - 95px); + overflow-y: auto; + overflow-x: hidden; + cursor : pointer; } .runall-settings-option { - padding: 20px 10px 10px 10px; + padding: 20px 10px 10px 10px; } .settings-option { - margin-left: 20px; + margin-left: 20px; } .runall-settings-delay-panel { - margin-left: 15px; + margin-left: 15px; } .runall-delay-text { - width: 100px; + width: 100px; } .runall-settings-label { - width : 165px; - display: inline-block; + width : 165px; + display: inline-block; } .runall-settings-info-label { - margin-left: 5px; - cursor : pointer; + margin-left: 5px; + cursor : pointer; } .runall-delay-text:disabled, .runall-delay-text[disabled], .runall-delay-text:disabled:hover, .runall-delay-text[disabled]:hover { - background-color: var(--list-hover-background-color); - cursor : not-allowed; + background-color: var(--list-hover-background-color); + cursor : not-allowed; } .runall-iteration-selector-panel { - float : right; - margin-bottom: 10px; - margin-right : 12px; + float : right; + margin-bottom: 10px; + margin-right : 12px; } .runall-iteration-prevButton { - background-color: var(--button-background-color); - border : 1px; - border-radius : 3px 0 0 3px; - color : var(--button-text-color); - cursor : pointer; - display : inline-block; - height : 20px; - margin-left : 10px; + background-color: var(--button-background-color); + border : 1px; + border-radius : 3px 0 0 3px; + color : var(--button-text-color); + cursor : pointer; + display : inline-block; + height : 20px; + margin-left : 10px; } .runall-iteration-nextButton { - background-color: var(--button-background-color); - border : 1px; - border-radius : 0 3px 3px 0; - color : var(--button-text-color); - cursor : pointer; - display : inline-block; - height : 20px; + background-color: var(--button-background-color); + border : 1px; + border-radius : 0 3px 3px 0; + color : var(--button-text-color); + cursor : pointer; + display : inline-block; + height : 20px; } .runall-iteration-prevButton:disabled, .runall-iteration-prevButton[disabled], .runall-iteration-nextButton:disabled, .runall-iteration-nextButton[disabled] { - background-color: #ccc; - color : #666; - cursor : not-allowed; + background-color: #ccc; + color : #666; + cursor : not-allowed; } .runall-iteration-text { - width : 30px; - height : 14px; - text-align: center; + width : 30px; + height : 14px; + text-align: center; } .runall-iteration-process-text { - float : left; - margin : 10px; - padding-left: 5px; + float : left; + margin : 10px; + padding-left: 5px; } .table-padding-left { - padding-left : 10px; -} \ No newline at end of file + padding-left : 10px; +} diff --git a/src/fetch-client-ui/components/Common/Autocomplete/Autocomplete.tsx b/src/fetch-client-ui/components/Common/Autocomplete/Autocomplete.tsx index 6433018..93f598c 100644 --- a/src/fetch-client-ui/components/Common/Autocomplete/Autocomplete.tsx +++ b/src/fetch-client-ui/components/Common/Autocomplete/Autocomplete.tsx @@ -4,135 +4,135 @@ import { TextEditor } from "../TextEditor/TextEditor"; import "./style.css"; export interface IAutocompleteProps { - id: string; - value: string; - suggestions: string[]; - className?: string; - disabled: boolean; - onSelect: any; - placeholder: string; - selectedVariable: IVariable; + id: string; + value: string; + suggestions: string[]; + className?: string; + disabled: boolean; + onSelect: any; + placeholder: string; + selectedVariable: IVariable; } export const Autocomplete = (props: IAutocompleteProps) => { - const [activeSuggestion, setactiveSuggestion] = useState(0); - const [filteredSuggestions, setFilteredSuggestions] = useState([]); - const [showSuggestions, setShowSuggestions] = useState(false); - const [topPosition, setTopPosition] = useState(""); - const [width, setWidth] = useState(""); - - const styles = { - topStyle: { - top: topPosition + "px", - width: width + "px", - zIndex: 1 - } as React.CSSProperties, - }; - - function onFocus() { - let element = document.getElementById(props.id); - if (element) { - let rect = element.getBoundingClientRect(); - setTopPosition(rect.bottom.toString()); - setWidth(element.offsetWidth.toString()); - } - } - - const onChange = (value: string, existingValue: string) => { - if (value === existingValue) { - return; - } - - const { suggestions } = props; - - const filteredSuggestions = suggestions.filter( - suggestion => - suggestion.toLowerCase().indexOf(value.toLowerCase()) > -1 - ); - - setactiveSuggestion(0); - setFilteredSuggestions(filteredSuggestions); - setShowSuggestions(true); - props.onSelect(value); - }; - - const onMouseDown = (e: any) => { - e.preventDefault(); - setactiveSuggestion(0); - setFilteredSuggestions([]); - setShowSuggestions(false); - props.onSelect(e.currentTarget.innerText); - }; - - const onKeyDown = (keyCode: number) => { - - if (keyCode === 13) { - setactiveSuggestion(0); - setShowSuggestions(false); - props.onSelect(filteredSuggestions[activeSuggestion]); - } else if (keyCode === 38) { - if (activeSuggestion === 0) { - return; - } - setactiveSuggestion(activeSuggestion - 1); - } - else if (keyCode === 40) { - if (activeSuggestion - 1 === filteredSuggestions.length) { - return; - } - setactiveSuggestion(activeSuggestion + 1); - } - }; - - function suggestionsListComponentRender() { - let suggestionsListComponent: any; - - if (showSuggestions && props.value) { - if (filteredSuggestions.length) { - suggestionsListComponent = ( -
    - {filteredSuggestions.map((suggestion, index) => { - return ( -
  • - {suggestion} -
  • - ); - })} -
- ); - } else { - suggestionsListComponent = ( - <> - ); - } - } - - return suggestionsListComponent; - } - - function onBlurEvent() { - setactiveSuggestion(0); - setShowSuggestions(false); - } - - return ( - <> -
- { - props.selectedVariable.id && item.key)} - placeholder={props.placeholder} - onChange={(val) => onChange(val, props.value)} - value={props.value} - onKeyPress={onKeyDown} - onBlur={onBlurEvent} - disabled={props.disabled} - onFocus={onFocus} - focus={false} - /> - } -
- {suggestionsListComponentRender()} - - ); -}; \ No newline at end of file + const [activeSuggestion, setactiveSuggestion] = useState(0); + const [filteredSuggestions, setFilteredSuggestions] = useState([]); + const [showSuggestions, setShowSuggestions] = useState(false); + const [topPosition, setTopPosition] = useState(""); + const [width, setWidth] = useState(""); + + const styles = { + topStyle: { + top: topPosition + "px", + width: width + "px", + zIndex: 1 + } as React.CSSProperties, + }; + + function onFocus() { + let element = document.getElementById(props.id); + if (element) { + let rect = element.getBoundingClientRect(); + setTopPosition(rect.bottom.toString()); + setWidth(element.offsetWidth.toString()); + } + } + + const onChange = (value: string, existingValue: string) => { + if (value === existingValue) { + return; + } + + const { suggestions } = props; + + const filteredSuggestions = suggestions.filter( + suggestion => + suggestion.toLowerCase().indexOf(value.toLowerCase()) > -1 + ); + + setactiveSuggestion(0); + setFilteredSuggestions(filteredSuggestions); + setShowSuggestions(true); + props.onSelect(value); + }; + + const onMouseDown = (e: any) => { + e.preventDefault(); + setactiveSuggestion(0); + setFilteredSuggestions([]); + setShowSuggestions(false); + props.onSelect(e.currentTarget.innerText); + }; + + const onKeyDown = (keyCode: number) => { + + if (keyCode === 13) { + setactiveSuggestion(0); + setShowSuggestions(false); + props.onSelect(filteredSuggestions[activeSuggestion]); + } else if (keyCode === 38) { + if (activeSuggestion === 0) { + return; + } + setactiveSuggestion(activeSuggestion - 1); + } + else if (keyCode === 40) { + if (activeSuggestion - 1 === filteredSuggestions.length) { + return; + } + setactiveSuggestion(activeSuggestion + 1); + } + }; + + function suggestionsListComponentRender() { + let suggestionsListComponent: any; + + if (showSuggestions && props.value) { + if (filteredSuggestions.length) { + suggestionsListComponent = ( +
    + {filteredSuggestions.map((suggestion, index) => { + return ( +
  • + {suggestion} +
  • + ); + })} +
+ ); + } else { + suggestionsListComponent = ( + <> + ); + } + } + + return suggestionsListComponent; + } + + function onBlurEvent() { + setactiveSuggestion(0); + setShowSuggestions(false); + } + + return ( + <> +
+ { + props.selectedVariable.id && item.key)} + placeholder={props.placeholder} + onChange={(val) => onChange(val, props.value)} + value={props.value} + onKeyPress={onKeyDown} + onBlur={onBlurEvent} + disabled={props.disabled} + onFocus={onFocus} + focus={false} + /> + } +
+ {suggestionsListComponentRender()} + + ); +}; diff --git a/src/fetch-client-ui/components/Common/Autocomplete/style.css b/src/fetch-client-ui/components/Common/Autocomplete/style.css index a4933ff..d83a7df 100644 --- a/src/fetch-client-ui/components/Common/Autocomplete/style.css +++ b/src/fetch-client-ui/components/Common/Autocomplete/style.css @@ -1,25 +1,25 @@ .suggestions { - background-color: var(--background-color); - border-bottom: none; - border-top: none; - box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.4); - color: var(--text-color); - list-style: none; - margin-top: 0; - max-height: 200px; - overflow-y: auto; - padding-left: 0; - position: absolute; + background-color: var(--background-color); + border-bottom: none; + border-top: none; + box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.4); + color: var(--text-color); + list-style: none; + margin-top: 0; + max-height: 200px; + overflow-y: auto; + padding-left: 0; + position: absolute; } .suggestions li { - background-color: var(--background-color); - color: var(--text-color); - cursor: pointer; - padding: 10px; + background-color: var(--background-color); + color: var(--text-color); + cursor: pointer; + padding: 10px; } .suggestion-active, .suggestions li:hover { - background-color: var(--list-hover-background-color) !important; -} \ No newline at end of file + background-color: var(--list-hover-background-color) !important; +} diff --git a/src/fetch-client-ui/components/Common/CodeGenerator/consts.ts b/src/fetch-client-ui/components/Common/CodeGenerator/consts.ts index 3df70ed..3aba8a6 100644 --- a/src/fetch-client-ui/components/Common/CodeGenerator/consts.ts +++ b/src/fetch-client-ui/components/Common/CodeGenerator/consts.ts @@ -1,64 +1,64 @@ export const codeSnippetLangunages = [ - { - name: "C", value: "c", options: [ - { name: "LibCurl", value: "libcurl" } - ] - }, - { - name: "C#", value: "csharp", options: [ - { name: "Http Client", value: "httpclient" }, - { name: "Rest Sharp", value: "restsharp" } - ] - }, - { - name: "Go", value: "go", options: [ - { name: "Native", value: "native" } - ] - }, - { - name: "Java", value: "java", options: [ - { name: "AsyncHttp", value: "asynchttp" }, - { name: "Unirest", value: "unirest" }, - { name: "OkHttp", value: "okhttp" }, - { name: "NetHttp", value: "nethttp" } - ] - }, - { - name: "JavaScript", value: "javascript", options: [ - { name: "Axios", value: "axios" }, - { name: "Fetch", value: "fetch" }, - { name: "jQuery", value: "jquery" }, - { name: "XMLHttpRequest", value: "xhr" } - ] - }, - { - name: "Node", value: "node", options: [ - { name: "Axios", value: "axios" }, - { name: "Fetch", value: "fetch" }, - { name: "Native", value: "native" }, - { name: "Request", value: "request" }, - { name: "Unirest", value: "unirest" } - ] - }, - { - name: "PHP", value: "php", options: [ - { name: "Curl", value: "curl" }, - { name: "Fetch", value: "fetch" }, - { name: "pecl/http v1", value: "http1" }, - { name: "pecl/http v2", value: "http2" } - ] - }, - { - name: "Python", value: "python", options: [ - { name: "Python3 - http.client", value: "python3" }, - { name: "Requests", value: "requests" }, - ] - }, - { - name: "Shell", value: "shell", options: [ - { name: "cURL", value: "curl" }, - { name: "HTTPie", value: "httpie" }, - { name: "Wget", value: "wget" }, - ] - } -]; \ No newline at end of file + { + name: "C", value: "c", options: [ + { name: "LibCurl", value: "libcurl" } + ] + }, + { + name: "C#", value: "csharp", options: [ + { name: "Http Client", value: "httpclient" }, + { name: "Rest Sharp", value: "restsharp" } + ] + }, + { + name: "Go", value: "go", options: [ + { name: "Native", value: "native" } + ] + }, + { + name: "Java", value: "java", options: [ + { name: "AsyncHttp", value: "asynchttp" }, + { name: "Unirest", value: "unirest" }, + { name: "OkHttp", value: "okhttp" }, + { name: "NetHttp", value: "nethttp" } + ] + }, + { + name: "JavaScript", value: "javascript", options: [ + { name: "Axios", value: "axios" }, + { name: "Fetch", value: "fetch" }, + { name: "jQuery", value: "jquery" }, + { name: "XMLHttpRequest", value: "xhr" } + ] + }, + { + name: "Node", value: "node", options: [ + { name: "Axios", value: "axios" }, + { name: "Fetch", value: "fetch" }, + { name: "Native", value: "native" }, + { name: "Request", value: "request" }, + { name: "Unirest", value: "unirest" } + ] + }, + { + name: "PHP", value: "php", options: [ + { name: "Curl", value: "curl" }, + { name: "Fetch", value: "fetch" }, + { name: "pecl/http v1", value: "http1" }, + { name: "pecl/http v2", value: "http2" } + ] + }, + { + name: "Python", value: "python", options: [ + { name: "Python3 - http.client", value: "python3" }, + { name: "Requests", value: "requests" }, + ] + }, + { + name: "Shell", value: "shell", options: [ + { name: "cURL", value: "curl" }, + { name: "HTTPie", value: "httpie" }, + { name: "Wget", value: "wget" }, + ] + } +]; diff --git a/src/fetch-client-ui/components/Common/CodeGenerator/index.tsx b/src/fetch-client-ui/components/Common/CodeGenerator/index.tsx index d495038..e5a79f0 100644 --- a/src/fetch-client-ui/components/Common/CodeGenerator/index.tsx +++ b/src/fetch-client-ui/components/Common/CodeGenerator/index.tsx @@ -1,211 +1,214 @@ -import React from "react"; -import HTTPSnippet = require("httpsnippet"); -import { useEffect, useState } from "react"; +import React, { useEffect, useState } from "react"; import { useSelector } from "react-redux"; +import { replaceValueWithVariable } from "../../../../utils/helper"; import { IRootState } from "../../../reducer/combineReducer"; +import { IRequestModel } from "../../RequestUI/redux/types"; import { MonacoEditor } from "../Editor"; import { codeSnippetLangunages } from "./consts"; import "./style.css"; -import { IRequestModel } from "../../RequestUI/redux/types"; -import { replaceValueWithVariable } from "../../../../utils/helper"; +import HTTPSnippet = require("httpsnippet"); const CodeSnippetGenerator = () => { - const [language, setLang] = useState("csharp"); - const [option, setOption] = useState("httpclient"); - const [codeSnippet, setCodeSnippet] = useState(""); - - const requestData = useSelector((state: IRootState) => state.requestData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - - function onSelectedLanguage(e: React.ChangeEvent) { - setLang(e.target.value); - setOption(codeSnippetLangunages.filter(l => l.value === e.target.value)[0].options[0].value); - } - - function onSelectedOption(e: React.ChangeEvent) { - setOption(e.target.value); - } - - function getRawContentType(rawType: string): string { - let contentTypes = { - json: "application/json", - html: "text/html", - xml: "application/xml", - text: "text/plain", - }; - - return contentTypes[rawType]; - } - - useEffect(() => { - if (!requestData.url) { - return; - } - - let request: IRequestModel; - let varData = {}; - - if (selectedVariable.data.length > 0) { - selectedVariable.data.forEach(item => { - varData[item.key] = item.value; - }); - let copy = JSON.parse(JSON.stringify(requestData)); - request = replaceValueWithVariable(copy, varData); - } else { - request = requestData; - } - - request.url = requestData.url.startsWith("http://") || requestData.url.startsWith("https:// ") ? requestData.url : "https://" + requestData.url; - - let body: any; - - if (request.body.bodyType === "formdata") { - let params = []; - request.body.formdata.forEach(data => { - if (data.key && data.isChecked) { - if (data.type === "File") { - params.push({ "name": data.key, fileName: data.value }); - } else { - params.push({ "name": data.key, "value": data.value }); - } - } - }); - body = { - "mimeType": "multipart/form-data", - "params": params, - }; - } else if (request.body.bodyType === "formurlencoded") { - let params = []; - request.body.urlencoded.forEach(data => { - if (data.key && data.isChecked) { - params.push({ "name": data.key, "value": data.value }); - } - }); - body = { - "mimeType": "application/x-www-form-urlencoded", - "params": params, - }; - } else if (request.body.bodyType === "raw") { - body = { - "mimeType": getRawContentType(request.body.raw.lang), - "text": request.body.raw.data, - }; - } else if (request.body.bodyType === "binary") { - if (request.body.binary.data.length > 0) { - let contentType = request.headers.find(item => item.key.toUpperCase() === "Content-Type"); - body = { - "mimeType": contentType ? contentType.key : "application/octet-stream", - "text": request.body.binary.data - }; - } else { - body = {}; - } - } else if (request.body.bodyType === "graphql") { - body = { - "mimeType": "application/json", - "text": JSON.stringify({ - query: request.body.graphql.query, - variables: request.body.graphql.variables, - }), - }; - } else { - body = {}; - } - - let headers = []; - request.headers.forEach((header) => { - if (header.key) { - headers.push({ "name": header.key, "value": header.value }); - } - }); - - let value: any; - - try { - var snippet = new HTTPSnippet({ - method: request.method, - url: request.url, - httpVersion: "", - cookies: [], - headers: headers, - queryString: [], - headersSize: -1, - bodySize: -1, - postData: body - }); - value = snippet.convert(language, option); - } - catch (err) { - value = ""; - console.log("error", err); - } - - let str = isString(value) ? value as string : ""; - - setCodeSnippet(str); - - }, [language, option, requestData]); - - function isString(val: any): boolean { - if (typeof val === 'string' || val instanceof String) { - return true; - } - else { - return false; - } - } - - return ( -
-
- {codeSnippet && <>
-
- - -
-
- - -
-
-
- -
- - } -
- ); + const [language, setLang] = useState("csharp"); + const [option, setOption] = useState("httpclient"); + const [codeSnippet, setCodeSnippet] = useState(""); + + const requestData = useSelector((state: IRootState) => state.requestData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + + function onSelectedLanguage(e: React.ChangeEvent) { + setLang(e.target.value); + setOption(codeSnippetLangunages.filter(l => l.value === e.target.value)[0].options[0].value); + } + + function onSelectedOption(e: React.ChangeEvent) { + setOption(e.target.value); + } + + function getRawContentType(rawType: string): string { + let contentTypes = { + json: "application/json", + html: "text/html", + xml: "application/xml", + text: "text/plain", + }; + + return contentTypes[rawType]; + } + + useEffect(() => { + if (!requestData.url) { + return; + } + + let request: IRequestModel; + let varData = {}; + + if (selectedVariable.data.length > 0) { + selectedVariable.data.forEach(item => { + varData[item.key] = item.value; + }); + let copy = JSON.parse(JSON.stringify(requestData)); + request = replaceValueWithVariable(copy, varData); + } else { + request = requestData; + } + + if (requestData.url.startsWith("http://") || requestData.url.startsWith("https://")) { + request.url = requestData.url; + } else { + request.url = "https://" + requestData.url; + } + + let body: any; + + if (request.body.bodyType === "formdata") { + let params = []; + request.body.formdata.forEach(data => { + if (data.key && data.isChecked) { + if (data.type === "File") { + params.push({ "name": data.key, fileName: data.value }); + } else { + params.push({ "name": data.key, "value": data.value }); + } + } + }); + body = { + "mimeType": "multipart/form-data", + "params": params, + }; + } else if (request.body.bodyType === "formurlencoded") { + let params = []; + request.body.urlencoded.forEach(data => { + if (data.key && data.isChecked) { + params.push({ "name": data.key, "value": data.value }); + } + }); + body = { + "mimeType": "application/x-www-form-urlencoded", + "params": params, + }; + } else if (request.body.bodyType === "raw") { + body = { + "mimeType": getRawContentType(request.body.raw.lang), + "text": request.body.raw.data, + }; + } else if (request.body.bodyType === "binary") { + if (request.body.binary.data.length > 0) { + let contentType = request.headers.find(item => item.key.toUpperCase() === "Content-Type"); + body = { + "mimeType": contentType ? contentType.key : "application/octet-stream", + "text": request.body.binary.data + }; + } else { + body = {}; + } + } else if (request.body.bodyType === "graphql") { + body = { + "mimeType": "application/json", + "text": JSON.stringify({ + query: request.body.graphql.query, + variables: request.body.graphql.variables, + }), + }; + } else { + body = {}; + } + + let headers = []; + request.headers.forEach((header) => { + if (header.key) { + headers.push({ "name": header.key, "value": header.value }); + } + }); + + let value: any; + + try { + var snippet = new HTTPSnippet({ + method: request.method, + url: request.url, + httpVersion: "", + cookies: [], + headers: headers, + queryString: [], + headersSize: -1, + bodySize: -1, + postData: body + }); + value = snippet.convert(language, option); + } + catch (err) { + value = ""; + console.log("error", err); + } + + let str = isString(value) ? value as string : ""; + + setCodeSnippet(str); + + }, [language, option, requestData]); + + function isString(val: any): boolean { + if (typeof val === 'string' || val instanceof String) { + return true; + } + else { + return false; + } + } + + return ( +
+
+ {codeSnippet && <>
+
+ + +
+
+ + +
+
+
+ +
+ + } +
+ ); }; -export default CodeSnippetGenerator; \ No newline at end of file +export default CodeSnippetGenerator; diff --git a/src/fetch-client-ui/components/Common/CodeGenerator/style.css b/src/fetch-client-ui/components/Common/CodeGenerator/style.css index 823a8d3..5960734 100644 --- a/src/fetch-client-ui/components/Common/CodeGenerator/style.css +++ b/src/fetch-client-ui/components/Common/CodeGenerator/style.css @@ -1,42 +1,42 @@ .code-snippet-editor-panel { - height: calc(100% - 50px); + height: calc(100% - 50px); } .code-snippet-panel { - height: calc(100% - 15px); + height: calc(100% - 15px); } .code-snippet-select-panel { - display: flex; - padding: 10px; + display: flex; + padding: 10px; } .code-snippet-lang-panel { - margin-right: 10px; + margin-right: 10px; } .code-snippet-lang-label, .code-snippet-opt-label { - margin-right: 10px; + margin-right: 10px; } .code-snippet-lang-select, .code-snippet-opt-select { - height: 25px; - width: 110px; - outline: none; - border-radius: 3px; - background-color: var(--background-color); - color: var(--text-color); + height: 25px; + width: 110px; + outline: none; + border-radius: 3px; + background-color: var(--background-color); + color: var(--text-color); } .code-snippet-lang-select:focus, .code-snippet-opt-select:focus { - outline: none; + outline: none; } .code-snippet-lang-select option, .code-snippet-opt-select option { - background-color: var(--background-color); - color: var(--text-color); -} \ No newline at end of file + background-color: var(--background-color); + color: var(--text-color); +} diff --git a/src/fetch-client-ui/components/Common/Consts/sysVariables.ts b/src/fetch-client-ui/components/Common/Consts/sysVariables.ts index f8a1067..39d639d 100644 --- a/src/fetch-client-ui/components/Common/Consts/sysVariables.ts +++ b/src/fetch-client-ui/components/Common/Consts/sysVariables.ts @@ -2,99 +2,101 @@ import moment from 'moment-mini'; import { v4 as uuidv4 } from 'uuid'; export const SysVariables = [ - "{{#num}}", - "{{#num, min, max}}", - "{{#str}}", - "{{#strspl}}", - "{{#strnum}}", - "{{#char}}", - "{{#rdate}}", - "{{#date}}", - "{{#dateISO}}", - "{{#date, 'format'}}", - "{{#email}}", - "{{#guid}}", - "{{#bool}}" + "{{#num}}", + "{{#num, min, max}}", + "{{#str}}", + "{{#strspl}}", + "{{#strnum}}", + "{{#char}}", + "{{#rdate}}", + "{{#date}}", + "{{#dateISO}}", + "{{#date, 'format'}}", + "{{#email}}", + "{{#guid}}", + "{{#bool}}" ]; export function checkSysVariable(variable: string): string { - if ((variable.startsWith("{{#num,") || variable.startsWith("{{#date,")) && variable.endsWith("}}")) { - return variable.replace("{{", "").replace("}}", "").replace("#", "").trim(); - } - if (SysVariables.findIndex(t => t === variable) !== -1) { - return variable.replace("{{", "").replace("}}", "").replace("#", "").trim(); - } + if ((variable.startsWith("{{#num,") || variable.startsWith("{{#date,")) && variable.endsWith("}}")) { + return variable.replace("{{", "").replace("}}", "").replace("#", "").trim(); + } + if (SysVariables.findIndex(t => t === variable) !== -1) { + return variable.replace("{{", "").replace("}}", "").replace("#", "").trim(); + } - return null; + return null; } export function getSysVariableWithValue(data: string) { - try { - switch (data) { - case "num": - return getRandomIntFromInterval(1, 999999); - case "str": - return getRandomString(getRandomIntFromInterval(1, 15), "str"); - case "strnum": - return getRandomString(getRandomIntFromInterval(1, 15), "strnum"); - case "strspl": - return getRandomString(getRandomIntFromInterval(1, 15), "strspl"); - case "char": - return getRandomString(1, "str"); - case "date": - return new Date().toDateString(); - case "rdate": - return getRandomDate(new Date(1900, 1, 1), new Date(2100, 1, 1)); - case "dateISO": - return new Date().toISOString(); - case "guid": - return uuidv4(); - case "bool": - return [true, false].at(getRandomIntFromInterval(0, 1)); - case "email": - return getRandomEMail(); - default: - if (data.startsWith("num,")) { - let range = data.split(","); - let min = parseInt(range[1]); - let max = parseInt(range[2]); - if (!isNaN(min) && !isNaN(max)) { - return getRandomIntFromInterval(min, max); - } - } else if (data.startsWith("date,")) { - let range = data.split(","); - let format = range[1].trim(); - return moment().format(format); - } - } - } - catch { - return null; - } + try { + switch (data) { + case "num": + return getRandomIntFromInterval(1, 999999); + case "str": + return getRandomString(getRandomIntFromInterval(1, 15), "str"); + case "strnum": + return getRandomString(getRandomIntFromInterval(1, 15), "strnum"); + case "strspl": + return getRandomString(getRandomIntFromInterval(1, 15), "strspl"); + case "char": + return getRandomString(1, "str"); + case "date": + return new Date().toDateString(); + case "rdate": + return getRandomDate(new Date(1900, 1, 1), new Date(2100, 1, 1)); + case "dateISO": + return new Date().toISOString(); + case "guid": + return uuidv4(); + case "bool": + return [true, false].at(getRandomIntFromInterval(0, 1)); + case "email": + return getRandomEMail(); + default: + if (data.startsWith("num,")) { + let range = data.split(","); + let min = parseInt(range[1]); + let max = parseInt(range[2]); + if (!isNaN(min) && !isNaN(max)) { + return getRandomIntFromInterval(min, max); + } + return null; + } else if (data.startsWith("date,")) { + let range = data.split(","); + let format = range[1].trim(); + return moment().format(format); + } + return null; + } + } + catch { + return null; + } } function getRandomEMail() { - let name = getRandomString(getRandomIntFromInterval(1, 15), "str"); - let domain = ["yahoo", "gmail", "hotmail", "outlook"].at(getRandomIntFromInterval(0, 3)); - return name + "@" + domain + ".com"; + let name = getRandomString(getRandomIntFromInterval(1, 15), "str"); + let domain = ["yahoo", "gmail", "hotmail", "outlook"].at(getRandomIntFromInterval(0, 3)); + return name + "@" + domain + ".com"; } function getRandomDate(start: Date, end: Date) { - return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); + return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); } function getRandomString(len: number, type: string) { - var text = ""; - var charset = type === "str" ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : type === "strnum" ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_+-={}[]:\"\'<>?,./|\\'"; - for (var i = 0; i < len; i++) { - text += charset.charAt(Math.floor(Math.random() * charset.length)); - } + var text = ""; + var charset = type === "str" ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : type === "strnum" ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_+-={}[]:\"\'<>?,./|\\'"; + for (var i = 0; i < len; i++) { + text += charset.charAt(Math.floor(Math.random() * charset.length)); + } - return text; + return text; } function getRandomIntFromInterval(min: number, max: number) { - return Math.floor(Math.random() * (max - min + 1) + min); -} \ No newline at end of file + return Math.floor(Math.random() * (max - min + 1) + min); +} diff --git a/src/fetch-client-ui/components/Common/Editor/EditorProvider.tsx b/src/fetch-client-ui/components/Common/Editor/EditorProvider.tsx index 4d6e880..47208df 100644 --- a/src/fetch-client-ui/components/Common/Editor/EditorProvider.tsx +++ b/src/fetch-client-ui/components/Common/Editor/EditorProvider.tsx @@ -1,120 +1,121 @@ -import React from "react"; import * as monaco from "monaco-editor/esm/vs/editor/editor.api"; -import { useEffect, useRef, useState } from "react"; -import "./style.css"; +import React, { useEffect, useRef, useState } from "react"; import { EditorProps } from "."; +import "./style.css"; const EditorProvider = (props: EditorProps) => { - const editorElement = useRef(null); - - const [copyText, setCopyText] = useState("Copy"); - const [monacoEditor, setMonacoEditor] = useState(); - - function onCopyClick() { - navigator.clipboard.writeText(props.value) - .then(() => { - setCopyText("Copied"); - setTimeout(() => setCopyText("Copy"), 1000); - }); - } - - useEffect(() => { - if (editorElement.current) { - const tmpEditor = monaco.editor.create(editorElement.current, { - minimap: { enabled: false }, - scrollBeyondLastLine: false, - theme: props.theme === 1 ? 'vs' : (props.theme === 2 ? "vs-dark" : "hc-black"), - value: props.value, - language: props.language, - readOnly: props.readOnly, - automaticLayout: true, - formatOnType: true, - formatOnPaste: true, - renderLineHighlight: "none", - quickSuggestions: false, - wordBasedSuggestions: false, - scrollbar: { - verticalScrollbarSize: 10, - horizontalScrollbarSize: 10 - }, - wordWrap: "off" - }); - - window.addEventListener("resize", () => { - tmpEditor.layout(); - }); - - tmpEditor.onDidChangeModelContent(() => { - props.onContentChange && props.onContentChange(tmpEditor.getValue()); - }); - - if (props.value) { - formatContent(tmpEditor); - } - - setMonacoEditor(tmpEditor); - - return () => { - monacoEditor && monacoEditor.dispose(); - }; - } - }, []); - - useEffect(() => { - if (monacoEditor) { - const model = monacoEditor.getModel(); - if (model) { - monaco.editor.setModelLanguage(model, props.language); - formatContent(monacoEditor); - } - } - }, [props.language, props.format, props.value]); - - useEffect(() => { - if (monacoEditor) { - if (props.wordWrap) { - monacoEditor.updateOptions({ wordWrap: "on" }); - } else { - monacoEditor.updateOptions({ wordWrap: "off" }); - } - } - }, [props.wordWrap]); - - useEffect(() => { - if (monacoEditor) { - if (props.readOnly) { - monacoEditor.setValue(props.value); - } - } - }, [props.value]); - - const formatContent = (monacoEditor: monaco.editor.IStandaloneCodeEditor) => { - if (props.format) { - monacoEditor.updateOptions({ readOnly: false }); - setTimeout(() => { - monacoEditor - .getAction("editor.action.formatDocument") - .run() - .then(() => { - monacoEditor.updateOptions({ readOnly: props.readOnly }); - }); - }, 250); - } - }; - - return ( -
- {props.copyButtonVisible && ( - - )} -
- ); + const editorElement = useRef(null); + + const [copyText, setCopyText] = useState("Copy"); + const [monacoEditor, setMonacoEditor] = useState(); + + function onCopyClick() { + navigator.clipboard.writeText(props.value) + .then(() => { + setCopyText("Copied"); + setTimeout(() => setCopyText("Copy"), 1000); + }); + } + + useEffect(() => { + if (editorElement.current) { + const tmpEditor = monaco.editor.create(editorElement.current, { + minimap: { enabled: false }, + scrollBeyondLastLine: false, + theme: props.theme === 1 ? 'vs' : (props.theme === 2 ? "vs-dark" : "hc-black"), + value: props.value, + language: props.language, + readOnly: props.readOnly, + automaticLayout: true, + formatOnType: true, + formatOnPaste: true, + renderLineHighlight: "none", + quickSuggestions: false, + wordBasedSuggestions: false, + scrollbar: { + verticalScrollbarSize: 10, + horizontalScrollbarSize: 10 + }, + wordWrap: "off" + }); + + window.addEventListener("resize", () => { + tmpEditor.layout(); + }); + + tmpEditor.onDidChangeModelContent(() => { + props.onContentChange && props.onContentChange(tmpEditor.getValue()); + }); + + if (props.value) { + formatContent(tmpEditor); + } + + setMonacoEditor(tmpEditor); + + return () => { + monacoEditor && monacoEditor.dispose(); + }; + } else { + return null; + } + }, []); + + useEffect(() => { + if (monacoEditor) { + const model = monacoEditor.getModel(); + if (model) { + monaco.editor.setModelLanguage(model, props.language); + formatContent(monacoEditor); + } + } + }, [props.language, props.format, props.value]); + + useEffect(() => { + if (monacoEditor) { + if (props.wordWrap) { + monacoEditor.updateOptions({ wordWrap: "on" }); + } else { + monacoEditor.updateOptions({ wordWrap: "off" }); + } + } + }, [props.wordWrap]); + + useEffect(() => { + if (monacoEditor) { + if (props.readOnly) { + monacoEditor.setValue(props.value); + } + } + }, [props.value]); + + const formatContent = (monacoEditor: monaco.editor.IStandaloneCodeEditor) => { + if (props.format) { + monacoEditor.updateOptions({ readOnly: false }); + setTimeout(() => { + monacoEditor + .getAction("editor.action.formatDocument") + .run() + .then(() => { + monacoEditor.updateOptions({ readOnly: props.readOnly }); + }); + }, 250); + } + }; + + return ( +
+ {props.copyButtonVisible && ( + + )} +
+ ); }; -export default EditorProvider; \ No newline at end of file +export default EditorProvider; diff --git a/src/fetch-client-ui/components/Common/Editor/index.tsx b/src/fetch-client-ui/components/Common/Editor/index.tsx index 8829167..512f344 100644 --- a/src/fetch-client-ui/components/Common/Editor/index.tsx +++ b/src/fetch-client-ui/components/Common/Editor/index.tsx @@ -4,36 +4,36 @@ import { IRootState } from "../../../reducer/combineReducer"; import "./style.css"; export interface EditorProps { - copyButtonVisible: boolean; - format: boolean; - language: string; - readOnly: boolean; - value: string; - onContentChange?: any; - className?: string; - theme?: number; - wordWrap?:boolean; + copyButtonVisible: boolean; + format: boolean; + language: string; + readOnly: boolean; + value: string; + onContentChange?: any; + className?: string; + theme?: number; + wordWrap?:boolean; } const EditorProvider = React.lazy(() => import('./EditorProvider')); export const MonacoEditor = (props: EditorProps) => { - const { theme } = useSelector((state: IRootState) => state.uiData); + const { theme } = useSelector((state: IRootState) => state.uiData); - return ( - loading...}> - - - ); -}; \ No newline at end of file + return ( + loading...}> + + + ); +}; diff --git a/src/fetch-client-ui/components/Common/Editor/style.css b/src/fetch-client-ui/components/Common/Editor/style.css index 6d2ae7d..d1886ab 100644 --- a/src/fetch-client-ui/components/Common/Editor/style.css +++ b/src/fetch-client-ui/components/Common/Editor/style.css @@ -1,34 +1,34 @@ .editor { - position: relative; - border: var(--border-size) solid var(--border-color); - height: 100%; - box-sizing: border-box; + position: relative; + border: var(--border-size) solid var(--border-color); + height: 100%; + box-sizing: border-box; } .monaco-editor { - height: 100%; + height: 100%; } .copy-button { - background-color: var(--button-background-color); - border: 1px solid rgb(51, 51, 51); - border-radius: 5px; - color: var(--button-text-color); - cursor: pointer; - font-size: 14px; - opacity: 0; - outline: none; - padding: 0.2rem; - position: absolute; - right: 1rem; - top: 0.8rem; - transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out; - visibility: hidden; - z-index: 99; + background-color: var(--button-background-color); + border: 1px solid rgb(51, 51, 51); + border-radius: 5px; + color: var(--button-text-color); + cursor: pointer; + font-size: 14px; + opacity: 0; + outline: none; + padding: 0.2rem; + position: absolute; + right: 1rem; + top: 0.8rem; + transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out; + visibility: hidden; + z-index: 99; } .copy-button:hover, .editor:hover .copy-button { - opacity: 1; - visibility: visible; -} \ No newline at end of file + opacity: 1; + visibility: visible; +} diff --git a/src/fetch-client-ui/components/Common/Modal/index.tsx b/src/fetch-client-ui/components/Common/Modal/index.tsx new file mode 100644 index 0000000..fc8dec4 --- /dev/null +++ b/src/fetch-client-ui/components/Common/Modal/index.tsx @@ -0,0 +1,15 @@ +import React from 'react'; +import './style.css'; + +export const Modal = ({ show, children }) => { + const showHideClassName = show ? "modal display-block" : "modal display-none"; + + return ( +
+
+
+
{children}
+
+
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/Modal/style.css b/src/fetch-client-ui/components/Common/Modal/style.css new file mode 100644 index 0000000..5d6227b --- /dev/null +++ b/src/fetch-client-ui/components/Common/Modal/style.css @@ -0,0 +1,65 @@ +.modal { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.6); +} + +.modal-main { + position: fixed; + background: white; + width: 60%; + height: auto; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} + +.display-block { + display: block; +} + +.display-none { + display: none; +} + +.popup-loading-text { + position: absolute; + left: 30%; + bottom: 15%; + padding: 10px; + font-size: medium; + text-align: center; + color: black; +} + +.popup.loading { + padding: 50px; + text-align: center; +} + +.popup.loading:before { + content: ""; + height: 25px; + width: 25px; + margin: -15px auto auto -15px; + position: absolute; + left: 25%; + border-width: 3px; + border-style: solid; + border-color: #2180c0 #ccc #ccc; + border-radius: 100%; + animation: rotation .7s infinite linear; +} + +@keyframes rotation { + from { + transform: rotate(0deg); + } + + to { + transform: rotate(359deg); + } +} diff --git a/src/fetch-client-ui/components/Common/NotesEditor/index.tsx b/src/fetch-client-ui/components/Common/NotesEditor/index.tsx index 05bf9f5..95bf6e2 100644 --- a/src/fetch-client-ui/components/Common/NotesEditor/index.tsx +++ b/src/fetch-client-ui/components/Common/NotesEditor/index.tsx @@ -8,44 +8,44 @@ import "./style.css"; export const NotesEditor = () => { - const dispatch = useDispatch(); - const [count, _setCount] = useState(0); - const refCount = useRef(count); - const setCount = (data: number) => { - refCount.current = data; - _setCount(refCount.current); - }; - - const { notes } = useSelector((state: IRootState) => state.requestData); - - useEffect(() => { - const linkElement = document.querySelector('button[title="Link"]'); - if (linkElement) { - linkElement.remove(); - } - - const htmlFormatElement = document.querySelector('button[title="HTML mode"]'); - if (htmlFormatElement) { - htmlFormatElement.remove(); - } - - if (notes) { - const data = GetDataFromHTML(notes); - setCount(data.length); - } - - }, []); - - function onChange(e: any) { - const data = GetDataFromHTML(e.target.value); - dispatch(Actions.SetNotesAction(e.target.value)); - setCount(data.length); - } - - return ( -
- -
notesMaxLimit ? "error-text notes-text" : "notes-text"}>{count}/{notesMaxLimit} {count > notesMaxLimit ? " (Exceed the maximum character limit. Notes won't be saved.)" : ""}
-
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + const [count, _setCount] = useState(0); + const refCount = useRef(count); + const setCount = (data: number) => { + refCount.current = data; + _setCount(refCount.current); + }; + + const { notes } = useSelector((state: IRootState) => state.requestData); + + useEffect(() => { + const linkElement = document.querySelector('button[title="Link"]'); + if (linkElement) { + linkElement.remove(); + } + + const htmlFormatElement = document.querySelector('button[title="HTML mode"]'); + if (htmlFormatElement) { + htmlFormatElement.remove(); + } + + if (notes) { + const data = GetDataFromHTML(notes); + setCount(data.length); + } + + }, []); + + function onChange(e: any) { + const data = GetDataFromHTML(e.target.value); + dispatch(Actions.SetNotesAction(e.target.value)); + setCount(data.length); + } + + return ( +
+ +
notesMaxLimit ? "error-text notes-text" : "notes-text"}>{count}/{notesMaxLimit} {count > notesMaxLimit ? " (Exceed the maximum character limit. Notes won't be saved.)" : ""}
+
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/NotesEditor/style.css b/src/fetch-client-ui/components/Common/NotesEditor/style.css index 43c0c5e..c73db00 100644 --- a/src/fetch-client-ui/components/Common/NotesEditor/style.css +++ b/src/fetch-client-ui/components/Common/NotesEditor/style.css @@ -1,49 +1,49 @@ .notes-editor-panel { - height: calc(100% - 50px); - padding: 10px; + height: calc(100% - 50px); + padding: 10px; } .rsw-editor { - height: 100% !important; - border: 1px solid var(--border-color) !important; + height: 100% !important; + border: 1px solid var(--border-color) !important; } .rsw-toolbar { - background-color: var(--background-color) !important; - border-bottom: 1px solid var(--border-color) !important; + background-color: var(--background-color) !important; + border-bottom: 1px solid var(--border-color) !important; } .rsw-separator { - border-right: 1px solid var(--border-color) !important; + border-right: 1px solid var(--border-color) !important; } .rsw-btn { - color: var(--text-color) !important; - height: 35px !important; - width: 35px !important; - font-size: 15px !important; + color: var(--text-color) !important; + height: 35px !important; + width: 35px !important; + font-size: 15px !important; } .rsw-btn:hover { - background-color: var(--button-hover-color) !important; - color: var(--button-text-color) !important; + background-color: var(--button-hover-color) !important; + color: var(--button-text-color) !important; } .rsw-dd { - margin-left: 10px !important; + margin-left: 10px !important; } .rsw-btn[data-active=true] { - background-color: var(--button-hover-color) !important; - color: var(--button-text-color) !important; + background-color: var(--button-hover-color) !important; + color: var(--button-text-color) !important; } .rsw-ce { - font-size: 15px !important; - color: var(--text-color) !important; + font-size: 15px !important; + color: var(--text-color) !important; } .notes-text { - padding-top: 5px; - font-size: initial; -} \ No newline at end of file + padding-top: 5px; + font-size: initial; +} diff --git a/src/fetch-client-ui/components/Common/Table/ResponseTable.tsx b/src/fetch-client-ui/components/Common/Table/ResponseTable.tsx index fc7ab1a..87274c2 100644 --- a/src/fetch-client-ui/components/Common/Table/ResponseTable.tsx +++ b/src/fetch-client-ui/components/Common/Table/ResponseTable.tsx @@ -1,55 +1,55 @@ import React from 'react'; -import { ITableData } from "./types"; import { TableProps } from './Table'; import "./style.css"; +import { ITableData } from "./types"; export const ResponseTable = (props: TableProps) => { - const { data } = props; + const { data } = props; - const tableRow = (row: ITableData, index: number) => { - return ( - - -
- {row.key} -
- - -
- {row.value.split(";")[0]} -
- - {props.type === "resCookies" && -
- {row.value.substring(row.value.indexOf(";") + 1)} -
- } - - ); - }; + const tableRow = (row: ITableData, index: number) => { + return ( + + +
+ {row.key} +
+ + +
+ {row.value.split(";")[0]} +
+ + {props.type === "resCookies" && +
+ {row.value.substring(row.value.indexOf(";") + 1)} +
+ } + + ); + }; - const makeTable = (data: ITableData[]) => { - return ( - data.map((item: ITableData, index: number) => { - return tableRow(item, index); - }) - ); - }; + const makeTable = (data: ITableData[]) => { + return ( + data.map((item: ITableData, index: number) => { + return tableRow(item, index); + }) + ); + }; - return ( - - - - - - {props.type === "resCookies" && } - - - - { - makeTable(data) - } - -
{props.headers ? props.headers.key : "Key"}{props.headers ? props.headers.value : "Value"}{props.headers ? props.headers.value1 : "Details"}
- ); -}; \ No newline at end of file + return ( + + + + + + {props.type === "resCookies" && } + + + + { + makeTable(data) + } + +
{props.headers ? props.headers.key : "Key"}{props.headers ? props.headers.value : "Value"}{props.headers ? props.headers.value1 : "Details"}
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/Table/Table.tsx b/src/fetch-client-ui/components/Common/Table/Table.tsx index cae3d33..675558e 100644 --- a/src/fetch-client-ui/components/Common/Table/Table.tsx +++ b/src/fetch-client-ui/components/Common/Table/Table.tsx @@ -1,240 +1,242 @@ import React from 'react'; -import { dataTypes, HeadersKeys, HerdersValues, ITableData, TableType } from "./types"; import { ReactComponent as BinLogo } from '../../../../../icons/bin.svg'; -import { Autocomplete } from '../Autocomplete/Autocomplete'; import { IVariable } from '../../SideBar/redux/types'; +import { Autocomplete } from '../Autocomplete/Autocomplete'; +import { GetFileName } from '../helper'; import { TextEditor } from '../TextEditor/TextEditor'; import "./style.css"; -import { GetFileName } from '../helper'; +import { dataTypes, HeadersKeys, HerdersValues, ITableData, TableType, TextType } from "./types"; export interface TableProps { - data: ITableData[]; - onSelectChange?: any; - onSelectType?: any; - onFileSelect?: any; - onRowAdd?: any; - onRowUpdate?: any; - deleteData?: any; - readOnly: boolean; - type?: TableType; - placeholder?: { key: string, value: string } - selectedVariable?: IVariable; - highlightNeeded?: boolean; - headers?: { key: string, value: string, value1?: string } + data: ITableData[]; + onSelectChange?: any; + onSelectType?: any; + onFileSelect?: any; + onRowAdd?: any; + onRowUpdate?: any; + deleteData?: any; + readOnly: boolean; + type?: TableType; + placeholder?: { key: string, value: string } + selectedVariable?: IVariable; + highlightNeeded?: boolean; + headers?: { key: string, value: string, value1?: string } + valueType?: TextType; } export const Table = (props: TableProps) => { - const { data, onSelectChange, onSelectType, onFileSelect, onRowAdd, onRowUpdate, deleteData, readOnly, selectedVariable } = props; - - function isEnabled(row: ITableData, index: number): boolean { - - if (readOnly) { - return true; - } - - if (row.isFixed === true) { - return true; - } - - if (index === data.length - 1) { - return false; - } - - if (row.isChecked && index !== data.length - 1) { - return false; - } - - return true; - } - - function getRequetHeaderRow(row: ITableData, index: number) { - return (<> - - index === data.length - 1 ? onRowAdd(val, index, true) : onRowUpdate(val, index, true)} - suggestions={HeadersKeys} - disabled={isEnabled(row, index) ? true : false} - placeholder="header" - selectedVariable={selectedVariable} - /> - - - index === data.length - 1 ? onRowAdd(val, index, false) : onRowUpdate(val, index, false)} - suggestions={HerdersValues} - disabled={isEnabled(row, index) ? true : false} - placeholder="value" - selectedVariable={selectedVariable} - /> - - ); - } - - - function getKeyHighlightedColumn(row: ITableData, index: number) { - return ( - selectedVariable.id && item.key)} - placeholder={props.placeholder ? props.placeholder.key : "parameter"} - onChange={(event) => index === data.length - 1 ? onRowAdd(event, index, true) : onRowUpdate(event, index, true)} - value={row.key} - disabled={isEnabled(row, index) ? true : false} - focus={false} - /> - ); - } - - - function getKeyNonHighlightedColumn(row: ITableData, index: number) { - return ( - index === data.length - 1 ? onRowAdd(event, index, true) : onRowUpdate(event, index, true)} - disabled={isEnabled(row, index) ? true : false} - placeholder={props.placeholder ? props.placeholder.key : "parameter"} - /> - ); - } - - function getValueHighlightedColumn(row: ITableData, index: number) { - return ( - selectedVariable.id && item.key)} - placeholder={props.placeholder ? props.placeholder.value : "value"} - onChange={(event) => index === data.length - 1 ? onRowAdd(event, index, false) : onRowUpdate(event, index, false)} - value={row.value} - disabled={isEnabled(row, index) ? true : false} - focus={false} - /> - ); - } - - function getValueNonHighlightedColumn(row: ITableData, index: number) { - return ( - index === data.length - 1 ? onRowAdd(event, index, false) : onRowUpdate(event, index, false)} - disabled={isEnabled(row, index) ? true : false} - placeholder={props.placeholder ? props.placeholder.value : "value"} - /> - ); - } - - function fileSelect(index: number) { - onFileSelect(index); - } - - function getFileSelectColumn(row: ITableData, index: number) { - return ( - <> - - - - ); - } - - function getActionColumn(row: ITableData, index: number) { - return ( - {(row.key || row.value) && row.isFixed !== true ? - deleteData(index)} /> - : - <> - } - ); - } - - function getSelectColumn(row: ITableData, index: number) { - return ( - {index !== data.length - 1 ? - onSelectChange ? onSelectChange(index) : {}} - disabled={row.isFixed === true ? true : false} - /> - : - <> - } - ); - } - - function getTypeSelectColumn(row: ITableData, index: number) { - return ( - - ); - } - - function getKeyValueRow(row: ITableData, index: number) { - return (<> - - {props.highlightNeeded ? getKeyHighlightedColumn(row, index) : getKeyNonHighlightedColumn(row, index)} - - - {props.type === "formData" && row.type === "File" ? getFileSelectColumn(row, index) : (props.highlightNeeded ? getValueHighlightedColumn(row, index) : getValueNonHighlightedColumn(row, index))} - - ); - } - - const tableRow = (row: ITableData, index: number) => { - return ( - - {!readOnly && getSelectColumn(row, index)} - {props.type === "formData" && getTypeSelectColumn(row, index)} - {props.type === "reqHeaders" ? getRequetHeaderRow(row, index) : getKeyValueRow(row, index)} - {!readOnly && getActionColumn(row, index)} - - ); - }; - - const makeTable = (data: ITableData[]) => { - return ( - data.map((item: ITableData, index: number) => { - return tableRow(item, index); - }) - ); - }; - - return ( - - - - {!readOnly && } - {props.type === "formData" && } - - - {!readOnly && } - - - - {makeTable(data)} - -
Type{props.headers ? props.headers.key : "Key"}{props.headers ? props.headers.value : "Value"}
- ); -}; \ No newline at end of file + const { data, onSelectChange, onSelectType, onFileSelect, onRowAdd, onRowUpdate, deleteData, readOnly, selectedVariable, valueType } = props; + + function isEnabled(row: ITableData, index: number): boolean { + + if (readOnly) { + return true; + } + + if (row.isFixed === true) { + return true; + } + + if (index === data.length - 1) { + return false; + } + + if (row.isChecked && index !== data.length - 1) { + return false; + } + + return true; + } + + function getRequetHeaderRow(row: ITableData, index: number) { + return (<> + + index === data.length - 1 ? onRowAdd(val, index, true) : onRowUpdate(val, index, true)} + suggestions={HeadersKeys} + disabled={isEnabled(row, index) ? true : false} + placeholder="header" + selectedVariable={selectedVariable} + /> + + + index === data.length - 1 ? onRowAdd(val, index, false) : onRowUpdate(val, index, false)} + suggestions={HerdersValues} + disabled={isEnabled(row, index) ? true : false} + placeholder="value" + selectedVariable={selectedVariable} + /> + + ); + } + + + function getKeyHighlightedColumn(row: ITableData, index: number) { + return ( + selectedVariable.id && item.key)} + placeholder={props.placeholder ? props.placeholder.key : "parameter"} + onChange={(event) => index === data.length - 1 ? onRowAdd(event, index, true) : onRowUpdate(event, index, true)} + value={row.key} + disabled={isEnabled(row, index) ? true : false} + focus={false} + /> + ); + } + + + function getKeyNonHighlightedColumn(row: ITableData, index: number) { + return ( + index === data.length - 1 ? onRowAdd(event, index, true) : onRowUpdate(event, index, true)} + disabled={isEnabled(row, index) ? true : false} + placeholder={props.placeholder ? props.placeholder.key : "parameter"} + /> + ); + } + + function getValueHighlightedColumn(row: ITableData, index: number) { + return ( + selectedVariable.id && item.key)} + placeholder={props.placeholder ? props.placeholder.value : "value"} + onChange={(event) => index === data.length - 1 ? onRowAdd(event, index, false) : onRowUpdate(event, index, false)} + value={row.value} + disabled={isEnabled(row, index) ? true : false} + focus={false} + /> + ); + } + + function getValueNonHighlightedColumn(row: ITableData, index: number) { + return ( + index === data.length - 1 ? onRowAdd(event, index, false) : onRowUpdate(event, index, false)} + disabled={isEnabled(row, index) ? true : false} + placeholder={props.placeholder ? props.placeholder.value : "value"} + type={valueType === "password" ? "password" : "text"} + /> + ); + } + + function fileSelect(index: number) { + onFileSelect(index); + } + + function getFileSelectColumn(row: ITableData, index: number) { + return ( + <> + + + + ); + } + + function getActionColumn(row: ITableData, index: number) { + return ( + {(row.key || row.value) && row.isFixed !== true ? + deleteData(index)} /> + : + <> + } + ); + } + + function getSelectColumn(row: ITableData, index: number) { + return ( + {index !== data.length - 1 ? + onSelectChange ? onSelectChange(index) : {}} + disabled={row.isFixed === true ? true : false} + /> + : + <> + } + ); + } + + function getTypeSelectColumn(row: ITableData, index: number) { + return ( + + ); + } + + function getKeyValueRow(row: ITableData, index: number) { + return (<> + + {props.highlightNeeded ? getKeyHighlightedColumn(row, index) : getKeyNonHighlightedColumn(row, index)} + + + {props.type === "formData" && row.type === "File" ? getFileSelectColumn(row, index) : (props.highlightNeeded ? getValueHighlightedColumn(row, index) : getValueNonHighlightedColumn(row, index))} + + ); + } + + const tableRow = (row: ITableData, index: number) => { + return ( + + {!readOnly && getSelectColumn(row, index)} + {props.type === "formData" && getTypeSelectColumn(row, index)} + {props.type === "reqHeaders" ? getRequetHeaderRow(row, index) : getKeyValueRow(row, index)} + {!readOnly && getActionColumn(row, index)} + + ); + }; + + const makeTable = (data: ITableData[]) => { + return ( + data.map((item: ITableData, index: number) => { + return tableRow(item, index); + }) + ); + }; + + return ( + + + + {!readOnly && } + {props.type === "formData" && } + + + {!readOnly && } + + + + {makeTable(data)} + +
Type{props.headers ? props.headers.key : "Key"}{props.headers ? props.headers.value : "Value"}
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/Table/style.css b/src/fetch-client-ui/components/Common/Table/style.css index 15a635b..223e1b4 100644 --- a/src/fetch-client-ui/components/Common/Table/style.css +++ b/src/fetch-client-ui/components/Common/Table/style.css @@ -1,18 +1,18 @@ .option-table { - border-collapse: collapse; - width : 100%; - margin-top : 10px; - table-layout : fixed; - margin-bottom : 10px; + border-collapse: collapse; + width : 100%; + margin-top : 10px; + table-layout : fixed; + margin-bottom : 10px; } .option-table tr, .option-table thead { - width: 100%; + width: 100%; } .option-table thead { - background-color: var(--list-hover-background-color); + background-color: var(--list-hover-background-color); } .option-table, @@ -21,79 +21,83 @@ .option-table th, .option-table tr, .option-table td { - border: var(--border-size) solid var(--border-color) !important; + border: var(--border-size) solid var(--border-color) !important; } .table-input { - background-color: transparent; - border : 0; - box-sizing : border-box; - color : var(--text-color); - font-size : var(--font-size); - outline : none; - padding : 10px; - width : 100%; + background-color: transparent; + border : 0; + box-sizing : border-box; + color : var(--text-color); + font-size : var(--font-size); + outline : none; + padding : 10px; + width : 100%; } .table-input:focus { - outline: none; + outline: none; } .action-cell { - text-align: center; - width : 50px; + text-align: center; + width : 50px; } .type-action-cell { - width: 150px; + width: 150px; } .delete-button { - cursor: pointer; - height: 16px; - width : 16px; + cursor: pointer; + height: 16px; + width : 16px; } .delete-button path { - fill: #f05348; + fill: #f05348; } .option-names { - display: flex; + display: flex; } .disabled { - color: var(--input-unchecked); + color: var(--input-unchecked); } .option-table>tbody>tr:hover, .option-table>tbody>tr:focus { - background-color: var(--list-hover-background-color); - border : var(--border-size) solid var(--border-color); + background-color: var(--list-hover-background-color); + border : var(--border-size) solid var(--border-color); } .option-table>tbody>tr:hover .DraftEditor-editorContainer, .option-table>tbody>tr:focus .DraftEditor-editorContainer { - background-color: var(--list-hover-background-color); + background-color: var(--list-hover-background-color); } .res-table-input { - background-color: transparent; - border : 0; - box-sizing : border-box; - color : var(--text-color); - font-size : var(--font-size); - outline : none; - padding : 10px; - width : 100%; - word-break : break-word; + background-color: transparent; + border : 0; + box-sizing : border-box; + color : var(--text-color); + font-size : var(--font-size); + outline : none; + padding : 10px; + width : 100%; + word-break : break-word; } .file-select { - width : 52px; - margin-left: 5px; + width : 52px; + margin-left: 5px; } .file-name { - margin-left: 5px; -} \ No newline at end of file + margin-left: 5px; +} + +.password-textbox { + width: 85%; +} diff --git a/src/fetch-client-ui/components/Common/Table/types.ts b/src/fetch-client-ui/components/Common/Table/types.ts index 83031f8..2ead546 100644 --- a/src/fetch-client-ui/components/Common/Table/types.ts +++ b/src/fetch-client-ui/components/Common/Table/types.ts @@ -1,77 +1,79 @@ export interface ITableData { - isFixed?: boolean; - isChecked?: boolean; - type?: string; - key: string; - value: string; + isFixed?: boolean; + isChecked?: boolean; + type?: string; + key: string; + value: string; } export type TableType = "reqHeaders" | "queryParams" | "resHeaders" | "formData" | "urlEncoded" | "resCookies"; +export type TextType = "text" | "password"; + export const dataTypes = ["Text", "File"]; export const HerdersValues = [ - "application/atom+xml", - "application/hal+json", - "application/javascript", - "application/json", - "application/ld+json", - "application/vnd.api+json", - "application/octet-stream", - "application/x-www-form-urlencoded", - "application/xml", - "image/bmp", - "image/gif", - "image/jpeg", - "image/png", - "image/svg", - "image/webp", - "multipart/form-data", - "text/csv", - "text/html", - "text/plain", - "text/xml", + "application/atom+xml", + "application/hal+json", + "application/javascript", + "application/json", + "application/ld+json", + "application/vnd.api+json", + "application/octet-stream", + "application/x-www-form-urlencoded", + "application/xml", + "image/bmp", + "image/gif", + "image/jpeg", + "image/png", + "image/svg", + "image/webp", + "multipart/form-data", + "text/csv", + "text/html", + "text/plain", + "text/xml", ]; export const HeadersKeys = [ - "Accept-Charset", - "Accept-Encoding", - "Accept-Language", - "Accept", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Authorization", - "Cache-Control", - "Connection", - "Content-Encoding", - "Content-Length", - "Content-Type", - "Cookie", - "Date", - "DNT", - "Expect", - "Forwarded", - "Host", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Location", - "Max-Forwards", - "Origin", - "Pragma", - "Proxy-Authorization", - "Range", - "Referer", - "Set-Cookie", - "Strict-Transport-Security", - "Upgrade-Insecure-Requests", - "User-Agent", - "X-Authorization" -]; \ No newline at end of file + "Accept-Charset", + "Accept-Encoding", + "Accept-Language", + "Accept", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Authorization", + "Cache-Control", + "Connection", + "Content-Encoding", + "Content-Length", + "Content-Type", + "Cookie", + "Date", + "DNT", + "Expect", + "Forwarded", + "Host", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Location", + "Max-Forwards", + "Origin", + "Pragma", + "Proxy-Authorization", + "Range", + "Referer", + "Set-Cookie", + "Strict-Transport-Security", + "Upgrade-Insecure-Requests", + "User-Agent", + "X-Authorization" +]; diff --git a/src/fetch-client-ui/components/Common/TextEditor/TextEditor.tsx b/src/fetch-client-ui/components/Common/TextEditor/TextEditor.tsx index 4e8bba5..f503f1c 100644 --- a/src/fetch-client-ui/components/Common/TextEditor/TextEditor.tsx +++ b/src/fetch-client-ui/components/Common/TextEditor/TextEditor.tsx @@ -1,251 +1,251 @@ +import { CompositeDecorator, ContentState, DraftHandleValue, Editor, EditorState, getDefaultKeyBinding, Modifier } from "draft-js"; import React, { useEffect, useRef, useState } from "react"; -import { Editor, EditorState, CompositeDecorator, Modifier, DraftHandleValue, ContentState, getDefaultKeyBinding, KeyBindingUtil } from "draft-js"; import { useSelector } from "react-redux"; +import { replaceDataWithVariable } from "../../../../utils/helper"; import { IRootState } from "../../../reducer/combineReducer"; import { checkSysVariable, SysVariables } from "../Consts/sysVariables"; import "./style.css"; -import { replaceDataWithVariable } from "../../../../utils/helper"; export interface TextEditorProps { - varWords: string[]; - focus: boolean; - className?: string; - value?: string; - placeholder?: string; - maxLength?: number; - disabled?: boolean; - onChange?: any; - onKeyPress?: any; - onBlur?: any; - onFocus?: any; + varWords: string[]; + focus: boolean; + className?: string; + value?: string; + placeholder?: string; + maxLength?: number; + disabled?: boolean; + onChange?: any; + onKeyPress?: any; + onBlur?: any; + onFocus?: any; } export const TextEditor = (props: TextEditorProps) => { - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - - const [charLength, setLength] = useState(0); - const [curValue, setCurValue] = useState(""); - const [changeHandle, setChangeHandle] = useState(false); - - const refVarData = useRef({}); - const setVarData = (value: {}) => { - refVarData.current = value; - }; - - const editor = React.useRef(null); - - const matchedDecorated = (props: any) => { - if (!checkSysVariable(props.decoratedText)) { - let title = replaceDataWithVariable(props.decoratedText, refVarData.current); - if (title) { - return {props.children}; - } - } - - return {props.children}; - }; - - const unmatchedDecorated = ({ children }) => { - return {children}; - }; - - function findWithRegex(words: string[], contentBlock: any, callback: any) { - const text = contentBlock.getText(); - - let regexEx = /{{[A-Za-z0-9\s!@#$%^&*()_+=-`~\\\]\[|';:\/.,?><]+}}/; - let sysVarRegex = /(({{#)((num|str|char|rdate|date|dateISO|email|guid|bool)|(num,[ ]?[0-9]+,[ ]?[0-9]+)|(date,( )*[a-zA-Z $&+,:;=?@#|'<>.^*()%!-\/]*))(}}))/; - const matches = [...text.matchAll(new RegExp(regexEx, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); - const sysVarMatches = [...text.matchAll(new RegExp(sysVarRegex, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); - - [...matches].forEach(match => { - let word = match.word.replace("{{", "").replace("}}", "").trim(); - if (words.includes(word)) { - callback(match.index, match.index + match.word.length); - } - }); - - [...sysVarMatches].forEach(match => { - if (SysVariables.includes(match.word) || match.word.includes("{{#num,") || match.word.includes("{{#date,")) { - callback(match.index, match.index + match.word.length); - } - } - ); - } - - function findWithRegexUnMatched(words: string[], contentBlock: any, callback: any) { - const text = contentBlock.getText(); - - let regexEx = /{{[A-Za-z0-9\s!@#$%^&*()_+=-`~\\\]\[|';:\/.,?><]+}}/; - let sysVarRegex = /(({{#)((num|str|char|rdate|date|dateISO|email|guid|bool)|(num,[ ]?[0-9]+,[ ]?[0-9]+)|(date,( )*[a-zA-Z $&+,:;=?@#|'<>.^*()%!-\/]*))(}}))/; - const matches = [...text.matchAll(new RegExp(regexEx, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); - const sysVarMatches = [...text.matchAll(new RegExp(sysVarRegex, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); - - [...matches].forEach(match => { - let word = match.word.replace("{{", "").replace("}}", "").trim(); - if (!words.includes(word)) { - callback(match.index, match.index + match.word.length); - } - } - ); - - [...sysVarMatches].forEach(match => { - if (!SysVariables.includes(match.word) && !match.word.includes("{{#num,") && !match.word.includes("{{#date,")) { - callback(match.index, match.index + match.word.length); - } - } - ); - } - - function matchedHandleStrategy(contentBlock: any, callback: any) { - findWithRegex(props.varWords, contentBlock, callback); - } - - function unmatchedHandleStrategy(contentBlock: any, callback: any) { - findWithRegexUnMatched(props.varWords, contentBlock, callback); - } - - const createDecorator = () => - new CompositeDecorator([ - { - strategy: matchedHandleStrategy, - component: matchedDecorated - }, - { - strategy: unmatchedHandleStrategy, - component: unmatchedDecorated - } - ]); - - const [editorState, setEditorState] = React.useState( - EditorState.createWithContent(ContentState.createFromText(props.value ?? ""), createDecorator()) - ); - - useEffect(() => { - if (props.value !== curValue) { - - setChangeHandle(false); - - let currentContent = editorState.getCurrentContent(); - - let selection = editorState.getSelection().merge({ - anchorKey: currentContent.getFirstBlock().getKey(), - anchorOffset: 0, - focusOffset: currentContent.getLastBlock().getText().length, - focusKey: currentContent.getLastBlock().getKey(), - }); - - handleChange(EditorState.push( - editorState, - Modifier.replaceText( - currentContent, - selection, - props.value), - editorState.getLastChangeType(), - )); - } - }, [props.value]); - - function focusEditor() { - if (props.focus) { - editor.current.focus(); - } - } - - useEffect(() => { - if (selectedVariable.data.length > 0) { - let varData = {}; - - setEditorState(EditorState.set(editorState, { decorator: createDecorator() })); - - selectedVariable.data.forEach(item => { - varData[item.key] = item.value; - }); - - setVarData(varData); - } - }, [selectedVariable]); - - React.useEffect(() => { - focusEditor(); - }, []); - - const handlePaste = (text: string, _html: string | undefined, editorState: EditorState): DraftHandleValue => { - if (props.maxLength) { - const totalLength = charLength + text.length; - - if (totalLength > props.maxLength) { - text = text.trim().replace(/\n/g, ' ').substring(0, props.maxLength); - } - } - handleChange(EditorState.push( - editorState, - Modifier.replaceText( - editorState.getCurrentContent(), - editorState.getSelection(), - text.replace(/\n/g, ' ')), - editorState.getLastChangeType(), - )); - - return 'handled'; - }; - - const handleChange = (changeEditorState: EditorState) => { - - setEditorState(changeEditorState); - - let hasText = changeEditorState.getCurrentContent().hasText(); - let text = ""; - - if (hasText) { - text = changeEditorState.getCurrentContent().getPlainText('\u0001'); - } - - if (props.onChange && changeHandle) { - props.onChange(text); - } - - setCurValue(text); - setLength(text.length); - setChangeHandle(true); - }; - - function handleBeforeInput(chars: string, _changeEditorState: EditorState, _eventTimeStamp: number) { - if (!props.maxLength) { - return 'not-handled'; - } - const totalLength = charLength + chars.length; - return totalLength > props.maxLength ? 'handled' : 'not-handled'; - } - - function myKeyBindingFn(e: any): string | null { - if (props.onKeyPress) { - props.onKeyPress(e.keyCode); - } - - if (e.keyCode === 13) { - return 'enter_command'; - } - - return getDefaultKeyBinding(e); - } - - return ( -
-
- -
-
- ); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + + const [charLength, setLength] = useState(0); + const [curValue, setCurValue] = useState(""); + const [changeHandle, setChangeHandle] = useState(false); + + const refVarData = useRef({}); + const setVarData = (value: {}) => { + refVarData.current = value; + }; + + const editor = React.useRef(null); + + const matchedDecorated = (props: any) => { + if (!checkSysVariable(props.decoratedText)) { + let title = replaceDataWithVariable(props.decoratedText, refVarData.current); + if (title) { + return {props.children}; + } + } + + return {props.children}; + }; + + const unmatchedDecorated = ({ children }) => { + return {children}; + }; + + function findWithRegex(words: string[], contentBlock: any, callback: any) { + const text = contentBlock.getText(); + + let regexEx = /{{[A-Za-z0-9\s!@#$%^&*()_+=-`~\\\]\[|';:\/.,?><]+}}/; + let sysVarRegex = /(({{#)((num|str|char|rdate|date|dateISO|email|guid|bool)|(num,[ ]?[0-9]+,[ ]?[0-9]+)|(date,( )*[a-zA-Z $&+,:;=?@#|'<>.^*()%!-\/]*))(}}))/; + const matches = [...text.matchAll(new RegExp(regexEx, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); + const sysVarMatches = [...text.matchAll(new RegExp(sysVarRegex, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); + + [...matches].forEach(match => { + let word = match.word.replace("{{", "").replace("}}", "").trim(); + if (words.includes(word)) { + callback(match.index, match.index + match.word.length); + } + }); + + [...sysVarMatches].forEach(match => { + if (SysVariables.includes(match.word) || match.word.includes("{{#num,") || match.word.includes("{{#date,")) { + callback(match.index, match.index + match.word.length); + } + } + ); + } + + function findWithRegexUnMatched(words: string[], contentBlock: any, callback: any) { + const text = contentBlock.getText(); + + let regexEx = /{{[A-Za-z0-9\s!@#$%^&*()_+=-`~\\\]\[|';:\/.,?><]+}}/; + let sysVarRegex = /(({{#)((num|str|char|rdate|date|dateISO|email|guid|bool)|(num,[ ]?[0-9]+,[ ]?[0-9]+)|(date,( )*[a-zA-Z $&+,:;=?@#|'<>.^*()%!-\/]*))(}}))/; + const matches = [...text.matchAll(new RegExp(regexEx, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); + const sysVarMatches = [...text.matchAll(new RegExp(sysVarRegex, 'gm'))].map(a => { return { index: a.index, word: a[0] }; }); + + [...matches].forEach(match => { + let word = match.word.replace("{{", "").replace("}}", "").trim(); + if (!words.includes(word)) { + callback(match.index, match.index + match.word.length); + } + } + ); + + [...sysVarMatches].forEach(match => { + if (!SysVariables.includes(match.word) && !match.word.includes("{{#num,") && !match.word.includes("{{#date,")) { + callback(match.index, match.index + match.word.length); + } + } + ); + } + + function matchedHandleStrategy(contentBlock: any, callback: any) { + findWithRegex(props.varWords, contentBlock, callback); + } + + function unmatchedHandleStrategy(contentBlock: any, callback: any) { + findWithRegexUnMatched(props.varWords, contentBlock, callback); + } + + const createDecorator = () => + new CompositeDecorator([ + { + strategy: matchedHandleStrategy, + component: matchedDecorated + }, + { + strategy: unmatchedHandleStrategy, + component: unmatchedDecorated + } + ]); + + const [editorState, setEditorState] = React.useState( + EditorState.createWithContent(ContentState.createFromText(props.value ?? ""), createDecorator()) + ); + + useEffect(() => { + if (props.value !== curValue) { + + setChangeHandle(false); + + let currentContent = editorState.getCurrentContent(); + + let selection = editorState.getSelection().merge({ + anchorKey: currentContent.getFirstBlock().getKey(), + anchorOffset: 0, + focusOffset: currentContent.getLastBlock().getText().length, + focusKey: currentContent.getLastBlock().getKey(), + }); + + handleChange(EditorState.push( + editorState, + Modifier.replaceText( + currentContent, + selection, + props.value), + editorState.getLastChangeType(), + )); + } + }, [props.value]); + + function focusEditor() { + if (props.focus) { + editor.current.focus(); + } + } + + useEffect(() => { + if (selectedVariable.data.length > 0) { + let varData = {}; + + setEditorState(EditorState.set(editorState, { decorator: createDecorator() })); + + selectedVariable.data.forEach(item => { + varData[item.key] = item.value; + }); + + setVarData(varData); + } + }, [selectedVariable]); + + React.useEffect(() => { + focusEditor(); + }, []); + + const handlePaste = (text: string, _html: string | undefined, editorState: EditorState): DraftHandleValue => { + if (props.maxLength) { + const totalLength = charLength + text.length; + + if (totalLength > props.maxLength) { + text = text.trim().replace(/\n/g, ' ').substring(0, props.maxLength); + } + } + handleChange(EditorState.push( + editorState, + Modifier.replaceText( + editorState.getCurrentContent(), + editorState.getSelection(), + text.replace(/\n/g, ' ')), + editorState.getLastChangeType(), + )); + + return 'handled'; + }; + + const handleChange = (changeEditorState: EditorState) => { + + setEditorState(changeEditorState); + + let hasText = changeEditorState.getCurrentContent().hasText(); + let text = ""; + + if (hasText) { + text = changeEditorState.getCurrentContent().getPlainText('\u0001'); + } + + if (props.onChange && changeHandle) { + props.onChange(text); + } + + setCurValue(text); + setLength(text.length); + setChangeHandle(true); + }; + + function handleBeforeInput(chars: string, _changeEditorState: EditorState, _eventTimeStamp: number) { + if (!props.maxLength) { + return 'not-handled'; + } + const totalLength = charLength + chars.length; + return totalLength > props.maxLength ? 'handled' : 'not-handled'; + } + + function myKeyBindingFn(e: any): string | null { + if (props.onKeyPress) { + props.onKeyPress(e.keyCode); + } + + if (e.keyCode === 13) { + return 'enter_command'; + } + + return getDefaultKeyBinding(e); + } + + return ( +
+
+ +
+
+ ); }; diff --git a/src/fetch-client-ui/components/Common/TextEditor/style.css b/src/fetch-client-ui/components/Common/TextEditor/style.css index e58589e..ba49bfd 100644 --- a/src/fetch-client-ui/components/Common/TextEditor/style.css +++ b/src/fetch-client-ui/components/Common/TextEditor/style.css @@ -1,24 +1,24 @@ .public-DraftStyleDefault-block { - overflow-x : auto; - white-space: pre; + overflow-x : auto; + white-space: pre; } .outer-container *::-webkit-scrollbar { - height : 0px; - background: transparent; + height : 0px; + background: transparent; } .outer-container * { - scrollbar-width: none; + scrollbar-width: none; } .public-DraftEditorPlaceholder-inner { - position : absolute; - pointer-events: none; - color : gray; - padding : 10px; + position : absolute; + pointer-events: none; + color : gray; + padding : 10px; } .DraftEditor-root { - position: relative; -} \ No newline at end of file + position: relative; +} diff --git a/src/fetch-client-ui/components/Common/TypesGenerator/consts.ts b/src/fetch-client-ui/components/Common/TypesGenerator/consts.ts index b1e6975..8974620 100644 --- a/src/fetch-client-ui/components/Common/TypesGenerator/consts.ts +++ b/src/fetch-client-ui/components/Common/TypesGenerator/consts.ts @@ -1,14 +1,14 @@ export const codeTypesLangunages = [ - { name: "C#", value: "cs", editorLang: "csharp" }, - { name: "C++", value: "cpp", editorLang: "cpp" }, - { name: "Dart", value: "dart", editorLang: "dart" }, - { name: "Go", value: "go", editorLang: "go" }, - { name: "Java", value: "java" , editorLang: "java"}, - { name: "JavaScript", value: "js" , editorLang: "javascript"}, - { name: "JSON Schema", value: "schema", editorLang: "json" }, - { name: "Kotlin", value: "kotlin" , editorLang: "kotlin"}, - { name: "Python", value: "python", editorLang: "python" }, - { name: "Ruby", value: "ruby", editorLang: "ruby" }, - { name: "Swift", value: "swift" , editorLang: "swift"}, - { name: "TypeScript", value: "ts" , editorLang: "typescript"}, -]; \ No newline at end of file + { name: "C#", value: "cs", editorLang: "csharp" }, + { name: "C++", value: "cpp", editorLang: "cpp" }, + { name: "Dart", value: "dart", editorLang: "dart" }, + { name: "Go", value: "go", editorLang: "go" }, + { name: "Java", value: "java" , editorLang: "java"}, + { name: "JavaScript", value: "js" , editorLang: "javascript"}, + { name: "JSON Schema", value: "schema", editorLang: "json" }, + { name: "Kotlin", value: "kotlin" , editorLang: "kotlin"}, + { name: "Python", value: "python", editorLang: "python" }, + { name: "Ruby", value: "ruby", editorLang: "ruby" }, + { name: "Swift", value: "swift" , editorLang: "swift"}, + { name: "TypeScript", value: "ts" , editorLang: "typescript"}, +]; diff --git a/src/fetch-client-ui/components/Common/TypesGenerator/index.tsx b/src/fetch-client-ui/components/Common/TypesGenerator/index.tsx index 34b04e5..048a542 100644 --- a/src/fetch-client-ui/components/Common/TypesGenerator/index.tsx +++ b/src/fetch-client-ui/components/Common/TypesGenerator/index.tsx @@ -1,92 +1,92 @@ +import { InputData, jsonInputForTargetLanguage, quicktype } from "quicktype-core"; import React, { useEffect, useState } from "react"; -import { quicktype, InputData, jsonInputForTargetLanguage } from "quicktype-core"; +import { useSelector } from "react-redux"; +import { IRootState } from "../../../reducer/combineReducer"; import { MonacoEditor } from "../Editor"; import { codeTypesLangunages } from "./consts"; -import { IRootState } from "../../../reducer/combineReducer"; -import { useSelector } from "react-redux"; const TypesGenerator = () => { - const responseData = useSelector((state: IRootState) => state.responseData.response.responseData); + const responseData = useSelector((state: IRootState) => state.responseData.response.responseData); - const [language, setLang] = useState("cs"); - const [editorLanguage, setEditorLang] = useState("csharp"); - const [codeTypes, setCodeTypes] = useState(""); + const [language, setLang] = useState("cs"); + const [editorLanguage, setEditorLang] = useState("csharp"); + const [codeTypes, setCodeTypes] = useState(""); - async function quicktypeJSON(targetLanguage: string, typeName: string, jsonString: string) { - const jsonInput = jsonInputForTargetLanguage(targetLanguage); + async function quicktypeJSON(targetLanguage: string, typeName: string, jsonString: string) { + const jsonInput = jsonInputForTargetLanguage(targetLanguage); - await jsonInput.addSource({ - name: typeName, - samples: [jsonString], - }); + await jsonInput.addSource({ + name: typeName, + samples: [jsonString], + }); - const inputData = new InputData(); - inputData.addInput(jsonInput); - let rendererOptions = { package: "generated_types", namespace: "Generated_Types" }; - if (targetLanguage === "cs") { - rendererOptions["features"] = "just-types"; - } else if (targetLanguage === "kotlin") { - rendererOptions["framework"] = "just-types"; - } else { - rendererOptions["just-types"] = "true"; - } + const inputData = new InputData(); + inputData.addInput(jsonInput); + let rendererOptions = { package: "generated_types", namespace: "Generated_Types" }; + if (targetLanguage === "cs") { + rendererOptions["features"] = "just-types"; + } else if (targetLanguage === "kotlin") { + rendererOptions["framework"] = "just-types"; + } else { + rendererOptions["just-types"] = "true"; + } - return await quicktype({ - inputData, - lang: targetLanguage, - rendererOptions: rendererOptions, - }); - } + return await quicktype({ + inputData, + lang: targetLanguage, + rendererOptions: rendererOptions, + }); + } - useEffect(() => { - quicktypeJSON(language, "Root", responseData).then((i) => { - setCodeTypes(i.lines.join("\n")); - }); - }, []); + useEffect(() => { + quicktypeJSON(language, "Root", responseData).then((i) => { + setCodeTypes(i.lines.join("\n")); + }); + }, []); - function onSelectedLanguage(e: React.ChangeEvent) { - setLang(e.target.value); - let editorLang = codeTypesLangunages.filter(i => i.value === e.target.value)[0].editorLang; - setEditorLang(editorLang); - quicktypeJSON(e.target.value, "Root", responseData).then((i) => { - setCodeTypes(i.lines.join("\n")); - }); - } + function onSelectedLanguage(e: React.ChangeEvent) { + setLang(e.target.value); + let editorLang = codeTypesLangunages.filter(i => i.value === e.target.value)[0].editorLang; + setEditorLang(editorLang); + quicktypeJSON(e.target.value, "Root", responseData).then((i) => { + setCodeTypes(i.lines.join("\n")); + }); + } - return ( -
-
- {codeTypes && <>
-
- - -
-
-
- -
- - } -
- ); + return ( +
+
+ {codeTypes && <>
+
+ + +
+
+
+ +
+ + } +
+ ); }; -export default TypesGenerator; \ No newline at end of file +export default TypesGenerator; diff --git a/src/fetch-client-ui/components/Common/Viewer/HTMLViewer.tsx b/src/fetch-client-ui/components/Common/Viewer/HTMLViewer.tsx index 241cd38..d973b6c 100644 --- a/src/fetch-client-ui/components/Common/Viewer/HTMLViewer.tsx +++ b/src/fetch-client-ui/components/Common/Viewer/HTMLViewer.tsx @@ -3,9 +3,9 @@ import "./style.css"; import { ViewerProps } from './types'; export const HTMLViewer = (props: ViewerProps) => { - return ( -
- -
- ); -}; \ No newline at end of file + return ( +
+ +
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/Viewer/JSONViewer.tsx b/src/fetch-client-ui/components/Common/Viewer/JSONViewer.tsx index d4e20c7..290037d 100644 --- a/src/fetch-client-ui/components/Common/Viewer/JSONViewer.tsx +++ b/src/fetch-client-ui/components/Common/Viewer/JSONViewer.tsx @@ -7,33 +7,33 @@ import { ViewerProps } from './types'; export const JSONViewer = (props: ViewerProps) => { - const { theme } = useSelector((state: IRootState) => state.uiData); - - const [jsonData, setJsonData] = useState({}); - const [isValid, setValid] = useState(false); + const { theme } = useSelector((state: IRootState) => state.uiData); - useEffect(() => { - try { - setJsonData(JSON.parse(props.data)); - setValid(true); - } catch { - setValid(false); - } - }, []); + const [jsonData, setJsonData] = useState({}); + const [isValid, setValid] = useState(false); - return ( -
- { - isValid ? - - : - {"Invalid JSON."} - } -
- ); -}; \ No newline at end of file + useEffect(() => { + try { + setJsonData(JSON.parse(props.data)); + setValid(true); + } catch { + setValid(false); + } + }, []); + + return ( +
+ { + isValid ? + + : + {"Invalid JSON."} + } +
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/Viewer/XMLViewer.tsx b/src/fetch-client-ui/components/Common/Viewer/XMLViewer.tsx index fdb3467..a37e768 100644 --- a/src/fetch-client-ui/components/Common/Viewer/XMLViewer.tsx +++ b/src/fetch-client-ui/components/Common/Viewer/XMLViewer.tsx @@ -1,48 +1,48 @@ -import { IRootState } from '../../../reducer/combineReducer'; -import { useSelector } from 'react-redux'; -import { ViewerProps } from './types'; import { XMLParser, XMLValidator } from 'fast-xml-parser'; import React, { useEffect, useState } from 'react'; import ReactJson from 'react-json-view'; +import { useSelector } from 'react-redux'; +import { IRootState } from '../../../reducer/combineReducer'; import "./style.css"; +import { ViewerProps } from './types'; export const XMLViewer = (props: ViewerProps) => { - const { theme } = useSelector((state: IRootState) => state.uiData); - - const [jsonData, setJsonData] = useState({}); - const [isValid, setValid] = useState(false); + const { theme } = useSelector((state: IRootState) => state.uiData); + + const [jsonData, setJsonData] = useState({}); + const [isValid, setValid] = useState(false); - useEffect(() => { - if (XMLValidator.validate(props.data) === true) { - const options = { - ignoreAttributes: false, - attributeNamePrefix: "@", - allowBooleanAttributes: true, - removeNSPrefix: true - }; - const parser = new XMLParser(options); - const jsonObj = parser.parse(props.data); - setJsonData(jsonObj); - setValid(true); - } else { - setValid(false); - } - }, []); + useEffect(() => { + if (XMLValidator.validate(props.data) === true) { + const options = { + ignoreAttributes: false, + attributeNamePrefix: "@", + allowBooleanAttributes: true, + removeNSPrefix: true + }; + const parser = new XMLParser(options); + const jsonObj = parser.parse(props.data); + setJsonData(jsonObj); + setValid(true); + } else { + setValid(false); + } + }, []); - return ( -
- { - isValid ? - - : - {"Invalid XML."} - } -
- ); -}; \ No newline at end of file + return ( +
+ { + isValid ? + + : + {"Invalid XML."} + } +
+ ); +}; diff --git a/src/fetch-client-ui/components/Common/Viewer/style.css b/src/fetch-client-ui/components/Common/Viewer/style.css index a80d809..22172e2 100644 --- a/src/fetch-client-ui/components/Common/Viewer/style.css +++ b/src/fetch-client-ui/components/Common/Viewer/style.css @@ -1,34 +1,34 @@ .react-json-view { - background-color: transparent !important; - padding: 10px; - height: 99% !important; + background-color: transparent !important; + padding: 10px; + height: 99% !important; } .json-viewer-panel { - height: 100%; - box-sizing: border-box; - overflow: scroll; - border: var(--border-size) solid var(--border-color); + height: 100%; + box-sizing: border-box; + overflow: scroll; + border: var(--border-size) solid var(--border-color); } .json-viewer-error { - padding-left: 10px; + padding-left: 10px; } .variable-row { - border-left: 0 !important + border-left: 0 !important } .object-key-val { - border-left: 0 !important + border-left: 0 !important } .html-viewer-panel { - height: 100%; + height: 100%; } .html-viewer-panel iframe { - width: 100%; - height: 100%; - border: var(--border-size) solid var(--border-color); -} \ No newline at end of file + width: 100%; + height: 100%; + border: var(--border-size) solid var(--border-color); +} diff --git a/src/fetch-client-ui/components/Common/Viewer/types.ts b/src/fetch-client-ui/components/Common/Viewer/types.ts index 138c74d..6f5cea2 100644 --- a/src/fetch-client-ui/components/Common/Viewer/types.ts +++ b/src/fetch-client-ui/components/Common/Viewer/types.ts @@ -1,4 +1,4 @@ export interface ViewerProps { - data: string; - theme?: number; - } \ No newline at end of file + data: string; + theme?: number; + } diff --git a/src/fetch-client-ui/components/Common/helper.ts b/src/fetch-client-ui/components/Common/helper.ts index b95962e..53a2c5d 100644 --- a/src/fetch-client-ui/components/Common/helper.ts +++ b/src/fetch-client-ui/components/Common/helper.ts @@ -3,37 +3,59 @@ import { ITableData } from "./Table/types"; export const notesMaxLimit = 2500; export function GetDataFromHTML(data: string): string { - let removedData: string; - removedData = data?.replace(/(<([^>]+)>)/gm, ''); - removedData = removedData?.replace(/( |>|<|&)/gm, ' '); - return removedData; + let removedData: string; + removedData = data?.replace(/(<([^>]+)>)/gm, ''); + removedData = removedData?.replace(/( |>|<|&)/gm, ' '); + return removedData; } export function GetDomainName(url: string, cookie: ITableData): string { - let domainName = ""; - - try { - url = url.startsWith("http://") || url.startsWith("https:// ") ? url : "https://" + url; - let domain = (new URL(url)); - domainName = domain.hostname.replace('www.', '').trim(); - } - catch { - let startIndex = cookie.value.indexOf("domain="); - let endIndex = -1; - if (startIndex !== -1) { - let str = cookie.value.substring(startIndex); - str = str.replace("domain=", "").trim(); - endIndex = str.indexOf(";"); - domainName = str.substring(0, endIndex === -1 ? cookie.value.length - 1 : endIndex); - if (domainName.charAt(0) === ".") { - domainName = domainName.replace(".", "").trim(); - } - } - } - - return domainName; + let domainName = ""; + + if (!url && !cookie) { + return null; + } + + try { + domainName = getDomainNameFromURL(url); + } + catch { + domainName = getDomainNameFromCookie(cookie); + } + + return domainName; +} + +function getDomainNameFromCookie(cookie: ITableData): string { + let domainName = ""; + let startIndex = cookie.value.indexOf("domain="); + let endIndex = -1; + if (startIndex !== -1) { + let str = cookie.value.substring(startIndex); + str = str.replace("domain=", "").trim(); + endIndex = str.indexOf(";"); + domainName = str.substring(0, endIndex === -1 ? cookie.value.length - 1 : endIndex); + if (domainName.charAt(0) === ".") { + domainName = domainName.replace(".", "").trim(); + } + } + + return domainName; +} + +export function getDomainNameFromURL(url: string): string { + let domainName = ""; + if (url.startsWith("http://") || url.startsWith("https://")) { + url = url; + } else { + url = "https://" + url; + } + let domain = new URL(url); + domainName = domain.hostname.replace('www.', '').trim(); + + return domainName; } export function GetFileName(path: string) { - return path.split('\\').pop().split("/").pop(); -} \ No newline at end of file + return path.split('\\').pop().split("/").pop(); +} diff --git a/src/fetch-client-ui/components/Common/icons.tsx b/src/fetch-client-ui/components/Common/icons.tsx index 8f9b17a..f2e6587 100644 --- a/src/fetch-client-ui/components/Common/icons.tsx +++ b/src/fetch-client-ui/components/Common/icons.tsx @@ -1,21 +1,21 @@ import React from "react"; export function getPlusIconSVG(toolTip: string, className: string, onContextMenu: React.MouseEventHandler, onClick: React.MouseEventHandler) { - return ( - - {toolTip} - - {toolTip} - - - ); + return ( + + {toolTip} + + {toolTip} + + + ); } export function getColFolDotMenu(id: string, toolTip: string, className: string, onContextMenu: React.MouseEventHandler, onClick: React.MouseEventHandler) { - return ( - {toolTip} - - - - ); + return ( + {toolTip} + + + + ); } diff --git a/src/fetch-client-ui/components/Common/vscodeAPI.ts b/src/fetch-client-ui/components/Common/vscodeAPI.ts index 1a98e06..02f1853 100644 --- a/src/fetch-client-ui/components/Common/vscodeAPI.ts +++ b/src/fetch-client-ui/components/Common/vscodeAPI.ts @@ -2,7 +2,7 @@ declare var acquireVsCodeApi: any; let vscode; if (typeof acquireVsCodeApi !== "undefined") { - vscode = acquireVsCodeApi(); + vscode = acquireVsCodeApi(); } -export default vscode; \ No newline at end of file +export default vscode; diff --git a/src/fetch-client-ui/components/Cookies/index.tsx b/src/fetch-client-ui/components/Cookies/index.tsx index 6ae514d..54e4cb0 100644 --- a/src/fetch-client-ui/components/Cookies/index.tsx +++ b/src/fetch-client-ui/components/Cookies/index.tsx @@ -1,150 +1,143 @@ import React, { useEffect, useRef, useState } from "react"; import { requestTypes, responseTypes } from "../../../utils/configuration"; +import { ResponseTable } from "../Common/Table/ResponseTable"; import vscode from "../Common/vscodeAPI"; -import { ICookie } from "./redux/types"; import { InitialCookie } from "./redux/reducer"; -import { ResponseTable } from "../Common/Table/ResponseTable"; +import { ICookie } from "./redux/types"; import "./style.css"; const ManageCookies = () => { - const [isDone, setDone] = useState(false); - const [cookies, _setCookies] = useState(null); - const cookiesRef = useRef(cookies); - const setCookies = (data: ICookie[]) => { - cookiesRef.current = data; - _setCookies(data); - }; + const [cookies, _setCookies] = useState(null); + const cookiesRef = useRef(cookies); + const setCookies = (data: ICookie[]) => { + cookiesRef.current = data; + _setCookies(data); + }; - const [currentCookie, setCurrentCookie] = useState(InitialCookie); - const [cookieId, setSelecetdCookieId] = useState(""); + const [currentCookie, setCurrentCookie] = useState(InitialCookie); + const [cookieId, setSelecetdCookieId] = useState(""); - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getAllCookiesResponse) { - let cookies = event.data.cookies as ICookie[]; - setCookies(cookies); - } else if (event.data && event.data.type === responseTypes.deleteCookieByIdResponse) { - setDone(true); - let localData = [...cookiesRef.current]; - let index = localData.findIndex(item => item.id === event.data.id); - if (index !== -1) { - localData.splice(index, 1); - } - setCookies(localData); - } else if (event.data && event.data.type === responseTypes.deleteAllCookieResponse) { - setDone(true); - let localData = [...cookiesRef.current]; - localData.length = 0; - setCookies(localData); - } - }); + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getAllCookiesResponse) { + let cookies = event.data.cookies as ICookie[]; + setCookies(cookies); + } else if (event.data && event.data.type === responseTypes.deleteCookieByIdResponse) { + let localData = [...cookiesRef.current]; + let index = localData.findIndex(item => item.id === event.data.id); + if (index !== -1) { + localData.splice(index, 1); + } + setCookies(localData); + } else if (event.data && event.data.type === responseTypes.deleteAllCookieResponse) { + let localData = [...cookiesRef.current]; + localData.length = 0; + setCookies(localData); + } + }); - vscode.postMessage({ type: requestTypes.getAllCookiesRequest }); - }, []); + vscode.postMessage({ type: requestTypes.getAllCookiesRequest }); + }, []); - useEffect(() => { - if (cookies && cookies.length > 0) { - let id = document.title.split("@:@")[1]; - if (id !== "undefined" && id !== '[object Object]') { - setSelecetdCookieId(id); - setCurrentCookie(cookies.find(item => item.id === id)); - } else { - setSelecetdCookieId(cookies[0].id); - setCurrentCookie(cookies[0]); - } - } else { - setCurrentCookie(InitialCookie); - setSelecetdCookieId(""); - } - }, [cookies]); + useEffect(() => { + if (cookies && cookies.length > 0) { + let id = document.title.split("@:@")[1]; + if (id !== "undefined" && id !== '[object Object]') { + setSelecetdCookieId(id); + setCurrentCookie(cookies.find(item => item.id === id)); + } else { + setSelecetdCookieId(cookies[0].id); + setCurrentCookie(cookies[0]); + } + } else { + setCurrentCookie(InitialCookie); + setSelecetdCookieId(""); + } + }, [cookies]); - function onSubmitClick() { - vscode.postMessage({ type: requestTypes.deleteCookieByIdRequest, data: currentCookie.id }); - } + function onSubmitClick() { + vscode.postMessage({ type: requestTypes.deleteCookieByIdRequest, data: currentCookie.id }); + } - function onDeleteAllClick() { - vscode.postMessage({ type: requestTypes.deleteAllCookieRequest }); - } + function onDeleteAllClick() { + vscode.postMessage({ type: requestTypes.deleteAllCookieRequest }); + } - function isDisabled(): boolean { - if (currentCookie && !currentCookie.id) { - return true; - } + function isDisabled(): boolean { + if (currentCookie && !currentCookie.id) { + return true; + } - return false; - } + return false; + } - const onSelect = (event: React.ChangeEvent) => { - setSelecetdCookieId(event.target.value); - setCurrentCookie(cookies.find(item => item.id === event.target.value)); - setDone(false); - }; + const onSelect = (event: React.ChangeEvent) => { + setSelecetdCookieId(event.target.value); + setCurrentCookie(cookies.find(item => item.id === event.target.value)); + }; - return ( -
-
Manage Cookies
- { - cookies && cookies.length > 0 ? - <> -
- Cookie : - -
-
- {currentCookie && currentCookie.data && currentCookie.data.length && } -
-
- - -
-
- {isDone && (Deleted successfully)} -
- - : -
{"No Cookies Available"}
- } -
- ); + return ( +
+
🌐 Manage Cookies
+ { + cookies && cookies.length > 0 ? + <> +
+ Cookie : + +
+ + +
+
+
+ {currentCookie && currentCookie.data && currentCookie.data.length && } +
+ + : +
{"No Cookies Available"}
+ } +
+ ); }; -export default ManageCookies; \ No newline at end of file +export default ManageCookies; diff --git a/src/fetch-client-ui/components/Cookies/redux/actions.ts b/src/fetch-client-ui/components/Cookies/redux/actions.ts index ee2a8c5..25cf104 100644 --- a/src/fetch-client-ui/components/Cookies/redux/actions.ts +++ b/src/fetch-client-ui/components/Cookies/redux/actions.ts @@ -1,10 +1,10 @@ import { CookieActionTypes, FETCH_CLIENT_SET_ALL_COOKIE, ICookie } from "./types"; export const SetAllCookiesAction = (value: ICookie[]): CookieActionTypes => { - return { - type: FETCH_CLIENT_SET_ALL_COOKIE, - payload: { - cookies: value - } - }; + return { + type: FETCH_CLIENT_SET_ALL_COOKIE, + payload: { + cookies: value + } + }; }; diff --git a/src/fetch-client-ui/components/Cookies/redux/index.ts b/src/fetch-client-ui/components/Cookies/redux/index.ts index 5989f36..860a85c 100644 --- a/src/fetch-client-ui/components/Cookies/redux/index.ts +++ b/src/fetch-client-ui/components/Cookies/redux/index.ts @@ -3,6 +3,6 @@ import { CookieReducer } from "./reducer"; export { - CookiesActions, - CookieReducer + CookiesActions, + CookieReducer }; diff --git a/src/fetch-client-ui/components/Cookies/redux/reducer.ts b/src/fetch-client-ui/components/Cookies/redux/reducer.ts index 24babcb..1892b4c 100644 --- a/src/fetch-client-ui/components/Cookies/redux/reducer.ts +++ b/src/fetch-client-ui/components/Cookies/redux/reducer.ts @@ -1,28 +1,28 @@ -import { CookieActionTypes, FETCH_CLIENT_SET_ALL_COOKIE, FETCH_CLIENT_SET_COOKIE, ICookie, ICookiesModel } from "./types"; +import { CookieActionTypes, FETCH_CLIENT_SET_ALL_COOKIE, ICookie, ICookiesModel } from "./types"; export const InitialCookie: ICookie = { - id: "", - name: "", - data: [] + id: "", + name: "", + data: [] }; export const InitialState: ICookiesModel = { - cookies: [], + cookies: [], }; export const CookieReducer: (state?: ICookiesModel, - action?: CookieActionTypes) => ICookiesModel = - (state: ICookiesModel = InitialState, - action: CookieActionTypes = {} as CookieActionTypes): ICookiesModel => { - switch (action.type) { - case FETCH_CLIENT_SET_ALL_COOKIE: { - return { - ...state, - cookies: action.payload.cookies - }; - } - default: { - return state; - } - } - }; + action?: CookieActionTypes) => ICookiesModel = + (state: ICookiesModel = InitialState, + action: CookieActionTypes = {} as CookieActionTypes): ICookiesModel => { + switch (action.type) { + case FETCH_CLIENT_SET_ALL_COOKIE: { + return { + ...state, + cookies: action.payload.cookies + }; + } + default: { + return state; + } + } + }; diff --git a/src/fetch-client-ui/components/Cookies/redux/types.ts b/src/fetch-client-ui/components/Cookies/redux/types.ts index ec83fcb..49e45cc 100644 --- a/src/fetch-client-ui/components/Cookies/redux/types.ts +++ b/src/fetch-client-ui/components/Cookies/redux/types.ts @@ -4,28 +4,28 @@ export const FETCH_CLIENT_SET_COOKIE: "FETCH_CLIENT_SET_COOKIE" = "FETCH_CLIENT_ export const FETCH_CLIENT_SET_ALL_COOKIE: "FETCH_CLIENT_SET_ALL_COOKIE" = "FETCH_CLIENT_SET_ALL_COOKIE"; export interface ICookie { - id: string; - name: string; - data: ITableData[] + id: string; + name: string; + data: ITableData[] } export interface ICookiesModel { - cookies: ICookie[]; + cookies: ICookie[]; } export interface ISetCookie { - type: typeof FETCH_CLIENT_SET_COOKIE; - payload: { - currentCookie: ICookie; - }; + type: typeof FETCH_CLIENT_SET_COOKIE; + payload: { + currentCookie: ICookie; + }; } export interface ISetAllCookies { - type: typeof FETCH_CLIENT_SET_ALL_COOKIE; - payload: { - cookies: ICookie[]; - }; + type: typeof FETCH_CLIENT_SET_ALL_COOKIE; + payload: { + cookies: ICookie[]; + }; } -export type CookieActionTypes = | ISetCookie | ISetAllCookies; \ No newline at end of file +export type CookieActionTypes = | ISetCookie | ISetAllCookies; diff --git a/src/fetch-client-ui/components/Cookies/style.css b/src/fetch-client-ui/components/Cookies/style.css index 2943ece..612a0ac 100644 --- a/src/fetch-client-ui/components/Cookies/style.css +++ b/src/fetch-client-ui/components/Cookies/style.css @@ -1,19 +1,34 @@ .delete-all-button { - margin-left: 20px; - width : fit-content; + margin-left: 20px; + width : fit-content; } .cookie-panel { - padding: 25px 40px; - margin : 0 auto; - height : 92%; + padding: 25px 40px; + margin : 0 auto; + height : 92%; } .no-cookie-text { - padding: 20px; - padding-left: 100px; + padding: 20px; + padding-left: 100px; } .cookie-select { - width: 80% !important; -} \ No newline at end of file + width: 80% !important; +} + +.cookie-align-parent { + display: table; + vertical-align: middle; +} + +.cookie-align-child { + vertical-align: middle; +} + +.cookie-button-panel { + padding-left: 10px; + display: table-cell; + width: 40%; +} diff --git a/src/fetch-client-ui/components/Curl/helper.ts b/src/fetch-client-ui/components/Curl/helper.ts index 2eafffe..2e723f1 100644 --- a/src/fetch-client-ui/components/Curl/helper.ts +++ b/src/fetch-client-ui/components/Curl/helper.ts @@ -1,26 +1,26 @@ export function HandleColSelectionValidation(selectedCollection: string, colName: string, selectedFolder: string, folderName: string, errors: any, setErrors: any) { - if (selectedCollection === "") { - setErrors({ ...errors, "colSelect": "Please select/create the collection" }); - return false; - } + if (selectedCollection === "") { + setErrors({ ...errors, "colSelect": "Please select/create the collection" }); + return false; + } - if (selectedCollection === "0") { - if (!colName) { - setErrors({ ...errors, "colName": "Cannot be empty" }); - return false; - } - if (colName.toUpperCase().trim() === "DEFAULT") { - setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); - return false; - } - } + if (selectedCollection === "0") { + if (!colName) { + setErrors({ ...errors, "colName": "Cannot be empty" }); + return false; + } + if (colName.toUpperCase().trim() === "DEFAULT") { + setErrors({ ...errors, "colName": "Collection name should not be 'Default'" }); + return false; + } + } - if (selectedFolder === "0") { - if (!folderName) { - setErrors({ ...errors, "folderName": "Cannot be empty" }); - return false; - } - } + if (selectedFolder === "0") { + if (!folderName) { + setErrors({ ...errors, "folderName": "Cannot be empty" }); + return false; + } + } - return true; -} \ No newline at end of file + return true; +} diff --git a/src/fetch-client-ui/components/Curl/index.tsx b/src/fetch-client-ui/components/Curl/index.tsx index ffbb3c3..dffcfd3 100644 --- a/src/fetch-client-ui/components/Curl/index.tsx +++ b/src/fetch-client-ui/components/Curl/index.tsx @@ -3,301 +3,301 @@ import { useDispatch } from "react-redux"; import { v4 as uuidv4 } from 'uuid'; import { requestTypes, responseTypes } from "../../../utils/configuration"; import { formatDate } from "../../../utils/helper"; -import { HandleColSelectionValidation } from "./helper"; import vscode from "../Common/vscodeAPI"; import { ResponseActions } from "../ResponseUI/redux"; import { ReponsePanel } from "../ResponseUI/ResponsePanel"; import { InitialSettings } from "../SideBar/redux/reducer"; import { ICollections, IFolder, IHistory } from "../SideBar/redux/types"; +import { HandleColSelectionValidation } from "./helper"; import "./style.css"; const CurlUI = () => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const [curl, setCurl] = useState(""); - const [curlOption, setCurlOption] = useState("import"); - const [errors, setErrors] = useState({ - "colSelect": "", - "colName": "", - "folderName": "", - "curlError": "" - }); + const [curl, setCurl] = useState(""); + const [curlOption, setCurlOption] = useState("import"); + const [errors, setErrors] = useState({ + "colSelect": "", + "colName": "", + "folderName": "", + "curlError": "" + }); - const [selectedCollection, selSelectedCollection] = useState(""); - const [colName, setColName] = useState(""); - const [collections, setCollections] = useState([]); + const [selectedCollection, selSelectedCollection] = useState(""); + const [colName, setColName] = useState(""); + const [collections, setCollections] = useState([]); - const [isDone, setDone] = useState(false); + const [isDone, setDone] = useState(false); - const [selectedFolder, setSelectedFolder] = useState(""); - const [folderName, setFolderName] = useState(""); - const [folders, setFolders] = useState([]); - const [currentFolders, setCurrentFolders] = useState([]); + const [selectedFolder, setSelectedFolder] = useState(""); + const [folderName, setFolderName] = useState(""); + const [folders, setFolders] = useState([]); + const [currentFolders, setCurrentFolders] = useState([]); - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.runCurlResponse) { - dispatch(ResponseActions.SetResponseCookiesAction(event.data.response.cookies)); - dispatch(ResponseActions.SetResponseAction(event.data.response.response)); - dispatch(ResponseActions.SetResponseHeadersAction(event.data.response.headers)); - } else if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { - let colNames = [{ name: "Select", value: "", disabled: true }]; - colNames = [...colNames, ...event.data.collectionNames]; - colNames.push({ name: "----------------------", value: "-1", disabled: true }); - colNames.push({ name: "Create New", value: "0", disabled: false }); - setCollections(colNames); - setFolders(event.data.folderNames); - } else if (event.data && event.data.type === responseTypes.addToCollectionsResponse) { - setDone(true); - vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { colId: event.data.colId, folderId: event.data.folderId, id: event.data.historyId, name: event.data.historyName, varId: event.data.varId } }); - } else if (event.data && event.data.type === responseTypes.curlErrorResponse) { - setErrors({ - ...errors, "colSelect": "", - "colName": "", - "folderName": "", - "curlError": event.data.error - }); - } - }); + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.runCurlResponse) { + dispatch(ResponseActions.SetResponseCookiesAction(event.data.response.cookies)); + dispatch(ResponseActions.SetResponseAction(event.data.response.response)); + dispatch(ResponseActions.SetResponseHeadersAction(event.data.response.headers)); + } else if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { + let colNames = [{ name: "Select", value: "", disabled: true }]; + colNames = [...colNames, ...event.data.collectionNames]; + colNames.push({ name: "----------------------", value: "-1", disabled: true }); + colNames.push({ name: "Create New", value: "0", disabled: false }); + setCollections(colNames); + setFolders(event.data.folderNames); + } else if (event.data && event.data.type === responseTypes.addToCollectionsResponse) { + setDone(true); + vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { colId: event.data.colId, folderId: event.data.folderId, id: event.data.historyId, name: event.data.historyName, varId: event.data.varId } }); + } else if (event.data && event.data.type === responseTypes.curlErrorResponse) { + setErrors({ + ...errors, "colSelect": "", + "colName": "", + "folderName": "", + "curlError": event.data.error + }); + } + }); - vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }); + vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }); - }, []); + }, []); - function onCurlOptionSelect(type: string) { - setCurlOption(type); - } + function onCurlOptionSelect(type: string) { + setCurlOption(type); + } - function getCurlCommandSelection() { - return ( -
- onCurlOptionSelect("import")} /> Import - onCurlOptionSelect("run")} /> Run (Without Save) -
- ); - } + function getCurlCommandSelection() { + return ( +
+ onCurlOptionSelect("import")} /> Import + onCurlOptionSelect("run")} /> Run (Without Save) +
+ ); + } - function onRunClick() { - dispatch(ResponseActions.SetResponseLoadingAction(true)); - vscode.postMessage({ type: requestTypes.runCurlRequest, data: curl }); - } + function onRunClick() { + dispatch(ResponseActions.SetResponseLoadingAction(true)); + vscode.postMessage({ type: requestTypes.runCurlRequest, data: curl }); + } - function onImportClick() { - if (HandleColSelectionValidation(selectedCollection, colName, selectedFolder, folderName, errors, setErrors)) { + function onImportClick() { + if (HandleColSelectionValidation(selectedCollection, colName, selectedFolder, folderName, errors, setErrors)) { - let folder: IFolder; - let history: IHistory = { - id: uuidv4(), - method: "", - name: "", - url: "", - createdTime: formatDate() - }; + let folder: IFolder; + let history: IHistory = { + id: uuidv4(), + method: "", + name: "", + url: "", + createdTime: formatDate() + }; - if (selectedFolder) { - folder = { - id: selectedFolder === "0" ? uuidv4() : selectedFolder, - name: selectedFolder === "0" ? folderName : "", - createdTime: formatDate(), - type: "folder", - data: [history], - settings: InitialSettings - }; - } + if (selectedFolder) { + folder = { + id: selectedFolder === "0" ? uuidv4() : selectedFolder, + name: selectedFolder === "0" ? folderName : "", + createdTime: formatDate(), + type: "folder", + data: [history], + settings: InitialSettings + }; + } - let collection: ICollections = { - id: selectedCollection === "0" ? uuidv4() : selectedCollection, - createdTime: formatDate(), - name: selectedCollection === "0" ? colName : "", - data: folder ? [folder] : [history], - variableId: "", - settings: InitialSettings - }; + let collection: ICollections = { + id: selectedCollection === "0" ? uuidv4() : selectedCollection, + createdTime: formatDate(), + name: selectedCollection === "0" ? colName : "", + data: folder ? [folder] : [history], + variableId: "", + settings: InitialSettings + }; - vscode.postMessage({ type: requestTypes.convertCurlToJsonRequest, data: { curl: curl, col: collection, hasFolder: folder ? true : false, isNewFolder: selectedFolder === "0" ? true : false } }); - } - } + vscode.postMessage({ type: requestTypes.convertCurlToJsonRequest, data: { curl: curl, col: collection, hasFolder: folder ? true : false, isNewFolder: selectedFolder === "0" ? true : false } }); + } + } - function getButtonSection() { - return ( -
- -
- ); - } + function getButtonSection() { + return ( +
+ +
+ ); + } - function getCurlCommandUI() { - return ( -
- {getCurlCommandSelection()} - -
-
- - {curlOption === "run" && getButtonSection()} -
-
- ); - } + function getCurlCommandUI() { + return ( +
+ {getCurlCommandSelection()} + +
+
+ + {curlOption === "run" && getButtonSection()} +
+
+ ); + } - const onSelect = (event: React.ChangeEvent) => { - selSelectedCollection(event.target.value); - setColName(""); + const onSelect = (event: React.ChangeEvent) => { + selSelectedCollection(event.target.value); + setColName(""); - let folderNames = [{ colId: "", name: "Select", value: "", disabled: true }]; - folderNames = [...folderNames, ...folders.filter(item => item.colId === event.target.value)]; - folderNames.push({ colId: "-1", name: "----------------------", value: "-1", disabled: true }); - folderNames.push({ colId: "0", name: "Create New", value: "0", disabled: false }); + let folderNames = [{ colId: "", name: "Select", value: "", disabled: true }]; + folderNames = [...folderNames, ...folders.filter(item => item.colId === event.target.value)]; + folderNames.push({ colId: "-1", name: "----------------------", value: "-1", disabled: true }); + folderNames.push({ colId: "0", name: "Create New", value: "0", disabled: false }); - setCurrentFolders(folderNames); - setSelectedFolder(""); - setFolderName(""); + setCurrentFolders(folderNames); + setSelectedFolder(""); + setFolderName(""); - setErrors({ - ...errors, "colSelect": "", - "colName": "", - "folderName": "", - "curlError": "" - }); - }; + setErrors({ + ...errors, "colSelect": "", + "colName": "", + "folderName": "", + "curlError": "" + }); + }; - const onSelectFolder = (event: React.ChangeEvent) => { - setErrors({ ...errors, "folderName": "" }); - setSelectedFolder(event.target.value); - setFolderName(""); - }; + const onSelectFolder = (event: React.ChangeEvent) => { + setErrors({ ...errors, "folderName": "" }); + setSelectedFolder(event.target.value); + setFolderName(""); + }; - function onNameChange(e: any) { - setColName(e.target.value); - setErrors({ ...errors, "colName": (e.target.value ? (e.target.value.toUpperCase().trim() === "DEFAULT" ? "Collection name should not be 'Default'" : "") : "Cannot be empty") }); - } + function onNameChange(e: any) { + setColName(e.target.value); + setErrors({ ...errors, "colName": (e.target.value ? (e.target.value.toUpperCase().trim() === "DEFAULT" ? "Collection name should not be 'Default'" : "") : "Cannot be empty") }); + } - function onFolderNameChange(e: any) { - setFolderName(e.target.value); - setErrors({ ...errors, "folderName": (e.target.value ? "" : "Cannot be empty") }); - } + function onFolderNameChange(e: any) { + setFolderName(e.target.value); + setErrors({ ...errors, "folderName": (e.target.value ? "" : "Cannot be empty") }); + } - function getCollectionSelectionUI() { - return ( -
- - - - - - - {selectedCollection === "0" ? - - - : null} - {selectedCollection ? - - - : null} - {selectedFolder === "0" ? - - - : null} - {curlOption === "import" && - - - } - {errors["curlError"] && - - - } - -
- Collection : - - -
- Collection Name : - - -
- Folder : - - -
- Folder Name : - - -
- - {getButtonSection()} -
- -
{errors["curlError"]}
-
-
- ); - } + function getCollectionSelectionUI() { + return ( +
+ + + + + + + {selectedCollection === "0" ? + + + : null} + {selectedCollection ? + + + : null} + {selectedFolder === "0" ? + + + : null} + {curlOption === "import" && + + + } + {errors["curlError"] && + + + } + +
+ Collection : + + +
+ Collection Name : + + +
+ Folder : + + +
+ Folder Name : + + +
+ + {getButtonSection()} +
+ +
{errors["curlError"]}
+
+
+ ); + } - return ( - <> - {getCurlCommandUI()} - {curlOption === "import" && getCollectionSelectionUI()} - {curlOption === "run" && <>
- -
} - - ); + return ( + <> + {getCurlCommandUI()} + {curlOption === "import" && getCollectionSelectionUI()} + {curlOption === "run" && <>
+ +
} + + ); }; -export default CurlUI; \ No newline at end of file +export default CurlUI; diff --git a/src/fetch-client-ui/components/Curl/style.css b/src/fetch-client-ui/components/Curl/style.css index 1604391..4624c86 100644 --- a/src/fetch-client-ui/components/Curl/style.css +++ b/src/fetch-client-ui/components/Curl/style.css @@ -1,99 +1,99 @@ .curl-text-panel { - height : 49%; - padding : 15px; - box-sizing: border-box; + height : 49%; + padding : 15px; + box-sizing: border-box; } .curl-res-panel { - height: 48%; + height: 48%; } .curl-text-box { - width : calc(100% - 100px); - height : calc(100% - 25px); - resize : none; - background-color: var(--background-color); - color : var(--text-color); - border-color : var(--border-color); - outline : none; - margin-top : 5px; - padding : 10px; + width : calc(100% - 100px); + height : calc(100% - 25px); + resize : none; + background-color: var(--background-color); + color : var(--text-color); + border-color : var(--border-color); + outline : none; + margin-top : 5px; + padding : 10px; } .curl-text-box:focus { - outline: none; + outline: none; } .curl-options { - margin-bottom: 15px; + margin-bottom: 15px; } .curl-option { - margin-left: 20px; + margin-left: 20px; } .curl-label { - padding-left: 5px; + padding-left: 5px; } .curl-text-section { - display: flex; - height : calc(100% - 45px); - padding: 5px; + display: flex; + height : calc(100% - 45px); + padding: 5px; } .curl-run-btn { - top : 30%; - position : relative; - margin-left: 15px; + top : 30%; + position : relative; + margin-left: 15px; } .curl-run-col-btn:disabled, .curl-run-col-btn[disabled] .curl-run-btn:disabled, .curl-run-btn[disabled] { - background-color: #ccc; - color : #666; - cursor : not-allowed; + background-color: #ccc; + color : #666; + cursor : not-allowed; } .curl-run-col-btn { - margin: 0 auto; + margin: 0 auto; } .curl-col-table-panel { - display: block; + display: block; } .curl-col-table { - width : 50%; - padding : 10px; - margin-left: 10px; + width : 50%; + padding : 10px; + margin-left: 10px; } .curl-col-table td, .curl-col-table tr { - display: flex; + display: flex; } .curl-col-table tr { - height: 60px; + height: 60px; } .curl-col-table tr:hover { - background-color: transparent !important; + background-color: transparent !important; } .curl-run-btn-panel { - text-align: center; + text-align: center; } .curl-import-btn-panel { - width : 100%; - text-align: center; + width : 100%; + text-align: center; } .curl-error { - width : 100%; - margin : 0 auto; - text-align: center; -} \ No newline at end of file + width : 100%; + margin : 0 auto; + text-align: center; +} diff --git a/src/fetch-client-ui/components/ErrorLog/ErrorLog.tsx b/src/fetch-client-ui/components/ErrorLog/ErrorLog.tsx index 7296162..210d8ec 100644 --- a/src/fetch-client-ui/components/ErrorLog/ErrorLog.tsx +++ b/src/fetch-client-ui/components/ErrorLog/ErrorLog.tsx @@ -1,28 +1,27 @@ -import React, { useEffect } from "react"; -import { useState } from "react"; +import React, { useEffect, useState } from "react"; import { requestTypes, responseTypes } from "../../../utils/configuration"; import vscode from "../Common/vscodeAPI"; import "./style.css"; const ErrorLog = () => { - const [errorLogData, setErrorLog] = useState(""); + const [errorLogData, setErrorLog] = useState(""); - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getErrorLogResponse) { - setErrorLog(event.data.fileData ? event.data.fileData : "No Error"); - } - }); + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getErrorLogResponse) { + setErrorLog(event.data.fileData ? event.data.fileData : "No Error"); + } + }); - vscode.postMessage({ type: requestTypes.getErrorLogRequest }); - }, []); + vscode.postMessage({ type: requestTypes.getErrorLogRequest }); + }, []); - return ( -
- -
- ); + return ( +
+ +
+ ); }; -export default ErrorLog; \ No newline at end of file +export default ErrorLog; diff --git a/src/fetch-client-ui/components/ErrorLog/style.css b/src/fetch-client-ui/components/ErrorLog/style.css index 369c074..348d41c 100644 --- a/src/fetch-client-ui/components/ErrorLog/style.css +++ b/src/fetch-client-ui/components/ErrorLog/style.css @@ -1,22 +1,22 @@ .error-log-text-box { - padding : 20px; - width : 100%; - height : 100%; - resize : none; - background-color: var(--background-color); - color : var(--text-color); - border-color : var(--border-color); - outline : none; - box-sizing : border-box; + padding : 20px; + width : 100%; + height : 100%; + resize : none; + background-color: var(--background-color); + color : var(--text-color); + border-color : var(--border-color); + outline : none; + box-sizing : border-box; } .error-log-text-box:focus { - outline: none; + outline: none; } .error-log-panel { - padding : 10px; - width : 100%; - height : 100%; - box-sizing: border-box; -} \ No newline at end of file + padding : 10px; + width : 100%; + height : 100%; + box-sizing: border-box; +} diff --git a/src/fetch-client-ui/components/MainUI/index.tsx b/src/fetch-client-ui/components/MainUI/index.tsx index 9bee4e9..c8d2be1 100644 --- a/src/fetch-client-ui/components/MainUI/index.tsx +++ b/src/fetch-client-ui/components/MainUI/index.tsx @@ -22,421 +22,421 @@ import "./style.css"; const MainUI = () => { - const dispatch = useDispatch(); - - const { open } = useSelector((state: IRootState) => state.uiData); - const { loading, response } = useSelector((state: IRootState) => state.responseData); - const requestData = useSelector((state: IRootState) => state.requestData); - const { variables } = useSelector((state: IRootState) => state.variableData); - const { parentSettings, collectionList } = useSelector((state: IRootState) => state.reqColData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const reqSettings = useSelector((state: IRootState) => state.reqSettings); - - const refReq = useRef(requestData); - const setReq = (data: IRequestModel) => { - refReq.current = data; - }; - - const [reqClass, setReqClass] = useState("full-height"); - const [resClass, setResClass] = useState("zero-height"); - - const [reqBorderClass, setReqBorderClass] = useState(""); - const [varId, setVarId] = useState(""); - const [resBorderClass, setResBorderClass] = useState("no-border"); - - const [layout, setLayout] = useState(""); - const [horiLayout, setHoriLayout] = useState(""); - - const [saveVisible, setVisible] = useState(false); - const [loadingApp, setLoadingApp] = useState(true); - const [waitForSend, setWaitForSend] = useState(false); - - useEffect(() => { - if (loading && resClass === "zero-height") { - setOpenPanel(1); - } - }, [loading]); - - useEffect(() => { - if ((response.status !== 0 || response.isError) && resClass === "zero-height") { - setOpenPanel(1); - } - }, [response]); - - useEffect(() => { - setReq(requestData); - }, [requestData]); - - useEffect(() => { - if (reqClass === "zero-height") { - setReqBorderClass("no-border"); - } else { - setReqBorderClass(""); - } - - if (resClass === "zero-height") { - setResBorderClass("no-border"); - } else { - setResBorderClass(""); - } - }, [reqClass, resClass]); - - useEffect(() => { - if (saveVisible) { - setTimeout(() => { - setVisible(false); - }, 2000); - } - }, [saveVisible]); - - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.apiResponse) { - dispatch(ResponseActions.SetResponseCookiesAction(event.data.cookies)); - dispatch(ResponseActions.SetResponseAction(event.data.response)); - dispatch(ResponseActions.SetResponseHeadersAction(event.data.headers)); - } else if (event.data && event.data.type === responseTypes.configResponse) { - let config = JSON.parse(event.data.configData); - let layoutConfig = config["layout"]; - setLayout(layoutConfig); - let hariLayoutConfig = config["horizontalLayout"]; - setHoriLayout(hariLayoutConfig); - let responseLimit = (config["responseLimit"] as number) * 1048576; - dispatch(UIActions.SetLayoutAction(layoutConfig === "Horizontal Split" ? true : false, event.data.theme)); - dispatch(UIActions.SetResponseLimitAction(responseLimit)); - } else if (event.data && (event.data.type === responseTypes.openExistingItemResponse || event.data.type === responseTypes.getOpenAndRunItemDataResponse)) { - const reqData = event.data.item[0] as IRequestModel; - dispatch(Actions.SetRequestAction(reqData)); - if (reqData.body.bodyType === "binary" && reqData.body.binary.fileName) { - vscode.postMessage({ type: requestTypes.readFileRequest, path: reqData.body.binary.fileName }); - } - setLoadingApp(false); - if (event.data.type === responseTypes.getOpenAndRunItemDataResponse) { - if ((reqData.body.bodyType === "binary" && reqData.body.binary.fileName) || reqData.auth.authType === "inherit") { - setWaitForSend(true); - } else { - SendRequest(dispatch, false, colId, reqData, selectedVariable, parentSettings, reqSettings); - } - } - } else if (event.data && event.data.type === responseTypes.readFileResponse) { - dispatch(Actions.SetRequestBinaryDataAction(event.data.fileData)); - if (waitForSend === true) { - setWaitForSend(false); - SendRequest(dispatch, false, colId, requestData, selectedVariable, parentSettings, reqSettings); - } - } else if (event.data && event.data.type === responseTypes.getAllVariableResponse) { - dispatch(VariableActions.SetReqAllVariableAction(event.data.variable as IVariable[])); - setLoadingApp(false); - } else if (event.data && event.data.type === responseTypes.getRunItemDataResponse) { - const reqData = event.data.reqData as IRequestModel; - dispatch(Actions.SetRequestAction(reqData)); - if (reqData.body.bodyType === "binary" && reqData.body.binary.fileName) { - vscode.postMessage({ type: requestTypes.readFileRequest, path: reqData.body.binary.fileName }); - } - dispatch(ResponseActions.SetResponseAction(event.data.resData.response)); - dispatch(ResponseActions.SetResponseHeadersAction(event.data.resData.headers)); - dispatch(ResponseActions.SetResponseCookiesAction(event.data.resData.cookies)); - setLoadingApp(false); - } else if (event.data && event.data.type === responseTypes.saveResponse) { - setVisible(true); - } else if (event.data && event.data.type === responseTypes.getAllCookiesResponse) { - dispatch(CookiesActions.SetAllCookiesAction(event.data.cookies as ICookie[])); - } else if (event.data && event.data.type === responseTypes.getParentSettingsResponse) { - dispatch(Actions.SetReqParentSettingsAction(event.data.settings as ISettings)); - if (waitForSend === true) { - setWaitForSend(false); - SendRequest(dispatch, false, colId, requestData, selectedVariable, event.data.settings as ISettings, reqSettings); - } - } else if (event.data && event.data.type === pubSubTypes.updateVariables) { - vscode.postMessage({ type: requestTypes.getAllVariableRequest }); - } else if (event.data && event.data.type === pubSubTypes.removeCurrentVariable) { - setVarId(""); - } else if (event.data && event.data.type === pubSubTypes.addCurrentVariable) { - setVarId(event.data.data.varId); - } else if (event.data && event.data.type === pubSubTypes.themeChanged) { - vscode.postMessage({ type: requestTypes.themeRequest }); - } else if (event.data && event.data.type === responseTypes.themeResponse) { - dispatch(UIActions.SetThemeAction(event.data.theme)); - } else if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { - let col: ICollection[] = event.data.collectionNames?.map((item: { value: any; name: any; }) => { - return { - id: item.value, - name: item.name - }; - }); - col.unshift({ id: "", name: "select" }); - dispatch(Actions.SetCollectionListAction(col)); - } - }); - - vscode.postMessage({ type: requestTypes.configRequest }); - - let reqId = document.title.split("@:@")[0]; - let colId = document.title.split("@:@")[1]; - let varId = document.title.split("@:@")[2]; - let isRunItem = document.title.split("@:@")[3]; - let folderId = document.title.split("@:@")[4]; - - vscode.postMessage({ type: requestTypes.getAllVariableRequest }); - - if (reqId !== "undefined" && isRunItem === "undefined") { - vscode.postMessage({ type: requestTypes.openExistingItemRequest, data: reqId }); - } else if (reqId !== "undefined" && isRunItem !== "undefined" && isRunItem === "OpenAndRun") { - dispatch(UIActions.SetRunItemAction(true)); - vscode.postMessage({ type: requestTypes.getOpenAndRunItemDataRequest, data: reqId }); - } else if (isRunItem !== "undefined" && isRunItem !== "OpenAndRun") { - dispatch(UIActions.SetRunItemAction(true)); - vscode.postMessage({ type: requestTypes.getRunItemDataRequest }); - } - - vscode.postMessage({ type: requestTypes.getParentSettingsRequest, data: { colId: colId, folderId: folderId } }); - - if (collectionList.length === 0) { - setTimeout(vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }), 1000); - } - - dispatch(Actions.SetReqColDetailsAction(colId !== "undefined" ? colId : "", folderId !== "undefined" ? folderId : "")); - - if (varId !== "undefined") { - setVarId(varId); - } - - document.addEventListener("keydown", function (e) { - if (e.ctrlKey && (e.key === 'S' || e.key === 's')) { - e.preventDefault(); - if (!refReq.current.url) { - return; - } - - let reqData = { ...refReq.current }; - let isNew = false; - if (!reqData.name) { - reqData.id = uuidv4(); - reqData.name = reqData.url.trim(); - reqData.createdTime = formatDate(); - dispatch(Actions.SetRequestAction(reqData)); - isNew = true; - } - vscode.postMessage({ type: requestTypes.saveRequest, data: { reqData: reqData, isNew: isNew, colId: colId === "undefined" ? undefined : colId } }); - } - }); - - vscode.postMessage({ type: requestTypes.getAllCookiesRequest }); - - }, []); - - useEffect(() => { - if (variables && variables.length > 0) { - if (varId) { - updateVaribleData(varId); - } else { - setRequiredGlobalVariable(); - } - } - }, [variables, varId]); - - function updateVaribleData(varId: string) { - let index = variables.findIndex(item => item.id === varId); - if (index !== -1) { - setRequiredVariable(index); - } else { - setRequiredGlobalVariable(); - } - } - - function setRequiredVariable(index: number) { - dispatch(VariableActions.SetReqVariableAction(variables[index] as IVariable)); - } - - function setRequiredGlobalVariable() { - let index = variables.findIndex(item => item.name.toUpperCase().trim() === "GLOBAL" && item.isActive === true); - if (index !== -1) { - setRequiredVariable(index); - setVarId(variables[index].id); - } - } - - useEffect(() => { - if (parentSettings && parentSettings.auth.authType === "apikey") { - modifyQueryParam(parentSettings.auth.addTo, parentSettings.auth.userName, parentSettings.auth.password); - } - }, [parentSettings]); - - const modifyQueryParam = (section: string, userName: string, password: string) => { - if (section === "queryparams") { - let localParams = [...requestData.params]; - let available = localParams.findIndex(item => item.isFixed === true && item.key === userName && item.value === password); - - if (available === -1 && userName) { - localParams.unshift({ - isChecked: true, - key: userName, - value: password, - isFixed: true - }); - - dispatch(Actions.SetRequestParamsAction(localParams)); - } - - } else { - let localHeaders = [...requestData.headers]; - let available = localHeaders.findIndex(item => item.isFixed === true && item.key === userName && item.value === password); - - if (available === -1 && userName) { - localHeaders.unshift({ - isChecked: true, - key: userName, - value: password, - isFixed: true - }); - } - - dispatch(Actions.SetRequestHeadersAction(localHeaders)); - } - }; - - function setOpenPanel(index: number) { - let localData = [...open]; - - if (index === 0) { - if (open[0] && open[1]) { - setResFull(); - localData[index] = !localData[index]; - } - - if (open[0] && !open[1]) { - setResFull(); - localData = localData.map((item) => !item); - } - - if (!open[0] && open[1]) { - setBothHalf(); - localData[index] = !localData[index]; - } - - if (!open[0] && !open[1]) { - setReqFull(); - localData[index] = !localData[index]; - } - } - - if (index === 1) { - if (open[0] && open[1]) { - setReqFull(); - localData[index] = !localData[index]; - } - - if (open[0] && !open[1]) { - setBothHalf(); - localData[index] = !localData[index]; - } - - if (!open[0] && open[1]) { - setReqFull(); - localData = localData.map((item) => !item); - } - - if (!open[0] && !open[1]) { - setResFull(); - localData[index] = !localData[index]; - } - } - dispatch(UIActions.SetOpenAction(localData)); - } - - function setBothHalf() { - setReqClass("half-height"); - setResClass("half-height"); - let fulScreenButton = document.getElementById("fullscreen-expand-btn"); - if (fulScreenButton) { - fulScreenButton.classList.remove("fullscreen-btn-invisible"); - } - } - - function setReqFull() { - setReqClass("full-height"); - setResClass("zero-height"); - let fulScreenButton = document.getElementById("fullscreen-expand-btn"); - if (fulScreenButton) { - fulScreenButton.classList.add("fullscreen-btn-invisible"); - } - } - - function setResFull() { - setReqClass("zero-height"); - setResClass("full-height"); - let fulScreenButton = document.getElementById("fullscreen-expand-btn"); - if (fulScreenButton) { - fulScreenButton.classList.remove("fullscreen-btn-invisible"); - } - } - - return ( - <> - { - loadingApp ? - <> -
-
{"Loading...."}
- - : - <> - { - layout === "Horizontal Split" ? - horiLayout === "Split Style" ? - -
- -
Saved Successfully
- -
-
- -
-
- : - <> -
- { setOpenPanel(0); }} checked={open[0]} /> -

- -

-
- -
Saved Successfully
- -
-
-
- { setOpenPanel(1); }} checked={open[1]} /> -

- -

-
- -
-
- - : - -
- -
Saved Successfully
- -
-
- -
-
- } - - } - - ); + const dispatch = useDispatch(); + + const { open } = useSelector((state: IRootState) => state.uiData); + const { loading, response } = useSelector((state: IRootState) => state.responseData); + const requestData = useSelector((state: IRootState) => state.requestData); + const { variables } = useSelector((state: IRootState) => state.variableData); + const { parentSettings, collectionList } = useSelector((state: IRootState) => state.reqColData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const reqSettings = useSelector((state: IRootState) => state.reqSettings); + + const refReq = useRef(requestData); + const setReq = (data: IRequestModel) => { + refReq.current = data; + }; + + const [reqClass, setReqClass] = useState("full-height"); + const [resClass, setResClass] = useState("zero-height"); + + const [reqBorderClass, setReqBorderClass] = useState(""); + const [varId, setVarId] = useState(""); + const [resBorderClass, setResBorderClass] = useState("no-border"); + + const [layout, setLayout] = useState(""); + const [horiLayout, setHoriLayout] = useState(""); + + const [saveVisible, setVisible] = useState(false); + const [loadingApp, setLoadingApp] = useState(true); + const [waitForSend, setWaitForSend] = useState(false); + + useEffect(() => { + if (loading && resClass === "zero-height") { + setOpenPanel(1); + } + }, [loading]); + + useEffect(() => { + if ((response.status !== 0 || response.isError) && resClass === "zero-height") { + setOpenPanel(1); + } + }, [response]); + + useEffect(() => { + setReq(requestData); + }, [requestData]); + + useEffect(() => { + if (reqClass === "zero-height") { + setReqBorderClass("no-border"); + } else { + setReqBorderClass(""); + } + + if (resClass === "zero-height") { + setResBorderClass("no-border"); + } else { + setResBorderClass(""); + } + }, [reqClass, resClass]); + + useEffect(() => { + if (saveVisible) { + setTimeout(() => { + setVisible(false); + }, 2000); + } + }, [saveVisible]); + + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.apiResponse) { + dispatch(ResponseActions.SetResponseCookiesAction(event.data.cookies)); + dispatch(ResponseActions.SetResponseAction(event.data.response)); + dispatch(ResponseActions.SetResponseHeadersAction(event.data.headers)); + } else if (event.data && event.data.type === responseTypes.configResponse) { + let config = JSON.parse(event.data.configData); + let layoutConfig = config["layout"]; + setLayout(layoutConfig); + let hariLayoutConfig = config["horizontalLayout"]; + setHoriLayout(hariLayoutConfig); + let responseLimit = (config["responseLimit"] as number) * 1048576; + dispatch(UIActions.SetLayoutAction(layoutConfig === "Horizontal Split" ? true : false, event.data.theme)); + dispatch(UIActions.SetResponseLimitAction(responseLimit)); + } else if (event.data && (event.data.type === responseTypes.openExistingItemResponse || event.data.type === responseTypes.getOpenAndRunItemDataResponse)) { + const reqData = event.data.item[0] as IRequestModel; + dispatch(Actions.SetRequestAction(reqData)); + if (reqData.body.bodyType === "binary" && reqData.body.binary.fileName) { + vscode.postMessage({ type: requestTypes.readFileRequest, path: reqData.body.binary.fileName }); + } + setLoadingApp(false); + if (event.data.type === responseTypes.getOpenAndRunItemDataResponse) { + if ((reqData.body.bodyType === "binary" && reqData.body.binary.fileName) || reqData.auth.authType === "inherit") { + setWaitForSend(true); + } else { + SendRequest(dispatch, false, colId, reqData, selectedVariable, parentSettings, reqSettings); + } + } + } else if (event.data && event.data.type === responseTypes.readFileResponse) { + dispatch(Actions.SetRequestBinaryDataAction(event.data.fileData)); + if (waitForSend === true) { + setWaitForSend(false); + SendRequest(dispatch, false, colId, requestData, selectedVariable, parentSettings, reqSettings); + } + } else if (event.data && event.data.type === responseTypes.getAllVariableResponse) { + dispatch(VariableActions.SetReqAllVariableAction(event.data.variable as IVariable[])); + setLoadingApp(false); + } else if (event.data && event.data.type === responseTypes.getRunItemDataResponse) { + const reqData = event.data.reqData as IRequestModel; + dispatch(Actions.SetRequestAction(reqData)); + if (reqData.body.bodyType === "binary" && reqData.body.binary.fileName) { + vscode.postMessage({ type: requestTypes.readFileRequest, path: reqData.body.binary.fileName }); + } + dispatch(ResponseActions.SetResponseAction(event.data.resData.response)); + dispatch(ResponseActions.SetResponseHeadersAction(event.data.resData.headers)); + dispatch(ResponseActions.SetResponseCookiesAction(event.data.resData.cookies)); + setLoadingApp(false); + } else if (event.data && event.data.type === responseTypes.saveResponse) { + setVisible(true); + } else if (event.data && event.data.type === responseTypes.getAllCookiesResponse) { + dispatch(CookiesActions.SetAllCookiesAction(event.data.cookies as ICookie[])); + } else if (event.data && event.data.type === responseTypes.getParentSettingsResponse) { + dispatch(Actions.SetReqParentSettingsAction(event.data.settings as ISettings)); + if (waitForSend === true) { + setWaitForSend(false); + SendRequest(dispatch, false, colId, requestData, selectedVariable, event.data.settings as ISettings, reqSettings); + } + } else if (event.data && event.data.type === pubSubTypes.updateVariables) { + vscode.postMessage({ type: requestTypes.getAllVariableRequest }); + } else if (event.data && event.data.type === pubSubTypes.removeCurrentVariable) { + setVarId(""); + } else if (event.data && event.data.type === pubSubTypes.addCurrentVariable) { + setVarId(event.data.data.varId); + } else if (event.data && event.data.type === pubSubTypes.themeChanged) { + vscode.postMessage({ type: requestTypes.themeRequest }); + } else if (event.data && event.data.type === responseTypes.themeResponse) { + dispatch(UIActions.SetThemeAction(event.data.theme)); + } else if (event.data && event.data.type === responseTypes.getAllCollectionNameResponse) { + let col: ICollection[] = event.data.collectionNames?.map((item: { value: any; name: any; }) => { + return { + id: item.value, + name: item.name + }; + }); + col.unshift({ id: "", name: "select" }); + dispatch(Actions.SetCollectionListAction(col)); + } + }); + + vscode.postMessage({ type: requestTypes.configRequest }); + + let reqId = document.title.split("@:@")[0]; + let colId = document.title.split("@:@")[1]; + let varId = document.title.split("@:@")[2]; + let isRunItem = document.title.split("@:@")[3]; + let folderId = document.title.split("@:@")[4]; + + vscode.postMessage({ type: requestTypes.getAllVariableRequest }); + + if (reqId !== "undefined" && isRunItem === "undefined") { + vscode.postMessage({ type: requestTypes.openExistingItemRequest, data: reqId }); + } else if (reqId !== "undefined" && isRunItem !== "undefined" && isRunItem === "OpenAndRun") { + dispatch(UIActions.SetRunItemAction(true)); + vscode.postMessage({ type: requestTypes.getOpenAndRunItemDataRequest, data: reqId }); + } else if (isRunItem !== "undefined" && isRunItem !== "OpenAndRun") { + dispatch(UIActions.SetRunItemAction(true)); + vscode.postMessage({ type: requestTypes.getRunItemDataRequest }); + } + + vscode.postMessage({ type: requestTypes.getParentSettingsRequest, data: { colId: colId, folderId: folderId } }); + + if (collectionList.length === 0) { + setTimeout(vscode.postMessage({ type: requestTypes.getAllCollectionNameRequest, data: "addtocol" }), 1000); + } + + dispatch(Actions.SetReqColDetailsAction(colId !== "undefined" ? colId : "", folderId !== "undefined" ? folderId : "")); + + if (varId !== "undefined") { + setVarId(varId); + } + + document.addEventListener("keydown", function (e) { + if (e.ctrlKey && (e.key === 'S' || e.key === 's')) { + e.preventDefault(); + if (!refReq.current.url) { + return; + } + + let reqData = { ...refReq.current }; + let isNew = false; + if (!reqData.name) { + reqData.id = uuidv4(); + reqData.name = reqData.url.trim(); + reqData.createdTime = formatDate(); + dispatch(Actions.SetRequestAction(reqData)); + isNew = true; + } + vscode.postMessage({ type: requestTypes.saveRequest, data: { reqData: reqData, isNew: isNew, colId: colId === "undefined" ? undefined : colId } }); + } + }); + + vscode.postMessage({ type: requestTypes.getAllCookiesRequest }); + + }, []); + + useEffect(() => { + if (variables && variables.length > 0) { + if (varId) { + updateVaribleData(varId); + } else { + setRequiredGlobalVariable(); + } + } + }, [variables, varId]); + + function updateVaribleData(varId: string) { + let index = variables.findIndex(item => item.id === varId); + if (index !== -1) { + setRequiredVariable(index); + } else { + setRequiredGlobalVariable(); + } + } + + function setRequiredVariable(index: number) { + dispatch(VariableActions.SetReqVariableAction(variables[index] as IVariable)); + } + + function setRequiredGlobalVariable() { + let index = variables.findIndex(item => item.name.toUpperCase().trim() === "GLOBAL" && item.isActive === true); + if (index !== -1) { + setRequiredVariable(index); + setVarId(variables[index].id); + } + } + + useEffect(() => { + if (parentSettings && parentSettings.auth.authType === "apikey") { + modifyQueryParam(parentSettings.auth.addTo, parentSettings.auth.userName, parentSettings.auth.password); + } + }, [parentSettings]); + + const modifyQueryParam = (section: string, userName: string, password: string) => { + if (section === "queryparams") { + let localParams = [...requestData.params]; + let available = localParams.findIndex(item => item.isFixed === true && item.key === userName && item.value === password); + + if (available === -1 && userName) { + localParams.unshift({ + isChecked: true, + key: userName, + value: password, + isFixed: true + }); + + dispatch(Actions.SetRequestParamsAction(localParams)); + } + + } else { + let localHeaders = [...requestData.headers]; + let available = localHeaders.findIndex(item => item.isFixed === true && item.key === userName && item.value === password); + + if (available === -1 && userName) { + localHeaders.unshift({ + isChecked: true, + key: userName, + value: password, + isFixed: true + }); + } + + dispatch(Actions.SetRequestHeadersAction(localHeaders)); + } + }; + + function setOpenPanel(index: number) { + let localData = [...open]; + + if (index === 0) { + if (open[0] && open[1]) { + setResFull(); + localData[index] = !localData[index]; + } + + if (open[0] && !open[1]) { + setResFull(); + localData = localData.map((item) => !item); + } + + if (!open[0] && open[1]) { + setBothHalf(); + localData[index] = !localData[index]; + } + + if (!open[0] && !open[1]) { + setReqFull(); + localData[index] = !localData[index]; + } + } + + if (index === 1) { + if (open[0] && open[1]) { + setReqFull(); + localData[index] = !localData[index]; + } + + if (open[0] && !open[1]) { + setBothHalf(); + localData[index] = !localData[index]; + } + + if (!open[0] && open[1]) { + setReqFull(); + localData = localData.map((item) => !item); + } + + if (!open[0] && !open[1]) { + setResFull(); + localData[index] = !localData[index]; + } + } + dispatch(UIActions.SetOpenAction(localData)); + } + + function setBothHalf() { + setReqClass("half-height"); + setResClass("half-height"); + let fulScreenButton = document.getElementById("fullscreen-expand-btn"); + if (fulScreenButton) { + fulScreenButton.classList.remove("fullscreen-btn-invisible"); + } + } + + function setReqFull() { + setReqClass("full-height"); + setResClass("zero-height"); + let fulScreenButton = document.getElementById("fullscreen-expand-btn"); + if (fulScreenButton) { + fulScreenButton.classList.add("fullscreen-btn-invisible"); + } + } + + function setResFull() { + setReqClass("zero-height"); + setResClass("full-height"); + let fulScreenButton = document.getElementById("fullscreen-expand-btn"); + if (fulScreenButton) { + fulScreenButton.classList.remove("fullscreen-btn-invisible"); + } + } + + return ( + <> + { + loadingApp ? + <> +
+
{"Loading...."}
+ + : + <> + { + layout === "Horizontal Split" ? + horiLayout === "Split Style" ? + +
+ +
Saved Successfully
+ +
+
+ +
+
+ : + <> +
+ { setOpenPanel(0); }} checked={open[0]} /> +

+ +

+
+ +
Saved Successfully
+ +
+
+
+ { setOpenPanel(1); }} checked={open[1]} /> +

+ +

+
+ +
+
+ + : + +
+ +
Saved Successfully
+ +
+
+ +
+
+ } + + } + + ); }; -export default MainUI; \ No newline at end of file +export default MainUI; diff --git a/src/fetch-client-ui/components/MainUI/redux/actions.ts b/src/fetch-client-ui/components/MainUI/redux/actions.ts index f2f5079..987bd79 100644 --- a/src/fetch-client-ui/components/MainUI/redux/actions.ts +++ b/src/fetch-client-ui/components/MainUI/redux/actions.ts @@ -1,48 +1,48 @@ import { FETCH_CLIENT_SET_ACC_OPEN, FETCH_CLIENT_SET_RESPONSE_LIMIT, FETCH_CLIENT_SET_RUN_ITEM, FETCH_CLIENT_SET_UI_HORIZONTAL, FETCH_CLIENT_SET_UI_THEME, UIActionTypes } from "./types"; export const SetOpenAction = (value: boolean[]): UIActionTypes => { - return { - type: FETCH_CLIENT_SET_ACC_OPEN, - payload: { - open: value - } - }; + return { + type: FETCH_CLIENT_SET_ACC_OPEN, + payload: { + open: value + } + }; }; export const SetLayoutAction = (value: boolean, value1: number): UIActionTypes => { - return { - type: FETCH_CLIENT_SET_UI_HORIZONTAL, - payload: { - horizontalLayout: value, - theme: value1 - } - }; + return { + type: FETCH_CLIENT_SET_UI_HORIZONTAL, + payload: { + horizontalLayout: value, + theme: value1 + } + }; }; export const SetThemeAction = (value: number): UIActionTypes => { - return { - type: FETCH_CLIENT_SET_UI_THEME, - payload: { - theme: value - } - }; + return { + type: FETCH_CLIENT_SET_UI_THEME, + payload: { + theme: value + } + }; }; export const SetRunItemAction = (value: boolean): UIActionTypes => { - return { - type: FETCH_CLIENT_SET_RUN_ITEM, - payload: { - runItem: value - } - }; + return { + type: FETCH_CLIENT_SET_RUN_ITEM, + payload: { + runItem: value + } + }; }; export const SetResponseLimitAction = (value: number): UIActionTypes => { - return { - type: FETCH_CLIENT_SET_RESPONSE_LIMIT, - payload: { - responseLimit: value - } - }; -}; \ No newline at end of file + return { + type: FETCH_CLIENT_SET_RESPONSE_LIMIT, + payload: { + responseLimit: value + } + }; +}; diff --git a/src/fetch-client-ui/components/MainUI/redux/index.ts b/src/fetch-client-ui/components/MainUI/redux/index.ts index dee2d6d..cd20d91 100644 --- a/src/fetch-client-ui/components/MainUI/redux/index.ts +++ b/src/fetch-client-ui/components/MainUI/redux/index.ts @@ -3,6 +3,6 @@ import { UIReducer } from "./reducer"; export { - UIActions, - UIReducer + UIActions, + UIReducer }; diff --git a/src/fetch-client-ui/components/MainUI/redux/reducer.ts b/src/fetch-client-ui/components/MainUI/redux/reducer.ts index 6064492..9231e5e 100644 --- a/src/fetch-client-ui/components/MainUI/redux/reducer.ts +++ b/src/fetch-client-ui/components/MainUI/redux/reducer.ts @@ -1,51 +1,51 @@ import { FETCH_CLIENT_SET_ACC_OPEN, FETCH_CLIENT_SET_RESPONSE_LIMIT, FETCH_CLIENT_SET_RUN_ITEM, FETCH_CLIENT_SET_UI_HORIZONTAL, FETCH_CLIENT_SET_UI_THEME, ICommonConfig, UIActionTypes } from "./types"; export const InitialState: ICommonConfig = { - open: [true, false], - horizontalLayout: true, - theme: 2, - runItem: false, - responseLimit: 5242880 + open: [true, false], + horizontalLayout: true, + theme: 2, + runItem: false, + responseLimit: 5242880 }; export const UIReducer: (state?: ICommonConfig, - action?: UIActionTypes) => ICommonConfig = - (state: ICommonConfig = InitialState, - action: UIActionTypes = {} as UIActionTypes): ICommonConfig => { - switch (action.type) { - case FETCH_CLIENT_SET_ACC_OPEN: { - return { - ...state, - open: action.payload.open, - }; - } - case FETCH_CLIENT_SET_UI_HORIZONTAL: { - return { - ...state, - horizontalLayout: action.payload.horizontalLayout, - theme: action.payload.theme, - }; - } - case FETCH_CLIENT_SET_RUN_ITEM: { - return { - ...state, - runItem: action.payload.runItem - }; - } - case FETCH_CLIENT_SET_UI_THEME: { - return { - ...state, - theme: action.payload.theme - }; - } - case FETCH_CLIENT_SET_RESPONSE_LIMIT: { - return { - ...state, - responseLimit: action.payload.responseLimit < 1 ? 5242880 : action.payload.responseLimit - }; - } - default: { - return state; - } - } - }; + action?: UIActionTypes) => ICommonConfig = + (state: ICommonConfig = InitialState, + action: UIActionTypes = {} as UIActionTypes): ICommonConfig => { + switch (action.type) { + case FETCH_CLIENT_SET_ACC_OPEN: { + return { + ...state, + open: action.payload.open, + }; + } + case FETCH_CLIENT_SET_UI_HORIZONTAL: { + return { + ...state, + horizontalLayout: action.payload.horizontalLayout, + theme: action.payload.theme, + }; + } + case FETCH_CLIENT_SET_RUN_ITEM: { + return { + ...state, + runItem: action.payload.runItem + }; + } + case FETCH_CLIENT_SET_UI_THEME: { + return { + ...state, + theme: action.payload.theme + }; + } + case FETCH_CLIENT_SET_RESPONSE_LIMIT: { + return { + ...state, + responseLimit: action.payload.responseLimit < 1 ? 5242880 : action.payload.responseLimit + }; + } + default: { + return state; + } + } + }; diff --git a/src/fetch-client-ui/components/MainUI/redux/types.ts b/src/fetch-client-ui/components/MainUI/redux/types.ts index 0f56602..fc842fe 100644 --- a/src/fetch-client-ui/components/MainUI/redux/types.ts +++ b/src/fetch-client-ui/components/MainUI/redux/types.ts @@ -1,9 +1,9 @@ export interface ICommonConfig { - open: boolean[], - horizontalLayout: boolean; - theme: number; - runItem: boolean; - responseLimit: number + open: boolean[], + horizontalLayout: boolean; + theme: number; + runItem: boolean; + responseLimit: number } export const FETCH_CLIENT_SET_ACC_OPEN: "FETCH_CLIENT_SET_ACC_OPEN" = "FETCH_CLIENT_SET_ACC_OPEN"; @@ -13,39 +13,39 @@ export const FETCH_CLIENT_SET_RUN_ITEM: "FETCH_CLIENT_SET_RUN_ITEM" = "FETCH_CLI export const FETCH_CLIENT_SET_RESPONSE_LIMIT: "FETCH_CLIENT_SET_RESPONSE_LIMIT" = "FETCH_CLIENT_SET_RESPONSE_LIMIT"; export interface ISetOpen { - type: typeof FETCH_CLIENT_SET_ACC_OPEN; - payload: { - open: boolean[]; - }; + type: typeof FETCH_CLIENT_SET_ACC_OPEN; + payload: { + open: boolean[]; + }; } export interface ISetLayout { - type: typeof FETCH_CLIENT_SET_UI_HORIZONTAL; - payload: { - horizontalLayout: boolean; - theme: number; - }; + type: typeof FETCH_CLIENT_SET_UI_HORIZONTAL; + payload: { + horizontalLayout: boolean; + theme: number; + }; } export interface ISetTheme { - type: typeof FETCH_CLIENT_SET_UI_THEME; - payload: { - theme: number; - }; + type: typeof FETCH_CLIENT_SET_UI_THEME; + payload: { + theme: number; + }; } export interface ISetRunItem { - type: typeof FETCH_CLIENT_SET_RUN_ITEM; - payload: { - runItem: boolean; - }; + type: typeof FETCH_CLIENT_SET_RUN_ITEM; + payload: { + runItem: boolean; + }; } export interface ISetResponseLimit { - type: typeof FETCH_CLIENT_SET_RESPONSE_LIMIT; - payload: { - responseLimit: number; - }; + type: typeof FETCH_CLIENT_SET_RESPONSE_LIMIT; + payload: { + responseLimit: number; + }; } -export type UIActionTypes = | ISetOpen | ISetLayout | ISetRunItem | ISetTheme |ISetResponseLimit; \ No newline at end of file +export type UIActionTypes = | ISetOpen | ISetLayout | ISetRunItem | ISetTheme |ISetResponseLimit; diff --git a/src/fetch-client-ui/components/MainUI/style.css b/src/fetch-client-ui/components/MainUI/style.css index 5b80957..aa66b4f 100644 --- a/src/fetch-client-ui/components/MainUI/style.css +++ b/src/fetch-client-ui/components/MainUI/style.css @@ -1,165 +1,165 @@ .accordion>input[name="collapse"] { - display: none; + display: none; } .accordion .accordion-title, .accordion .content { - margin: 0 auto; + margin: 0 auto; } .accordion .content { - border : 1px solid; - height : 0; - overflow : hidden; - transition: 0.5s; + border : 1px solid; + height : 0; + overflow : hidden; + transition: 0.5s; } .accordion>input[name="collapse"]:checked~.content { - height : calc(100% - 30px); - transition: height 0.5s; + height : calc(100% - 30px); + transition: height 0.5s; } .accordion .accordion-title { - display: block; + display: block; } /* For Desktop */ @media only screen and (min-width: 620px) { - .accordion>input[name="collapse"]:checked~.content { - /* height: 93%; */ - height: calc(100% - 30px); - } + .accordion>input[name="collapse"]:checked~.content { + /* height: 93%; */ + height: calc(100% - 30px); + } } /* .accordion { - margin-bottom: 2px; + margin-bottom: 2px; } */ .accordion>input[name="collapse"]:checked~.content { - border-top: 0; - transition: 0.3s; + border-top: 0; + transition: 0.3s; } .accordion .handle { - margin : 0; - font-size: 16px; - border : 1px solid; + margin : 0; + font-size: 16px; + border : 1px solid; } .accordion .accordion-title { - background : #0a95ff; - color : #fff; - cursor : pointer; - font-weight: normal; - padding : 3px 3px 3px 10px; - user-select: none; + background : #0a95ff; + color : #fff; + cursor : pointer; + font-weight: normal; + padding : 3px 3px 3px 10px; + user-select: none; } .accordion .accordion-title:hover, .accordion .accordion-title:focus { - /* background: #252525; */ - background: #194880; + /* background: #252525; */ + background: #194880; } .accordion .handle .accordion-title:before { - content : "+"; - display : inline-block; - font-size : 1em; - line-height : 1.556em; - margin-right: 10px; - transition : 0.4s; + content : "+"; + display : inline-block; + font-size : 1em; + line-height : 1.556em; + margin-right: 10px; + transition : 0.4s; } .accordion>input[name="collapse"]:checked~.handle .accordion-title:before { - content : "-"; - transform : rotate(180deg); - transform-origin: center; - transition : 0.4s; + content : "-"; + transform : rotate(180deg); + transform-origin: center; + transition : 0.4s; } .accordion>input[name="collapse"]:checked~.handle .accordion-title { - background: #194880; + background: #194880; } .half-height { - /* height: 49.5%; */ - height: 50%; + /* height: 49.5%; */ + height: 50%; } .full-height { - /* height: calc(100% - 40px); */ - height: calc(100% - 30px); + /* height: calc(100% - 40px); */ + height: calc(100% - 30px); } .zero-height { - height: 30px; + height: 30px; } .no-border { - border: 0 !important; + border: 0 !important; } .split-vertical { - display : flex; - flex-direction : row; - /* height : 99.2%; */ - height : 100%; + display : flex; + flex-direction : row; + /* height : 99.2%; */ + height : 100%; } .split-horizontal { - display : flex; - flex-direction: column; - height : calc(100% - 10px); + display : flex; + flex-direction: column; + height : calc(100% - 10px); } .gutter { - background-color : var(--border-color); - background-repeat : no-repeat; - background-position: 50%; + background-color : var(--border-color); + background-repeat : no-repeat; + background-position: 50%; } .gutter.gutter-vertical { - cursor: ns-resize; + cursor: ns-resize; } .gutter.gutter-horizontal { - cursor: ew-resize; + cursor: ew-resize; } .gutter.gutter-horizontal:hover { - background-color: var(--button-background-color); - width : 3px !important; + background-color: var(--button-background-color); + width : 3px !important; } .gutter.gutter-vertical:hover { - background-color: var(--button-background-color); + background-color: var(--button-background-color); } .save-text { - position : absolute; - top : 190px; - left : 25%; - transform : translateX(-50%); - font-size : 15px; - color : #2fb12f; - padding : 7px; - border-radius: 6px; - background : var(--list-hover-background-color); - opacity : .97; - z-index : 100; - font-weight : bold; - border : var(--border-size) solid var(--border-color) !important; + position : absolute; + top : 190px; + left : 25%; + transform : translateX(-50%); + font-size : 15px; + color : #2fb12f; + padding : 7px; + border-radius: 6px; + background : var(--list-hover-background-color); + opacity : .97; + z-index : 100; + font-weight : bold; + border : var(--border-size) solid var(--border-color) !important; } .save-visible { - visibility: visible; + visibility: visible; } .save-invisible { - visibility: hidden; + visibility: hidden; } .save-text-horizontal { - left: 50% !important; - top : 50% !important; -} \ No newline at end of file + left: 50% !important; + top : 50% !important; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/OptionTab/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/OptionTab/index.tsx index b638a9c..4c0c155 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/OptionTab/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/OptionTab/index.tsx @@ -1,46 +1,46 @@ import React from 'react'; import { useSelector } from "react-redux"; -import { IRootState } from "../../../../reducer/combineReducer"; import { ReactComponent as MenuLogo } from '../../../../../../icons/settings.svg'; +import { IRootState } from "../../../../reducer/combineReducer"; export const OptionsTab = (props: any) => { - const { selectedTab, setSelectedTab, options, settings } = props; + const { selectedTab, setSelectedTab, options, settings } = props; - const { headers } = useSelector((state: IRootState) => state.requestData); + const { headers } = useSelector((state: IRootState) => state.requestData); - const settingsCss = () => { - return selectedTab === "settings" ? "settings-menu settings-menu-clicked" : "settings-menu"; - }; + const settingsCss = () => { + return selectedTab === "settings" ? "settings-menu settings-menu-clicked" : "settings-menu"; + }; - return ( -
- { - options.map((option) => ( - - ))} - {settings &&
{ setSelectedTab("settings"); }} />
} -
- ); -}; \ No newline at end of file + return ( +
+ { + options.map((option) => ( + + ))} + {settings &&
{ setSelectedTab("settings"); }} />
} +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/index.tsx index 036dac2..ba0b58c 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/index.tsx @@ -1,314 +1,314 @@ -import { Actions } from "../../../../redux"; -import { ClientAuth, GrantType, IAuth, IRequestModel } from "../../../../redux/types"; -import { clientAuthOpt, grantTypeOpt } from "../consts"; +import React, { useEffect } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { v4 as uuidv4 } from 'uuid'; +import { requestTypes, responseTypes } from "../../../../../../../utils/configuration"; import { formatDate } from "../../../../../../../utils/helper"; -import { InitialBody, InitialPreFetch, InitialRequestHeaders, InitialSetVar, InitialTest } from "../../../../redux/reducer"; -import { IResponse } from "../../../../../ResponseUI/redux/types"; import { IRootState } from "../../../../../../reducer/combineReducer"; import { ITableData } from "../../../../../Common/Table/types"; -import { IVariable } from "../../../../../SideBar/redux/types"; -import { requestTypes, responseTypes } from "../../../../../../../utils/configuration"; import { TextEditor } from "../../../../../Common/TextEditor/TextEditor"; -import { useDispatch, useSelector } from "react-redux"; -import { v4 as uuidv4 } from 'uuid'; -import React, { useEffect } from "react"; import vscode from "../../../../../Common/vscodeAPI"; +import { IResponse } from "../../../../../ResponseUI/redux/types"; +import { IVariable } from "../../../../../SideBar/redux/types"; +import { Actions } from "../../../../redux"; +import { InitialBody, InitialPreFetch, InitialRequestHeaders, InitialSetVar, InitialTest } from "../../../../redux/reducer"; +import { ClientAuth, GrantType, IAuth, IRequestModel } from "../../../../redux/types"; +import { clientAuthOpt, grantTypeOpt } from "../consts"; import "./style.css"; export interface IOAuthProps { - inherit: boolean; - settingAuth?: IAuth; - envVar: any; - selectedVariable: IVariable; + inherit: boolean; + settingAuth?: IAuth; + envVar: any; + selectedVariable: IVariable; } export const OAuth = (props: IOAuthProps) => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const auth = props.settingAuth ? props.settingAuth : useSelector((state: IRootState) => state.requestData.auth); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const { parentSettings } = useSelector((state: IRootState) => state.reqColData); + const auth = props.settingAuth ? props.settingAuth : useSelector((state: IRootState) => state.requestData.auth); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const { parentSettings } = useSelector((state: IRootState) => state.reqColData); - const onSetGrantype = (value: GrantType) => { - let localAuth = { ...auth }; - localAuth.oauth.grantType = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetGrantype = (value: GrantType) => { + let localAuth = { ...auth }; + localAuth.oauth.grantType = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - const onSetClientAuth = (value: ClientAuth) => { - let localAuth = { ...auth }; - localAuth.oauth.clientAuth = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetClientAuth = (value: ClientAuth) => { + let localAuth = { ...auth }; + localAuth.oauth.clientAuth = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - const onSetValue = (type: string, value: string) => { - let localAuth = { ...auth }; - if (type === "tokenUrl") { - localAuth.oauth.tokenUrl = value; - } else if (type === "clientId") { - localAuth.oauth.clientId = value; - } else if (type === "clientSecret") { - localAuth.oauth.clientSecret = value; - } else if (type === "username") { - localAuth.oauth.username = value; - } else if (type === "password") { - localAuth.oauth.password = value; - } else if (type === "scope") { - localAuth.oauth.scope = value; - } else if (type === "tokenPrefix") { - localAuth.tokenPrefix = value; - } else if (type === "tokenName") { - localAuth.oauth.tokenName = value; - } else if (type === "audience") { - localAuth.oauth.advancedOpt.audience = value; - } else if (type === "resource") { - localAuth.oauth.advancedOpt.resource = value; - } + const onSetValue = (type: string, value: string) => { + let localAuth = { ...auth }; + if (type === "tokenUrl") { + localAuth.oauth.tokenUrl = value; + } else if (type === "clientId") { + localAuth.oauth.clientId = value; + } else if (type === "clientSecret") { + localAuth.oauth.clientSecret = value; + } else if (type === "username") { + localAuth.oauth.username = value; + } else if (type === "password") { + localAuth.oauth.password = value; + } else if (type === "scope") { + localAuth.oauth.scope = value; + } else if (type === "tokenPrefix") { + localAuth.tokenPrefix = value; + } else if (type === "tokenName") { + localAuth.oauth.tokenName = value; + } else if (type === "audience") { + localAuth.oauth.advancedOpt.audience = value; + } else if (type === "resource") { + localAuth.oauth.advancedOpt.resource = value; + } - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - function onNewtokenClick() { - let reqData: IRequestModel = { - id: uuidv4(), - url: auth.oauth.tokenUrl, - name: "tokenGen", - createdTime: formatDate(), - method: "post", - params: [{ isChecked: false, key: "", value: "" }], - auth: { - authType: "noauth", - userName: "", - password: "", - addTo: "queryparams", - showPwd: false, - tokenPrefix: "Bearer", - }, - headers: JSON.parse(JSON.stringify(InitialRequestHeaders)), - body: JSON.parse(JSON.stringify(InitialBody)), - tests: JSON.parse(JSON.stringify(InitialTest)), - setvar: JSON.parse(JSON.stringify(InitialSetVar)), - notes: "", - preFetch: JSON.parse(JSON.stringify(InitialPreFetch)), - }; - let localAuth = { ...auth }; - let urlencoded: ITableData[] = []; + function onNewtokenClick() { + let reqData: IRequestModel = { + id: uuidv4(), + url: auth.oauth.tokenUrl, + name: "tokenGen", + createdTime: formatDate(), + method: "post", + params: [{ isChecked: false, key: "", value: "" }], + auth: { + authType: "noauth", + userName: "", + password: "", + addTo: "queryparams", + showPwd: false, + tokenPrefix: "Bearer", + }, + headers: JSON.parse(JSON.stringify(InitialRequestHeaders)), + body: JSON.parse(JSON.stringify(InitialBody)), + tests: JSON.parse(JSON.stringify(InitialTest)), + setvar: JSON.parse(JSON.stringify(InitialSetVar)), + notes: "", + preFetch: JSON.parse(JSON.stringify(InitialPreFetch)), + }; + let localAuth = { ...auth }; + let urlencoded: ITableData[] = []; - urlencoded.push({ isChecked: true, key: "grant_type", value: auth.oauth.grantType === GrantType.Client_Crd ? "client_credentials" : "password" }); - urlencoded.push({ isChecked: true, key: "scope", value: auth.oauth.scope }); + urlencoded.push({ isChecked: true, key: "grant_type", value: auth.oauth.grantType === GrantType.Client_Crd ? "client_credentials" : "password" }); + urlencoded.push({ isChecked: true, key: "scope", value: auth.oauth.scope }); - if (auth.oauth.clientAuth === ClientAuth.Body) { - urlencoded.push({ isChecked: true, key: "client_id", value: auth.oauth.clientId }); - urlencoded.push({ isChecked: true, key: "client_secret", value: auth.oauth.clientSecret }); - } else { - let encodedString = Buffer.from(auth.oauth.clientId + ":" + auth.oauth.clientSecret).toString('base64'); - reqData.headers.push({ isChecked: true, key: "Authorization", value: "Basic " + encodedString }); - } + if (auth.oauth.clientAuth === ClientAuth.Body) { + urlencoded.push({ isChecked: true, key: "client_id", value: auth.oauth.clientId }); + urlencoded.push({ isChecked: true, key: "client_secret", value: auth.oauth.clientSecret }); + } else { + let encodedString = Buffer.from(auth.oauth.clientId + ":" + auth.oauth.clientSecret).toString('base64'); + reqData.headers.push({ isChecked: true, key: "Authorization", value: "Basic " + encodedString }); + } - if (auth.oauth.grantType === GrantType.PWD_Crd) { - urlencoded.push({ isChecked: true, key: "username", value: auth.oauth.username }); - urlencoded.push({ isChecked: true, key: "password", value: auth.oauth.password }); - } + if (auth.oauth.grantType === GrantType.PWD_Crd) { + urlencoded.push({ isChecked: true, key: "username", value: auth.oauth.username }); + urlencoded.push({ isChecked: true, key: "password", value: auth.oauth.password }); + } - if (auth.oauth.grantType === GrantType.Client_Crd && auth.oauth.advancedOpt?.resource) { - urlencoded.push({ isChecked: true, key: "resource", value: auth.oauth.advancedOpt.resource }); - } + if (auth.oauth.grantType === GrantType.Client_Crd && auth.oauth.advancedOpt?.resource) { + urlencoded.push({ isChecked: true, key: "resource", value: auth.oauth.advancedOpt.resource }); + } - if (auth.oauth.advancedOpt?.audience) { - urlencoded.push({ isChecked: true, key: "audience", value: auth.oauth.advancedOpt?.audience }); - } + if (auth.oauth.advancedOpt?.audience) { + urlencoded.push({ isChecked: true, key: "audience", value: auth.oauth.advancedOpt?.audience }); + } - reqData.body.bodyType = "formurlencoded"; - reqData.body.urlencoded = urlencoded; + reqData.body.bodyType = "formurlencoded"; + reqData.body.urlencoded = urlencoded; - localAuth.password = ""; - dispatch(Actions.SetRequestAuthAction(localAuth)); - vscode.postMessage({ type: requestTypes.tokenRequest, data: { reqData: reqData, variableData: selectedVariable?.data, settings: parentSettings } }); - } + localAuth.password = ""; + dispatch(Actions.SetRequestAuthAction(localAuth)); + vscode.postMessage({ type: requestTypes.tokenRequest, data: { reqData: reqData, variableData: selectedVariable?.data, settings: parentSettings } }); + } - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.tokenResponse) { - let tokenResponse: IResponse = event.data.response as IResponse; - if (!tokenResponse.isError && tokenResponse.status === 200) { - const responseData = JSON.parse(tokenResponse.responseData); - let tokenName = auth.oauth.tokenName ? auth.oauth.tokenName : "access_token"; - dispatch(Actions.SetOAuthTokenAction(responseData[tokenName] ? responseData[tokenName] : "")); - } - } - }); - }, []); + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.tokenResponse) { + let tokenResponse: IResponse = event.data.response as IResponse; + if (!tokenResponse.isError && tokenResponse.status === 200) { + const responseData = JSON.parse(tokenResponse.responseData); + let tokenName = auth.oauth.tokenName ? auth.oauth.tokenName : "access_token"; + dispatch(Actions.SetOAuthTokenAction(responseData[tokenName] ? responseData[tokenName] : "")); + } + } + }); + }, []); - return ( -
-
- Access Token - { - props.envVar && props.selectedVariable.id && - } + return ( +
+
+ Access Token + { + props.envVar && props.selectedVariable.id && + } -
-
- - { - props.envVar && props.selectedVariable.id && onSetValue("tokenPrefix", value)} - value={auth.tokenPrefix} - focus={false} - /> - } -
- -
- - -
-
- - { - props.envVar && props.selectedVariable.id && onSetValue("tokenUrl", value)} - value={auth.oauth.tokenUrl} - focus={false} - /> - } -
-
- - { - props.envVar && props.selectedVariable.id && onSetValue("clientId", value)} - value={auth.oauth.clientId} - focus={false} - /> - } -
-
- - { - props.envVar && props.selectedVariable.id && onSetValue("clientSecret", value)} - value={auth.oauth.clientSecret} - focus={false} - /> - } -
- {auth.oauth.grantType === GrantType.PWD_Crd && <> -
- - { - props.envVar && props.selectedVariable.id && onSetValue("username", value)} - value={auth.oauth.username} - focus={false} - /> - } -
-
- - { - props.envVar && props.selectedVariable.id && onSetValue("password", value)} - value={auth.oauth.password} - focus={false} - /> - } -
- - } -
- - { - props.envVar && props.selectedVariable.id && onSetValue("scope", value)} - value={auth.oauth.scope} - focus={false} - /> - } -
-
- - -
- - {auth.oauth.grantType === GrantType.Client_Crd &&
- - { - props.envVar && props.selectedVariable.id && onSetValue("resource", value)} - value={auth.oauth.advancedOpt?.resource} - placeholder="Resource (Optional)" - focus={false} - /> - } -
} -
- - { - props.envVar && props.selectedVariable.id && onSetValue("audience", value)} - value={auth.oauth.advancedOpt?.audience} - placeholder="Audience (Optional)" - focus={false} - /> - } -
-
- - { - props.envVar && props.selectedVariable.id && onSetValue("tokenName", value)} - value={auth.oauth.tokenName} - placeholder="Token Name (Optional)" - focus={false} - /> - } -
-
- -
-
- ); -}; \ No newline at end of file +
+
+ + { + props.envVar && props.selectedVariable.id && onSetValue("tokenPrefix", value)} + value={auth.tokenPrefix} + focus={false} + /> + } +
+ +
+ + +
+
+ + { + props.envVar && props.selectedVariable.id && onSetValue("tokenUrl", value)} + value={auth.oauth.tokenUrl} + focus={false} + /> + } +
+
+ + { + props.envVar && props.selectedVariable.id && onSetValue("clientId", value)} + value={auth.oauth.clientId} + focus={false} + /> + } +
+
+ + { + props.envVar && props.selectedVariable.id && onSetValue("clientSecret", value)} + value={auth.oauth.clientSecret} + focus={false} + /> + } +
+ {auth.oauth.grantType === GrantType.PWD_Crd && <> +
+ + { + props.envVar && props.selectedVariable.id && onSetValue("username", value)} + value={auth.oauth.username} + focus={false} + /> + } +
+
+ + { + props.envVar && props.selectedVariable.id && onSetValue("password", value)} + value={auth.oauth.password} + focus={false} + /> + } +
+ + } +
+ + { + props.envVar && props.selectedVariable.id && onSetValue("scope", value)} + value={auth.oauth.scope} + focus={false} + /> + } +
+
+ + +
+ + {auth.oauth.grantType === GrantType.Client_Crd &&
+ + { + props.envVar && props.selectedVariable.id && onSetValue("resource", value)} + value={auth.oauth.advancedOpt?.resource} + placeholder="Resource (Optional)" + focus={false} + /> + } +
} +
+ + { + props.envVar && props.selectedVariable.id && onSetValue("audience", value)} + value={auth.oauth.advancedOpt?.audience} + placeholder="Audience (Optional)" + focus={false} + /> + } +
+
+ + { + props.envVar && props.selectedVariable.id && onSetValue("tokenName", value)} + value={auth.oauth.tokenName} + placeholder="Token Name (Optional)" + focus={false} + /> + } +
+
+ +
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/style.css index ce999ce..90f52d5 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/OAuth/style.css @@ -1,56 +1,56 @@ .oauth-section-header { - height : 25px; - display : inline-block; - padding : 20px 15px 10px 0; - font-size : 16px; - font-weight: 300; + height : 25px; + display : inline-block; + padding : 20px 15px 10px 0; + font-size : 16px; + font-weight: 300; } .oauth-label { - display: block; - float : left; - width : 150px; - padding: 5px 0 0; + display: block; + float : left; + width : 150px; + padding: 5px 0 0; } .oauth-text-panel { - display: flex; - padding : 10px 10px 10px 0; - max-width: 100%; + display: flex; + padding : 10px 10px 10px 0; + max-width: 100%; } .oauth-text-panel .outer-container { - width: calc(100% - 155px); + width: calc(100% - 155px); } .oauth-text-panel .DraftEditor-editorContainer { - width : 100%; - height : 30px; - outline : none; - padding : 5px; - border-radius: 3px; - background : var(--background-color); - border : 0.25px solid var(--border-color); - color : var(--text-color); + width : 100%; + height : 30px; + outline : none; + padding : 5px; + border-radius: 3px; + background : var(--background-color); + border : 0.25px solid var(--border-color); + color : var(--text-color); } .oauth-text-panel .public-DraftEditorPlaceholder-inner { - padding-top: 5px; + padding-top: 5px; } .oauth-select { - width: 170px !important; + width: 170px !important; } .oauth-btn-panel { - margin-top: 15px; - text-align: center; + margin-top: 15px; + text-align: center; } .oauth-token-btn { - width: 120px !important; + width: 120px !important; } .oauth-info-label { - cursor: pointer; -} \ No newline at end of file + cursor: pointer; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/index.tsx index 4c72a83..c310071 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/index.tsx @@ -8,114 +8,114 @@ import { IAuth } from "../../../../redux/types"; import "./style.css"; export interface IAwsAuthProps { - settingAuth?: IAuth; - envVar: any; - selectedVariable: IVariable; + settingAuth?: IAuth; + envVar: any; + selectedVariable: IVariable; } export const AwsAuth = (props: IAwsAuthProps) => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const { auth } = useSelector((state: IRootState) => state.requestData); + const { auth } = useSelector((state: IRootState) => state.requestData); - const onSetAccessKey = (value: string) => { - let localAuth = { ...auth }; - localAuth.aws.accessKey = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetAccessKey = (value: string) => { + let localAuth = { ...auth }; + localAuth.aws.accessKey = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - const onSetSecretKey = (value: string) => { - let localAuth = { ...auth }; - localAuth.aws.secretAccessKey = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetSecretKey = (value: string) => { + let localAuth = { ...auth }; + localAuth.aws.secretAccessKey = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - const onSetRegion = (value: string) => { - let localAuth = { ...auth }; - localAuth.aws.region = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetRegion = (value: string) => { + let localAuth = { ...auth }; + localAuth.aws.region = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - const onSetServiceName = (value: string) => { - let localAuth = { ...auth }; - localAuth.aws.service = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetServiceName = (value: string) => { + let localAuth = { ...auth }; + localAuth.aws.service = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - const onSetSessionToken = (value: string) => { - let localAuth = { ...auth }; - localAuth.aws.sessionToken = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; + const onSetSessionToken = (value: string) => { + let localAuth = { ...auth }; + localAuth.aws.sessionToken = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; - return ( -
-
- - { - props.envVar && props.selectedVariable.id && - } -
-
- - { - props.envVar && props.selectedVariable.id && - } -
-
- - {"Advanced"} -
+ return ( +
+
+ + { + props.envVar && props.selectedVariable.id && + } +
+
+ + { + props.envVar && props.selectedVariable.id && + } +
+
+ + {"Advanced"} +
-
-
-
-
- - { - props.envVar && props.selectedVariable.id && - } -
-
- - { - props.envVar && props.selectedVariable.id && - } -
-
- - { - props.envVar && props.selectedVariable.id && - } -
-
-
-
- ); -}; \ No newline at end of file +
+
+
+
+ + { + props.envVar && props.selectedVariable.id && + } +
+
+ + { + props.envVar && props.selectedVariable.id && + } +
+
+ + { + props.envVar && props.selectedVariable.id && + } +
+
+
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/style.css index 571b0d6..0737009 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/aws/style.css @@ -1,22 +1,22 @@ .aws-label { - display: block; - float : left; - width : 125px; - padding: 5px 0 0; + display: block; + float : left; + width : 125px; + padding: 5px 0 0; } .aws-auth-text-panel { - padding: 10px 10px 10px 0; - max-width: 100%; + padding: 10px 10px 10px 0; + max-width: 100%; } .aws-auth-text-panel .DraftEditor-editorContainer { - width : calc(100% - 130px); - height : 30px; - outline : none; - padding : 5px; - border-radius: 3px; - background : var(--background-color); - border : 0.25px solid var(--border-color); - color : var(--text-color); -} \ No newline at end of file + width : calc(100% - 130px); + height : 30px; + outline : none; + padding : 5px; + border-radius: 3px; + background : var(--background-color); + border : 0.25px solid var(--border-color); + color : var(--text-color); +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/consts.ts b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/consts.ts index 71412a8..f846983 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/consts.ts +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/consts.ts @@ -1,39 +1,39 @@ import { ClientAuth, GrantType } from "../../../redux/types"; export const apiKeyAddTo = [ - { name: "Query Params", value: "queryparams" }, - { name: "Header", value: "header" } + { name: "Query Params", value: "queryparams" }, + { name: "Header", value: "header" } ]; export const grantTypeOpt = [ - { name: "Password Credentials", value: GrantType.PWD_Crd }, - { name: "Client Credentials", value: GrantType.Client_Crd } + { name: "Password Credentials", value: GrantType.PWD_Crd }, + { name: "Client Credentials", value: GrantType.Client_Crd } ]; export const clientAuthOpt = [ - { name: "As Auth Header", value: ClientAuth.Header }, - { name: "As Request Body", value: ClientAuth.Body } + { name: "As Auth Header", value: ClientAuth.Header }, + { name: "As Request Body", value: ClientAuth.Body } ]; export const basicAuthTypes = [ - { name: "No Auth", value: "noauth" }, - { name: "API Key", value: "apikey" }, - { name: "Bearer Token", value: "bearertoken" }, - { name: "Basic Auth", value: "basic" }, - { name: "AWS Signature", value: "aws" }, - { name: "OAuth 2.0", value: "oauth2" } + { name: "No Auth", value: "noauth" }, + { name: "API Key", value: "apikey" }, + { name: "Bearer Token", value: "bearertoken" }, + { name: "Basic Auth", value: "basic" }, + { name: "AWS Signature", value: "aws" }, + { name: "OAuth 2.0", value: "oauth2" } ]; export const allAuthTypes = [ - { name: "Inherit auth from parent", value: "inherit" }, - ...basicAuthTypes + { name: "Inherit auth from parent", value: "inherit" }, + ...basicAuthTypes ]; export const authCollection = { - "noauth": "No Auth", - "apikey": "API Key", - "bearertoken": "Bearer Token", - "basic": "Basic Auth", - "aws": "AWS Signature", - "oauth2": "OAuth 2.0" -}; \ No newline at end of file + "noauth": "No Auth", + "apikey": "API Key", + "bearertoken": "Bearer Token", + "basic": "Basic Auth", + "aws": "AWS Signature", + "oauth2": "OAuth 2.0" +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/index.tsx index 41384b3..da28b45 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/index.tsx @@ -14,438 +14,438 @@ import { OAuth } from './OAuth'; import "./style.css"; export interface IAuthProps { - settingsMode?: boolean; - authTypes: { name: string, value: string }[]; - selectedVariable: IVariable; + settingsMode?: boolean; + authTypes: { name: string, value: string }[]; + selectedVariable: IVariable; } export const AuthPanel = (props: IAuthProps) => { - const dispatch = useDispatch(); - - const { auth, params, headers } = useSelector((state: IRootState) => state.requestData); - const { colId, folderId, parentSettings } = useSelector((state: IRootState) => state.reqColData); - - const [varColor, setColor] = useState(""); - const [envVar, setEnvVar] = useState(null); - - useEffect(() => { - if (props.selectedVariable.id) { - setEnvVar(props.selectedVariable.data.map(item => item.key)); - } else { - setEnvVar([]); - } - }, [props.selectedVariable.data]); - - useEffect(() => { - if (props.selectedVariable.id) { - setEnvVar(props.selectedVariable.data.map(item => item.key)); - } else { - setEnvVar([]); - } - - if (auth.authType === "bearertoken") { - if (auth.password.length > 4 && auth.password.includes("{{") && auth.password.includes("}}")) { - var word = auth.password.substring(auth.password.indexOf("{{") + 2, auth.password.lastIndexOf("}}")); - if (props.selectedVariable.id) { - props.selectedVariable.data.map(item => item.key).includes(word) ? setColor("var-available") : setColor("var-notavailable"); - } else { - setColor("var-notavailable"); - } - } else { - setColor(""); - } - } - }, []); - - const setAuthValue = (evt: React.ChangeEvent) => { - let localAuth = { ...auth }; - - localAuth = InitialAuth; - localAuth.authType = evt.target.value; - - let localTable = [...params]; - let basicAuthData = localTable.find(isAvailable); - if (basicAuthData) { - removeParams(); - } else { - localTable = [...headers]; - basicAuthData = localTable.find(isAvailable); - if (basicAuthData) { - removeHeaders(); - } - } - - dispatch(Actions.SetRequestAuthAction(localAuth)); - - if (evt.target.value !== "inherit" && auth.authType === "inherit") { - if (auth.addTo = "queryparams") { - removeParams(); - } else { - removeHeaders(); - } - } - - if (evt.target.value === "inherit" && !parentSettings) { - vscode.postMessage({ type: requestTypes.getParentSettingsRequest, data: { colId: colId, folderId: folderId } }); - return; - } - - if (evt.target.value === "inherit" && parentSettings && parentSettings.auth.authType === "apikey") { - modifyQueryParam(parentSettings.auth.addTo, parentSettings.auth.userName, parentSettings.auth.password); - } - }; - - const setBearerToken = (evt: React.ChangeEvent) => { - let str = evt.target.value; - let localAuth = { ...auth }; - localAuth.userName = ""; - localAuth.password = str; - if (!auth.tokenPrefix) { - localAuth.tokenPrefix = "Bearer"; - } - - if (str.length > 4 && str.includes("{{") && str.includes("}}")) { - var word = str.substring(str.indexOf("{{") + 2, str.lastIndexOf("}}")); - envVar.includes(word) ? setColor("var-available") : setColor("var-notavailable"); - } else { - setColor(""); - } - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; - - const setTokenPrefix = (value: string) => { - let localAuth = { ...auth }; - localAuth.tokenPrefix = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; - - const setBasicAuthUserName = (value: string) => { - let localAuth = { ...auth }; - localAuth.userName = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - if (auth.authType === "apikey") { - if (localAuth.addTo === "queryparams") { - setQueryParam(value); - } - else { - setHeaderParam(value); - } - } - }; - - const setBasicAuthPassword = (value: string) => { - let localAuth = { ...auth }; - localAuth.password = value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - if (auth.authType === "apikey") { - if (localAuth.addTo === "queryparams") { - setQueryParam(value, true); - } else { - setHeaderParam(value, true); - } - } - }; - - const setQueryParam = (value: string, isPwd: boolean = false) => { - let localTable = [...params]; - let basicAuthData = localTable.find(isAvailable); - - if (basicAuthData) { - if (isPwd) { - basicAuthData.value = value; - } else { - basicAuthData.key = value; - } - if (!basicAuthData.value && !basicAuthData.key) { - localTable.shift(); - } - } else { - if (value) { - localTable.unshift({ - isChecked: true, - key: !isPwd ? value : "", - value: isPwd ? value : "", - isFixed: true - }); - } - } - - dispatch(Actions.SetRequestParamsAction(localTable)); - }; - - const setHeaderParam = (value: string, isPwd: boolean = false) => { - let localTable = [...headers]; - let basicAuthData = localTable.find(isAvailable); - - if (basicAuthData) { - if (isPwd) { - basicAuthData.value = value; - } else { - basicAuthData.key = value; - } - if (!basicAuthData.value && !basicAuthData.key) { - localTable.shift(); - } - } else { - if (value) { - localTable.unshift({ - isChecked: true, - key: !isPwd ? value : "", - value: isPwd ? value : "", - isFixed: true - }); - } - } - - dispatch(Actions.SetRequestHeadersAction(localTable)); - }; - - const setAPIKeyAddTo = (evt: React.ChangeEvent) => { - let localAuth = { ...auth }; - localAuth.addTo = evt.target.value; - dispatch(Actions.SetRequestAuthAction(localAuth)); - modifyQueryParam(evt.target.value, auth.userName, auth.password); - }; - - const modifyQueryParam = (section: string, userName: string, password: string) => { - if (section === "queryparams") { - let localParams = [...params]; - let localHeaders = [...headers]; - let basicAuthData = localHeaders.find(isAvailable); - - if (userName) { - localParams.unshift({ - isChecked: true, - key: userName, - value: password, - isFixed: true - }); - } - - dispatch(Actions.SetRequestParamsAction(localParams)); - if (basicAuthData) { - removeHeaders(); - } - - } else { - let localHeaders = [...headers]; - let localParams = [...params]; - let basicAuthData = localParams.find(isAvailable); - - if (userName) { - localHeaders.unshift({ - isChecked: true, - key: userName, - value: password, - isFixed: true - }); - } - - dispatch(Actions.SetRequestHeadersAction(localHeaders)); - if (basicAuthData) { - removeParams(); - } - } - }; - - function removeParams() { - let localParams = [...params]; - localParams.shift(); - dispatch(Actions.SetRequestParamsAction(localParams)); - } - - function removeHeaders() { - let localHeaders = [...headers]; - localHeaders.shift(); - dispatch(Actions.SetRequestHeadersAction(localHeaders)); - } - - const onSelectChange = (evt: React.ChangeEvent) => { - let localAuth = { ...auth }; - if (evt.currentTarget.checked === true) { - localAuth.showPwd = true; - } else { - localAuth.showPwd = false; - } - - dispatch(Actions.SetRequestAuthAction(localAuth)); - }; - - const bearerToken = () => { - return ( -
- - - - { - envVar && props.selectedVariable.id && - } -
- ); - }; - - const basicAuth = () => { - return ( -
-
- - { - envVar && props.selectedVariable.id && - } -
-
- - { - auth.showPwd ? - envVar && props.selectedVariable.id && - : - setBasicAuthPassword(e.target.value)} - /> - } -
- {auth.authType !== "inherit" &&
- - Show Password -
} -
- ); - }; - - const apiKeyAuth = () => { - return ( -
-
- - { - envVar && props.selectedVariable.id && - } -
-
- - { - envVar && props.selectedVariable.id && - } -
-
- - -
-
- ); - }; - - const inheritAuth = () => { - if (!parentSettings) { - return (<>); - } - - return ( - <> - -
- - {authCollection[parentSettings.auth.authType]} - -
- {authValuePanel(parentSettings.auth.authType, true)} -
-
- - ); - }; - - const authValuePanel = (type: string, isInherit: boolean = false) => { - switch (type) { - case "bearertoken": - return bearerToken(); - case "basic": - return basicAuth(); - case "apikey": - return apiKeyAuth(); - case "aws": - return ; - case "oauth2": - return ; - case "inherit": - return props.settingsMode ? <> : inheritAuth(); - default: - return (
); - } - }; - - return ( -
-
- - -
- {!props.settingsMode &&
} -
- {authValuePanel(auth.authType)} -
-
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const { auth, params, headers } = useSelector((state: IRootState) => state.requestData); + const { colId, folderId, parentSettings } = useSelector((state: IRootState) => state.reqColData); + + const [varColor, setColor] = useState(""); + const [envVar, setEnvVar] = useState(null); + + useEffect(() => { + if (props.selectedVariable.id) { + setEnvVar(props.selectedVariable.data.map(item => item.key)); + } else { + setEnvVar([]); + } + }, [props.selectedVariable.data]); + + useEffect(() => { + if (props.selectedVariable.id) { + setEnvVar(props.selectedVariable.data.map(item => item.key)); + } else { + setEnvVar([]); + } + + if (auth.authType === "bearertoken") { + if (auth.password.length > 4 && auth.password.includes("{{") && auth.password.includes("}}")) { + var word = auth.password.substring(auth.password.indexOf("{{") + 2, auth.password.lastIndexOf("}}")); + if (props.selectedVariable.id) { + props.selectedVariable.data.map(item => item.key).includes(word) ? setColor("var-available") : setColor("var-notavailable"); + } else { + setColor("var-notavailable"); + } + } else { + setColor(""); + } + } + }, []); + + const setAuthValue = (evt: React.ChangeEvent) => { + let localAuth = { ...auth }; + + localAuth = InitialAuth; + localAuth.authType = evt.target.value; + + let localTable = [...params]; + let basicAuthData = localTable.find(isAvailable); + if (basicAuthData) { + removeParams(); + } else { + localTable = [...headers]; + basicAuthData = localTable.find(isAvailable); + if (basicAuthData) { + removeHeaders(); + } + } + + dispatch(Actions.SetRequestAuthAction(localAuth)); + + if (evt.target.value !== "inherit" && auth.authType === "inherit") { + if (auth.addTo = "queryparams") { + removeParams(); + } else { + removeHeaders(); + } + } + + if (evt.target.value === "inherit" && !parentSettings) { + vscode.postMessage({ type: requestTypes.getParentSettingsRequest, data: { colId: colId, folderId: folderId } }); + return; + } + + if (evt.target.value === "inherit" && parentSettings && parentSettings.auth.authType === "apikey") { + modifyQueryParam(parentSettings.auth.addTo, parentSettings.auth.userName, parentSettings.auth.password); + } + }; + + const setBearerToken = (evt: React.ChangeEvent) => { + let str = evt.target.value; + let localAuth = { ...auth }; + localAuth.userName = ""; + localAuth.password = str; + if (!auth.tokenPrefix) { + localAuth.tokenPrefix = "Bearer"; + } + + if (str.length > 4 && str.includes("{{") && str.includes("}}")) { + var word = str.substring(str.indexOf("{{") + 2, str.lastIndexOf("}}")); + envVar.includes(word) ? setColor("var-available") : setColor("var-notavailable"); + } else { + setColor(""); + } + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; + + const setTokenPrefix = (value: string) => { + let localAuth = { ...auth }; + localAuth.tokenPrefix = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; + + const setBasicAuthUserName = (value: string) => { + let localAuth = { ...auth }; + localAuth.userName = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + if (auth.authType === "apikey") { + if (localAuth.addTo === "queryparams") { + setQueryParam(value); + } + else { + setHeaderParam(value); + } + } + }; + + const setBasicAuthPassword = (value: string) => { + let localAuth = { ...auth }; + localAuth.password = value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + if (auth.authType === "apikey") { + if (localAuth.addTo === "queryparams") { + setQueryParam(value, true); + } else { + setHeaderParam(value, true); + } + } + }; + + const setQueryParam = (value: string, isPwd: boolean = false) => { + let localTable = [...params]; + let basicAuthData = localTable.find(isAvailable); + + if (basicAuthData) { + if (isPwd) { + basicAuthData.value = value; + } else { + basicAuthData.key = value; + } + if (!basicAuthData.value && !basicAuthData.key) { + localTable.shift(); + } + } else { + if (value) { + localTable.unshift({ + isChecked: true, + key: !isPwd ? value : "", + value: isPwd ? value : "", + isFixed: true + }); + } + } + + dispatch(Actions.SetRequestParamsAction(localTable)); + }; + + const setHeaderParam = (value: string, isPwd: boolean = false) => { + let localTable = [...headers]; + let basicAuthData = localTable.find(isAvailable); + + if (basicAuthData) { + if (isPwd) { + basicAuthData.value = value; + } else { + basicAuthData.key = value; + } + if (!basicAuthData.value && !basicAuthData.key) { + localTable.shift(); + } + } else { + if (value) { + localTable.unshift({ + isChecked: true, + key: !isPwd ? value : "", + value: isPwd ? value : "", + isFixed: true + }); + } + } + + dispatch(Actions.SetRequestHeadersAction(localTable)); + }; + + const setAPIKeyAddTo = (evt: React.ChangeEvent) => { + let localAuth = { ...auth }; + localAuth.addTo = evt.target.value; + dispatch(Actions.SetRequestAuthAction(localAuth)); + modifyQueryParam(evt.target.value, auth.userName, auth.password); + }; + + const modifyQueryParam = (section: string, userName: string, password: string) => { + if (section === "queryparams") { + let localParams = [...params]; + let localHeaders = [...headers]; + let basicAuthData = localHeaders.find(isAvailable); + + if (userName) { + localParams.unshift({ + isChecked: true, + key: userName, + value: password, + isFixed: true + }); + } + + dispatch(Actions.SetRequestParamsAction(localParams)); + if (basicAuthData) { + removeHeaders(); + } + + } else { + let localHeaders = [...headers]; + let localParams = [...params]; + let basicAuthData = localParams.find(isAvailable); + + if (userName) { + localHeaders.unshift({ + isChecked: true, + key: userName, + value: password, + isFixed: true + }); + } + + dispatch(Actions.SetRequestHeadersAction(localHeaders)); + if (basicAuthData) { + removeParams(); + } + } + }; + + function removeParams() { + let localParams = [...params]; + localParams.shift(); + dispatch(Actions.SetRequestParamsAction(localParams)); + } + + function removeHeaders() { + let localHeaders = [...headers]; + localHeaders.shift(); + dispatch(Actions.SetRequestHeadersAction(localHeaders)); + } + + const onSelectChange = (evt: React.ChangeEvent) => { + let localAuth = { ...auth }; + if (evt.currentTarget.checked === true) { + localAuth.showPwd = true; + } else { + localAuth.showPwd = false; + } + + dispatch(Actions.SetRequestAuthAction(localAuth)); + }; + + const bearerToken = () => { + return ( +
+ + + + { + envVar && props.selectedVariable.id && + } +
+ ); + }; + + const basicAuth = () => { + return ( +
+
+ + { + envVar && props.selectedVariable.id && + } +
+
+ + { + auth.showPwd ? + envVar && props.selectedVariable.id && + : + setBasicAuthPassword(e.target.value)} + /> + } +
+ {auth.authType !== "inherit" &&
+ + Show Password +
} +
+ ); + }; + + const apiKeyAuth = () => { + return ( +
+
+ + { + envVar && props.selectedVariable.id && + } +
+
+ + { + envVar && props.selectedVariable.id && + } +
+
+ + +
+
+ ); + }; + + const inheritAuth = () => { + if (!parentSettings) { + return (<>); + } + + return ( + <> + +
+ + {authCollection[parentSettings.auth.authType]} + +
+ {authValuePanel(parentSettings.auth.authType, true)} +
+
+ + ); + }; + + const authValuePanel = (type: string, isInherit: boolean = false) => { + switch (type) { + case "bearertoken": + return bearerToken(); + case "basic": + return basicAuth(); + case "apikey": + return apiKeyAuth(); + case "aws": + return ; + case "oauth2": + return ; + case "inherit": + return props.settingsMode ? <> : inheritAuth(); + default: + return (
); + } + }; + + return ( +
+
+ + +
+ {!props.settingsMode &&
} +
+ {authValuePanel(auth.authType)} +
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/style.css index 765825a..8676f1f 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Auth/style.css @@ -1,99 +1,99 @@ .auth-panel { - padding: 7px 10px 5px; + padding: 7px 10px 5px; } .auth-type-panel { - display : flex; - padding-right: 20px; + display : flex; + padding-right: 20px; } .auth-type-select { - height : 30px; - outline : none; - margin : 5px 10px; - border-radius : 3px; - background-color: var(--background-color); - color : var(--text-color); - display : inline-block; - font-weight : 600; + height : 30px; + outline : none; + margin : 5px 10px; + border-radius : 3px; + background-color: var(--background-color); + color : var(--text-color); + display : inline-block; + font-weight : 600; } .auth-type-select option { - color : var(--text-color); - background-color: var(--background-color); + color : var(--text-color); + background-color: var(--background-color); } .auth-type-select:focus, .auth-type-select:hover { - outline: none; + outline: none; } .auth-token-text-panel { - max-width: 100%; - flex-grow: 1; + max-width: 100%; + flex-grow: 1; } .auth-type-label { - padding: 7px 10px 5px 0; + padding: 7px 10px 5px 0; } .auth-token-text { - width : calc(100% - 105px); - height : 250px; - outline : none; - margin : 10px; - padding : 10px; - border-radius: 3px; - resize : none; - font-size : var(--vscode-editor-font-size) !important; - font-family : var(--vscode-editor-font-family) !important; - font-weight : var(--vscode-font-weight); + width : calc(100% - 105px); + height : 250px; + outline : none; + margin : 10px; + padding : 10px; + border-radius: 3px; + resize : none; + font-size : var(--vscode-editor-font-size) !important; + font-family : var(--vscode-editor-font-family) !important; + font-weight : var(--vscode-font-weight); } .auth-token-prefix-text, .auth-token-text-panel .DraftEditor-editorContainer { - width : calc(100% - 83px); - height : 30px; - outline : none; - margin : 10px; - padding : 5px; - border-radius: 3px; + width : calc(100% - 83px); + height : 30px; + outline : none; + margin : 10px; + padding : 5px; + border-radius: 3px; } .auth-token-text:focus, .auth-token-prefix-text:focus, .basic-auth-username:focus, .basic-auth-password:focus { - outline: none; + outline: none; } .auth-token-label { - display: block; - float : left; - height : 30px; - width : 50px; - padding: 15px 10px 10px 0; + display: block; + float : left; + height : 30px; + width : 50px; + padding: 15px 10px 10px 0; } label { - font-size: var(--font-size); + font-size: var(--font-size); } .basic-auth-username, .basic-auth-text-panel .DraftEditor-editorContainer { - width : calc(100% - 110px); - height : 30px; - outline : none; - padding : 5px; - border-radius: 3px; + width : calc(100% - 110px); + height : 30px; + outline : none; + padding : 5px; + border-radius: 3px; } .basic-auth-password { - width : calc(100% - 120px); - height : 28px; - outline : none; - padding : 0 4px; - border-radius: 3px + width : calc(100% - 120px); + height : 28px; + outline : none; + padding : 0 4px; + border-radius: 3px } .basic-auth-username:focus, @@ -102,100 +102,100 @@ label { .basic-auth-password:hover, .auth-token-text:focus, .auth-token-text:hover { - outline: none; + outline: none; } .basic-auth-label { - display: block; - float : left; - width : 80px; - padding: 5px 0 0; + display: block; + float : left; + width : 80px; + padding: 5px 0 0; } .basic-auth-text-panel { - padding : 10px 10px 10px 0; - max-width: 100%; + padding : 10px 10px 10px 0; + max-width: 100%; } .apikey-add-select { - height : 30px; - outline : none; - border-radius : 3px; - background-color: var(--background-color); - color : var(--text-color); + height : 30px; + outline : none; + border-radius : 3px; + background-color: var(--background-color); + color : var(--text-color); } .apikey-add-select option { - background-color: var(--background-color); - color : var(--text-color); + background-color: var(--background-color); + color : var(--text-color); } .apikey-add-select:focus, .apikey-add-select:hover { - outline: none; + outline: none; } .basic-auth-check { - padding-top : 10px; - margin-left : 96px; - border-radius: 3px; - font-size : var(--font-size); + padding-top : 10px; + margin-left : 96px; + border-radius: 3px; + font-size : var(--font-size); } .basic-auth-check-box { - margin-right: 10px; + margin-right: 10px; } .basic-auth-check-box:focus, .basic-auth-check-box.hover { - outline: none; + outline: none; } .auth-text, .basic-auth-text-panel .DraftEditor-editorContainer, .auth-token-text-panel .DraftEditor-editorContainer { - background: var(--background-color); - border : 0.25px solid var(--border-color); - color : var(--text-color); + background: var(--background-color); + border : 0.25px solid var(--border-color); + color : var(--text-color); } .var-available { - color: rgb(18, 187, 18); + color: rgb(18, 187, 18); } .var-notavailable { - color: #f05348; + color: #f05348; } .setting-mode { - width : calc(100% - 131px) !important; - height : 28px !important; - padding: 0 10px !important; + width : calc(100% - 131px) !important; + height : 28px !important; + padding: 0 10px !important; } .auth-token-setting-mode { - width: calc(100% - 131px) !important; + width: calc(100% - 131px) !important; } .auth-no-label { - padding-top: 10px; + padding-top: 10px; } .auth-label { - font-size: medium; + font-size: medium; } .inherit-auth-summary { - padding-left: 5px; + padding-left: 5px; } .inherit-auth-details { - padding-top: 15px; + padding-top: 15px; } .inherit-auth-summary-panel { - pointer-events: none; - background-color: var(--list-hover-background-color); - padding-left: 10px; - padding-bottom: 10px; -} \ No newline at end of file + pointer-events: none; + background-color: var(--list-hover-background-color); + padding-left: 10px; + padding-bottom: 10px; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/consts.ts b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/consts.ts index 03adfcd..20fe930 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/consts.ts +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/consts.ts @@ -1,77 +1,77 @@ export const FileTypes = { - "aac": "audio/aac", - "abw": "application/x-abiword", - "arc": "application/x-freearc", - "avif": "image/avif", - "avi": "video/x-msvideo", - "azw": "application/vnd.amazon.ebook", - "bin": "application/octet-stream", - "bmp": "image/bmp", - "bz": "application/x-bzip", - "bz2": "application/x-bzip2", - "cda": "application/x-cdf", - "csh": "application/x-csh", - "css": "text/css", - "csv": "text/csv", - "doc": "application/msword", - "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - "eot": "application/vnd.ms-fontobject", - "epub": "application/epub+zip", - "gz": "application/gzip", - "gif": "image/gif", - "html": "text/html", - "ico": "image/vnd.microsoft.icon", - "ics": "text/calendar", - "jar": "application/java-archive", - "jpg": "image/jpeg", - "js": "text/javascript", - "json": "application/json", - "jsonld": "application/ld+json", - "mid": "audio/midi", - "midi": "audio/x-midi", - "mjs": "text/javascript", - "mp3": "audio/mpeg", - "mp4": "video/mp4", - "mpeg": "video/mpeg", - "mpkg": "application/vnd.apple.installer+xml", - "odp": "application/vnd.oasis.opendocument.presentation", - "ods": "application/vnd.oasis.opendocument.spreadsheet", - "odt": "application/vnd.oasis.opendocument.text", - "oga": "audio/ogg", - "ogv": "video/ogg", - "ogx": "application/ogg", - "opus": "audio/opus", - "otf": "font/otf", - "png": "image/png", - "pdf": "application/pdf", - "php": "application/x-httpd-php", - "ppt": "application/vnd.ms-powerpoint", - "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", - "rar": "application/vnd.rar", - "rtf": "application/rtf", - "sh": "application/x-sh", - "svg": "image/svg+xml", - "swf": "application/x-shockwave-flash", - "tar": "application/x-tar", - "tif tiff": "image/tiff", - "ts": "video/mp2t", - "ttf": "font/ttf", - "txt": "text/plain", - "text": "text/plain", - "vsd": "application/vnd.visio", - "wav": "audio/wav", - "weba": "audio/webm", - "webm": "video/webm", - "webp": "image/webp", - "woff": "font/woff", - "woff2": "font/woff2", - "xhtml": "application/xhtml+xml", - "xls": "application/vnd.ms-excel", - "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "xml": "application/xml ", - "xul": "application/vnd.mozilla.xul+xml", - "zip": "application/zip", - "3gp": "video/3gpp", - "3g2": "video/3gpp2", - "7z": "application/x-7z-compressed" -}; \ No newline at end of file + "aac": "audio/aac", + "abw": "application/x-abiword", + "arc": "application/x-freearc", + "avif": "image/avif", + "avi": "video/x-msvideo", + "azw": "application/vnd.amazon.ebook", + "bin": "application/octet-stream", + "bmp": "image/bmp", + "bz": "application/x-bzip", + "bz2": "application/x-bzip2", + "cda": "application/x-cdf", + "csh": "application/x-csh", + "css": "text/css", + "csv": "text/csv", + "doc": "application/msword", + "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "eot": "application/vnd.ms-fontobject", + "epub": "application/epub+zip", + "gz": "application/gzip", + "gif": "image/gif", + "html": "text/html", + "ico": "image/vnd.microsoft.icon", + "ics": "text/calendar", + "jar": "application/java-archive", + "jpg": "image/jpeg", + "js": "text/javascript", + "json": "application/json", + "jsonld": "application/ld+json", + "mid": "audio/midi", + "midi": "audio/x-midi", + "mjs": "text/javascript", + "mp3": "audio/mpeg", + "mp4": "video/mp4", + "mpeg": "video/mpeg", + "mpkg": "application/vnd.apple.installer+xml", + "odp": "application/vnd.oasis.opendocument.presentation", + "ods": "application/vnd.oasis.opendocument.spreadsheet", + "odt": "application/vnd.oasis.opendocument.text", + "oga": "audio/ogg", + "ogv": "video/ogg", + "ogx": "application/ogg", + "opus": "audio/opus", + "otf": "font/otf", + "png": "image/png", + "pdf": "application/pdf", + "php": "application/x-httpd-php", + "ppt": "application/vnd.ms-powerpoint", + "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "rar": "application/vnd.rar", + "rtf": "application/rtf", + "sh": "application/x-sh", + "svg": "image/svg+xml", + "swf": "application/x-shockwave-flash", + "tar": "application/x-tar", + "tif tiff": "image/tiff", + "ts": "video/mp2t", + "ttf": "font/ttf", + "txt": "text/plain", + "text": "text/plain", + "vsd": "application/vnd.visio", + "wav": "audio/wav", + "weba": "audio/webm", + "webm": "video/webm", + "webp": "image/webp", + "woff": "font/woff", + "woff2": "font/woff2", + "xhtml": "application/xhtml+xml", + "xls": "application/vnd.ms-excel", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "xml": "application/xml ", + "xul": "application/vnd.mozilla.xul+xml", + "zip": "application/zip", + "3gp": "video/3gpp", + "3g2": "video/3gpp2", + "7z": "application/x-7z-compressed" +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/index.tsx index 8b8ee79..b30f883 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/index.tsx @@ -9,128 +9,128 @@ import "./style.css"; export const Binary = () => { - const dispatch = useDispatch(); - - const { body, headers } = useSelector((state: IRootState) => state.requestData); - - - const [contentType, setContentType] = useState(body.binary.fileName ? getFileType(body.binary.fileName) : ""); - - const overrideEventDefaults = - (event: Event | React.DragEvent | React.ChangeEvent): void => { - event.preventDefault(); - event.stopPropagation(); - }; - - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.selectFileResponse) { - const fileName = event.data.path; - const fileType = getFileType(fileName); - if (fileType) { - setContentType(fileType); - } - dispatch(Actions.SetRequestBodyAction({ - ...body, binary: { - fileName: fileName, - data: event.data.fileData, - contentTypeOption: "manual" - } - })); - } - }); - }, []); - - function getFileType(fileName: string): string { - const lastDot = fileName.lastIndexOf('.'); - const ext = fileName.substring(lastDot + 1); - if (FileTypes[ext]) { - return FileTypes[ext]; - } - - return ""; - } - - const onSelectFile = (evt: any) => { - overrideEventDefaults(evt); - vscode.postMessage({ type: requestTypes.selectFileRequest }); - }; - - const onResetFile = (evt: any) => { - overrideEventDefaults(evt); - dispatch(Actions.SetRequestBodyAction({ - ...body, binary: { - fileName: "", - data: "", - contentTypeOption: "manual" - } - })); - }; - - function onChanged(evt: React.ChangeEvent) { - if(evt.target.id !== "manual"){ - if (evt.target.value === "application/octet-stream") { - updateContentType("application/octet-stream"); - } else if (evt.target.value === contentType) { - updateContentType(contentType); - } - } - - dispatch(Actions.SetRequestBodyAction({ - ...body, binary: { - fileName: body.binary.fileName, - data: body.binary.data, - contentTypeOption: evt.target.value - } - })); - } - - function updateContentType(contentTypeValue: string) { - let localHeaders = [...headers]; - let index = headers.findIndex(item => item.isChecked && item.key.trim().toLocaleLowerCase() === "content-type"); - if (index === -1) { - index = headers.findIndex(item => item.key.trim().toLocaleLowerCase() === "content-type"); - if (index === -1) { - localHeaders.splice(localHeaders.length - 1, 0, { - isChecked: true, - key: "Content-Type", - value: contentTypeValue, - isFixed: false - }); - } else { - localHeaders[index].isChecked = true; - localHeaders[index].value = contentTypeValue; - } - } else { - localHeaders[index].value = contentTypeValue; - } - - dispatch(Actions.SetRequestHeadersAction(localHeaders)); - } - - return ( -
-

-
- -
{body.binary.fileName}
- {body.binary.data && body.binary.data.length > 0 &&
} -
- {body.binary.fileName && body.binary.data.length === 0 && {"The file is not available in the specified location. Please select the file again."}} - { - body.binary.data && body.binary.data.length > 0 && (
- Content Type : -
- {"Added by Manual"} - {"application/octet-stream"} - {contentType && {contentType}} - {"Note: "} -
{"For option 1, No Change in the headers section."}
-
{"For Options 2 and 3, manually added content type header will be unchecked and new content type header will be added with the selected value. If you want to return to the old content-type, then you need to do it manually."}
-
-
-
) - } -
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const { body, headers } = useSelector((state: IRootState) => state.requestData); + + + const [contentType, setContentType] = useState(body.binary.fileName ? getFileType(body.binary.fileName) : ""); + + const overrideEventDefaults = + (event: Event | React.DragEvent | React.ChangeEvent): void => { + event.preventDefault(); + event.stopPropagation(); + }; + + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.selectFileResponse) { + const fileName = event.data.path; + const fileType = getFileType(fileName); + if (fileType) { + setContentType(fileType); + } + dispatch(Actions.SetRequestBodyAction({ + ...body, binary: { + fileName: fileName, + data: event.data.fileData, + contentTypeOption: "manual" + } + })); + } + }); + }, []); + + function getFileType(fileName: string): string { + const lastDot = fileName.lastIndexOf('.'); + const ext = fileName.substring(lastDot + 1); + if (FileTypes[ext]) { + return FileTypes[ext]; + } + + return ""; + } + + const onSelectFile = (evt: any) => { + overrideEventDefaults(evt); + vscode.postMessage({ type: requestTypes.selectFileRequest }); + }; + + const onResetFile = (evt: any) => { + overrideEventDefaults(evt); + dispatch(Actions.SetRequestBodyAction({ + ...body, binary: { + fileName: "", + data: "", + contentTypeOption: "manual" + } + })); + }; + + function onChanged(evt: React.ChangeEvent) { + if(evt.target.id !== "manual"){ + if (evt.target.value === "application/octet-stream") { + updateContentType("application/octet-stream"); + } else if (evt.target.value === contentType) { + updateContentType(contentType); + } + } + + dispatch(Actions.SetRequestBodyAction({ + ...body, binary: { + fileName: body.binary.fileName, + data: body.binary.data, + contentTypeOption: evt.target.value + } + })); + } + + function updateContentType(contentTypeValue: string) { + let localHeaders = [...headers]; + let index = headers.findIndex(item => item.isChecked && item.key.trim().toLocaleLowerCase() === "content-type"); + if (index === -1) { + index = headers.findIndex(item => item.key.trim().toLocaleLowerCase() === "content-type"); + if (index === -1) { + localHeaders.splice(localHeaders.length - 1, 0, { + isChecked: true, + key: "Content-Type", + value: contentTypeValue, + isFixed: false + }); + } else { + localHeaders[index].isChecked = true; + localHeaders[index].value = contentTypeValue; + } + } else { + localHeaders[index].value = contentTypeValue; + } + + dispatch(Actions.SetRequestHeadersAction(localHeaders)); + } + + return ( +
+

+
+ +
{body.binary.fileName}
+ {body.binary.data && body.binary.data.length > 0 &&
} +
+ {body.binary.fileName && body.binary.data.length === 0 && {"The file is not available in the specified location. Please select the file again."}} + { + body.binary.data && body.binary.data.length > 0 && (
+ Content Type : +
+ {"Added by Manual"} + {"application/octet-stream"} + {contentType && {contentType}} + {"Note: "} +
{"For option 1, No Change in the headers section."}
+
{"For Options 2 and 3, manually added content type header will be unchecked and new content type header will be added with the selected value. If you want to return to the old content-type, then you need to do it manually."}
+
+
+
) + } +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/style.css index d75156e..6b31ab1 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Binary/style.css @@ -1,102 +1,102 @@ .file-upload-button { - display: none; + display: none; } .file-upload-panel { - display: flex; - margin-top: 20px; + display: flex; + margin-top: 20px; } .file-upload-text { - background-color: var(--background-color); - border-radius: 3px; - color: var(--text-color); - cursor: pointer; - padding: 5px; - border: var(--border-size) solid var(--border-color); + background-color: var(--background-color); + border-radius: 3px; + color: var(--text-color); + cursor: pointer; + padding: 5px; + border: var(--border-size) solid var(--border-color); } .file-upload-text:hover { - background-color: var(--input-hover); + background-color: var(--input-hover); } .filename-text { - color: var(--text-color); - font-size: var(--font-size); - padding-top: 5px; - margin-left: 10px; + color: var(--text-color); + font-size: var(--font-size); + padding-top: 5px; + margin-left: 10px; } .file-reset-panel { - margin-left: auto; - order: 2; - padding: 5px; + margin-left: auto; + order: 2; + padding: 5px; } .file-reset-text { - background-color: transparent; - outline: none; - border: 0; - color: var(--button-background-color); - cursor: pointer; - font-weight: bolder; - padding-left: 5px; + background-color: transparent; + outline: none; + border: 0; + color: var(--button-background-color); + cursor: pointer; + font-weight: bolder; + padding-left: 5px; } .file-reset-text:hover, .file-reset-text:focus { - background-color: transparent; - outline: none; - border: 0; + background-color: transparent; + outline: none; + border: 0; } .file-reset-text:hover { - color: var(--button-hover-color); + color: var(--button-hover-color); } .content-type-panel { - margin-top: 15px; + margin-top: 15px; } .content-type-radio-button-panel { - display: grid; - padding: 5px; + display: grid; + padding: 5px; } .content-type-radio-button-wrapper { - padding: 5px; + padding: 5px; } .content-type-radio-button { - padding: 5px; + padding: 5px; } .content-type-radio-button-text { - font-weight: bold; + font-weight: bold; } .content-type-info { - padding-left: 5px; - cursor: pointer; - width: 16px; - height: 16px; + padding-left: 5px; + cursor: pointer; + width: 16px; + height: 16px; } .content-type-info path { - fill: gray; + fill: gray; } .file-not-available { - padding: 15px 5px 5px 0; - display: block; - color: #ea5b5b; - font-size: medium; + padding: 15px 5px 5px 0; + display: block; + color: #ea5b5b; + font-size: medium; } .note-text { - padding: 10px; + padding: 10px; } .note-text-part { - padding-top: 5px; -} \ No newline at end of file + padding-top: 5px; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/FormData/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/FormData/index.tsx index ce0d137..ae8f6b3 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/FormData/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/FormData/index.tsx @@ -1,125 +1,125 @@ import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; +import { requestTypes, responseTypes } from "../../../../../../../utils/configuration"; import { IRootState } from "../../../../../../reducer/combineReducer"; -import { ITableData } from "../../../../../Common/Table/types"; import { Table } from "../../../../../Common/Table/Table"; -import { Actions } from "../../../../redux"; +import { ITableData } from "../../../../../Common/Table/types"; import vscode from "../../../../../Common/vscodeAPI"; -import { requestTypes, responseTypes } from "../../../../../../../utils/configuration"; +import { Actions } from "../../../../redux"; export const FormDataBody = () => { - const dispatch = useDispatch(); - - const { body } = useSelector((state: IRootState) => state.requestData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.formDataFileResponse) { - dispatch(Actions.SetRequestFormDataAction(event.data.path, event.data.index)); - } - }); - }, []); - - const onSelectChange = (index: number) => { - let localbody = { ...body }; - if (localbody.formdata) { - let localFormData = [...localbody.formdata]; - let rowData = localFormData[index]; - localFormData[index] = { - isChecked: !rowData.isChecked, - key: rowData.key, - value: rowData.value, - type: rowData.type - }; - localbody.formdata = localFormData; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - }; - - const onSelectType = (type: string, index: number) => { - let localbody = { ...body }; - if (localbody.formdata) { - let localFormData = [...localbody.formdata]; - let rowData = localFormData[index]; - localFormData[index] = { - isChecked: rowData.isChecked, - key: rowData.key, - value: "", - type: type - }; - localbody.formdata = localFormData; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - }; - - const onFileSelect = (index: number) => { - vscode.postMessage({ type: requestTypes.formDataFileRequest, index: index }); - }; - - const onRowAdd = (value: string, index: number, isKey: boolean = true) => { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "", - type: "Text" - }; - - let localTable = addValue(value, index, isKey); - - if (localTable[index].key && localTable[index].value) { - localTable.push(newRow); - } - - dispatch(Actions.SetRequestBodyAction({ ...body, formdata: localTable })); - }; - - const onRowUpdate = (value: string, index: number, isKey: boolean = true) => { - let localTable = addValue(value, index, isKey); - dispatch(Actions.SetRequestBodyAction({ ...body, formdata: localTable })); - }; - - const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { - let localbody = { ...body }; - if (localbody.formdata) { - let localFormData = [...localbody.formdata]; - let rowData = localFormData[index]; - localFormData[index] = { - isChecked: true, - key: isKey ? value : rowData.key, - value: !isKey ? value : rowData.value, - type: rowData.type - }; - return localFormData; - } - - return []; - }; - - function deleteParam(index: number) { - let localbody = { ...body }; - if (localbody.formdata) { - let localFormData = [...localbody.formdata]; - localFormData.splice(index, 1); - localbody.formdata = localFormData; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - } - - return ( - - ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const { body } = useSelector((state: IRootState) => state.requestData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.formDataFileResponse) { + dispatch(Actions.SetRequestFormDataAction(event.data.path, event.data.index)); + } + }); + }, []); + + const onSelectChange = (index: number) => { + let localbody = { ...body }; + if (localbody.formdata) { + let localFormData = [...localbody.formdata]; + let rowData = localFormData[index]; + localFormData[index] = { + isChecked: !rowData.isChecked, + key: rowData.key, + value: rowData.value, + type: rowData.type + }; + localbody.formdata = localFormData; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + }; + + const onSelectType = (type: string, index: number) => { + let localbody = { ...body }; + if (localbody.formdata) { + let localFormData = [...localbody.formdata]; + let rowData = localFormData[index]; + localFormData[index] = { + isChecked: rowData.isChecked, + key: rowData.key, + value: "", + type: type + }; + localbody.formdata = localFormData; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + }; + + const onFileSelect = (index: number) => { + vscode.postMessage({ type: requestTypes.formDataFileRequest, index: index }); + }; + + const onRowAdd = (value: string, index: number, isKey: boolean = true) => { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "", + type: "Text" + }; + + let localTable = addValue(value, index, isKey); + + if (localTable[index].key && localTable[index].value) { + localTable.push(newRow); + } + + dispatch(Actions.SetRequestBodyAction({ ...body, formdata: localTable })); + }; + + const onRowUpdate = (value: string, index: number, isKey: boolean = true) => { + let localTable = addValue(value, index, isKey); + dispatch(Actions.SetRequestBodyAction({ ...body, formdata: localTable })); + }; + + const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { + let localbody = { ...body }; + if (localbody.formdata) { + let localFormData = [...localbody.formdata]; + let rowData = localFormData[index]; + localFormData[index] = { + isChecked: true, + key: isKey ? value : rowData.key, + value: !isKey ? value : rowData.value, + type: rowData.type + }; + return localFormData; + } + + return []; + }; + + function deleteParam(index: number) { + let localbody = { ...body }; + if (localbody.formdata) { + let localFormData = [...localbody.formdata]; + localFormData.splice(index, 1); + localbody.formdata = localFormData; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + } + + return ( +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/index.tsx index 0b0ed70..833247a 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/index.tsx @@ -7,52 +7,52 @@ import "./style.css"; export const GraphQL = () => { - const dispatch = useDispatch(); - const { body } = useSelector((state: IRootState) => state.requestData); - const { horizontalLayout } = useSelector((state: IRootState) => state.uiData); + const dispatch = useDispatch(); + const { body } = useSelector((state: IRootState) => state.requestData); + const { horizontalLayout } = useSelector((state: IRootState) => state.uiData); - function onQueryContentChange(value: string) { - let localbody = { ...body }; - if (localbody.graphql !== undefined) { - localbody.graphql.query = value; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - } + function onQueryContentChange(value: string) { + let localbody = { ...body }; + if (localbody.graphql !== undefined) { + localbody.graphql.query = value; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + } - function onVariablesContentChange(value: string) { - let localbody = { ...body }; - if (localbody.graphql !== undefined) { - localbody.graphql.variables = value; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - } + function onVariablesContentChange(value: string) { + let localbody = { ...body }; + if (localbody.graphql !== undefined) { + localbody.graphql.variables = value; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + } - return ( -
-
- Query - -
-
- Variables - -
-
- ); -}; \ No newline at end of file + return ( +
+
+ Query + +
+
+ Variables + +
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/style.css index 1761f3b..0fe4fc5 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/GraphQL/style.css @@ -1,46 +1,46 @@ .graphql-panel { - width: 100%; - height: 100%; - margin-top: 10px; + width: 100%; + height: 100%; + margin-top: 10px; } .graphql-horizontal-panel { - display: flex; + display: flex; } .graphql-query-panel, .graphql-variable-panel { - padding: 0 10px; - display: flex; - flex-direction: column; - flex: 1; + padding: 0 10px; + display: flex; + flex-direction: column; + flex: 1; } .graphql-horizontal-query-panel { - height: 100%; + height: 100%; } .graphql-vertical-query-panel { - height: 50%; + height: 50%; } .graphql-horizontal-variable-panel { - height: 100%; + height: 100%; } .graphql-vertical-variable-panel { - margin-top: 10px; - height: calc(50% - 15px); + margin-top: 10px; + height: calc(50% - 15px); } .graphql-query-head, .graphql-variable-head { - font-size: small; - padding-bottom: 5px; - font-weight: 600; - margin-bottom: 5px; + font-size: small; + padding-bottom: 5px; + font-weight: 600; + margin-bottom: 5px; } .graphql-editor { - height: calc(100% - 20px); -} \ No newline at end of file + height: calc(100% - 20px); +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/index.tsx index 8e7d094..db8d9cf 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/index.tsx @@ -2,10 +2,10 @@ import React from "react"; import "./style.css"; export const None = () => { - return ( -
-

-
{"This request does not have a body"}
-
- ); -}; \ No newline at end of file + return ( +
+

+
{"This request does not have a body"}
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/style.css index e3c6232..be8890c 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/None/style.css @@ -1,13 +1,13 @@ .none-panel { - width: 100%; + width: 100%; } .hr-container { - width: 100%; + width: 100%; } .none-text { - width: 100%; - font-size: var(--font-size); - margin-top: 20px; + width: 100%; + font-size: var(--font-size); + margin-top: 20px; } diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/Raw.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/Raw.tsx index c02d211..81b0bcf 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/Raw.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/Raw.tsx @@ -8,24 +8,24 @@ import "./style.css"; export const Raw = (props: any) => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const requestData = useSelector((state: IRootState) => state.requestData); + const requestData = useSelector((state: IRootState) => state.requestData); - const onContentChange = (value: string) => { - dispatch(Actions.SetRequestRawAction(value)); - }; + const onContentChange = (value: string) => { + dispatch(Actions.SetRequestRawAction(value)); + }; - return ( -
- -
- ); -}; \ No newline at end of file + return ( +
+ +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/style.css index a77d2a3..91c3c06 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/Raw/style.css @@ -1,9 +1,9 @@ .raw-panel { - width: 100%; - height: 100%; - margin-top: 10px; + width: 100%; + height: 100%; + margin-top: 10px; } #container { - height: 100%; + height: 100%; } diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/UrlEncoded/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/UrlEncoded/index.tsx index 25de48d..828396e 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/UrlEncoded/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/UrlEncoded/index.tsx @@ -1,95 +1,95 @@ import React from "react"; import { useDispatch, useSelector } from "react-redux"; import { IRootState } from "../../../../../../reducer/combineReducer"; -import { ITableData } from "../../../../../Common/Table/types"; import { Table } from "../../../../../Common/Table/Table"; +import { ITableData } from "../../../../../Common/Table/types"; import { Actions } from "../../../../redux"; export const UrlEncoded = () => { - const dispatch = useDispatch(); - const { body } = useSelector((state: IRootState) => state.requestData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const dispatch = useDispatch(); + const { body } = useSelector((state: IRootState) => state.requestData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const onSelectChange = (index: number) => { - let localbody = { ...body }; - if (localbody.urlencoded) { - let localUrlEncoded = [...localbody.urlencoded]; - let rowData = localUrlEncoded[index]; - localUrlEncoded[index] = { - isChecked: !rowData.isChecked, - key: rowData.key, - value: rowData.value - }; - localbody.formdata = localUrlEncoded; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - }; + const onSelectChange = (index: number) => { + let localbody = { ...body }; + if (localbody.urlencoded) { + let localUrlEncoded = [...localbody.urlencoded]; + let rowData = localUrlEncoded[index]; + localUrlEncoded[index] = { + isChecked: !rowData.isChecked, + key: rowData.key, + value: rowData.value + }; + localbody.formdata = localUrlEncoded; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + }; - const onRowAdd = (value: string, index: number, isKey: boolean = true) => { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "" - }; + const onRowAdd = (value: string, index: number, isKey: boolean = true) => { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "" + }; - let localbody = { ...body }; + let localbody = { ...body }; - let localTable = addValue(value, index, isKey); + let localTable = addValue(value, index, isKey); - if (localTable[index].key && localTable[index].value) { - localTable.push(newRow); - } + if (localTable[index].key && localTable[index].value) { + localTable.push(newRow); + } - localbody.urlencoded = localTable; + localbody.urlencoded = localTable; - dispatch(Actions.SetRequestBodyAction(localbody)); - }; + dispatch(Actions.SetRequestBodyAction(localbody)); + }; - const onRowUpdate = (value: string, index: number, isKey: boolean = true) => { - let localbody = { ...body }; - let localTable = addValue(value, index, isKey); - localbody.urlencoded = localTable; + const onRowUpdate = (value: string, index: number, isKey: boolean = true) => { + let localbody = { ...body }; + let localTable = addValue(value, index, isKey); + localbody.urlencoded = localTable; - dispatch(Actions.SetRequestBodyAction(localbody)); - }; + dispatch(Actions.SetRequestBodyAction(localbody)); + }; - const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { - let localbody = { ...body }; - if (localbody.urlencoded) { - let localUrlEncoded = [...localbody.urlencoded]; - let rowData = localUrlEncoded[index]; - localUrlEncoded[index] = { - isChecked: true, - key: isKey ? value : rowData.key, - value: !isKey ? value : rowData.value - }; - return localUrlEncoded; - } + const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { + let localbody = { ...body }; + if (localbody.urlencoded) { + let localUrlEncoded = [...localbody.urlencoded]; + let rowData = localUrlEncoded[index]; + localUrlEncoded[index] = { + isChecked: true, + key: isKey ? value : rowData.key, + value: !isKey ? value : rowData.value + }; + return localUrlEncoded; + } - return []; - }; + return []; + }; - function deleteParam(index: number) { - let localbody = { ...body }; - if (localbody.urlencoded) { - let localUrlEncoded = [...localbody.urlencoded]; - localUrlEncoded.splice(index, 1); - localbody.urlencoded = localUrlEncoded; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - } + function deleteParam(index: number) { + let localbody = { ...body }; + if (localbody.urlencoded) { + let localUrlEncoded = [...localbody.urlencoded]; + localUrlEncoded.splice(index, 1); + localbody.urlencoded = localUrlEncoded; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + } - return ( -
- ); -}; \ No newline at end of file + return ( +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/consts.ts b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/consts.ts index 9404271..1f98fa7 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/consts.ts +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/consts.ts @@ -1,16 +1,16 @@ export const requestBodyTypes = [ - { name: "None", value: "none" }, - { name: "Form", value: "formdata" }, - { name: "Form-encode", value: "formurlencoded" }, - { name: "Raw", value: "raw" }, - { name: "Binary", value: "binary" }, - { name: "GraphQL", value: "graphql" }, + { name: "None", value: "none" }, + { name: "Form", value: "formdata" }, + { name: "Form-encode", value: "formurlencoded" }, + { name: "Raw", value: "raw" }, + { name: "Binary", value: "binary" }, + { name: "GraphQL", value: "graphql" }, ]; export const requestBodyRaw = [ - { name: "Text", value: "text" }, - { name: "JSON", value: "json" }, - { name: "HTML", value: "html" }, - { name: "XML", value: "xml" } + { name: "Text", value: "text" }, + { name: "JSON", value: "json" }, + { name: "HTML", value: "html" }, + { name: "XML", value: "xml" } ]; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/index.tsx index f2deba7..a23bcd3 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/index.tsx @@ -1,11 +1,11 @@ -import React, { useEffect, useState } from "react"; -import { useDispatch, useSelector, useStore } from "react-redux"; +import React, { useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; import { IRootState } from "../../../../../reducer/combineReducer"; import { Actions } from "../../../redux"; -import { GraphQL } from "./GraphQL"; import { Binary } from "./Binary"; import { requestBodyRaw, requestBodyTypes } from "./consts"; import { FormDataBody } from "./FormData"; +import { GraphQL } from "./GraphQL"; import { None } from "./None"; import { Raw } from "./Raw/Raw"; import "./style.css"; @@ -13,85 +13,85 @@ import { UrlEncoded } from "./UrlEncoded"; export const Body = () => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const { bodyType, raw } = useSelector((state: IRootState) => state.requestData.body); + const { bodyType, raw } = useSelector((state: IRootState) => state.requestData.body); - const [format, setFormat] = useState(false); + const [format, setFormat] = useState(false); - function setBodyType(value: string) { - dispatch(Actions.SetRequestResetBodyAction(value)); - } + function setBodyType(value: string) { + dispatch(Actions.SetRequestResetBodyAction(value)); + } - function setBodyLang(value: string) { - dispatch(Actions.SetRequestRawLangAction(value)); - } + function setBodyLang(value: string) { + dispatch(Actions.SetRequestRawLangAction(value)); + } - const renderBody = (bodyType: string) => { - switch (bodyType) { - case "none": - return ; - case "formdata": - return ; - case "formurlencoded": - return ; - case "raw": - return ; - case "binary": - return ; - default: - return ; - } - }; + const renderBody = (bodyType: string) => { + switch (bodyType) { + case "none": + return ; + case "formdata": + return ; + case "formurlencoded": + return ; + case "raw": + return ; + case "binary": + return ; + default: + return ; + } + }; - function onFormatClick() { - setFormat(!format); - } + function onFormatClick() { + setFormat(!format); + } - function renderTextmodeUI() { - return ( - <> - - - - ); - } + function renderTextmodeUI() { + return ( + <> + + + + ); + } - return ( - <> -
- {requestBodyTypes.map(({ name, value }) => ( -
- -
- ))} -
- { - bodyType === "raw" &&
- Type : {renderTextmodeUI()} -
- } -
- {renderBody(bodyType)} -
- - ); -}; \ No newline at end of file + return ( + <> +
+ {requestBodyTypes.map(({ name, value }) => ( +
+ +
+ ))} +
+ { + bodyType === "raw" &&
+ Type : {renderTextmodeUI()} +
+ } +
+ {renderBody(bodyType)} +
+ + ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/style.css index e5ed63f..f197a4e 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Body/style.css @@ -1,89 +1,89 @@ .reqest-body-options-panel { - align-items: center; - display: flex; + align-items: center; + display: flex; } .reqest-body-options { - align-items: center; - display: flex; - justify-content: center; - margin: 0 10px 0 0; - padding: 5px 0; + align-items: center; + display: flex; + justify-content: center; + margin: 0 10px 0 0; + padding: 5px 0; } .reqest-body-option { - border-radius: 0; - cursor: pointer; - margin: 0 8px; - outline: none; + border-radius: 0; + cursor: pointer; + margin: 0 8px; + outline: none; } .body-option-label { - color: var(--text-color); - font-size: var(--font-size); + color: var(--text-color); + font-size: var(--font-size); } .raw-lang-select { - height: 25px; - outline: none; - border-radius: 3px; - background-color: var(--background-color); - color: var(--text-color); - display: inline-block; - font-weight: 600; - margin-left: 5px; + height: 25px; + outline: none; + border-radius: 3px; + background-color: var(--background-color); + color: var(--text-color); + display: inline-block; + font-weight: 600; + margin-left: 5px; } .raw-lang-select option { - background-color: var(--background-color); - color: var(--text-color); + background-color: var(--background-color); + color: var(--text-color); } .raw-lang-select:focus, .raw-lang-select:hover { - outline: none; + outline: none; } .raw-type { - height: calc(100% - 95px) !important; + height: calc(100% - 95px) !important; } .request-body-details-panel { - height: calc(100% - 70px); + height: calc(100% - 70px); } .reqest-body-raw-type { - margin: 5px; + margin: 5px; } .reqest-body-raw-type-text { - margin-left: 5px; + margin-left: 5px; } .format-button { - background-color: transparent; - outline: none; - border: 0; - color: var(--button-background-color); - cursor: pointer; - float: right; - font-weight: bolder; - padding-left: 5px; + background-color: transparent; + outline: none; + border: 0; + color: var(--button-background-color); + cursor: pointer; + float: right; + font-weight: bolder; + padding-left: 5px; } .format-button:hover, .format-button:focus { - background-color: transparent; - outline: none; - border: 0; + background-color: transparent; + outline: none; + border: 0; } .format-button:hover { - color: var(--button-hover-color); + color: var(--button-hover-color); } .format-button:disabled, .format-button[disabled] { - color : #666; - cursor : not-allowed; + color : #666; + cursor : not-allowed; } diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/index.tsx index 51c9ff2..0b8edbf 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/index.tsx @@ -7,52 +7,52 @@ import "./style.css"; export const GraphQL = () => { - const dispatch = useDispatch(); - const { body } = useSelector((state: IRootState) => state.requestData); - const { horizontalLayout } = useSelector((state: IRootState) => state.uiData); + const dispatch = useDispatch(); + const { body } = useSelector((state: IRootState) => state.requestData); + const { horizontalLayout } = useSelector((state: IRootState) => state.uiData); - function onQueryContentChange(value: string) { - let localbody = { ...body }; - if (localbody.graphql !== undefined) { - localbody.graphql.query = value; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - } + function onQueryContentChange(value: string) { + let localbody = { ...body }; + if (localbody.graphql !== undefined) { + localbody.graphql.query = value; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + } - function onVariablesContentChange(value: string) { - let localbody = { ...body }; - if (localbody.graphql !== undefined) { - localbody.graphql.variables = value; - dispatch(Actions.SetRequestBodyAction(localbody)); - } - } + function onVariablesContentChange(value: string) { + let localbody = { ...body }; + if (localbody.graphql !== undefined) { + localbody.graphql.variables = value; + dispatch(Actions.SetRequestBodyAction(localbody)); + } + } - return ( -
-
- Query - -
-
- Variables - -
-
- ); -}; \ No newline at end of file + return ( +
+
+ Query + +
+
+ Variables + +
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/style.css index 1761f3b..0fe4fc5 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/GraphQL/style.css @@ -1,46 +1,46 @@ .graphql-panel { - width: 100%; - height: 100%; - margin-top: 10px; + width: 100%; + height: 100%; + margin-top: 10px; } .graphql-horizontal-panel { - display: flex; + display: flex; } .graphql-query-panel, .graphql-variable-panel { - padding: 0 10px; - display: flex; - flex-direction: column; - flex: 1; + padding: 0 10px; + display: flex; + flex-direction: column; + flex: 1; } .graphql-horizontal-query-panel { - height: 100%; + height: 100%; } .graphql-vertical-query-panel { - height: 50%; + height: 50%; } .graphql-horizontal-variable-panel { - height: 100%; + height: 100%; } .graphql-vertical-variable-panel { - margin-top: 10px; - height: calc(50% - 15px); + margin-top: 10px; + height: calc(50% - 15px); } .graphql-query-head, .graphql-variable-head { - font-size: small; - padding-bottom: 5px; - font-weight: 600; - margin-bottom: 5px; + font-size: small; + padding-bottom: 5px; + font-weight: 600; + margin-bottom: 5px; } .graphql-editor { - height: calc(100% - 20px); -} \ No newline at end of file + height: calc(100% - 20px); +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/index.tsx index 523918b..c803e08 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/index.tsx @@ -1,108 +1,108 @@ import React from 'react'; -import { ITableData } from "../../../../Common/Table/types"; -import { Table } from "../../../../Common/Table/Table"; import { useDispatch, useSelector } from "react-redux"; import { IRootState } from "../../../../../reducer/combineReducer"; -import { Actions } from "../../../redux"; +import { Table } from "../../../../Common/Table/Table"; +import { ITableData } from "../../../../Common/Table/types"; import { IVariable } from '../../../../SideBar/redux/types'; +import { Actions } from "../../../redux"; export interface IHeadersPanelProps { - selectedVariable: IVariable; + selectedVariable: IVariable; } export const HeadersPanel = (props: IHeadersPanelProps) => { - const dispatch = useDispatch(); - - const { headers } = useSelector((state: IRootState) => state.requestData); - - const onSelectChange = (index: number) => { - let localTable = [...headers]; - let rowData = localTable[index]; - localTable[index] = { - isChecked: !rowData.isChecked, - key: rowData.key, - value: rowData.value - }; - dispatch(Actions.SetRequestHeadersAction(localTable)); - }; - - const onRowAdd = (event: React.ChangeEvent | string, index: number, isKey: boolean = true) => { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "" - }; - - let value: any; - - if (typeof event === 'string' || event instanceof String) { - value = event; - } - else { - value = event.target.value; - } - - let localTable = addValue(value, index, isKey); - - if (localTable[index].key) { - localTable.push(newRow); - } - - dispatch(Actions.SetRequestHeadersAction(localTable)); - }; - - const onRowUpdate = (event: React.ChangeEvent | string, index: number, isKey: boolean = true) => { - let value: any; - - if (typeof event === 'string' || event instanceof String) { - value = event; - } - else { - value = event.target.value; - } - - let localTable = addValue(value, index, isKey); - dispatch(Actions.SetRequestHeadersAction(localTable)); - }; - - const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { - let localTable = [...headers]; - let rowData = localTable[index]; - localTable[index] = { - isChecked: true, - key: isKey ? value : rowData.key, - value: !isKey ? value : rowData.value - }; - - return localTable; - }; - - function deleteParam(index: number) { - let localTable = [...headers]; - localTable.splice(index, 1); - if (localTable.length > 0 && localTable[localTable.length - 1].key) { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "" - }; - localTable.push(newRow); - } - dispatch(Actions.SetRequestHeadersAction(localTable)); - } - - return ( -
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const { headers } = useSelector((state: IRootState) => state.requestData); + + const onSelectChange = (index: number) => { + let localTable = [...headers]; + let rowData = localTable[index]; + localTable[index] = { + isChecked: !rowData.isChecked, + key: rowData.key, + value: rowData.value + }; + dispatch(Actions.SetRequestHeadersAction(localTable)); + }; + + const onRowAdd = (event: React.ChangeEvent | string, index: number, isKey: boolean = true) => { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "" + }; + + let value: any; + + if (typeof event === 'string' || event instanceof String) { + value = event; + } + else { + value = event.target.value; + } + + let localTable = addValue(value, index, isKey); + + if (localTable[index].key) { + localTable.push(newRow); + } + + dispatch(Actions.SetRequestHeadersAction(localTable)); + }; + + const onRowUpdate = (event: React.ChangeEvent | string, index: number, isKey: boolean = true) => { + let value: any; + + if (typeof event === 'string' || event instanceof String) { + value = event; + } + else { + value = event.target.value; + } + + let localTable = addValue(value, index, isKey); + dispatch(Actions.SetRequestHeadersAction(localTable)); + }; + + const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { + let localTable = [...headers]; + let rowData = localTable[index]; + localTable[index] = { + isChecked: true, + key: isKey ? value : rowData.key, + value: !isKey ? value : rowData.value + }; + + return localTable; + }; + + function deleteParam(index: number) { + let localTable = [...headers]; + localTable.splice(index, 1); + if (localTable.length > 0 && localTable[localTable.length - 1].key) { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "" + }; + localTable.push(newRow); + } + dispatch(Actions.SetRequestHeadersAction(localTable)); + } + + return ( +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/parentHeaders.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/parentHeaders.tsx index 30c5ada..c2320ee 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/parentHeaders.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/parentHeaders.tsx @@ -3,11 +3,11 @@ import { HeadersPanel } from '.'; import { IVariable } from '../../../../SideBar/redux/types'; export interface IParentHeaderProps { - selectedVariable: IVariable; + selectedVariable: IVariable; } export const ParentHeadersPanel = (props: IParentHeaderProps) => { - return ( - - ); -}; \ No newline at end of file + return ( + + ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/requestHeaders.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/requestHeaders.tsx index ca2c308..3b17ea2 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/requestHeaders.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Headers/requestHeaders.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React from 'react'; import { useDispatch, useSelector } from "react-redux"; import { HeadersPanel } from '.'; import { IRootState } from "../../../../../reducer/combineReducer"; @@ -6,26 +6,26 @@ import { Actions } from '../../../redux'; export const RequestHeadersPanel = () => { - const dispatch = useDispatch(); - - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const { skipParentHeaders } = useSelector((state: IRootState) => state.reqSettings); + const dispatch = useDispatch(); - function onSelectChange(evt: React.ChangeEvent) { - dispatch(Actions.SetSkipHeadersAction(evt.currentTarget.checked)); - } + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const { skipParentHeaders } = useSelector((state: IRootState) => state.reqSettings); - return ( -
-
- -
- -
- ); -}; \ No newline at end of file + function onSelectChange(evt: React.ChangeEvent) { + dispatch(Actions.SetSkipHeadersAction(evt.currentTarget.checked)); + } + + return ( +
+
+ +
+ +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PostFetch/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PostFetch/index.tsx index 6ee3cb6..e3d9bcd 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PostFetch/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PostFetch/index.tsx @@ -1,28 +1,28 @@ -import { OptionsTab } from "../../OptionTab"; -import { postFetchOptions } from "../../consts"; -import { TestPanel } from "../../../../TestUI/TestPanel"; import React, { useState } from "react"; +import { TestPanel } from "../../../../TestUI/TestPanel"; import ResToVariables from "../../../../Variables/resToVar"; +import { OptionsTab } from "../../OptionTab"; +import { postFetchOptions } from "../../consts"; export const PostFetch = () => { - const [selectedTab, setSelectedTab] = useState("tests"); + const [selectedTab, setSelectedTab] = useState("tests"); - const renderOptionsUI = (tab: string) => { - switch (tab) { - case 'setvar': - return ; - default: - return ; - } - }; + const renderOptionsUI = (tab: string) => { + switch (tab) { + case 'setvar': + return ; + default: + return ; + } + }; - return ( -
- -
- {renderOptionsUI(selectedTab)} -
-
- ); -}; \ No newline at end of file + return ( +
+ +
+ {renderOptionsUI(selectedTab)} +
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/consts.ts b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/consts.ts index 73a0733..c54371f 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/consts.ts +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/consts.ts @@ -1,39 +1,39 @@ export const preConditions = [ - { name: "parameter", value: "", }, - { name: "No Condition", value: "noCondition", }, - { name: "ResponseCode", value: "Response Code", }, - { name: "ResponseBody", value: "Response Body", }, - { name: "Variable", value: "Variable", } + { name: "parameter", value: "", }, + { name: "No Condition", value: "noCondition", }, + { name: "ResponseCode", value: "Response Code", }, + { name: "ResponseBody", value: "Response Body", }, + { name: "Variable", value: "Variable", } ]; export const preConditionActions = { - "Response Code": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "<", value: "<" }, - { name: "<=", value: "<=" }, - { name: ">", value: ">" }, - { name: ">=", value: ">=" }, - { name: "regex", value: "regex" }, - ] - }, - "Response Body": { - "action": [ - { name: "select", value: "", }, - { name: "isJSON", value: "isJSON" }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "contains", value: "contains" }, - { name: "regex", value: "regex" }, - ] - }, - "Variable": { - "action": [ - { name: "select", value: "", }, - { name: "empty", value: "empty" }, - { name: "notEmpty", value: "notEmpty" }, - ] - } -}; \ No newline at end of file + "Response Code": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "<", value: "<" }, + { name: "<=", value: "<=" }, + { name: ">", value: ">" }, + { name: ">=", value: ">=" }, + { name: "regex", value: "regex" }, + ] + }, + "Response Body": { + "action": [ + { name: "select", value: "", }, + { name: "isJSON", value: "isJSON" }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "contains", value: "contains" }, + { name: "regex", value: "regex" }, + ] + }, + "Variable": { + "action": [ + { name: "select", value: "", }, + { name: "empty", value: "empty" }, + { name: "notEmpty", value: "notEmpty" }, + ] + } +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/index.tsx index dfd7f99..a23026d 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/index.tsx @@ -1,87 +1,87 @@ +import React, { useEffect } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { IRootState } from "../../../../../reducer/combineReducer"; import { Actions } from "../../../redux"; -import { IRunRequest } from "../../../redux/types"; import { InitialTest } from "../../../redux/reducer"; -import { IRootState } from "../../../../../reducer/combineReducer"; +import { IRunRequest } from "../../../redux/types"; import { PreRequest } from "./preRequest"; -import { useDispatch, useSelector } from "react-redux"; -import React, { useEffect } from "react"; import "./style.css"; export interface IPreFecthProps { - settingsMode?: boolean; + settingsMode?: boolean; } export const PreFetch = (props: IPreFecthProps) => { - const dispatch = useDispatch(); - const { preFetch } = useSelector((state: IRootState) => state.requestData); - const { skipParentPreFetch } = useSelector((state: IRootState) => state.reqSettings); + const dispatch = useDispatch(); + const { preFetch } = useSelector((state: IRootState) => state.requestData); + const { skipParentPreFetch } = useSelector((state: IRootState) => state.reqSettings); - function onAddReqClick() { - let newPreReq: IRunRequest = { - reqId: "", - parentId: "", - colId: "", - order: preFetch && preFetch?.requests ? preFetch.requests.length + 1 : 1, - condition: JSON.parse(JSON.stringify(InitialTest)) - }; - dispatch(Actions.SetAddPreRequestAction(newPreReq)); - }; + function onAddReqClick() { + let newPreReq: IRunRequest = { + reqId: "", + parentId: "", + colId: "", + order: preFetch && preFetch?.requests ? preFetch.requests.length + 1 : 1, + condition: JSON.parse(JSON.stringify(InitialTest)) + }; + dispatch(Actions.SetAddPreRequestAction(newPreReq)); + }; - useEffect(() => { - if (preFetch?.requests?.length <= 0) { - let newPreReq: IRunRequest = { - reqId: "", - parentId: "", - colId: "", - order: preFetch && preFetch?.requests ? preFetch.requests.length + 1 : 1, - condition: JSON.parse(JSON.stringify(InitialTest)) - }; - dispatch(Actions.SetAddPreRequestAction(newPreReq)); - } - }, []); + useEffect(() => { + if (preFetch?.requests?.length <= 0) { + let newPreReq: IRunRequest = { + reqId: "", + parentId: "", + colId: "", + order: preFetch && preFetch?.requests ? preFetch.requests.length + 1 : 1, + condition: JSON.parse(JSON.stringify(InitialTest)) + }; + dispatch(Actions.SetAddPreRequestAction(newPreReq)); + } + }, []); - const makeRequests = (reqs: IRunRequest[]) => { - return ( - reqs?.map((item: IRunRequest, index: number) => { - return
; - }) - ); - }; + const makeRequests = (reqs: IRunRequest[]) => { + return ( + reqs?.map((item: IRunRequest, index: number) => { + return
; + }) + ); + }; - const isDisabled = () => { - return props.settingsMode ? preFetch?.requests?.length > 1 : preFetch?.requests?.length > 4; - }; + const isDisabled = () => { + return props.settingsMode ? preFetch?.requests?.length > 1 : preFetch?.requests?.length > 4; + }; - function onSelectChange(evt: React.ChangeEvent) { - dispatch(Actions.SetSkipPreFetchAction(evt.currentTarget.checked)); - } + function onSelectChange(evt: React.ChangeEvent) { + dispatch(Actions.SetSkipPreFetchAction(evt.currentTarget.checked)); + } - return ( -
-
-
- {props?.settingsMode ? "* Max 2 request (It is recommended that each request does not contain any PreFetch requests. If there are any PreFetch requests, then they won't be executed.)" : "* Max 5 request"} -
- -
- {!props?.settingsMode ? -
- -
- : - <> - - } - { - makeRequests(preFetch?.requests) - } -
- ); -}; \ No newline at end of file + return ( +
+
+
+ {props?.settingsMode ? "* Max 2 request (It is recommended that each request does not contain any PreFetch requests. If there are any PreFetch requests, then they won't be executed.)" : "* Max 5 request"} +
+ +
+ {!props?.settingsMode ? +
+ +
+ : + <> + + } + { + makeRequests(preFetch?.requests) + } +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/preRequest.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/preRequest.tsx index 079b665..047f000 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/preRequest.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/preRequest.tsx @@ -11,255 +11,255 @@ import { preConditionActions, preConditions } from "./consts"; import "./style.css"; export interface IPreRequestProps { - request: IRunRequest, - reqIndex: number + request: IRunRequest, + reqIndex: number } export const PreRequest = (props: IPreRequestProps) => { - const dispatch = useDispatch(); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const { collectionList, colRequestList } = useSelector((state: IRootState) => state.reqColData); + const dispatch = useDispatch(); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const { collectionList, colRequestList } = useSelector((state: IRootState) => state.reqColData); - const [selectedRequestList, setSelectedRequestList] = useState([]); + const [selectedRequestList, setSelectedRequestList] = useState([]); - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getCollectionsByIdWithPathResponse && props.request.colId === event.data.colId) { - let reqList: IRequestList[] = []; - for (const [key, value] of Object.entries(event.data.paths)) { - reqList.push({ - id: key, - name: value as string - }); - } - let col: IColRequest = { - id: event.data.colId, - reqs: reqList - }; + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getCollectionsByIdWithPathResponse && props.request.colId === event.data.colId) { + let reqList: IRequestList[] = []; + for (const [key, value] of Object.entries(event.data.paths)) { + reqList.push({ + id: key, + name: value as string + }); + } + let col: IColRequest = { + id: event.data.colId, + reqs: reqList + }; - dispatch(Actions.SetColRequestListAction(col)); - setSelectedRequestList(col.reqs); + dispatch(Actions.SetColRequestListAction(col)); + setSelectedRequestList(col.reqs); - let reqId = col.reqs.length > 0 ? (props.request.reqId ? props.request.reqId : col.reqs[0].id) : ""; - let parentId = col.reqs.length > 0 ? col.reqs.find(i => i.id === reqId)?.name.split(";")[1] : ""; - dispatch(Actions.SetSelectedReqAction(reqId, props.reqIndex, parentId)); - } - }); + let reqId = col.reqs.length > 0 ? (props.request.reqId ? props.request.reqId : col.reqs[0].id) : ""; + let parentId = col.reqs.length > 0 ? col.reqs.find(i => i.id === reqId)?.name.split(";")[1] : ""; + dispatch(Actions.SetSelectedReqAction(reqId, props.reqIndex, parentId)); + } + }); - if (props.request.colId && colRequestList.findIndex(i => i.id === props.request.colId) === -1) { - vscode.postMessage({ type: requestTypes.getCollectionsByIdWithPathRequest, data: props.request.colId }); - } - }, []); + if (props.request.colId && colRequestList.findIndex(i => i.id === props.request.colId) === -1) { + vscode.postMessage({ type: requestTypes.getCollectionsByIdWithPathRequest, data: props.request.colId }); + } + }, []); - useEffect(() => { - if (props.request.colId && colRequestList.length > 0) { - setSelectedRequestList(colRequestList.find(i => i.id === props.request.colId)?.reqs); - } - }, [colRequestList]); + useEffect(() => { + if (props.request.colId && colRequestList.length > 0) { + setSelectedRequestList(colRequestList.find(i => i.id === props.request.colId)?.reqs); + } + }, [colRequestList]); - const onSelectCollection = (colId: string, index: number) => { - dispatch(Actions.SetSelectedColAction(colId, index)); + const onSelectCollection = (colId: string, index: number) => { + dispatch(Actions.SetSelectedColAction(colId, index)); - if (colRequestList.findIndex(i => i.id === colId) === -1) { - vscode.postMessage({ type: requestTypes.getCollectionsByIdWithPathRequest, data: colId }); - } else { - let reqs = colRequestList.find(i => i.id === colId)?.reqs; - setSelectedRequestList(reqs); - dispatch(Actions.SetSelectedReqAction(reqs.length > 0 ? reqs[0].id : "", index, reqs.length > 0 ? reqs[0].name.split(";")[1] : "")); - } - }; + if (colRequestList.findIndex(i => i.id === colId) === -1) { + vscode.postMessage({ type: requestTypes.getCollectionsByIdWithPathRequest, data: colId }); + } else { + let reqs = colRequestList.find(i => i.id === colId)?.reqs; + setSelectedRequestList(reqs); + dispatch(Actions.SetSelectedReqAction(reqs.length > 0 ? reqs[0].id : "", index, reqs.length > 0 ? reqs[0].name.split(";")[1] : "")); + } + }; - const onSelectRequest = (value: string, selectedIndex: number, reqIndex: number) => { - dispatch(Actions.SetSelectedReqAction(value, reqIndex, selectedRequestList[selectedIndex].name.split(";")[1])); - }; + const onSelectRequest = (value: string, selectedIndex: number, reqIndex: number) => { + dispatch(Actions.SetSelectedReqAction(value, reqIndex, selectedRequestList[selectedIndex].name.split(";")[1])); + }; - const onSelectItem = (value: string, reqIndex: number, condIndex: number, type: string) => { - let localTable = addValue(value, condIndex, type); - dispatch(Actions.SetPreConditionAction(localTable, reqIndex, condIndex)); - }; + const onSelectItem = (value: string, reqIndex: number, condIndex: number, type: string) => { + let localTable = addValue(value, condIndex, type); + dispatch(Actions.SetPreConditionAction(localTable, reqIndex, condIndex)); + }; - const onSelect = (event: React.ChangeEvent | React.ChangeEvent, reqIndex: number, condIndex: number, type: string) => { - onSelectItem(event.target.value, reqIndex, condIndex, type); - }; + const onSelect = (event: React.ChangeEvent | React.ChangeEvent, reqIndex: number, condIndex: number, type: string) => { + onSelectItem(event.target.value, reqIndex, condIndex, type); + }; - const addValue = (value: string, condIndex: number, selectType: string): ITest => { - let localValue = { ...props.request }; - let condition = localValue.condition[condIndex]; - localValue.condition[condIndex] = { - parameter: selectType === "parameter" ? value : condition.parameter, - action: selectType === "action" ? value : condition.action, - expectedValue: selectType === "expectedValue" ? value : condition.expectedValue, - customParameter: selectType === "customParameter" ? value : condition.customParameter - }; + const addValue = (value: string, condIndex: number, selectType: string): ITest => { + let localValue = { ...props.request }; + let condition = localValue.condition[condIndex]; + localValue.condition[condIndex] = { + parameter: selectType === "parameter" ? value : condition.parameter, + action: selectType === "action" ? value : condition.action, + expectedValue: selectType === "expectedValue" ? value : condition.expectedValue, + customParameter: selectType === "customParameter" ? value : condition.customParameter + }; - return localValue.condition[condIndex]; - }; + return localValue.condition[condIndex]; + }; - function onDelete(reqIndex: number, condIndex: number) { - dispatch(Actions.SetDeletePreConditionAction(reqIndex, condIndex)); - } + function onDelete(reqIndex: number, condIndex: number) { + dispatch(Actions.SetDeletePreConditionAction(reqIndex, condIndex)); + } - function onDeleteReqClick(index: number) { - dispatch(Actions.SetDeletePreRequestAction(index)); - } + function onDeleteReqClick(index: number) { + dispatch(Actions.SetDeletePreRequestAction(index)); + } - function getParameterList(row: ITest, reqIndex: number, conIndex: number) { - return ( - - ); - } + function getParameterList(row: ITest, reqIndex: number, conIndex: number) { + return ( + + ); + } - function getActionList(row: ITest, reqIndex: number, conIndex: number) { - let parameter = preConditionActions[row.parameter]; - let actionList: any; + function getActionList(row: ITest, reqIndex: number, conIndex: number) { + let parameter = preConditionActions[row.parameter]; + let actionList: any; - if (parameter) { - actionList = row.parameter ? (row.parameter === "noCondition" ? [] : parameter["action"]) : [{ name: "action", value: "" }]; - } - else { - actionList = [{ name: "action", value: "", }]; - } + if (parameter) { + actionList = row.parameter ? (row.parameter === "noCondition" ? [] : parameter["action"]) : [{ name: "action", value: "" }]; + } + else { + actionList = [{ name: "action", value: "", }]; + } - return ( - - ); - } + return ( + + ); + } - const makeCondition = (conditions: ITest[], reqIndex: number) => { + const makeCondition = (conditions: ITest[], reqIndex: number) => { - return ( -
- Condition {reqIndex} - { - conditions.map((item: ITest, conIndex: number) => { - return ( -
-
- {getParameterList(item, reqIndex, conIndex)} -
-
- {getActionList(item, reqIndex, conIndex)} -
-
- item.key)} - placeholder="condition" - onChange={(val) => onSelectItem(val, reqIndex, conIndex, "expectedValue")} - value={item.expectedValue} - focus={false} - disabled={item.parameter === "noCondition"} - /> -
-
- {conIndex !== conditions.length - 1 ? - onDelete(reqIndex, conIndex)} /> - : - <> - } -
-
- ); - }) - } -
- ); - }; + return ( +
+ Condition {reqIndex} + { + conditions.map((item: ITest, conIndex: number) => { + return ( +
+
+ {getParameterList(item, reqIndex, conIndex)} +
+
+ {getActionList(item, reqIndex, conIndex)} +
+
+ item.key)} + placeholder="condition" + onChange={(val) => onSelectItem(val, reqIndex, conIndex, "expectedValue")} + value={item.expectedValue} + focus={false} + disabled={item.parameter === "noCondition"} + /> +
+
+ {conIndex !== conditions.length - 1 ? + onDelete(reqIndex, conIndex)} /> + : + <> + } +
+
+ ); + }) + } +
+ ); + }; - const makeRequest = (req: IRunRequest, reqIndex: number) => { - return ( - <> - { - reqIndex > 0 && makeCondition(req.condition, reqIndex) - } -
- Pre-request {reqIndex + 1} -
-
- onDeleteReqClick(reqIndex)} /> -
-
- - -
-
- - -
-
-
- - ); - }; + const makeRequest = (req: IRunRequest, reqIndex: number) => { + return ( + <> + { + reqIndex > 0 && makeCondition(req.condition, reqIndex) + } +
+ Pre-request {reqIndex + 1} +
+
+ onDeleteReqClick(reqIndex)} /> +
+
+ + +
+
+ + +
+
+
+ + ); + }; - return ( -
- {makeRequest(props.request, props.reqIndex)} -
- ); -}; \ No newline at end of file + return ( +
+ {makeRequest(props.request, props.reqIndex)} +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/style.css index 2a7b0af..d01107c 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/PreFetch/style.css @@ -1,97 +1,97 @@ .preReq-container { - display: grid; - padding: 10px 0 5px 0; + display: grid; + padding: 10px 0 5px 0; } .preReq-panel { - padding: 3px 0px 2px 0; + padding: 3px 0px 2px 0; } .preReq-delete-panel { - float: right; + float: right; } .preReq-condition-panel { - display: flex; - padding: 3px 0 7px 0; + display: flex; + padding: 3px 0 7px 0; } .preReq-select { - padding: 2px 4px 4px 4px !important; - border: 1px solid !important; + padding: 2px 4px 4px 4px !important; + border: 1px solid !important; } .preReq-condition-param-panel { - width: 30%; - margin-right: 10px; + width: 30%; + margin-right: 10px; } .preReq-condition-param-panel .public-DraftEditorPlaceholder-inner { - padding: 2px 4px 4px 4px; + padding: 2px 4px 4px 4px; } .preReq-condition-param-panel .DraftEditor-editorContainer { - padding: 2px 4px 4px 4px; - border: var(--border-size) solid var(--border-color); - border-radius: 2px; + padding: 2px 4px 4px 4px; + border: var(--border-size) solid var(--border-color); + border-radius: 2px; } .preReq-condition-delete-panel { - display: flex; - align-items: center; + display: flex; + align-items: center; } .preReq-condition-delete-btn { - transform: scale(0.80); + transform: scale(0.80); } .preReq-col-select { - height: 30px; - outline: none; - border-radius: 3px; - background-color: var(--background-color); - color: var(--text-color); - width: 170px !important; + height: 30px; + outline: none; + border-radius: 3px; + background-color: var(--background-color); + color: var(--text-color); + width: 170px !important; } .preReq-col-select option { - background-color: var(--background-color); - color: var(--text-color); + background-color: var(--background-color); + color: var(--text-color); } .preReq-col-select:focus, .preReq-col-select:hover { - outline: none; + outline: none; } .preReq-col-select:invalid { - color: var(--input-unchecked); + color: var(--input-unchecked); } .preReq-col-select option[value=""][disabled] { - display: none; + display: none; } .preReq-field-panel { - margin-top: 3px + margin-top: 3px } .preReq-text-panel { - display: flex; - padding: 5px 5px 5px 0; - max-width: 100%; + display: flex; + padding: 5px 5px 5px 0; + max-width: 100%; } .max-req { - float: left; - color: red; - padding-bottom: 7px; + float: left; + color: red; + padding-bottom: 7px; } fieldset { - border: 1px solid rgb(161 161 161) !important; + border: 1px solid rgb(161 161 161) !important; } .request-prefetch-panel { - padding: 5px 0 10px 0; -} \ No newline at end of file + padding: 5px 0 10px 0; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/QueryParams/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/QueryParams/index.tsx index fcd87f8..dbe01d2 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/QueryParams/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/QueryParams/index.tsx @@ -1,77 +1,77 @@ import React from 'react'; -import { ITableData } from "../../../../Common/Table/types"; -import { Table } from "../../../../Common/Table/Table"; import { useDispatch, useSelector } from "react-redux"; import { IRootState } from "../../../../../reducer/combineReducer"; +import { Table } from "../../../../Common/Table/Table"; +import { ITableData } from "../../../../Common/Table/types"; import { Actions } from "../../../redux"; export const QueryParams = () => { - const dispatch = useDispatch(); + const dispatch = useDispatch(); - const { params } = useSelector((state: IRootState) => state.requestData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const { params } = useSelector((state: IRootState) => state.requestData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const onSelectChange = (index: number) => { - let localTable = [...params]; - let rowData = localTable[index]; - localTable[index] = { - isChecked: !rowData.isChecked, - key: rowData.key, - value: rowData.value - }; - dispatch(Actions.SetRequestParamsAction(localTable)); - }; + const onSelectChange = (index: number) => { + let localTable = [...params]; + let rowData = localTable[index]; + localTable[index] = { + isChecked: !rowData.isChecked, + key: rowData.key, + value: rowData.value + }; + dispatch(Actions.SetRequestParamsAction(localTable)); + }; - const onRowAdd = (event: any, index: number, isKey: boolean = true) => { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "" - }; + const onRowAdd = (event: any, index: number, isKey: boolean = true) => { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "" + }; - let localTable = addValue(event, index, isKey); + let localTable = addValue(event, index, isKey); - if (localTable[index].key && localTable[index].value) { - localTable.push(newRow); - } + if (localTable[index].key && localTable[index].value) { + localTable.push(newRow); + } - dispatch(Actions.SetRequestParamsAction(localTable)); - }; + dispatch(Actions.SetRequestParamsAction(localTable)); + }; - const onRowUpdate = (event: any, index: number, isKey: boolean = true) => { - let localTable = addValue(event, index, isKey); - dispatch(Actions.SetRequestParamsAction(localTable)); - }; + const onRowUpdate = (event: any, index: number, isKey: boolean = true) => { + let localTable = addValue(event, index, isKey); + dispatch(Actions.SetRequestParamsAction(localTable)); + }; - const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { - let localTable = [...params]; - let rowData = localTable[index]; - localTable[index] = { - isChecked: true, - key: isKey ? value : rowData.key, - value: !isKey ? value : rowData.value - }; + const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { + let localTable = [...params]; + let rowData = localTable[index]; + localTable[index] = { + isChecked: true, + key: isKey ? value : rowData.key, + value: !isKey ? value : rowData.value + }; - return localTable; - }; + return localTable; + }; - function deleteParam(index: number) { - let localTable = [...params]; - localTable.splice(index, 1); - dispatch(Actions.SetRequestParamsAction(localTable)); - } + function deleteParam(index: number) { + let localTable = [...params]; + localTable.splice(index, 1); + dispatch(Actions.SetRequestParamsAction(localTable)); + } - return ( -
- ); -}; \ No newline at end of file + return ( +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/index.tsx index 8791e41..4581211 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/index.tsx @@ -10,121 +10,122 @@ import "./style.css"; export const Settings = () => { - const dispatch = useDispatch(); - - const { selectedVariable, variables, isLocalChange } = useSelector((state: IRootState) => state.variableData); - const { url } = useSelector((state: IRootState) => state.requestData); - const { cookies } = useSelector((state: IRootState) => state.cookieData); - const responseData = useSelector((state: IRootState) => state.responseData); - - const [enabled, setEnabled] = useState(true); - const [globalActive, setGlobalActive] = useState(false); - - function onSelectVariable(evt: any) { - let vars = variables.filter(item => item.id === evt.target.value); - setGlobalActive(false); - dispatch(VariableActions.SetReqVariableAction(vars[0] as IVariable)); - dispatch(VariableActions.SetReqLocalChangeAction(true)); - } - - useEffect(() => { - if (isLocalChange) { - setEnabled(true); - } - else if (selectedVariable.id && selectedVariable.name.toUpperCase().trim() !== "GLOBAL") { - setEnabled(false); - } else { - let globalVar = variables.filter(item => item.name.toUpperCase().trim() === "GLOBAL" && item.isActive === true); - if (globalVar && globalVar.length > 0) { - setGlobalActive(true); - } - } - }, []); - - function getVariableData() { - let colNames = [{ name: "Select", value: "", disabled: true }]; - variables.forEach(item => { - if (item.isActive) { - colNames.push({ name: item.name, value: item.id, disabled: false }); - } - }); - - return colNames.map((param: any, index: number) => { - return ( - - ); - }); - } - - function onOpenVariable() { - vscode.postMessage({ type: requestTypes.openVariableItemRequest, data: selectedVariable.id }); - } - - function onRefreshVariable() { - vscode.postMessage({ type: requestTypes.getAllVariableRequest }); - } - - function onOpenCookies() { - let id = ""; - if (cookies.length > 0) { - let domainName = GetDomainName(url, responseData.cookies[0]); - - if (!domainName) { - return; - } - - let cookie = cookies.filter(item => item.name === domainName); - if (cookie.length > 0) { - id = cookie[0].id; - } - } - - if (id) { - vscode.postMessage({ type: requestTypes.openManageCookiesRequest, data: id }); - } else { - vscode.postMessage({ type: requestTypes.openManageCookiesRequest }); - } - - } - - function onRefreshCookies() { - vscode.postMessage({ type: requestTypes.getAllCookiesRequest }); - } - - return ( -
-
Variable :
-
- - - -

- {globalActive && Note : Currently, global variable is active. If you select the other variable, then it will be replace the global variable for this request.} -
-
Cookies :
-
- - -

-
- Note : These settings will not be saved to history. It is only used for performing this request. -
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const { selectedVariable, variables, isLocalChange } = useSelector((state: IRootState) => state.variableData); + const { url } = useSelector((state: IRootState) => state.requestData); + const { cookies } = useSelector((state: IRootState) => state.cookieData); + const responseData = useSelector((state: IRootState) => state.responseData); + + const [enabled, setEnabled] = useState(true); + const [globalActive, setGlobalActive] = useState(false); + + function onSelectVariable(evt: any) { + let vars = variables.filter(item => item.id === evt.target.value); + setGlobalActive(false); + dispatch(VariableActions.SetReqVariableAction(vars[0] as IVariable)); + dispatch(VariableActions.SetReqLocalChangeAction(true)); + } + + useEffect(() => { + if (isLocalChange) { + setEnabled(true); + } + else if (selectedVariable.id && selectedVariable.name.toUpperCase().trim() !== "GLOBAL") { + setEnabled(false); + } else { + let globalVar = variables.filter(item => item.name.toUpperCase().trim() === "GLOBAL" && item.isActive === true); + if (globalVar && globalVar.length > 0) { + setGlobalActive(true); + } + } + }, []); + + function getVariableData() { + let colNames = [{ name: "Select", value: "", disabled: true }]; + variables.forEach(item => { + if (item.isActive) { + colNames.push({ name: item.name, value: item.id, disabled: false }); + } + }); + + return colNames.map((param: any, index: number) => { + return ( + + ); + }); + } + + function onOpenVariable() { + vscode.postMessage({ type: requestTypes.openVariableItemRequest, data: selectedVariable.id }); + } + + function onRefreshVariable() { + vscode.postMessage({ type: requestTypes.getAllVariableRequest }); + } + + function onOpenCookies() { + let id = ""; + if (cookies?.length > 0) { + let domainName = GetDomainName(url, responseData.cookies[0]); + + if (!domainName) { + vscode.postMessage({ type: requestTypes.openManageCookiesRequest }); + return; + } + + let cookie = cookies.filter(item => item.name === domainName); + if (cookie.length > 0) { + id = cookie[0].id; + } + } + + if (id) { + vscode.postMessage({ type: requestTypes.openManageCookiesRequest, data: id }); + } else { + vscode.postMessage({ type: requestTypes.openManageCookiesRequest }); + } + + } + + function onRefreshCookies() { + vscode.postMessage({ type: requestTypes.getAllCookiesRequest }); + } + + return ( +
+
Variable :
+
+ + + +

+ {globalActive && Note : Currently, global variable is active. If you select the other variable, then it will be replace the global variable for this request.} +
+
Cookies :
+
+ + +

+
+ Note : These settings will not be saved to history. It is only used for performing this request. +
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/style.css index 95a1f21..14abefb 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/Settings/style.css @@ -1,60 +1,60 @@ .settings-panel { - display: flex; - flex-wrap: wrap; - padding: 20px 10px; - width: 100%; - border-top: 1px solid #5e5e5e; - margin-top: 5px; + display: flex; + flex-wrap: wrap; + padding: 20px 10px; + width: 100%; + border-top: 1px solid #5e5e5e; + margin-top: 5px; } .settings-panel>div { - margin-bottom: 20px; + margin-bottom: 20px; } .settings-item-left { - width: 15%; + width: 15%; } .settings-item-right { - width: 85%; + width: 85%; } .settings-var-select { - background-color: var(--background-color); - box-sizing: border-box; - color: var(--text-color); - padding: 5px; - font-size: small; - outline: none; - width: 50%; + background-color: var(--background-color); + box-sizing: border-box; + color: var(--text-color); + padding: 5px; + font-size: small; + outline: none; + width: 50%; } .settings-var-select:focus { - outline: none; + outline: none; } .settings-var-select:required:invalid { - color: var(--input-unchecked); + color: var(--input-unchecked); } .settings-var-select option[value=""][disabled] { - display: none; + display: none; } .settings-var-select option { - color: var(--text-color) !important; - background: var(--background-color) !important; + color: var(--text-color) !important; + background: var(--background-color) !important; } .global-var-text { - color: gray; + color: gray; } .open-var-button { - float: none !important; - padding-left: 20px; + float: none !important; + padding-left: 20px; } .manage-cookie-button{ - padding-left: 0 !important; -} \ No newline at end of file + padding-left: 0 !important; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/helper.ts b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/helper.ts index 967ffc4..0507cf4 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/helper.ts +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/Options/helper.ts @@ -1,5 +1,5 @@ import { ITableData } from "../../../Common/Table/types"; export function isAvailable(item: ITableData) { - return item.isFixed === true && item.key !== "Cookie"; -} \ No newline at end of file + return item.isFixed === true && item.key !== "Cookie"; +} diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/consts.ts b/src/fetch-client-ui/components/RequestUI/OptionsPanel/consts.ts index f968fb3..1d0dd01 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/consts.ts +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/consts.ts @@ -1,13 +1,13 @@ export const requestOptions = [ - { name: "Params", value: "params" }, - { name: "Authorization", value: "authorization" }, - { name: "Headers", value: "headers" }, - { name: "Body", value: "body" }, - { name: "PreFetch", value: "preFetch" }, - { name: "PostFetch", value: "postFetch" } + { name: "Params", value: "params" }, + { name: "Authorization", value: "authorization" }, + { name: "Headers", value: "headers" }, + { name: "Body", value: "body" }, + { name: "PreFetch", value: "preFetch" }, + { name: "PostFetch", value: "postFetch" } ]; export const postFetchOptions = [ - { name: "Tests", value: "tests" }, - { name: "Variable", value: "setvar" } + { name: "Tests", value: "tests" }, + { name: "Variable", value: "setvar" } ]; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/index.tsx b/src/fetch-client-ui/components/RequestUI/OptionsPanel/index.tsx index 27d71c9..e3ece33 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/index.tsx @@ -15,39 +15,39 @@ import "./style.css"; export const OptionsPanel = () => { - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const { colId } = useSelector((state: IRootState) => state.reqColData); - const { runItem } = useSelector((state: IRootState) => state.uiData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const { colId } = useSelector((state: IRootState) => state.reqColData); + const { runItem } = useSelector((state: IRootState) => state.uiData); - const [selectedTab, setSelectedTab] = useState(runItem ? "postFetch" : "params"); + const [selectedTab, setSelectedTab] = useState(runItem ? "postFetch" : "params"); - const renderOptionsUI = (tab: string) => { - switch (tab) { - case 'params': - return ; - case 'authorization': - return ; - case 'headers': - return ; - case 'body': - return ; - case 'settings': - return ; - case 'preFetch': - return ; - default: - return ; - } - }; + const renderOptionsUI = (tab: string) => { + switch (tab) { + case 'params': + return ; + case 'authorization': + return ; + case 'headers': + return ; + case 'body': + return ; + case 'settings': + return ; + case 'preFetch': + return ; + default: + return ; + } + }; - return ( -
-
- -
- {renderOptionsUI(selectedTab)} -
-
-
- ); + return ( +
+
+ +
+ {renderOptionsUI(selectedTab)} +
+
+
+ ); }; diff --git a/src/fetch-client-ui/components/RequestUI/OptionsPanel/style.css b/src/fetch-client-ui/components/RequestUI/OptionsPanel/style.css index 4a960d8..69f1a62 100644 --- a/src/fetch-client-ui/components/RequestUI/OptionsPanel/style.css +++ b/src/fetch-client-ui/components/RequestUI/OptionsPanel/style.css @@ -1,74 +1,74 @@ .options-panel { - margin: 5px; - padding: 0 0 0 10px; - /* height: calc(100% - 60px); */ - height: calc(100% - 70px); + margin: 5px; + padding: 0 0 0 10px; + /* height: calc(100% - 60px); */ + height: calc(100% - 70px); } .options-container { - overflow-x: auto; - width: 100%; - height: 100%; + overflow-x: auto; + width: 100%; + height: 100%; } .tab-options { - display: flex; + display: flex; } .option { - cursor: pointer; - background-color: transparent; - color: var(--text-color); - outline: none; - border: 3px solid transparent; - border-radius: 0; - padding-bottom: 5px; + cursor: pointer; + background-color: transparent; + color: var(--text-color); + outline: none; + border: 3px solid transparent; + border-radius: 0; + padding-bottom: 5px; } .option-selected { - border-bottom: 2px solid var(--button-background-color); + border-bottom: 2px solid var(--button-background-color); } .options-tab-panel { - height: calc(100% - 30px); - overflow-x: hidden; - padding: 1px 10px 5px 0; - box-sizing: border-box; + height: calc(100% - 30px); + overflow-x: hidden; + padding: 1px 10px 5px 0; + box-sizing: border-box; } .header-count { - margin-left: 4px; - color: #f05348; + margin-left: 4px; + color: #f05348; } .settings-menu-panel { - margin-left: auto; - padding-right: 5px; - margin-top: 2px; + margin-left: auto; + padding-right: 5px; + margin-top: 2px; } .settings-menu { - height: 19px; - width: 19px; - cursor: pointer; + height: 19px; + width: 19px; + cursor: pointer; } .settings-menu path { - fill: var(--text-color); + fill: var(--text-color); } .settings-menu-clicked path { - fill: var(--button-background-color); + fill: var(--button-background-color); } .request-header-panel { - padding-top: 10px; + padding-top: 10px; } .request-header-panel-text{ - display: flex; + display: flex; } .request-header-panel-option{ - margin-right: 5px; + margin-right: 5px; } diff --git a/src/fetch-client-ui/components/RequestUI/RequestPanel/common.ts b/src/fetch-client-ui/components/RequestUI/RequestPanel/common.ts index 6da8269..11d645f 100644 --- a/src/fetch-client-ui/components/RequestUI/RequestPanel/common.ts +++ b/src/fetch-client-ui/components/RequestUI/RequestPanel/common.ts @@ -10,19 +10,19 @@ import { Actions } from "../redux"; import { IReqSettings, IRequestModel } from "../redux/types"; export const SendRequest = (dispatch: Dispatch, newReq: boolean, colId: string, requestData: IRequestModel, selectedVariable: IVariable, parentSettings: ISettings, reqSettings: IReqSettings) => { - dispatch(ResponseActions.SetResponseLoadingAction(true)); + dispatch(ResponseActions.SetResponseLoadingAction(true)); - let reqData = { ...requestData }; + let reqData = { ...requestData }; - if (newReq) { - reqData.id = uuidv4(); - reqData.name = reqData.url.trim(); - reqData.createdTime = formatDate(); - dispatch(Actions.SetRequestAction(reqData)); - } + if (newReq) { + reqData.id = uuidv4(); + reqData.name = reqData.url.trim(); + reqData.createdTime = formatDate(); + dispatch(Actions.SetRequestAction(reqData)); + } - const data = GetDataFromHTML(reqData.notes); - reqData.notes = data.length > notesMaxLimit ? "" : reqData.notes; + const data = GetDataFromHTML(reqData.notes); + reqData.notes = data.length > notesMaxLimit ? "" : reqData.notes; - vscode.postMessage({ type: requestTypes.apiRequest, data: { reqData: reqData, isNew: newReq, variableData: selectedVariable, settings: parentSettings, colId: colId, reqSettings: reqSettings } }); + vscode.postMessage({ type: requestTypes.apiRequest, data: { reqData: reqData, isNew: newReq, variableData: selectedVariable, settings: parentSettings, colId: colId, reqSettings: reqSettings } }); }; diff --git a/src/fetch-client-ui/components/RequestUI/RequestPanel/consts.ts b/src/fetch-client-ui/components/RequestUI/RequestPanel/consts.ts index 3b9bd0a..8dcdb04 100644 --- a/src/fetch-client-ui/components/RequestUI/RequestPanel/consts.ts +++ b/src/fetch-client-ui/components/RequestUI/RequestPanel/consts.ts @@ -1,9 +1,9 @@ export const requestMethods = [ - { name: "GET", value: "get" }, - { name: "POST", value: "post" }, - { name: "PUT", value: "put" }, - { name: "PATCH", value: "patch" }, - { name: "DELETE", value: "delete" }, - { name: "OPTIONS", value: "options" }, - { name: "HEAD", value: "head" }, -]; \ No newline at end of file + { name: "GET", value: "get" }, + { name: "POST", value: "post" }, + { name: "PUT", value: "put" }, + { name: "PATCH", value: "patch" }, + { name: "DELETE", value: "delete" }, + { name: "OPTIONS", value: "options" }, + { name: "HEAD", value: "head" }, +]; diff --git a/src/fetch-client-ui/components/RequestUI/RequestPanel/index.tsx b/src/fetch-client-ui/components/RequestUI/RequestPanel/index.tsx index 626df08..7488d01 100644 --- a/src/fetch-client-ui/components/RequestUI/RequestPanel/index.tsx +++ b/src/fetch-client-ui/components/RequestUI/RequestPanel/index.tsx @@ -2,9 +2,8 @@ import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from "react-redux"; import { v4 as uuidv4 } from 'uuid'; import { requestTypes } from '../../../../utils/configuration'; -import { formatDate } from '../../../../utils/helper'; import { IRootState } from "../../../reducer/combineReducer"; -import { GetDataFromHTML, GetDomainName, notesMaxLimit } from '../../Common/helper'; +import { GetDomainName, getDomainNameFromURL } from '../../Common/helper'; import { ITableData } from '../../Common/Table/types'; import { TextEditor } from '../../Common/TextEditor/TextEditor'; import vscode from '../../Common/vscodeAPI'; @@ -20,211 +19,209 @@ import "./style.css"; export const RequestPanel = () => { - const dispatch = useDispatch(); - - const [newReq, setNewReq] = useState(false); - - const requestData = useSelector((state: IRootState) => state.requestData); - const responseData = useSelector((state: IRootState) => state.responseData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - const { cookies } = useSelector((state: IRootState) => state.cookieData); - const { parentSettings, colId } = useSelector((state: IRootState) => state.reqColData); - const reqSettings = useSelector((state: IRootState) => state.reqSettings); - - const selectRequestMethod = (evt: React.ChangeEvent): void => { - dispatch(Actions.SetRequestMethodAction(evt.target.value as MethodType)); - }; - - const enterUrl = (value: string): void => { - dispatch(Actions.SetRequestURLAction(value)); - }; - - function addCookieHeader(currentCookie: ICookie) { - let cookieHeader = ""; - currentCookie.data.forEach(item => { - let index = item.value.indexOf(";"); - if (index !== -1) { - let value = item.key + "=" + item.value.substring(0, index); - cookieHeader = cookieHeader ? (cookieHeader + "; " + value) : value; - } - }); - if (cookieHeader) { - let localTable = [...requestData.headers]; - let newRow: ITableData = { - isChecked: true, - isFixed: false, - key: "Cookie", - value: cookieHeader - }; - - let index = localTable.findIndex(item => item.key.toUpperCase() === "COOKIE"); - - if (index === -1) { - if (localTable[0].isFixed) { - localTable.splice(1, 0, newRow); - } else { - localTable.unshift(newRow); - } - } else { - localTable[index] = newRow; - } - - dispatch(Actions.SetRequestHeadersAction(localTable)); - } - } - - function removeCookieHeader() { - let localTable = [...requestData.headers]; - let index = localTable.findIndex(item => item.key.toUpperCase() === "COOKIE"); - if (index !== -1) { - localTable.splice(index, 1); - dispatch(Actions.SetRequestHeadersAction(localTable)); - } - } - - function checkCookieHeader() { - if (cookies.length > 0) { - try { - let url = requestData.url.startsWith("http://") || requestData.url.startsWith("https:// ") ? requestData.url : "https://" + requestData.url; - let domain = new URL(url); - let name = domain.hostname.replace('www.', ''); - if (name) { - let index = cookies.findIndex(item => item.name === name); - if (index !== -1) { - addCookieHeader(cookies[index]); - } else { - removeCookieHeader(); - } - } - } catch { - removeCookieHeader(); - } - } else { - removeCookieHeader(); - } - } - - useEffect(() => { - checkCookieHeader(); - }, [cookies]); - - const onSendClick = () => { - SendRequest(dispatch, newReq, colId, requestData, selectedVariable, parentSettings, reqSettings); - setNewReq(false); - }; - - useEffect(() => { - if (responseData.loading === false && responseData.response.status !== 0) { - if (requestData.tests.length - 1 > 0) { - let testResult = executeTests(requestData.tests, responseData, selectedVariable.data); - dispatch(ResponseActions.SetTestResultAction(testResult)); - } - - if (requestData.setvar.length - 1 > 0) { - let variable = setVariable(selectedVariable, requestData.setvar, responseData); - vscode.postMessage({ type: requestTypes.updateVariableRequest, data: variable }); - } - } - }, [responseData.headers]); - - useEffect(() => { - if (responseData.cookies.length > 0) { - let domainName = GetDomainName(requestData.url, responseData.cookies[0]); - - if (!domainName) { - return; - } - - let index = cookies.findIndex(item => item.name === domainName); - - let cookie: ICookie = { - id: index !== -1 ? cookies[index].id : uuidv4(), - name: domainName, - data: responseData.cookies - }; - - let localData = [...cookies]; - if (index !== -1) { - localData[index] = cookie; - } else { - localData.push(cookie); - } - - CookiesActions.SetAllCookiesAction(localData); - - vscode.postMessage({ type: requestTypes.saveCookieRequest, data: cookie }); - } - }, [responseData.cookies]); - - useEffect(() => { - let reqId = document.title.split("@:@")[0]; - if (reqId === "undefined") { - setNewReq(true); - } - }, []); - - const isEnabled = (): boolean => { - if (responseData.loading === true) { - return false; - } - - if (requestData.url.length > 0) { - return true; - } - - return false; - }; - - const handleKeypress = (charCode: number) => { - if (charCode === 13 && isEnabled()) { - onSendClick(); - } - }; - - function onBlur() { - checkCookieHeader(); - } - - return ( -
-
-
- -
-
- { - selectedVariable.id && item.key)} - placeholder="Enter request URL" - onChange={enterUrl} - value={requestData.url} - onKeyPress={handleKeypress} - onBlur={onBlur} - focus={true} - /> - } -
-
- -
-
-
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const [newReq, setNewReq] = useState(false); + + const requestData = useSelector((state: IRootState) => state.requestData); + const responseData = useSelector((state: IRootState) => state.responseData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + const { cookies } = useSelector((state: IRootState) => state.cookieData); + const { parentSettings, colId } = useSelector((state: IRootState) => state.reqColData); + const reqSettings = useSelector((state: IRootState) => state.reqSettings); + + const selectRequestMethod = (evt: React.ChangeEvent): void => { + dispatch(Actions.SetRequestMethodAction(evt.target.value as MethodType)); + }; + + const enterUrl = (value: string): void => { + dispatch(Actions.SetRequestURLAction(value)); + }; + + function addCookieHeader(currentCookie: ICookie) { + let cookieHeader = ""; + currentCookie?.data?.forEach(item => { + let index = item.value.indexOf(";"); + if (index !== -1) { + let value = item.key + "=" + item.value.substring(0, index); + cookieHeader = cookieHeader ? (cookieHeader + "; " + value) : value; + } + }); + if (cookieHeader) { + let localTable = [...requestData.headers]; + let newRow: ITableData = { + isChecked: true, + isFixed: false, + key: "Cookie", + value: cookieHeader + }; + + let index = localTable.findIndex(item => item.key.toUpperCase() === "COOKIE"); + + if (index === -1) { + if (localTable[0].isFixed) { + localTable.splice(1, 0, newRow); + } else { + localTable.unshift(newRow); + } + } else { + localTable[index] = newRow; + } + + dispatch(Actions.SetRequestHeadersAction(localTable)); + } + } + + function removeCookieHeader() { + let localTable = [...requestData.headers]; + let index = localTable.findIndex(item => item.key.toUpperCase() === "COOKIE"); + if (index !== -1) { + localTable.splice(index, 1); + dispatch(Actions.SetRequestHeadersAction(localTable)); + } + } + + function checkCookieHeader() { + if (cookies.length > 0) { + try { + let name = getDomainNameFromURL(requestData.url); + if (name) { + let index = cookies.findIndex(item => item.name === name); + if (index !== -1) { + addCookieHeader(cookies[index]); + } else { + removeCookieHeader(); + } + } + } catch { + removeCookieHeader(); + } + } else { + removeCookieHeader(); + } + } + + useEffect(() => { + checkCookieHeader(); + }, [cookies]); + + const onSendClick = () => { + SendRequest(dispatch, newReq, colId, requestData, selectedVariable, parentSettings, reqSettings); + setNewReq(false); + }; + + useEffect(() => { + if (responseData.loading === false && responseData.response.status !== 0) { + if (requestData.tests.length - 1 > 0) { + let testResult = executeTests(requestData.tests, responseData, selectedVariable.data); + dispatch(ResponseActions.SetTestResultAction(testResult)); + } + + if (requestData.setvar.length - 1 > 0) { + let variable = setVariable(selectedVariable, requestData.setvar, responseData); + vscode.postMessage({ type: requestTypes.updateVariableRequest, data: variable }); + } + } + }, [responseData.headers]); + + useEffect(() => { + if (responseData?.cookies?.length > 0) { + let domainName = GetDomainName(requestData.url, responseData.cookies[0]); + + if (!domainName) { + return; + } + + let index = cookies.findIndex(item => item.name === domainName); + + let cookie: ICookie = { + id: index !== -1 ? cookies[index].id : uuidv4(), + name: domainName, + data: responseData.cookies + }; + + let localData = [...cookies]; + if (index !== -1) { + localData[index] = cookie; + } else { + localData.push(cookie); + } + + CookiesActions.SetAllCookiesAction(localData); + + vscode.postMessage({ type: requestTypes.saveCookieRequest, data: cookie }); + } + }, [responseData.cookies]); + + useEffect(() => { + let reqId = document.title.split("@:@")[0]; + if (reqId === "undefined") { + setNewReq(true); + } + }, []); + + const isEnabled = (): boolean => { + if (responseData.loading === true) { + return false; + } + + if (requestData.url.length > 0) { + return true; + } + + return false; + }; + + const handleKeypress = (charCode: number) => { + if (charCode === 13 && isEnabled()) { + onSendClick(); + } + }; + + function onBlur() { + checkCookieHeader(); + } + + return ( +
+
+
+ +
+
+ { + selectedVariable.id && item.key)} + placeholder="Enter request URL" + onChange={enterUrl} + value={requestData.url} + onKeyPress={handleKeypress} + onBlur={onBlur} + focus={true} + /> + } +
+
+ +
+
+
+ ); +}; diff --git a/src/fetch-client-ui/components/RequestUI/RequestPanel/style.css b/src/fetch-client-ui/components/RequestUI/RequestPanel/style.css index f3050ac..2b6f0a0 100644 --- a/src/fetch-client-ui/components/RequestUI/RequestPanel/style.css +++ b/src/fetch-client-ui/components/RequestUI/RequestPanel/style.css @@ -1,113 +1,113 @@ .request-panel { - margin : 5px; - padding: 10px; + margin : 5px; + padding: 10px; } .request-container { - display : flex; - flex-direction: row; - width : 100%; + display : flex; + flex-direction: row; + width : 100%; } .request-drop-down-panel { - width: 100px; + width: 100px; } .request-method-drop-down { - border-radius : 2px; - cursor : pointer; - font-weight : bolder; - outline : none; - padding : 9px; - width : 90px; - color : var(--text-color); - background-color: var(--background-color); - border : var(--border-size) solid var(--border-color); + border-radius : 2px; + cursor : pointer; + font-weight : bolder; + outline : none; + padding : 9px; + width : 90px; + color : var(--text-color); + background-color: var(--background-color); + border : var(--border-size) solid var(--border-color); } .request-method-drop-down option { - color : var(--text-color); - background-color: var(--background-color); + color : var(--text-color); + background-color: var(--background-color); } .request-method-drop-down:focus, .request-method-drop-down:hover { - outline: none; + outline: none; } .request-url-panel { - width: calc(100% - 200px); - flex : auto; + width: calc(100% - 200px); + flex : auto; } .request-url-text, .DraftEditor-editorContainer { - display : inline-block; - outline : none; - padding : 10px; - width : 100%; - color : var(--text-color); - background-color: var(--background-color); - box-sizing : border-box; + display : inline-block; + outline : none; + padding : 10px; + width : 100%; + color : var(--text-color); + background-color: var(--background-color); + box-sizing : border-box; } .request-url-panel .DraftEditor-editorContainer { - border : var(--border-size) solid var(--border-color); - border-radius: 2px; - padding : 9px !important; + border : var(--border-size) solid var(--border-color); + border-radius: 2px; + padding : 9px !important; } mark { - color : var(--button-background-color); - background-color: var(--background-color); + color : var(--button-background-color); + background-color: var(--background-color); } .request-url-text:focus, .request-url-text:hover { - outline: none; + outline: none; } .request-send-panel { - margin-left: 10px; - width : 80px; + margin-left: 10px; + width : 80px; } .request-send-button { - background-color: var(--button-background-color); - border : 0; - border-radius : 3px; - color : var(--button-text-color); - cursor : pointer; - display : inline-block; - font-weight : bold; - outline : none; - padding : 11px; - width : 75px; + background-color: var(--button-background-color); + border : 0; + border-radius : 3px; + color : var(--button-text-color); + cursor : pointer; + display : inline-block; + font-weight : bold; + outline : none; + padding : 11px; + width : 75px; } .request-send-button:disabled, .request-send-button[disabled], .request-send-button:disabled:hover, .request-send-button[disabled]:hover { - background-color: #ccc; - color : #666; - cursor : not-allowed; + background-color: #ccc; + color : #666; + cursor : not-allowed; } .request-send-button:hover { - background-color: var(--button-hover-color); + background-color: var(--button-hover-color); } #custom-url-editor { - width : 400px; - height : 100px; - padding : 10px; - background-color: #444; - color : white; - font-size : 14px; - font-family : monospace; + width : 400px; + height : 100px; + padding : 10px; + background-color: #444; + color : white; + font-size : 14px; + font-family : monospace; } .statement { - color: orange !important; -} \ No newline at end of file + color: orange !important; +} diff --git a/src/fetch-client-ui/components/RequestUI/redux/actions.ts b/src/fetch-client-ui/components/RequestUI/redux/actions.ts index e4b4185..e9e3661 100644 --- a/src/fetch-client-ui/components/RequestUI/redux/actions.ts +++ b/src/fetch-client-ui/components/RequestUI/redux/actions.ts @@ -1,286 +1,292 @@ import { ITableData } from "../../Common/Table/types"; import { ISettings } from "../../SideBar/redux/types"; import { - FETCH_CLIENT_SET_ADD_PREREQUEST, FETCH_CLIENT_SET_COLLECTION_LIST, FETCH_CLIENT_SET_COL_ID, FETCH_CLIENT_SET_COL_REQUEST_LIST, FETCH_CLIENT_SET_DELETE_PRECONDITION, FETCH_CLIENT_SET_DELETE_PREREQUEST, - FETCH_CLIENT_SET_NOTES, FETCH_CLIENT_SET_OAUTH_TOKEN, FETCH_CLIENT_SET_PRECONDITION, FETCH_CLIENT_SET_REQ, FETCH_CLIENT_SET_REQ_AUTH, - FETCH_CLIENT_SET_REQ_BINARY_DATA, FETCH_CLIENT_SET_REQ_BODY, FETCH_CLIENT_SET_REQ_COL_DETAILS, FETCH_CLIENT_SET_REQ_FORM_DATA_BODY, - FETCH_CLIENT_SET_REQ_HEADERS, FETCH_CLIENT_SET_REQ_ID, FETCH_CLIENT_SET_REQ_METHOD, FETCH_CLIENT_SET_REQ_PARAMS, FETCH_CLIENT_SET_REQ_PARENT_SETTINGS, - FETCH_CLIENT_SET_REQ_RAW, FETCH_CLIENT_SET_REQ_RAW_LANG, FETCH_CLIENT_SET_REQ_RESET_BODY, FETCH_CLIENT_SET_REQ_URL, FETCH_CLIENT_SET_SET_VAR, - FETCH_CLIENT_SET_TEST, IAuth, IBodyData, ICollection, IColRequest, IRequestModel, IRunRequest, ISetVar, ITest, MethodType, RequestActionTypes, - FETCH_CLIENT_SET_PREFETCH, IPreFetch, - FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH, - FETCH_CLIENT_SET_SKIP_PARENT_HEADERS + FETCH_CLIENT_SET_ADD_PREREQUEST, + FETCH_CLIENT_SET_COL_ID, FETCH_CLIENT_SET_COL_REQUEST_LIST, + FETCH_CLIENT_SET_COLLECTION_LIST, + FETCH_CLIENT_SET_DELETE_PRECONDITION, FETCH_CLIENT_SET_DELETE_PREREQUEST, + FETCH_CLIENT_SET_NOTES, FETCH_CLIENT_SET_OAUTH_TOKEN, FETCH_CLIENT_SET_PRECONDITION, + FETCH_CLIENT_SET_PREFETCH, + FETCH_CLIENT_SET_REQ, FETCH_CLIENT_SET_REQ_AUTH, + FETCH_CLIENT_SET_REQ_BINARY_DATA, FETCH_CLIENT_SET_REQ_BODY, FETCH_CLIENT_SET_REQ_COL_DETAILS, FETCH_CLIENT_SET_REQ_FORM_DATA_BODY, + FETCH_CLIENT_SET_REQ_HEADERS, FETCH_CLIENT_SET_REQ_ID, FETCH_CLIENT_SET_REQ_METHOD, FETCH_CLIENT_SET_REQ_PARAMS, FETCH_CLIENT_SET_REQ_PARENT_SETTINGS, + FETCH_CLIENT_SET_REQ_RAW, FETCH_CLIENT_SET_REQ_RAW_LANG, FETCH_CLIENT_SET_REQ_RESET_BODY, FETCH_CLIENT_SET_REQ_URL, FETCH_CLIENT_SET_SET_VAR, + FETCH_CLIENT_SET_SKIP_PARENT_HEADERS, + FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH, + FETCH_CLIENT_SET_TEST, IAuth, IBodyData, ICollection, IColRequest, + IPreFetch, + IRequestModel, IRunRequest, ISetVar, ITest, MethodType, RequestActionTypes } from "./types"; export const SetRequestAction = (value: IRequestModel): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ, - payload: { - req: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ, + payload: { + req: value + } + }; }; export const SetRequestURLAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_URL, - payload: { - url: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_URL, + payload: { + url: value + } + }; }; export const SetRequestMethodAction = (value: MethodType): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_METHOD, - payload: { - method: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_METHOD, + payload: { + method: value + } + }; }; export const SetRequestParamsAction = (value: ITableData[]): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_PARAMS, - payload: { - params: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_PARAMS, + payload: { + params: value + } + }; }; export const SetRequestAuthAction = (value: IAuth): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_AUTH, - payload: { - auth: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_AUTH, + payload: { + auth: value + } + }; }; export const SetRequestHeadersAction = (value: ITableData[]): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_HEADERS, - payload: { - headers: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_HEADERS, + payload: { + headers: value + } + }; }; export const SetRequestBodyAction = (value: IBodyData): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_BODY, - payload: { - body: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_BODY, + payload: { + body: value + } + }; }; export const SetRequestFormDataAction = (value: string, value1: number): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_FORM_DATA_BODY, - payload: { - value: value, - index: value1 - } - }; + return { + type: FETCH_CLIENT_SET_REQ_FORM_DATA_BODY, + payload: { + value: value, + index: value1 + } + }; }; export const SetTestAction = (value: ITest[]): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_TEST, - payload: { - tests: value - } - }; + return { + type: FETCH_CLIENT_SET_TEST, + payload: { + tests: value + } + }; }; export const SetRequestRawLangAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_RAW_LANG, - payload: { - rawLang: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_RAW_LANG, + payload: { + rawLang: value + } + }; }; export const SetRequestRawAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_RAW, - payload: { - raw: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_RAW, + payload: { + raw: value + } + }; }; export const SetRequestBinaryDataAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_BINARY_DATA, - payload: { - data: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_BINARY_DATA, + payload: { + data: value + } + }; }; export const SetRequestResetBodyAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_RESET_BODY, - payload: { - bodyType: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_RESET_BODY, + payload: { + bodyType: value + } + }; }; export const SetNotesAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_NOTES, - payload: { - notes: value - } - }; + return { + type: FETCH_CLIENT_SET_NOTES, + payload: { + notes: value + } + }; }; export const SetVarAction = (value: ISetVar[]): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_SET_VAR, - payload: { - data: value - } - }; + return { + type: FETCH_CLIENT_SET_SET_VAR, + payload: { + data: value + } + }; }; export const SetReqColDetailsAction = (value: string, value1: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_COL_DETAILS, - payload: { - colId: value, - folderId: value1 - } - }; + return { + type: FETCH_CLIENT_SET_REQ_COL_DETAILS, + payload: { + colId: value, + folderId: value1 + } + }; }; export const SetReqParentSettingsAction = (value: ISettings): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_PARENT_SETTINGS, - payload: { - parentSettings: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_PARENT_SETTINGS, + payload: { + parentSettings: value + } + }; }; export const SetOAuthTokenAction = (value: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_OAUTH_TOKEN, - payload: { - token: value - } - }; + return { + type: FETCH_CLIENT_SET_OAUTH_TOKEN, + payload: { + token: value + } + }; }; export const SetPreConditionAction = (value: ITest, reqIndex: number, condIndex: number): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_PRECONDITION, - payload: { - condition: value, - reqIndex: reqIndex, - condIndex: condIndex - } - }; + return { + type: FETCH_CLIENT_SET_PRECONDITION, + payload: { + condition: value, + reqIndex: reqIndex, + condIndex: condIndex + } + }; }; export const SetAddPreRequestAction = (value: IRunRequest): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_ADD_PREREQUEST, - payload: { - request: value - } - }; + return { + type: FETCH_CLIENT_SET_ADD_PREREQUEST, + payload: { + request: value + } + }; }; export const SetDeletePreRequestAction = (index: number): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_DELETE_PREREQUEST, - payload: { - index: index - } - }; + return { + type: FETCH_CLIENT_SET_DELETE_PREREQUEST, + payload: { + index: index + } + }; }; export const SetDeletePreConditionAction = (index: number, index1: number): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_DELETE_PRECONDITION, - payload: { - reqIndex: index, - condIndex: index1 - } - }; + return { + type: FETCH_CLIENT_SET_DELETE_PRECONDITION, + payload: { + reqIndex: index, + condIndex: index1 + } + }; }; export const SetCollectionListAction = (value: ICollection[]): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_COLLECTION_LIST, - payload: { - colList: value - } - }; + return { + type: FETCH_CLIENT_SET_COLLECTION_LIST, + payload: { + colList: value + } + }; }; export const SetColRequestListAction = (value: IColRequest): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_COL_REQUEST_LIST, - payload: { - colReqList: value - } - }; + return { + type: FETCH_CLIENT_SET_COL_REQUEST_LIST, + payload: { + colReqList: value + } + }; }; export const SetSelectedColAction = (value: string, value2: number): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_COL_ID, - payload: { - colId: value, - index: value2 - } - }; + return { + type: FETCH_CLIENT_SET_COL_ID, + payload: { + colId: value, + index: value2 + } + }; }; export const SetSelectedReqAction = (reqId: string, reqIndex: number, parentId: string): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_ID, - payload: { - reqId: reqId, - index: reqIndex, - parentId: parentId - } - }; + return { + type: FETCH_CLIENT_SET_REQ_ID, + payload: { + reqId: reqId, + index: reqIndex, + parentId: parentId + } + }; }; export const SetPreFetchAction = (value: IPreFetch): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_PREFETCH, - payload: { - preFetch: value - } - }; + return { + type: FETCH_CLIENT_SET_PREFETCH, + payload: { + preFetch: value + } + }; }; export const SetSkipPreFetchAction = (value: boolean): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH, - payload: { - skip: value - } - }; + return { + type: FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH, + payload: { + skip: value + } + }; }; export const SetSkipHeadersAction = (value: boolean): RequestActionTypes => { - return { - type: FETCH_CLIENT_SET_SKIP_PARENT_HEADERS, - payload: { - skip: value - } - }; + return { + type: FETCH_CLIENT_SET_SKIP_PARENT_HEADERS, + payload: { + skip: value + } + }; }; diff --git a/src/fetch-client-ui/components/RequestUI/redux/colReducer.ts b/src/fetch-client-ui/components/RequestUI/redux/colReducer.ts index 6796c4e..4dc1d2e 100644 --- a/src/fetch-client-ui/components/RequestUI/redux/colReducer.ts +++ b/src/fetch-client-ui/components/RequestUI/redux/colReducer.ts @@ -1,45 +1,45 @@ import { FETCH_CLIENT_SET_COLLECTION_LIST, FETCH_CLIENT_SET_COL_REQUEST_LIST, FETCH_CLIENT_SET_REQ_COL_DETAILS, FETCH_CLIENT_SET_REQ_PARENT_SETTINGS, IReqColModel, RequestActionTypes } from "./types"; export const InitialState: IReqColModel = { - colId: "", - folderId: "", - parentSettings: null, - collectionList: [], - colRequestList: [] + colId: "", + folderId: "", + parentSettings: null, + collectionList: [], + colRequestList: [] }; export const ReqColReducer: (state?: IReqColModel, - action?: RequestActionTypes) => IReqColModel = - (state: IReqColModel = InitialState, - action: RequestActionTypes = {} as RequestActionTypes): IReqColModel => { - switch (action.type) { - case FETCH_CLIENT_SET_REQ_COL_DETAILS: { - return { - ...state, - colId: action.payload.colId, - folderId: action.payload.folderId - }; - } - case FETCH_CLIENT_SET_REQ_PARENT_SETTINGS: { - return { - ...state, - parentSettings: action.payload.parentSettings - }; - } - case FETCH_CLIENT_SET_COLLECTION_LIST: { - return { - ...state, - collectionList: action.payload.colList - }; - } - case FETCH_CLIENT_SET_COL_REQUEST_LIST: { - return { - ...state, - colRequestList: [...state.colRequestList, action.payload.colReqList] - }; - } - default: { - return state; - } - } - }; + action?: RequestActionTypes) => IReqColModel = + (state: IReqColModel = InitialState, + action: RequestActionTypes = {} as RequestActionTypes): IReqColModel => { + switch (action.type) { + case FETCH_CLIENT_SET_REQ_COL_DETAILS: { + return { + ...state, + colId: action.payload.colId, + folderId: action.payload.folderId + }; + } + case FETCH_CLIENT_SET_REQ_PARENT_SETTINGS: { + return { + ...state, + parentSettings: action.payload.parentSettings + }; + } + case FETCH_CLIENT_SET_COLLECTION_LIST: { + return { + ...state, + collectionList: action.payload.colList + }; + } + case FETCH_CLIENT_SET_COL_REQUEST_LIST: { + return { + ...state, + colRequestList: [...state.colRequestList, action.payload.colReqList] + }; + } + default: { + return state; + } + } + }; diff --git a/src/fetch-client-ui/components/RequestUI/redux/index.ts b/src/fetch-client-ui/components/RequestUI/redux/index.ts index 7e6633a..d27d3f9 100644 --- a/src/fetch-client-ui/components/RequestUI/redux/index.ts +++ b/src/fetch-client-ui/components/RequestUI/redux/index.ts @@ -3,7 +3,7 @@ import { InitialBinaryData, RequestReducer } from "./reducer"; export { - Actions, - RequestReducer, - InitialBinaryData + Actions, + RequestReducer, + InitialBinaryData }; diff --git a/src/fetch-client-ui/components/RequestUI/redux/reducer.ts b/src/fetch-client-ui/components/RequestUI/redux/reducer.ts index 3740f34..0e01097 100644 --- a/src/fetch-client-ui/components/RequestUI/redux/reducer.ts +++ b/src/fetch-client-ui/components/RequestUI/redux/reducer.ts @@ -2,383 +2,383 @@ import { v4 as uuidv4 } from 'uuid'; import { ITableData } from "../../Common/Table/types"; import { requestBodyRaw } from '../OptionsPanel/Options/Body/consts'; import { - ClientAuth, - FETCH_CLIENT_SET_ADD_PREREQUEST, FETCH_CLIENT_SET_COL_ID, FETCH_CLIENT_SET_DELETE_PRECONDITION, FETCH_CLIENT_SET_DELETE_PREREQUEST, - FETCH_CLIENT_SET_NOTES, FETCH_CLIENT_SET_OAUTH_TOKEN, FETCH_CLIENT_SET_PRECONDITION, FETCH_CLIENT_SET_PREFETCH, FETCH_CLIENT_SET_REQ, - FETCH_CLIENT_SET_REQ_AUTH, FETCH_CLIENT_SET_REQ_BINARY_DATA, FETCH_CLIENT_SET_REQ_BODY, FETCH_CLIENT_SET_REQ_FORM_DATA_BODY, FETCH_CLIENT_SET_REQ_HEADERS, - FETCH_CLIENT_SET_REQ_ID, FETCH_CLIENT_SET_REQ_METHOD, FETCH_CLIENT_SET_REQ_PARAMS, FETCH_CLIENT_SET_REQ_RAW, FETCH_CLIENT_SET_REQ_RAW_LANG, - FETCH_CLIENT_SET_REQ_RESET_BODY, FETCH_CLIENT_SET_REQ_URL, FETCH_CLIENT_SET_SET_VAR, FETCH_CLIENT_SET_TEST, - GrantType, IAuth, IAwsAuth, IBinaryFileData, IBodyData, IOAuth, IPreFetch, IRequestModel, IRunRequest, ISetVar, ITest, RequestActionTypes + ClientAuth, + FETCH_CLIENT_SET_ADD_PREREQUEST, FETCH_CLIENT_SET_COL_ID, FETCH_CLIENT_SET_DELETE_PRECONDITION, FETCH_CLIENT_SET_DELETE_PREREQUEST, + FETCH_CLIENT_SET_NOTES, FETCH_CLIENT_SET_OAUTH_TOKEN, FETCH_CLIENT_SET_PRECONDITION, FETCH_CLIENT_SET_PREFETCH, FETCH_CLIENT_SET_REQ, + FETCH_CLIENT_SET_REQ_AUTH, FETCH_CLIENT_SET_REQ_BINARY_DATA, FETCH_CLIENT_SET_REQ_BODY, FETCH_CLIENT_SET_REQ_FORM_DATA_BODY, FETCH_CLIENT_SET_REQ_HEADERS, + FETCH_CLIENT_SET_REQ_ID, FETCH_CLIENT_SET_REQ_METHOD, FETCH_CLIENT_SET_REQ_PARAMS, FETCH_CLIENT_SET_REQ_RAW, FETCH_CLIENT_SET_REQ_RAW_LANG, + FETCH_CLIENT_SET_REQ_RESET_BODY, FETCH_CLIENT_SET_REQ_URL, FETCH_CLIENT_SET_SET_VAR, FETCH_CLIENT_SET_TEST, + GrantType, IAuth, IAwsAuth, IBinaryFileData, IBodyData, IOAuth, IPreFetch, IRequestModel, IRunRequest, ISetVar, ITest, RequestActionTypes } from "./types"; export const InitialRequestHeaders: ITableData[] = [ - { - key: "Cache-Control", - value: "no-cache", - isChecked: true, - }, - { - key: "Accept", - value: "*/*", - isChecked: true, - }, - { - key: "User-Agent", - value: "Fetch Client", - isChecked: true, - }, - { - key: "Accept-Encoding", - value: "gzip, deflate", - isChecked: true, - }, - { - key: "Connection", - value: "keep-alive", - isChecked: true, - }, - { - key: "", - value: "", - isChecked: false, - }, + { + key: "Cache-Control", + value: "no-cache", + isChecked: true, + }, + { + key: "Accept", + value: "*/*", + isChecked: true, + }, + { + key: "User-Agent", + value: "Fetch Client", + isChecked: true, + }, + { + key: "Accept-Encoding", + value: "gzip, deflate", + isChecked: true, + }, + { + key: "Connection", + value: "keep-alive", + isChecked: true, + }, + { + key: "", + value: "", + isChecked: false, + }, ]; export const emptyRow: ITableData = { - isChecked: false, - key: "", - value: "" + isChecked: false, + key: "", + value: "" }; export const InitialAwsAuth: IAwsAuth = { - service: "", - region: "", - accessKey: "", - secretAccessKey: "", - sessionToken: "", + service: "", + region: "", + accessKey: "", + secretAccessKey: "", + sessionToken: "", }; export const InitialOAuth: IOAuth = { - clientAuth: ClientAuth.Body, - clientId: "", - clientSecret: "", - grantType: GrantType.Client_Crd, - password: "", - scope: "", - tokenName: "access_token", - tokenUrl: "", - username: "", - advancedOpt: { - audience: "", - resource: "" - } + clientAuth: ClientAuth.Body, + clientId: "", + clientSecret: "", + grantType: GrantType.Client_Crd, + password: "", + scope: "", + tokenName: "access_token", + tokenUrl: "", + username: "", + advancedOpt: { + audience: "", + resource: "" + } }; export const InitialAuth: IAuth = { - authType: "noauth", - userName: "", - password: "", - addTo: "queryparams", - showPwd: false, - tokenPrefix: "Bearer", - aws: InitialAwsAuth, - oauth: InitialOAuth + authType: "noauth", + userName: "", + password: "", + addTo: "queryparams", + showPwd: false, + tokenPrefix: "Bearer", + aws: InitialAwsAuth, + oauth: InitialOAuth }; export const InitialBinaryData: IBinaryFileData = { - fileName: "", - data: {}, - contentTypeOption: "manual" + fileName: "", + data: {}, + contentTypeOption: "manual" }; export const InitialBody: IBodyData = { - bodyType: "none", - formdata: [{ isChecked: false, key: "", value: "" }], - urlencoded: [{ isChecked: false, key: "", value: "" }], - raw: { data: "", lang: requestBodyRaw[1].value }, - binary: InitialBinaryData, - graphql: { query: "", variables: "" }, + bodyType: "none", + formdata: [{ isChecked: false, key: "", value: "" }], + urlencoded: [{ isChecked: false, key: "", value: "" }], + raw: { data: "", lang: requestBodyRaw[1].value }, + binary: InitialBinaryData, + graphql: { query: "", variables: "" }, }; export const InitialTest: ITest[] = [{ - parameter: "", - action: "", - expectedValue: "" + parameter: "", + action: "", + expectedValue: "" }]; export const InitialSetVar: ISetVar[] = [{ - parameter: "", - key: "", - variableName: "" + parameter: "", + key: "", + variableName: "" }]; export const InitialPreFetch: IPreFetch = { - requests: [] + requests: [] }; export const InitialState: IRequestModel = { - id: uuidv4(), - url: "", - name: "", - createdTime: "", - method: "get", - params: [{ isChecked: false, key: "", value: "" }], - auth: InitialAuth, - headers: InitialRequestHeaders, - body: InitialBody, - tests: InitialTest, - setvar: InitialSetVar, - notes: "", - preFetch: InitialPreFetch + id: uuidv4(), + url: "", + name: "", + createdTime: "", + method: "get", + params: [{ isChecked: false, key: "", value: "" }], + auth: InitialAuth, + headers: InitialRequestHeaders, + body: InitialBody, + tests: InitialTest, + setvar: InitialSetVar, + notes: "", + preFetch: InitialPreFetch }; export const RequestReducer: (state?: IRequestModel, - action?: RequestActionTypes) => IRequestModel = - (state: IRequestModel = InitialState, - action: RequestActionTypes = {} as RequestActionTypes): IRequestModel => { - switch (action.type) { - case FETCH_CLIENT_SET_REQ_URL: { - return { - ...state, - url: action.payload.url.trim(), - params: updateQueryParams(action.payload.url.trim(), state.params) - }; - } - case FETCH_CLIENT_SET_REQ_METHOD: { - return { - ...state, - method: action.payload.method - }; - } - case FETCH_CLIENT_SET_REQ_PARAMS: { - return { - ...state, - params: action.payload.params, - url: updateURL(state.url.trim(), action.payload.params) - }; - } - case FETCH_CLIENT_SET_REQ_AUTH: { - return { - ...state, - auth: action.payload.auth, - }; - } - case FETCH_CLIENT_SET_REQ_HEADERS: { - return { - ...state, - headers: action.payload.headers, - }; - } - case FETCH_CLIENT_SET_REQ_BODY: { - return { - ...state, - body: action.payload.body, - }; - } - case FETCH_CLIENT_SET_REQ_FORM_DATA_BODY: { - return { - ...state, - body: setFormDataBody(state.body, action.payload.value, action.payload.index), - }; - } - case FETCH_CLIENT_SET_REQ: { - return { - ...state, - id: action.payload.req.id, - url: action.payload.req.url.trim(), - name: action.payload.req.name.trim(), - createdTime: action.payload.req.createdTime, - method: action.payload.req.method, - params: action.payload.req.params, - auth: action.payload.req.auth, - headers: action.payload.req.headers, - body: action.payload.req.body, - tests: action.payload.req.tests, - setvar: action.payload.req.setvar ? action.payload.req.setvar : JSON.parse(JSON.stringify(InitialSetVar)), - notes: action.payload.req.notes, - preFetch: action.payload.req.preFetch ?? InitialPreFetch - }; - } - case FETCH_CLIENT_SET_TEST: { - return { - ...state, - tests: action.payload.tests, - }; - } - case FETCH_CLIENT_SET_REQ_RAW_LANG: { - return { - ...state, - body: { - ...state.body, - raw: { - ...state.body.raw, - lang: action.payload.rawLang - }, - } - }; - } - case FETCH_CLIENT_SET_REQ_RAW: { - return { - ...state, - body: { - ...state.body, - raw: { - ...state.body.raw, - data: action.payload.raw - }, - } - }; - } - case FETCH_CLIENT_SET_REQ_BINARY_DATA: { - return { - ...state, - body: { - ...state.body, - binary: { - ...state.body.binary, - data: action.payload.data - }, - } - }; - } - case FETCH_CLIENT_SET_REQ_RESET_BODY: { - return { - ...state, - body: { - ...state.body, - bodyType: action.payload.bodyType - } - }; - } - case FETCH_CLIENT_SET_NOTES: { - return { - ...state, - notes: action.payload.notes, - }; - } - case FETCH_CLIENT_SET_SET_VAR: { - return { - ...state, - setvar: action.payload.data - }; - } - case FETCH_CLIENT_SET_OAUTH_TOKEN: { - return { - ...state, - auth: { - ...state.auth, - password: action.payload.token, - } - }; - } - case FETCH_CLIENT_SET_PRECONDITION: { - return { - ...state, - preFetch: { - ...state.preFetch, - requests: updateCondition(state.preFetch?.requests, action.payload.condition, action.payload.reqIndex, action.payload.condIndex) - } - }; - } - case FETCH_CLIENT_SET_ADD_PREREQUEST: { - return { - ...state, - preFetch: { - ...state.preFetch, - requests: [...state.preFetch?.requests, action.payload.request] - } - }; - } - case FETCH_CLIENT_SET_DELETE_PREREQUEST: { - return { - ...state, - preFetch: { - ...state.preFetch, - requests: deleteRequest(state.preFetch?.requests, action.payload.index) - } - }; - } - case FETCH_CLIENT_SET_DELETE_PRECONDITION: { - return { - ...state, - preFetch: { - ...state.preFetch, - requests: deleteCondition(state.preFetch?.requests, action.payload.reqIndex, action.payload.condIndex) - } - }; - } - case FETCH_CLIENT_SET_COL_ID: { - return { - ...state, - preFetch: { - ...state.preFetch, - requests: updateSelectedCol(state.preFetch?.requests, action.payload.index, action.payload.colId, "", "col") - } - }; - } - case FETCH_CLIENT_SET_REQ_ID: { - return { - ...state, - preFetch: { - ...state.preFetch, - requests: updateSelectedCol(state.preFetch?.requests, action.payload.index, action.payload.reqId, action.payload.parentId, "req") - } - }; - } - case FETCH_CLIENT_SET_PREFETCH: { - return { - ...state, - preFetch: action.payload.preFetch - }; - } - default: { - return state; - } - } - }; + action?: RequestActionTypes) => IRequestModel = + (state: IRequestModel = InitialState, + action: RequestActionTypes = {} as RequestActionTypes): IRequestModel => { + switch (action.type) { + case FETCH_CLIENT_SET_REQ_URL: { + return { + ...state, + url: action.payload.url.trim(), + params: updateQueryParams(action.payload.url.trim(), state.params) + }; + } + case FETCH_CLIENT_SET_REQ_METHOD: { + return { + ...state, + method: action.payload.method + }; + } + case FETCH_CLIENT_SET_REQ_PARAMS: { + return { + ...state, + params: action.payload.params, + url: updateURL(state.url.trim(), action.payload.params) + }; + } + case FETCH_CLIENT_SET_REQ_AUTH: { + return { + ...state, + auth: action.payload.auth, + }; + } + case FETCH_CLIENT_SET_REQ_HEADERS: { + return { + ...state, + headers: action.payload.headers, + }; + } + case FETCH_CLIENT_SET_REQ_BODY: { + return { + ...state, + body: action.payload.body, + }; + } + case FETCH_CLIENT_SET_REQ_FORM_DATA_BODY: { + return { + ...state, + body: setFormDataBody(state.body, action.payload.value, action.payload.index), + }; + } + case FETCH_CLIENT_SET_REQ: { + return { + ...state, + id: action.payload.req.id, + url: action.payload.req.url.trim(), + name: action.payload.req.name.trim(), + createdTime: action.payload.req.createdTime, + method: action.payload.req.method, + params: action.payload.req.params, + auth: action.payload.req.auth, + headers: action.payload.req.headers, + body: action.payload.req.body, + tests: action.payload.req.tests, + setvar: action.payload.req.setvar ? action.payload.req.setvar : JSON.parse(JSON.stringify(InitialSetVar)), + notes: action.payload.req.notes, + preFetch: action.payload.req.preFetch ?? InitialPreFetch + }; + } + case FETCH_CLIENT_SET_TEST: { + return { + ...state, + tests: action.payload.tests, + }; + } + case FETCH_CLIENT_SET_REQ_RAW_LANG: { + return { + ...state, + body: { + ...state.body, + raw: { + ...state.body.raw, + lang: action.payload.rawLang + }, + } + }; + } + case FETCH_CLIENT_SET_REQ_RAW: { + return { + ...state, + body: { + ...state.body, + raw: { + ...state.body.raw, + data: action.payload.raw + }, + } + }; + } + case FETCH_CLIENT_SET_REQ_BINARY_DATA: { + return { + ...state, + body: { + ...state.body, + binary: { + ...state.body.binary, + data: action.payload.data + }, + } + }; + } + case FETCH_CLIENT_SET_REQ_RESET_BODY: { + return { + ...state, + body: { + ...state.body, + bodyType: action.payload.bodyType + } + }; + } + case FETCH_CLIENT_SET_NOTES: { + return { + ...state, + notes: action.payload.notes, + }; + } + case FETCH_CLIENT_SET_SET_VAR: { + return { + ...state, + setvar: action.payload.data + }; + } + case FETCH_CLIENT_SET_OAUTH_TOKEN: { + return { + ...state, + auth: { + ...state.auth, + password: action.payload.token, + } + }; + } + case FETCH_CLIENT_SET_PRECONDITION: { + return { + ...state, + preFetch: { + ...state.preFetch, + requests: updateCondition(state.preFetch?.requests, action.payload.condition, action.payload.reqIndex, action.payload.condIndex) + } + }; + } + case FETCH_CLIENT_SET_ADD_PREREQUEST: { + return { + ...state, + preFetch: { + ...state.preFetch, + requests: [...state.preFetch?.requests, action.payload.request] + } + }; + } + case FETCH_CLIENT_SET_DELETE_PREREQUEST: { + return { + ...state, + preFetch: { + ...state.preFetch, + requests: deleteRequest(state.preFetch?.requests, action.payload.index) + } + }; + } + case FETCH_CLIENT_SET_DELETE_PRECONDITION: { + return { + ...state, + preFetch: { + ...state.preFetch, + requests: deleteCondition(state.preFetch?.requests, action.payload.reqIndex, action.payload.condIndex) + } + }; + } + case FETCH_CLIENT_SET_COL_ID: { + return { + ...state, + preFetch: { + ...state.preFetch, + requests: updateSelectedCol(state.preFetch?.requests, action.payload.index, action.payload.colId, "", "col") + } + }; + } + case FETCH_CLIENT_SET_REQ_ID: { + return { + ...state, + preFetch: { + ...state.preFetch, + requests: updateSelectedCol(state.preFetch?.requests, action.payload.index, action.payload.reqId, action.payload.parentId, "req") + } + }; + } + case FETCH_CLIENT_SET_PREFETCH: { + return { + ...state, + preFetch: action.payload.preFetch + }; + } + default: { + return state; + } + } + }; function updateSelectedCol(requests: IRunRequest[], reqIndex: number, id: string, parentId: string, type: string): IRunRequest[] { - let localRequests = [...requests]; - - if (type === "col") { - localRequests[reqIndex].colId = id; - localRequests[reqIndex].reqId = ""; - localRequests[reqIndex].parentId = parentId; - } else { - localRequests[reqIndex].reqId = id; - localRequests[reqIndex].parentId = parentId; - } - - return localRequests; + let localRequests = [...requests]; + + if (type === "col") { + localRequests[reqIndex].colId = id; + localRequests[reqIndex].reqId = ""; + localRequests[reqIndex].parentId = parentId; + } else { + localRequests[reqIndex].reqId = id; + localRequests[reqIndex].parentId = parentId; + } + + return localRequests; } function updateCondition(requests: IRunRequest[], condition: ITest, reqIndex: number, condIndex: number): IRunRequest[] { - let localRequests = [...requests]; - localRequests[reqIndex].condition[condIndex] = condition; - - if (condIndex === requests[reqIndex].condition.length - 1 && requests[reqIndex].condition[condIndex].action) { - let newCondition: ITest = { - parameter: "", - action: "", - expectedValue: "", - customParameter: "" - }; - localRequests[reqIndex].condition.push(newCondition); - } - - return localRequests; + let localRequests = [...requests]; + localRequests[reqIndex].condition[condIndex] = condition; + + if (condIndex === requests[reqIndex].condition.length - 1 && requests[reqIndex].condition[condIndex].action) { + let newCondition: ITest = { + parameter: "", + action: "", + expectedValue: "", + customParameter: "" + }; + localRequests[reqIndex].condition.push(newCondition); + } + + return localRequests; } function deleteCondition(requests: IRunRequest[], reqIndex: number, condIndex: number): IRunRequest[] { - let localRequests = [...requests]; - localRequests[reqIndex].condition.splice(condIndex, 1); - return localRequests; + let localRequests = [...requests]; + localRequests[reqIndex].condition.splice(condIndex, 1); + return localRequests; } function deleteRequest(requests: IRunRequest[], reqIndex: number): IRunRequest[] { - let localRequests = [...requests]; - localRequests.splice(reqIndex, 1); - return localRequests; + let localRequests = [...requests]; + localRequests.splice(reqIndex, 1); + return localRequests; } // function updateURL(url: string, params: ITableData[]): string { @@ -396,78 +396,78 @@ function deleteRequest(requests: IRunRequest[], reqIndex: number): IRunRequest[] // } function updateURL(url: string, params: ITableData[]): string { - let searchParams: string = ""; + let searchParams: string = ""; - params.forEach((param: ITableData) => { - if (param.key.trim() && param.isChecked && !param.isFixed) { - searchParams = (searchParams ? (searchParams + "&") : searchParams) + param.key.trim() + (param.value ? "=" + param.value.trim() : ""); - } - }); + params.forEach((param: ITableData) => { + if (param.key.trim() && param.isChecked && !param.isFixed) { + searchParams = (searchParams ? (searchParams + "&") : searchParams) + param.key.trim() + (param.value ? "=" + param.value.trim() : ""); + } + }); - let combineUrl = searchParams ? url.split("?")[0] + "?" + searchParams : url.split("?")[0]; + let combineUrl = searchParams ? url.split("?")[0] + "?" + searchParams : url.split("?")[0]; - return combineUrl; + return combineUrl; } function updateQueryParams(url: string, params: ITableData[]) { - let splitURL = url.split("?"); - let queryParams: ITableData[] = params.filter(getUnchecked); - - if (splitURL.length > 1) { - if (splitURL[1].trim().length > 0) { - let searchParams = new URLSearchParams(splitURL[1].trim()); - for (let p of searchParams) { - if (p[0] && p[0].trim()) { - let queryParam: ITableData = { - isChecked: true, - key: p[0] ? p[0].trim() : "", - value: p[1] ? p[1].trim() : "", - }; - queryParams.splice(queryParams.length === 0 ? 0 : queryParams.length, 0, queryParam); - } - } - } - } - - queryParams.push(emptyRow); - - let fixedParams = params.filter(getFixed); - queryParams = fixedParams.length > 0 ? fixedParams.concat(queryParams) : queryParams; - - return queryParams; + let splitURL = url.split("?"); + let queryParams: ITableData[] = params.filter(getUnchecked); + + if (splitURL.length > 1) { + if (splitURL[1].trim().length > 0) { + let searchParams = new URLSearchParams(splitURL[1].trim()); + for (let p of searchParams) { + if (p[0] && p[0].trim()) { + let queryParam: ITableData = { + isChecked: true, + key: p[0] ? p[0].trim() : "", + value: p[1] ? p[1].trim() : "", + }; + queryParams.splice(queryParams.length === 0 ? 0 : queryParams.length, 0, queryParam); + } + } + } + } + + queryParams.push(emptyRow); + + let fixedParams = params.filter(getFixed); + queryParams = fixedParams.length > 0 ? fixedParams.concat(queryParams) : queryParams; + + return queryParams; } function getUnchecked(item: ITableData) { - return item.isChecked === false && item.key !== ""; + return item.isChecked === false && item.key !== ""; } function getFixed(item: ITableData) { - return item.isFixed === true; + return item.isFixed === true; } function setFormDataBody(body: IBodyData, path: string, index: number): IBodyData { - let localbody = { ...body }; - if (localbody.formdata) { - let localFormData = [...localbody.formdata]; - let rowData = localFormData[index]; - localFormData[index] = { - isChecked: rowData.isChecked, - key: rowData.key, - value: path, - type: rowData.type - }; - localbody.formdata = localFormData; - - if (localbody.formdata.length - 1 === index && localFormData[index].key) { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "", - type: "Text" - }; - - localbody.formdata.push(newRow); - } - } - return localbody; + let localbody = { ...body }; + if (localbody.formdata) { + let localFormData = [...localbody.formdata]; + let rowData = localFormData[index]; + localFormData[index] = { + isChecked: rowData.isChecked, + key: rowData.key, + value: path, + type: rowData.type + }; + localbody.formdata = localFormData; + + if (localbody.formdata.length - 1 === index && localFormData[index].key) { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "", + type: "Text" + }; + + localbody.formdata.push(newRow); + } + } + return localbody; } diff --git a/src/fetch-client-ui/components/RequestUI/redux/reqSettingsReducer.ts b/src/fetch-client-ui/components/RequestUI/redux/reqSettingsReducer.ts index b55ede0..b65ad9c 100644 --- a/src/fetch-client-ui/components/RequestUI/redux/reqSettingsReducer.ts +++ b/src/fetch-client-ui/components/RequestUI/redux/reqSettingsReducer.ts @@ -1,29 +1,29 @@ import { FETCH_CLIENT_SET_SKIP_PARENT_HEADERS, FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH, IReqSettings, RequestActionTypes } from "./types"; export const InitialState: IReqSettings = { - skipParentHeaders: false, - skipParentPreFetch: false + skipParentHeaders: false, + skipParentPreFetch: false }; export const ReqSettingsReducer: (state?: IReqSettings, - action?: RequestActionTypes) => IReqSettings = - (state: IReqSettings = InitialState, - action: RequestActionTypes = {} as RequestActionTypes): IReqSettings => { - switch (action.type) { - case FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH: { - return { - ...state, - skipParentPreFetch: action.payload.skip - }; - } - case FETCH_CLIENT_SET_SKIP_PARENT_HEADERS: { - return { - ...state, - skipParentHeaders: action.payload.skip - }; - } - default: { - return state; - } - } - }; + action?: RequestActionTypes) => IReqSettings = + (state: IReqSettings = InitialState, + action: RequestActionTypes = {} as RequestActionTypes): IReqSettings => { + switch (action.type) { + case FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH: { + return { + ...state, + skipParentPreFetch: action.payload.skip + }; + } + case FETCH_CLIENT_SET_SKIP_PARENT_HEADERS: { + return { + ...state, + skipParentHeaders: action.payload.skip + }; + } + default: { + return state; + } + } + }; diff --git a/src/fetch-client-ui/components/RequestUI/redux/types.ts b/src/fetch-client-ui/components/RequestUI/redux/types.ts index e3b80fb..b30bcaa 100644 --- a/src/fetch-client-ui/components/RequestUI/redux/types.ts +++ b/src/fetch-client-ui/components/RequestUI/redux/types.ts @@ -4,144 +4,144 @@ import { ISettings } from "../../SideBar/redux/types"; export type MethodType = "get" | "post" | "put" | "patch" | "delete" | "options" | "head"; export interface IAwsAuth { - service: string; - region: string; - accessKey: string; - secretAccessKey: string; - sessionToken: string; + service: string; + region: string; + accessKey: string; + secretAccessKey: string; + sessionToken: string; } export interface IAdvancedOAuth { - audience: string; - resource: string; + audience: string; + resource: string; } export interface IOAuth { - clientAuth: ClientAuth; - clientId: string; - clientSecret: string; - grantType: GrantType; - password?: string; - scope: string; - tokenName: string; - tokenUrl: string; - username?: string; - advancedOpt: IAdvancedOAuth; + clientAuth: ClientAuth; + clientId: string; + clientSecret: string; + grantType: GrantType; + password?: string; + scope: string; + tokenName: string; + tokenUrl: string; + username?: string; + advancedOpt: IAdvancedOAuth; } export enum GrantType { - PWD_Crd = "password_credentials", - Client_Crd = "client_credentials" + PWD_Crd = "password_credentials", + Client_Crd = "client_credentials" } export enum ClientAuth { - Header = "header", - Body = "body" + Header = "header", + Body = "body" } export interface IAuth { - authType: string; - userName: string; - password: string; - addTo: string; - showPwd: boolean; - tokenPrefix: string; - aws?: IAwsAuth; - oauth?: IOAuth; + authType: string; + userName: string; + password: string; + addTo: string; + showPwd: boolean; + tokenPrefix: string; + aws?: IAwsAuth; + oauth?: IOAuth; } export interface IBinaryFileData { - fileName: string; - data: any; - contentTypeOption: string; + fileName: string; + data: any; + contentTypeOption: string; } export interface IRawData { - data: string; - lang: string; + data: string; + lang: string; } export interface IGraphQLData { - query: string; - variables: string + query: string; + variables: string } export interface IBodyData { - bodyType: string; - formdata?: ITableData[]; - urlencoded?: ITableData[]; - raw?: IRawData; - binary?: IBinaryFileData; - graphql?: IGraphQLData; + bodyType: string; + formdata?: ITableData[]; + urlencoded?: ITableData[]; + raw?: IRawData; + binary?: IBinaryFileData; + graphql?: IGraphQLData; } export interface ITest { - parameter: string; - action: string; - expectedValue: string; - customParameter?: string; + parameter: string; + action: string; + expectedValue: string; + customParameter?: string; } export interface IRunRequest { - reqId: string; - parentId: string; - colId: string; - order: number; - condition: ITest[]; + reqId: string; + parentId: string; + colId: string; + order: number; + condition: ITest[]; } export interface IPreFetch { - requests: IRunRequest[] + requests: IRunRequest[] } export interface IRequestModel { - id: string; - url: string; - name: string; - createdTime: string; - method: MethodType; - params: ITableData[]; - auth: IAuth; - headers: ITableData[]; - body: IBodyData; - tests: ITest[]; - setvar: ISetVar[]; - notes: string; - preFetch: IPreFetch; + id: string; + url: string; + name: string; + createdTime: string; + method: MethodType; + params: ITableData[]; + auth: IAuth; + headers: ITableData[]; + body: IBodyData; + tests: ITest[]; + setvar: ISetVar[]; + notes: string; + preFetch: IPreFetch; } export interface ISetVar { - parameter: string; - key: string; - variableName: string; + parameter: string; + key: string; + variableName: string; } export interface ICollection { - id: string; - name: string; + id: string; + name: string; } export interface IRequestList { - id: string; - name: string; + id: string; + name: string; } export interface IColRequest { - id: string; - reqs: IRequestList[]; + id: string; + reqs: IRequestList[]; } export interface IReqColModel { - colId: string; - folderId: string; - parentSettings: ISettings; - collectionList: ICollection[]; - colRequestList: IColRequest[] + colId: string; + folderId: string; + parentSettings: ISettings; + collectionList: ICollection[]; + colRequestList: IColRequest[] } export interface IReqSettings { - skipParentHeaders: boolean; - skipParentPreFetch: boolean; + skipParentHeaders: boolean; + skipParentPreFetch: boolean; } export const FETCH_CLIENT_SET_REQ_URL: "FETCH_CLIENT_SET_REQ_URL" = "FETCH_CLIENT_SET_REQ_URL"; @@ -175,217 +175,217 @@ export const FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH: "FETCH_CLIENT_SET_SKIP_PAREN export const FETCH_CLIENT_SET_SKIP_PARENT_HEADERS: "FETCH_CLIENT_SET_SKIP_PARENT_HEADERS" = "FETCH_CLIENT_SET_SKIP_PARENT_HEADERS"; export interface ISetTest { - type: typeof FETCH_CLIENT_SET_TEST; - payload: { - tests: ITest[]; - }; + type: typeof FETCH_CLIENT_SET_TEST; + payload: { + tests: ITest[]; + }; } export interface ISetRequest { - type: typeof FETCH_CLIENT_SET_REQ; - payload: { - req: IRequestModel; - }; + type: typeof FETCH_CLIENT_SET_REQ; + payload: { + req: IRequestModel; + }; } export interface ISetURL { - type: typeof FETCH_CLIENT_SET_REQ_URL; - payload: { - url: string; - }; + type: typeof FETCH_CLIENT_SET_REQ_URL; + payload: { + url: string; + }; } export interface ISetMethod { - type: typeof FETCH_CLIENT_SET_REQ_METHOD; - payload: { - method: MethodType; - }; + type: typeof FETCH_CLIENT_SET_REQ_METHOD; + payload: { + method: MethodType; + }; } export interface ISetParams { - type: typeof FETCH_CLIENT_SET_REQ_PARAMS; - payload: { - params: ITableData[]; - }; + type: typeof FETCH_CLIENT_SET_REQ_PARAMS; + payload: { + params: ITableData[]; + }; } export interface ISetAuth { - type: typeof FETCH_CLIENT_SET_REQ_AUTH; - payload: { - auth: IAuth; - }; + type: typeof FETCH_CLIENT_SET_REQ_AUTH; + payload: { + auth: IAuth; + }; } export interface ISetHeaders { - type: typeof FETCH_CLIENT_SET_REQ_HEADERS; - payload: { - headers: ITableData[]; - }; + type: typeof FETCH_CLIENT_SET_REQ_HEADERS; + payload: { + headers: ITableData[]; + }; } export interface ISetBody { - type: typeof FETCH_CLIENT_SET_REQ_BODY; - payload: { - body: IBodyData; - }; + type: typeof FETCH_CLIENT_SET_REQ_BODY; + payload: { + body: IBodyData; + }; } export interface ISetFormDataBody { - type: typeof FETCH_CLIENT_SET_REQ_FORM_DATA_BODY; - payload: { - value: string; - index: number; - }; + type: typeof FETCH_CLIENT_SET_REQ_FORM_DATA_BODY; + payload: { + value: string; + index: number; + }; } export interface ISetRawValue { - type: typeof FETCH_CLIENT_SET_REQ_RAW; - payload: { - raw: string; - }; + type: typeof FETCH_CLIENT_SET_REQ_RAW; + payload: { + raw: string; + }; } export interface ISetRawLang { - type: typeof FETCH_CLIENT_SET_REQ_RAW_LANG; - payload: { - rawLang: string; - }; + type: typeof FETCH_CLIENT_SET_REQ_RAW_LANG; + payload: { + rawLang: string; + }; } export interface ISetBinaryData { - type: typeof FETCH_CLIENT_SET_REQ_BINARY_DATA; - payload: { - data: string; - }; + type: typeof FETCH_CLIENT_SET_REQ_BINARY_DATA; + payload: { + data: string; + }; } export interface ISetResetBody { - type: typeof FETCH_CLIENT_SET_REQ_RESET_BODY; - payload: { - bodyType: string; - } + type: typeof FETCH_CLIENT_SET_REQ_RESET_BODY; + payload: { + bodyType: string; + } } export interface ISetNotes { - type: typeof FETCH_CLIENT_SET_NOTES; - payload: { - notes: string; - } + type: typeof FETCH_CLIENT_SET_NOTES; + payload: { + notes: string; + } } export interface ISetAddVar { - type: typeof FETCH_CLIENT_SET_SET_VAR; - payload: { - data: ISetVar[]; - }; + type: typeof FETCH_CLIENT_SET_SET_VAR; + payload: { + data: ISetVar[]; + }; } export interface ISetReqColDetails { - type: typeof FETCH_CLIENT_SET_REQ_COL_DETAILS; - payload: { - colId: string; - folderId: string; - } + type: typeof FETCH_CLIENT_SET_REQ_COL_DETAILS; + payload: { + colId: string; + folderId: string; + } } export interface ISetReqParentSettings { - type: typeof FETCH_CLIENT_SET_REQ_PARENT_SETTINGS; - payload: { - parentSettings: ISettings; - } + type: typeof FETCH_CLIENT_SET_REQ_PARENT_SETTINGS; + payload: { + parentSettings: ISettings; + } } export interface ISetOAuthToken { - type: typeof FETCH_CLIENT_SET_OAUTH_TOKEN; - payload: { - token: string; - } + type: typeof FETCH_CLIENT_SET_OAUTH_TOKEN; + payload: { + token: string; + } } export interface ISetPreCondition { - type: typeof FETCH_CLIENT_SET_PRECONDITION; - payload: { - condition: ITest; - reqIndex: number; - condIndex: number; - } + type: typeof FETCH_CLIENT_SET_PRECONDITION; + payload: { + condition: ITest; + reqIndex: number; + condIndex: number; + } } export interface ISetAddPreRequest { - type: typeof FETCH_CLIENT_SET_ADD_PREREQUEST; - payload: { - request: IRunRequest; - } + type: typeof FETCH_CLIENT_SET_ADD_PREREQUEST; + payload: { + request: IRunRequest; + } } export interface ISetDeletePreRequest { - type: typeof FETCH_CLIENT_SET_DELETE_PREREQUEST; - payload: { - index: number; - } + type: typeof FETCH_CLIENT_SET_DELETE_PREREQUEST; + payload: { + index: number; + } } export interface ISetDeletePreCondition { - type: typeof FETCH_CLIENT_SET_DELETE_PRECONDITION; - payload: { - reqIndex: number; - condIndex: number; - } + type: typeof FETCH_CLIENT_SET_DELETE_PRECONDITION; + payload: { + reqIndex: number; + condIndex: number; + } } export interface ISetCollectionList { - type: typeof FETCH_CLIENT_SET_COLLECTION_LIST; - payload: { - colList: ICollection[]; - } + type: typeof FETCH_CLIENT_SET_COLLECTION_LIST; + payload: { + colList: ICollection[]; + } } export interface ISetColRequestList { - type: typeof FETCH_CLIENT_SET_COL_REQUEST_LIST; - payload: { - colReqList: IColRequest; - } + type: typeof FETCH_CLIENT_SET_COL_REQUEST_LIST; + payload: { + colReqList: IColRequest; + } } export interface ISetSelectedCol { - type: typeof FETCH_CLIENT_SET_COL_ID; - payload: { - colId: string; - index: number; - } + type: typeof FETCH_CLIENT_SET_COL_ID; + payload: { + colId: string; + index: number; + } } export interface ISetSelectedRequest { - type: typeof FETCH_CLIENT_SET_REQ_ID; - payload: { - reqId: string; - index: number; - parentId: string; - } + type: typeof FETCH_CLIENT_SET_REQ_ID; + payload: { + reqId: string; + index: number; + parentId: string; + } } export interface ISetPreFetch { - type: typeof FETCH_CLIENT_SET_PREFETCH; - payload: { - preFetch: IPreFetch; - } + type: typeof FETCH_CLIENT_SET_PREFETCH; + payload: { + preFetch: IPreFetch; + } } export interface ISetSkipPreFetch { - type: typeof FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH; - payload: { - skip: boolean; - } + type: typeof FETCH_CLIENT_SET_SKIP_PARENT_PREFETCH; + payload: { + skip: boolean; + } } export interface ISetSkipHeaders { - type: typeof FETCH_CLIENT_SET_SKIP_PARENT_HEADERS - payload: { - skip: boolean; - } + type: typeof FETCH_CLIENT_SET_SKIP_PARENT_HEADERS + payload: { + skip: boolean; + } } export type RequestActionTypes = | ISetURL | ISetMethod | ISetParams | ISetAuth | ISetHeaders | ISetBody | ISetRequest | ISetTest | - ISetRawLang | ISetResetBody | ISetRawValue | ISetBinaryData | ISetNotes | ISetAddVar | ISetReqColDetails | ISetReqParentSettings | ISetFormDataBody | - ISetOAuthToken | ISetPreCondition | ISetAddPreRequest | ISetDeletePreRequest | ISetDeletePreCondition | ISetCollectionList | ISetColRequestList | - ISetSelectedCol | ISetSelectedRequest | ISetPreFetch | ISetSkipPreFetch | ISetSkipHeaders; \ No newline at end of file + ISetRawLang | ISetResetBody | ISetRawValue | ISetBinaryData | ISetNotes | ISetAddVar | ISetReqColDetails | ISetReqParentSettings | ISetFormDataBody | + ISetOAuthToken | ISetPreCondition | ISetAddPreRequest | ISetDeletePreRequest | ISetDeletePreCondition | ISetCollectionList | ISetColRequestList | + ISetSelectedCol | ISetSelectedRequest | ISetPreFetch | ISetSkipPreFetch | ISetSkipHeaders; diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/index.tsx b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/index.tsx index dba78ac..5717698 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/index.tsx +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/index.tsx @@ -1,210 +1,194 @@ import React, { useEffect, useRef, useState } from 'react'; import { useSelector } from "react-redux"; +import { ReactComponent as CodeLogo } from '../../../../../../icons/code.svg'; +import { requestTypes } from '../../../../../utils/configuration'; import { IRootState } from "../../../../reducer/combineReducer"; +import { getColFolDotMenu } from '../../../Common/icons'; +import vscode from '../../../Common/vscodeAPI'; import { curlResponseOptions, responseOptions } from "../../ResponsePanel/consts"; -import { ReactComponent as CodeLogo } from '../../../../../../icons/code.svg'; import "./style.css"; import { FormatBytes, GetResponseTime } from "./util"; -import vscode from '../../../Common/vscodeAPI'; -import { requestTypes } from '../../../../../utils/configuration'; -import { getColFolDotMenu } from '../../../Common/icons'; export const ResponseOptionsTab = (props: any) => { - const { selectedTab, setSelectedTab, isVerticalLayout } = props; - - const { headers, response, testResults, cookies } = useSelector((state: IRootState) => state.responseData); - const { url } = useSelector((state: IRootState) => state.requestData); - - const [menuShow, setMenuShow] = useState(false); - const [codeMenuShow, setCodeMenuShow] = useState(false); - - const wrapperRef = useRef(null); - const codeWrapperRef = useRef(null); - - function getClassName(status: number): string { - if (response.isError) { - return "response-params error-text"; - } - - if (status <= 399) { - return "response-params"; - } - - return "response-params error-text"; - - } - - function responseParamsRender() { - return ( -
- - - -
- ); - } - - useEffect(() => { - document.addEventListener("mousedown", handleClickOutside, false); - - return () => { - document.removeEventListener("mousedown", handleClickOutside, false); - }; - }, []); - - function handleClickOutside(evt: any) { - if (wrapperRef.current && !wrapperRef.current.contains(evt.target)) { - setMenuShow(false); - } - - if (codeWrapperRef.current && !codeWrapperRef.current.contains(evt.target)) { - setCodeMenuShow(false); - } - } - - function setShowMenu(evt: any) { - evt.preventDefault(); - setMenuShow(!menuShow); - setCodeMenuShow(false); - } - - function setCodeShowMenu(evt: any) { - evt.preventDefault(); - setMenuShow(false); - setCodeMenuShow(!codeMenuShow); - } - - - function onSaveResponse(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.saveResponseRequest, data: response.responseData, fileType: response.responseType?.format }); - setMenuShow(false); - } - - function onSaveTestResponse(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.saveTestResponseRequest, data: JSON.stringify(testResults) }); - setMenuShow(false); - } - - const codeSnippetCss = () => { - return url ? (selectedTab === "codesnippet" ? "code-snippet-icon code-snippet-icon-clicked" : "code-snippet-icon") : "code-snippet-icon-disabled"; - }; - - function onSelectTab(opt: string) { - setSelectedTab(opt); - setCodeMenuShow(false); - } - - function isDisabled(opt: string) { - if (opt === "codesnippet" && url) { - return false; - } - - if (opt === "codetype" && url ) { //&& !response.isError && isJson(response.responseData)) { - return false; - } - - return true; - } - - function isJson(response: any) { - try { - if (response) { - JSON.parse(response); - return true; - } - return false; - } catch { - return false; - } - } - - function getResponseOptions(): { name: string; value: string; }[] { - return props.isCurl ? curlResponseOptions : responseOptions; - } - - return ( - <> - { - isVerticalLayout ? - responseParamsRender() - : - <> - } -
- { - getResponseOptions().map((option) => ( - - ))} - { - !isVerticalLayout - ? - responseParamsRender() - : - <> - } -
-
-
- - {codeMenuShow && (
- - -
- )} -
-
- {getColFolDotMenu("res-menu", "Menu", "hamburger-menu", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => setShowMenu(e))} - {menuShow && (
- - {!props.isCurl && } -
- )} -
-
-
-
- - ); -}; \ No newline at end of file + const { selectedTab, setSelectedTab, isVerticalLayout } = props; + + const { headers, response, testResults, cookies } = useSelector((state: IRootState) => state.responseData); + const { url } = useSelector((state: IRootState) => state.requestData); + + const [menuShow, setMenuShow] = useState(false); + const [codeMenuShow, setCodeMenuShow] = useState(false); + + const wrapperRef = useRef(null); + const codeWrapperRef = useRef(null); + + function getClassName(status: number): string { + if (response.isError) { + return "response-params error-text"; + } + + if (status <= 399) { + return "response-params"; + } + + return "response-params error-text"; + + } + + function responseParamsRender() { + return ( +
+ + + +
+ ); + } + + useEffect(() => { + document.addEventListener("mousedown", handleClickOutside, false); + + return () => { + document.removeEventListener("mousedown", handleClickOutside, false); + }; + }, []); + + function handleClickOutside(evt: any) { + if (wrapperRef.current && !wrapperRef.current.contains(evt.target)) { + setMenuShow(false); + } + + if (codeWrapperRef.current && !codeWrapperRef.current.contains(evt.target)) { + setCodeMenuShow(false); + } + } + + function setShowMenu(evt: any) { + evt.preventDefault(); + setMenuShow(!menuShow); + setCodeMenuShow(false); + } + + function setCodeShowMenu(evt: any) { + evt.preventDefault(); + setMenuShow(false); + setCodeMenuShow(!codeMenuShow); + } + + + function onSaveResponse(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.saveResponseRequest, data: response.responseData, fileType: response.responseType?.format }); + setMenuShow(false); + } + + function onSaveTestResponse(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.saveTestResponseRequest, data: JSON.stringify(testResults) }); + setMenuShow(false); + } + + function onSelectTab(opt: string) { + setSelectedTab(opt); + setCodeMenuShow(false); + } + + function isDisabled(opt: string) { + if (opt === "codesnippet" && url) { + return false; + } + + if (opt === "codetype" && url ) { //&& !response.isError && isJson(response.responseData)) { + return false; + } + + return true; + } + + function getResponseOptions(): { name: string; value: string; }[] { + return props.isCurl ? curlResponseOptions : responseOptions; + } + + return ( + <> + { + isVerticalLayout ? + responseParamsRender() + : + <> + } +
+ { + getResponseOptions().map((option) => ( + + ))} + { + !isVerticalLayout + ? + responseParamsRender() + : + <> + } +
+
+
+ + {codeMenuShow && (
+ + +
+ )} +
+
+ {getColFolDotMenu("res-menu", "Menu", "hamburger-menu", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => setShowMenu(e))} + {menuShow && (
+ + {!props.isCurl && } +
+ )} +
+
+
+
+ + ); +}; diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/style.css b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/style.css index 0f851fb..fdb35c3 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/style.css +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/style.css @@ -1,80 +1,80 @@ .response-params-panel { - float : right; - margin-left : auto; - display : flex; - width : auto; - justify-content: space-around; + float : right; + margin-left : auto; + display : flex; + width : auto; + justify-content: space-around; } .response-params { - color : #4bb543; - padding : 0 10px; - font-weight: bolder; + color : #4bb543; + padding : 0 10px; + font-weight: bolder; } .response-params-panel-vertical { - display : flex; - margin : 5px; - padding-bottom: 20px; + display : flex; + margin : 5px; + padding-bottom: 20px; } .menu-panel { - margin-left: auto !important; - padding-top: 4px; + margin-left: auto !important; + padding-top: 4px; } .code-snippet-icon, .code-snippet-icon-disabled { - cursor : pointer; - transform : scale(1.2); - margin-right: 5px; + cursor : pointer; + transform : scale(1.2); + margin-right: 5px; } .code-snippet-icon path { - fill: var(--text-color); + fill: var(--text-color); } .res-menu { - margin-left : 10px; - cursor : pointer; - width : 16px; - margin-bottom: 3px; + margin-left : 10px; + cursor : pointer; + width : 16px; + margin-bottom: 3px; } .res-menu path { - fill: var(--text-color); + fill: var(--text-color); } .code-snippet-icon-clicked path { - fill: var(--button-background-color); + fill: var(--button-background-color); } .save-to-file-button:disabled, .save-to-file-button[disabled], .save-to-file-button:disabled:hover, .save-to-file-button[disabled]:hover { - color : #666; - cursor : not-allowed; - background-color: lightgrey; + color : #666; + cursor : not-allowed; + background-color: lightgrey; } .save-to-file-button:hover { - color: var(--button-text-color); + color: var(--button-text-color); } .code-snippet-icon-disabled { - cursor: not-allowed; + cursor: not-allowed; } .code-snippet-icon-disabled path { - fill: #666; + fill: #666; } .res-drop-down-menu { - width: 175px !important; + width: 175px !important; } .res-code-drop-down-menu { - width: 125px !important; -} \ No newline at end of file + width: 125px !important; +} diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/util.ts b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/util.ts index ae15f7f..c91f3db 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/util.ts +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/OptionTab/util.ts @@ -1,31 +1,31 @@ export function GetResponseTime(duration: number) { - if (duration > 0) { - var milliseconds = duration % 1000; - var seconds = Math.floor((duration / 1000) % 60); - var minutes = Math.floor((duration / (60 * 1000)) % 60); + if (duration > 0) { + var milliseconds = duration % 1000; + var seconds = Math.floor((duration / 1000) % 60); + var minutes = Math.floor((duration / (60 * 1000)) % 60); - if (minutes > 0) { - return minutes + ":" + seconds + "." + milliseconds + " mins"; - } else if (seconds > 0) { - return seconds + "." + milliseconds + " secs"; - } else { - return milliseconds + " ms"; - } - } + if (minutes > 0) { + return minutes + ":" + seconds + "." + milliseconds + " mins"; + } else if (seconds > 0) { + return seconds + "." + milliseconds + " secs"; + } else { + return milliseconds + " ms"; + } + } - return ""; + return ""; } export function FormatBytes(bytes: number, decimals = 2): string { - if (bytes === 0) { - return '0 Bytes'; - } + if (bytes === 0) { + return '0 Bytes'; + } - const k = 1024; - const dm = decimals < 0 ? 0 : decimals; - const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + const k = 1024; + const dm = decimals < 0 ? 0 : decimals; + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - const i = Math.floor(Math.log(bytes) / Math.log(k)); + const i = Math.floor(Math.log(bytes) / Math.log(k)); - return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; + return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/index.tsx b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/index.tsx index ceb4fec..7e9ba8f 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/index.tsx +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/index.tsx @@ -1,27 +1,37 @@ import React from 'react'; import { useSelector } from "react-redux"; +import { requestTypes } from '../../../../../../utils/configuration'; import { IRootState } from "../../../../../reducer/combineReducer"; import { ResponseTable } from '../../../../Common/Table/ResponseTable'; +import vscode from '../../../../Common/vscodeAPI'; +import "./style.css"; export const ResponseCookies = () => { - const { cookies } = useSelector((state: IRootState) => state.responseData); + const { cookies } = useSelector((state: IRootState) => state.responseData); - return ( - <> - { - cookies.length > 0 ? - - : - <> -
-
- - } - - ); -}; \ No newline at end of file + function onOpenCookies() { + vscode.postMessage({ type: requestTypes.openManageCookiesRequest }); + } + + return ( + <> + {cookies?.length === 0 &&
} +
+ +
+ { + cookies?.length > 0 ? + + : + <> +
+ + } + + ); +}; diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/style.css b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/style.css new file mode 100644 index 0000000..a547331 --- /dev/null +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Cookies/style.css @@ -0,0 +1,6 @@ +.manage-cookie-btn-panel { + padding: 10px 0 10px 10px; + margin-left: auto; + margin-right: 0; + float: right; +} diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/index.tsx b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/index.tsx index 632b6cb..2a5e944 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/index.tsx +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/index.tsx @@ -6,24 +6,24 @@ import "./style.css"; export const ResponseHeaders = () => { - const { headers } = useSelector((state: IRootState) => state.responseData); + const { headers } = useSelector((state: IRootState) => state.responseData); - return ( - <> - { - headers.length > 0 ? - - : - <> -
-
- - } - - ); -}; \ No newline at end of file + return ( + <> + { + headers.length > 0 ? + + : + <> +
+
+ + } + + ); +}; diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/style.css b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/style.css index dd4e73e..c283ed2 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/style.css +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Headers/style.css @@ -1,5 +1,5 @@ .auth-header-label { - padding: 20px 10px 20px 0; - margin-left: 10px; - text-align: center; -} \ No newline at end of file + padding: 20px 10px 20px 0; + margin-left: 10px; + text-align: center; +} diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/consts.ts b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/consts.ts index d0eb211..a6ce5bd 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/consts.ts +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/consts.ts @@ -1,7 +1,7 @@ export const responseType = [ - { name: "Text", value: "text" }, - { name: "JSON", value: "json" }, - { name: "HTML", value: "html" }, - { name: "XML", value: "xml" }, - { name: "JavaScript", value: "javascript" } + { name: "Text", value: "text" }, + { name: "JSON", value: "json" }, + { name: "HTML", value: "html" }, + { name: "XML", value: "xml" }, + { name: "JavaScript", value: "javascript" } ]; diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/index.tsx b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/index.tsx index 7dcb04c..b650df7 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/index.tsx +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/index.tsx @@ -1,225 +1,224 @@ -import React, { useState } from 'react'; -import { useMemo } from "react"; +import React, { useMemo, useState } from 'react'; import { useSelector } from "react-redux"; -import { IRootState } from "../../../../../reducer/combineReducer"; -import { MonacoEditor } from "../../../../Common/Editor"; -import { responseType } from "./consts"; +import { ReactComponent as CollapseLogo } from '../../../../../../../icons/collapse.svg'; +import { ReactComponent as ExpandLogo } from '../../../../../../../icons/expand.svg'; import FetchClientIcon from "../../../../../../../icons/fetch-client.png"; import { requestTypes } from '../../../../../../utils/configuration'; -import vscode from '../../../../Common/vscodeAPI'; -import { JSONViewer } from '../../../../Common/Viewer/JSONViewer'; +import { IRootState } from "../../../../../reducer/combineReducer"; +import { MonacoEditor } from "../../../../Common/Editor"; import { HTMLViewer } from '../../../../Common/Viewer/HTMLViewer'; +import { JSONViewer } from '../../../../Common/Viewer/JSONViewer'; import { XMLViewer } from '../../../../Common/Viewer/XMLViewer'; -import { ReactComponent as ExpandLogo } from '../../../../../../../icons/expand.svg'; -import { ReactComponent as CollapseLogo } from '../../../../../../../icons/collapse.svg'; +import vscode from '../../../../Common/vscodeAPI'; +import { responseType } from "./consts"; import "./style.css"; export const ResponseSection = (props: any) => { - const { response, loading } = useSelector((state: IRootState) => state.responseData); - const { horizontalLayout, responseLimit } = useSelector((state: IRootState) => state.uiData); - - const [viewType, setType] = useState("raw"); - const [fullScreenMode, setFullScreenMode] = useState(false); - const [wordWrap, setWordWrap] = useState(false); - - const editor = useMemo(() => { - return ; - }, [response.responseData, wordWrap]); - - - function onDownloadFile() { - vscode.postMessage({ type: requestTypes.downloadFileTypeRequest, resData: response.responseData, fileType: response.responseType?.format }); - } - - function onCancelRequest() { - vscode.postMessage({ type: requestTypes.cancelRequest }); - } - - function onTextResponseClick() { - setType("raw"); - } - - function onJsonViewResponseClick() { - setType("viewer"); - } - - function isPreViewVisible(): boolean { - return (response.responseType?.format === "json" || response.responseType?.format === "html" || response.responseType?.format === "xml"); - } - - function onFullScreenClick() { - let responseSection = document.getElementById("response-section-panel"); - if (responseSection) { - if (fullScreenMode) { - responseSection.classList.remove("response-section-panel-full-screen"); - responseSection.classList.add("res-visible"); - document.body.classList.remove("body-full-screen"); - } else { - responseSection.classList.add("response-section-panel-full-screen"); - responseSection.classList.remove("res-visible"); - document.body.classList.add("body-full-screen"); - } - setFullScreenMode(!fullScreenMode); - } - } - - function getLoadingSection() { - return (
-
- {"Fetching data ..."} - {!props.isCurl &&
- -
} -
); - } - - function getIdealSection() { - return (
- - {props.isCurl ? "Enter the curl command and click Run to get a response." : "Enter the URL and click Send to get a response."} -
); - } - - function getErrorSection() { - return (
-
{response.responseData}
-
); - } - - function getBinaryResponseSection() { - return (
-
{"View response is not supported for 'file' response type."}
-
{"Please download it."}
- -
); - } - - function getMaxSizeResponseSection() { - return (
-
{"View response is not supported on large files (> 5MB)."}
-
{"Please download it."}
- -
); - } - - function getPreviewHeaderSection() { - return (
{isPreViewVisible() &&
- - - - -
} - {menuSection()} -
); - } - - function menuSection() { - return (
- -
); - } - - function getEditorPanelCss() { - if (viewType === "raw") { - if (fullScreenMode) { - return "res-visible"; - } - - if (horizontalLayout) { - return "res-visible"; - } else { - return "res-visible-inside"; - } - } - return "res-hidden"; - } - - function getViewerPanelCss() { - if (viewType !== "raw") { - if (fullScreenMode) { - return "res-visible"; - } - - if (horizontalLayout) { - return "res-visible"; - } else { - return "res-visible-inside"; - } - } - return "res-hidden"; - } - - function getResponseSection() { - return (
-
- {editor} -
-
- {response.responseType?.format === "json" && } - {response.responseType?.format === "html" && } - {response.responseType?.format === "xml" && } -
- { - fullScreenMode ? - - : - - } -
); - } - - return ( -
- { - response.isError ? - getErrorSection() - : - response.status === 0 - ? - <>
{loading === true ? getLoadingSection() : getIdealSection()} - : - response.responseData - ? - response.responseType.isBinaryFile ? - getBinaryResponseSection() - : - parseInt(response.size) > responseLimit ? - getMaxSizeResponseSection() - : - <> - {getPreviewHeaderSection()} - - {getResponseSection()} - - : - <> - } -
- ); -}; \ No newline at end of file + const { response, loading } = useSelector((state: IRootState) => state.responseData); + const { horizontalLayout, responseLimit } = useSelector((state: IRootState) => state.uiData); + + const [viewType, setType] = useState("raw"); + const [fullScreenMode, setFullScreenMode] = useState(false); + const [wordWrap, setWordWrap] = useState(false); + + const editor = useMemo(() => { + return ; + }, [response.responseData, wordWrap]); + + + function onDownloadFile() { + vscode.postMessage({ type: requestTypes.downloadFileTypeRequest, resData: response.responseData, fileType: response.responseType?.format }); + } + + function onCancelRequest() { + vscode.postMessage({ type: requestTypes.cancelRequest }); + } + + function onTextResponseClick() { + setType("raw"); + } + + function onJsonViewResponseClick() { + setType("viewer"); + } + + function isPreViewVisible(): boolean { + return (response.responseType?.format === "json" || response.responseType?.format === "html" || response.responseType?.format === "xml"); + } + + function onFullScreenClick() { + let responseSection = document.getElementById("response-section-panel"); + if (responseSection) { + if (fullScreenMode) { + responseSection.classList.remove("response-section-panel-full-screen"); + responseSection.classList.add("res-visible"); + document.body.classList.remove("body-full-screen"); + } else { + responseSection.classList.add("response-section-panel-full-screen"); + responseSection.classList.remove("res-visible"); + document.body.classList.add("body-full-screen"); + } + setFullScreenMode(!fullScreenMode); + } + } + + function getLoadingSection() { + return (
+
+ {"Fetching data ..."} + {!props.isCurl &&
+ +
} +
); + } + + function getIdealSection() { + return (
+ + {props.isCurl ? "Enter the curl command and click Run to get a response." : "Enter the URL and click send to get a response."} +
); + } + + function getErrorSection() { + return (
+
{response.responseData}
+
); + } + + function getBinaryResponseSection() { + return (
+
{"View response is not supported for 'file' response type."}
+
{"Please download it."}
+ +
); + } + + function getMaxSizeResponseSection() { + return (
+
{"View response is not supported on large files (> 5MB)."}
+
{"Please download it."}
+ +
); + } + + function getPreviewHeaderSection() { + return (
{isPreViewVisible() &&
+ + + + +
} + {menuSection()} +
); + } + + function menuSection() { + return (
+ +
); + } + + function getEditorPanelCss() { + if (viewType === "raw") { + if (fullScreenMode) { + return "res-visible"; + } + + if (horizontalLayout) { + return "res-visible"; + } else { + return "res-visible-inside"; + } + } + return "res-hidden"; + } + + function getViewerPanelCss() { + if (viewType !== "raw") { + if (fullScreenMode) { + return "res-visible"; + } + + if (horizontalLayout) { + return "res-visible"; + } else { + return "res-visible-inside"; + } + } + return "res-hidden"; + } + + function getResponseSection() { + return (
+
+ {editor} +
+
+ {response.responseType?.format === "json" && } + {response.responseType?.format === "html" && } + {response.responseType?.format === "xml" && } +
+ { + fullScreenMode ? + + : + + } +
); + } + + return ( +
+ { + response.isError ? + getErrorSection() + : + response.status === 0 + ? + <>
{loading === true ? getLoadingSection() : getIdealSection()} + : + response.responseData + ? + response.responseType.isBinaryFile ? + getBinaryResponseSection() + : + parseInt(response.size) > responseLimit ? + getMaxSizeResponseSection() + : + <> + {getPreviewHeaderSection()} + + {getResponseSection()} + + : + <> + } +
+ ); +}; diff --git a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/style.css b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/style.css index 6d9f6d0..37a8514 100644 --- a/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/style.css +++ b/src/fetch-client-ui/components/ResponseUI/OptionsPanel/Options/Response/style.css @@ -1,237 +1,237 @@ .response-content-panel { - height: 100%; + height: 100%; } .response-editor { - height : calc(100% - 33px); - padding-top: 10px; + height : calc(100% - 33px); + padding-top: 10px; } .response-editor-without-preview { - height : 100%; - padding-top: 10px; + height : 100%; + padding-top: 10px; } .response-header-label { - position : relative; - top : 15%; - text-align: center; - margin : 0 auto; - height : 75%; + position : relative; + top : 15%; + text-align: center; + margin : 0 auto; + height : 75%; } .arrow-4 { - width : 40px; - height : 30px; - display : grid; - margin : 0 auto; - margin-bottom: 20px; + width : 40px; + height : 30px; + display : grid; + margin : 0 auto; + margin-bottom: 20px; } .arrow-4:before, .arrow-4:after { - content : ""; - grid-area : 1/1; - background: var(--border-color); - clip-path : polygon(0 10px, calc(100% - 15px) 10px, calc(100% - 15px) 0, 100% 50%, calc(100% - 15px) 100%, calc(100% - 15px) calc(100% - 10px), 0 calc(100% - 10px)); - animation : a4 0.5s infinite alternate; + content : ""; + grid-area : 1/1; + background: var(--border-color); + clip-path : polygon(0 10px, calc(100% - 15px) 10px, calc(100% - 15px) 0, 100% 50%, calc(100% - 15px) 100%, calc(100% - 15px) calc(100% - 10px), 0 calc(100% - 10px)); + animation : a4 0.5s infinite alternate; } .arrow-4:after { - --s: -1; + --s: -1; } @keyframes a4 { - 0% { - transform: scale(var(--s, 1)) translate(12px, -6px) translate(4px); - } + 0% { + transform: scale(var(--s, 1)) translate(12px, -6px) translate(4px); + } - 100% { - transform: scale(var(--s, 1)) translate(12px, -6px) translate(-4px); - } + 100% { + transform: scale(var(--s, 1)) translate(12px, -6px) translate(-4px); + } } .fetch-data-text { - font-size : medium; - font-weight: 400; + font-size : medium; + font-weight: 400; } .fetch-client-image { - width : 60px; - height : 60px; - margin-bottom: 20px; - filter : brightness(85%); + width : 60px; + height : 60px; + margin-bottom: 20px; + filter : brightness(85%); } .fetch-image-panel { - position : relative; - top : 40%; - text-align : center; - margin : 0 auto; - display : flex; - flex-direction: column; - align-items : center; + position : relative; + top : 40%; + text-align : center; + margin : 0 auto; + display : flex; + flex-direction: column; + align-items : center; } .res-not-support-panel { - position : relative; - top : 40%; - text-align: center; - margin : 0 auto; + position : relative; + top : 40%; + text-align: center; + margin : 0 auto; } .res-not-support-text { - font-size: medium; - word-wrap: break-word; - padding : 5px; + font-size: medium; + word-wrap: break-word; + padding : 5px; } .res-not-support-download { - margin-top: 10px; - width : auto !important; + margin-top: 10px; + width : auto !important; } .cancel-button-panel { - position : absolute; - bottom : 10%; - text-align: center; - left : 45%; + position : absolute; + bottom : 10%; + text-align: center; + left : 45%; } .error-text { - color: #ea5b5b !important; + color: #ea5b5b !important; } .viewer-option-button-panel { - padding-top: 10px; + padding-top: 10px; } .viewer-option-button { - background-color: transparent; - outline : none; - border : 0; - color : var(--button-background-color); - cursor : pointer; - font-weight : bolder; - padding-left : 5px; + background-color: transparent; + outline : none; + border : 0; + color : var(--button-background-color); + cursor : pointer; + font-weight : bolder; + padding-left : 5px; } .viewer-option-button:hover, .viewer-option-button:focus { - background-color: transparent; - outline : none; - border : 0; + background-color: transparent; + outline : none; + border : 0; } .viewer-option-button:hover { - color: var(--button-hover-color); + color: var(--button-hover-color); } .toggle, .word-wrap-button { - box-sizing : border-box; - font-size : 0; - display : flex; - flex-flow : row nowrap; - justify-content: flex-start; - align-items : stretch; - margin-top : 10px; - outline : none; + box-sizing : border-box; + font-size : 0; + display : flex; + flex-flow : row nowrap; + justify-content: flex-start; + align-items : stretch; + margin-top : 10px; + outline : none; } .toggle input { - width : 0; - height : 0; - position: absolute; - left : -9999px; - outline : none; + width : 0; + height : 0; + position: absolute; + left : -9999px; + outline : none; } .toggle input+label { - margin : 0; - padding : 0.1rem 1rem; - box-sizing: border-box; - position : relative; - display : inline-block; - border : solid 1px var(--text-color); - ; - background-color: transparent; - font-weight : 600; - text-align : center; - transition : border-color 0.15s ease-out, color 0.25s ease-out, background-color 0.15s ease-out, box-shadow 0.15s ease-out; - color : var(--text-color); - outline : none; + margin : 0; + padding : 0.1rem 1rem; + box-sizing: border-box; + position : relative; + display : inline-block; + border : solid 1px var(--text-color); + ; + background-color: transparent; + font-weight : 600; + text-align : center; + transition : border-color 0.15s ease-out, color 0.25s ease-out, background-color 0.15s ease-out, box-shadow 0.15s ease-out; + color : var(--text-color); + outline : none; } .toggle input+label:first-of-type { - border-radius: 6px 0 0 6px; - border-right : none; + border-radius: 6px 0 0 6px; + border-right : none; } .toggle input+label:last-of-type { - border-radius: 0 6px 6px 0; - border-left : none; + border-radius: 0 6px 6px 0; + border-left : none; } .toggle input:hover+label { - border-color: #213140; + border-color: #213140; } .toggle input:checked+label { - background-color: var(--button-background-color); - color : var(--button-text-color); - border-color : var(--button-background-color); - z-index : 1; + background-color: var(--button-background-color); + color : var(--button-text-color); + border-color : var(--button-background-color); + z-index : 1; } .expand-btn { - position: fixed; - bottom : 28px; - right : 40px; - z-index : 20; - width : 17px; - cursor : pointer; + position: fixed; + bottom : 28px; + right : 40px; + z-index : 20; + width : 17px; + cursor : pointer; } .expand-btn path { - fill: var(--text-color); + fill: var(--text-color); } .collapse-btn { - position: fixed; - bottom : 15px; - right : 25px; - z-index : 20; - cursor : pointer; + position: fixed; + bottom : 15px; + right : 25px; + z-index : 20; + cursor : pointer; } .collapse-btn path { - fill: var(--text-color); + fill: var(--text-color); } .response-section-panel-full-screen { - height : auto; - width : auto; - border : 0; - margin : 0; - position : fixed !important; - top : 0; - bottom : 1px; - left : 0; - right : 0; - z-index : 15; - background-color: var(--vscode-editor-background); + height : auto; + width : auto; + border : 0; + margin : 0; + position : fixed !important; + top : 0; + bottom : 1px; + left : 0; + right : 0; + z-index : 15; + background-color: var(--vscode-editor-background); } .fullscreen-btn-invisible { - visibility: hidden; + visibility: hidden; } .word-wrap-button { - margin-left: auto; - order : 2; + margin-left: auto; + order : 2; } .res-prev-header { - display: flex; -} \ No newline at end of file + display: flex; +} diff --git a/src/fetch-client-ui/components/ResponseUI/ResponsePanel/consts.ts b/src/fetch-client-ui/components/ResponseUI/ResponsePanel/consts.ts index 197ee2f..e9a96b0 100644 --- a/src/fetch-client-ui/components/ResponseUI/ResponsePanel/consts.ts +++ b/src/fetch-client-ui/components/ResponseUI/ResponsePanel/consts.ts @@ -1,13 +1,13 @@ export const responseOptions = [ - { name: "Response", value: "response", }, - { name: "Headers", value: "headers", }, - { name: "Cookies", value: "cookies", }, - { name: "Test Results", value: "testresults", }, - { name: "Notes", value: "notes", } + { name: "Response", value: "response", }, + { name: "Headers", value: "headers", }, + { name: "Cookies", value: "cookies", }, + { name: "Test Results", value: "testresults", }, + { name: "Notes", value: "notes", } ]; export const curlResponseOptions = [ - { name: "Response", value: "response", }, - { name: "Headers", value: "headers", }, - { name: "Cookies", value: "cookies", } + { name: "Response", value: "response", }, + { name: "Headers", value: "headers", }, + { name: "Cookies", value: "cookies", } ]; diff --git a/src/fetch-client-ui/components/ResponseUI/ResponsePanel/index.tsx b/src/fetch-client-ui/components/ResponseUI/ResponsePanel/index.tsx index 5351f6c..80f06e8 100644 --- a/src/fetch-client-ui/components/ResponseUI/ResponsePanel/index.tsx +++ b/src/fetch-client-ui/components/ResponseUI/ResponsePanel/index.tsx @@ -1,5 +1,4 @@ -import React, { useEffect } from 'react'; -import { useState } from "react"; +import React, { useEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import { IRootState } from '../../../reducer/combineReducer'; import TypesGenerator from '../..//Common/TypesGenerator'; @@ -12,55 +11,55 @@ import { ResponseOptionsTab } from "../OptionsPanel/OptionTab"; import "./style.css"; export interface ResponsePanelProps { - isVerticalLayout: boolean; - isCurl: boolean; + isVerticalLayout: boolean; + isCurl: boolean; } export const ReponsePanel = (props: ResponsePanelProps) => { - const { loading } = useSelector((state: IRootState) => state.responseData); - const { runItem } = useSelector((state: IRootState) => state.uiData); + const { loading } = useSelector((state: IRootState) => state.responseData); + const { runItem } = useSelector((state: IRootState) => state.uiData); - const [selectedTab, setSelectedTab] = useState(runItem ? "testresults" : "response"); + const [selectedTab, setSelectedTab] = useState(runItem ? "testresults" : "response"); - const CodeSnippetGenerator = React.lazy(() => import('../../Common/CodeGenerator')); + const CodeSnippetGenerator = React.lazy(() => import('../../Common/CodeGenerator')); - const renderOptionsUI = (tab: string) => { - switch (tab) { - case 'headers': - return ; - case 'cookies': - return ; - case 'testresults': - return ; - case 'codesnippet': - return loading...}>; - case 'codetype': - return loading...}>; - case 'notes': - return ; - default: - return <>; - } - }; + const renderOptionsUI = (tab: string) => { + switch (tab) { + case 'headers': + return ; + case 'cookies': + return ; + case 'testresults': + return ; + case 'codesnippet': + return loading...}>; + case 'codetype': + return loading...}>; + case 'notes': + return ; + default: + return <>; + } + }; - useEffect(() => { - if (loading) { - setSelectedTab("response"); - } - }, [loading]); + useEffect(() => { + if (loading) { + setSelectedTab("response"); + } + }, [loading]); - return ( -
-
- -
-
- -
- {renderOptionsUI(selectedTab)} -
-
-
- ); -}; \ No newline at end of file + return ( +
+
+ +
+
+ +
+ {renderOptionsUI(selectedTab)} +
+
+
+ ); +}; diff --git a/src/fetch-client-ui/components/ResponseUI/ResponsePanel/style.css b/src/fetch-client-ui/components/ResponseUI/ResponsePanel/style.css index b47699f..96ce003 100644 --- a/src/fetch-client-ui/components/ResponseUI/ResponsePanel/style.css +++ b/src/fetch-client-ui/components/ResponseUI/ResponsePanel/style.css @@ -1,42 +1,42 @@ .response-panel { - border-radius: 3px; - margin: 5px; - padding: 10px; - /* height: 97%; */ - height: calc(100% - 5px); - box-sizing: border-box; + border-radius: 3px; + margin: 5px; + padding: 10px; + /* height: 97%; */ + height: calc(100% - 5px); + box-sizing: border-box; } .response-container { - height: 100%; + height: 100%; } .response-options-tab-panel { - height: calc(100% - 10px); + height: calc(100% - 10px); } .response-options-tab-panel-vertical { - /* height: calc(100% - 54px); */ - height: calc(100% - 69px); - margin-top: 4px; + /* height: calc(100% - 54px); */ + height: calc(100% - 69px); + margin-top: 4px; } .response-options-tab-panel, .response-options-tab-panel-vertical { - overflow: auto; + overflow: auto; } .res-hidden { - display: none; - height: calc(100% - 10px); + display: none; + height: calc(100% - 10px); } .res-visible { - display: block; - height: calc(100% - 10px); + display: block; + height: calc(100% - 10px); } .res-visible-inside { - display: block; - height: calc(100% - 1px); -} \ No newline at end of file + display: block; + height: calc(100% - 1px); +} diff --git a/src/fetch-client-ui/components/ResponseUI/redux/actions.ts b/src/fetch-client-ui/components/ResponseUI/redux/actions.ts index a0ee01b..536aa15 100644 --- a/src/fetch-client-ui/components/ResponseUI/redux/actions.ts +++ b/src/fetch-client-ui/components/ResponseUI/redux/actions.ts @@ -1,53 +1,53 @@ import { ITableData } from "../../Common/Table/types"; import { - FETCH_CLIENT_SET_LOADING, - FETCH_CLIENT_SET_RES_COOKIES, FETCH_CLIENT_SET_RES_HEADERS, FETCH_CLIENT_SET_RES_RESPONSE, - FETCH_CLIENT_SET_TEST_RESULT, - IResponse, ITestResult, ResponseActionTypes + FETCH_CLIENT_SET_LOADING, + FETCH_CLIENT_SET_RES_COOKIES, FETCH_CLIENT_SET_RES_HEADERS, FETCH_CLIENT_SET_RES_RESPONSE, + FETCH_CLIENT_SET_TEST_RESULT, + IResponse, ITestResult, ResponseActionTypes } from "./types"; export const SetResponseAction = (value: IResponse): ResponseActionTypes => { - return { - type: FETCH_CLIENT_SET_RES_RESPONSE, - payload: { - response: value - } - }; + return { + type: FETCH_CLIENT_SET_RES_RESPONSE, + payload: { + response: value + } + }; }; export const SetResponseHeadersAction = (value: ITableData[]): ResponseActionTypes => { - return { - type: FETCH_CLIENT_SET_RES_HEADERS, - payload: { - headers: value - } - }; + return { + type: FETCH_CLIENT_SET_RES_HEADERS, + payload: { + headers: value + } + }; }; export const SetResponseCookiesAction = (value: ITableData[]): ResponseActionTypes => { - return { - type: FETCH_CLIENT_SET_RES_COOKIES, - payload: { - cookies: value - } - }; + return { + type: FETCH_CLIENT_SET_RES_COOKIES, + payload: { + cookies: value + } + }; }; export const SetResponseLoadingAction = (value: boolean): ResponseActionTypes => { - return { - type: FETCH_CLIENT_SET_LOADING, - payload: { - loading: value - } - }; + return { + type: FETCH_CLIENT_SET_LOADING, + payload: { + loading: value + } + }; }; export const SetTestResultAction = (value: ITestResult[]): ResponseActionTypes => { - return { - type: FETCH_CLIENT_SET_TEST_RESULT, - payload: { - testResults: value - } - }; -}; \ No newline at end of file + return { + type: FETCH_CLIENT_SET_TEST_RESULT, + payload: { + testResults: value + } + }; +}; diff --git a/src/fetch-client-ui/components/ResponseUI/redux/index.ts b/src/fetch-client-ui/components/ResponseUI/redux/index.ts index 1c93c88..e85f025 100644 --- a/src/fetch-client-ui/components/ResponseUI/redux/index.ts +++ b/src/fetch-client-ui/components/ResponseUI/redux/index.ts @@ -3,6 +3,7 @@ import { ResponseReducer } from "./reducer"; export { - ResponseActions, - ResponseReducer + ResponseActions, + ResponseReducer }; + diff --git a/src/fetch-client-ui/components/ResponseUI/redux/reducer.ts b/src/fetch-client-ui/components/ResponseUI/redux/reducer.ts index 390f722..b0373d3 100644 --- a/src/fetch-client-ui/components/ResponseUI/redux/reducer.ts +++ b/src/fetch-client-ui/components/ResponseUI/redux/reducer.ts @@ -1,73 +1,73 @@ import { responseType } from "../OptionsPanel/Options/Response/consts"; import { - FETCH_CLIENT_SET_LOADING, - FETCH_CLIENT_SET_RES_COOKIES, FETCH_CLIENT_SET_RES_HEADERS, FETCH_CLIENT_SET_RES_RESPONSE, - FETCH_CLIENT_SET_TEST_RESULT, - IReponseModel, IResponse, ResponseActionTypes + FETCH_CLIENT_SET_LOADING, + FETCH_CLIENT_SET_RES_COOKIES, FETCH_CLIENT_SET_RES_HEADERS, FETCH_CLIENT_SET_RES_RESPONSE, + FETCH_CLIENT_SET_TEST_RESULT, + IReponseModel, IResponse, ResponseActionTypes } from "./types"; export const InitialResponse: IResponse = { - responseData: "", - responseType: { - isBinaryFile: false, - format: responseType[1].value - }, - status: 0, - statusText: "", - size: "", - duration: 0, - isError: false, + responseData: "", + responseType: { + isBinaryFile: false, + format: responseType[1].value + }, + status: 0, + statusText: "", + size: "", + duration: 0, + isError: false, }; export const InitialState: IReponseModel = { - response: InitialResponse, - headers: [], - cookies: [], - loading: false, - testResults: [] + response: InitialResponse, + headers: [], + cookies: [], + loading: false, + testResults: [] }; export const ResponseReducer: (state?: IReponseModel, - action?: ResponseActionTypes) => IReponseModel = - (state: IReponseModel = InitialState, - action: ResponseActionTypes = {} as ResponseActionTypes): IReponseModel => { - switch (action.type) { - case FETCH_CLIENT_SET_RES_RESPONSE: { - return { - ...state, - response: action.payload.response, - loading: false - }; - } - case FETCH_CLIENT_SET_RES_HEADERS: { - return { - ...state, - headers: action.payload.headers, - }; - } - case FETCH_CLIENT_SET_RES_COOKIES: { - return { - ...state, - cookies: action.payload.cookies, - }; - } - case FETCH_CLIENT_SET_LOADING: { - return { - ...state, - loading: action.payload.loading, - response: action.payload.loading === true ? InitialResponse : state.response, - }; - } - case FETCH_CLIENT_SET_TEST_RESULT: { - return { - ...state, - testResults: action.payload.testResults, - }; - } - default: { - return state; - } - } - }; + action?: ResponseActionTypes) => IReponseModel = + (state: IReponseModel = InitialState, + action: ResponseActionTypes = {} as ResponseActionTypes): IReponseModel => { + switch (action.type) { + case FETCH_CLIENT_SET_RES_RESPONSE: { + return { + ...state, + response: action.payload.response, + loading: false + }; + } + case FETCH_CLIENT_SET_RES_HEADERS: { + return { + ...state, + headers: action.payload.headers, + }; + } + case FETCH_CLIENT_SET_RES_COOKIES: { + return { + ...state, + cookies: action.payload.cookies, + }; + } + case FETCH_CLIENT_SET_LOADING: { + return { + ...state, + loading: action.payload.loading, + response: action.payload.loading === true ? InitialResponse : state.response, + }; + } + case FETCH_CLIENT_SET_TEST_RESULT: { + return { + ...state, + testResults: action.payload.testResults, + }; + } + default: { + return state; + } + } + }; diff --git a/src/fetch-client-ui/components/ResponseUI/redux/types.ts b/src/fetch-client-ui/components/ResponseUI/redux/types.ts index 6c36768..0b4eb92 100644 --- a/src/fetch-client-ui/components/ResponseUI/redux/types.ts +++ b/src/fetch-client-ui/components/ResponseUI/redux/types.ts @@ -1,30 +1,30 @@ import { ITableData } from "../../Common/Table/types"; export interface IResponse { - duration: number; - isError: boolean; - responseData: any; - responseType?: { - isBinaryFile: boolean; - format: string; - } - size: string; - status: number; - statusText: string; + duration: number; + isError: boolean; + responseData: any; + responseType?: { + isBinaryFile: boolean; + format: string; + } + size: string; + status: number; + statusText: string; } export interface ITestResult { - test: string; - actualValue: string; - result: boolean; + test: string; + actualValue: string; + result: boolean; } export interface IReponseModel { - response: IResponse; - headers: ITableData[]; - cookies: ITableData[]; - loading?: boolean; - testResults?: ITestResult[]; + response: IResponse; + headers: ITableData[]; + cookies: ITableData[]; + loading?: boolean; + testResults?: ITestResult[]; } export const FETCH_CLIENT_SET_RES_RESPONSE: "FETCH_CLIENT_SET_RES_RESPONSE" = "FETCH_CLIENT_SET_RES_RESPONSE"; @@ -35,38 +35,38 @@ export const FETCH_CLIENT_SET_LOADING: "FETCH_CLIENT_SET_LOADING" = "FETCH_CLIEN export const FETCH_CLIENT_SET_TEST_RESULT: "FETCH_CLIENT_SET_TEST_RESULT" = "FETCH_CLIENT_SET_TEST_RESULT"; export interface ISetResponse { - type: typeof FETCH_CLIENT_SET_RES_RESPONSE; - payload: { - response: IResponse; - }; + type: typeof FETCH_CLIENT_SET_RES_RESPONSE; + payload: { + response: IResponse; + }; } export interface ISetHeaders { - type: typeof FETCH_CLIENT_SET_RES_HEADERS; - payload: { - headers: ITableData[]; - }; + type: typeof FETCH_CLIENT_SET_RES_HEADERS; + payload: { + headers: ITableData[]; + }; } export interface ISetCookies { - type: typeof FETCH_CLIENT_SET_RES_COOKIES; - payload: { - cookies: ITableData[]; - }; + type: typeof FETCH_CLIENT_SET_RES_COOKIES; + payload: { + cookies: ITableData[]; + }; } export interface ISetLoading { - type: typeof FETCH_CLIENT_SET_LOADING; - payload: { - loading: boolean; - }; + type: typeof FETCH_CLIENT_SET_LOADING; + payload: { + loading: boolean; + }; } export interface ISetTestResult { - type: typeof FETCH_CLIENT_SET_TEST_RESULT; - payload: { - testResults: ITestResult[]; - }; + type: typeof FETCH_CLIENT_SET_TEST_RESULT; + payload: { + testResults: ITestResult[]; + }; } -export type ResponseActionTypes = | ISetResponse | ISetHeaders | ISetCookies | ISetLoading | ISetTestResult; \ No newline at end of file +export type ResponseActionTypes = | ISetResponse | ISetHeaders | ISetCookies | ISetLoading | ISetTestResult; diff --git a/src/fetch-client-ui/components/SideBar/Collection/index.tsx b/src/fetch-client-ui/components/SideBar/Collection/index.tsx index 69deac8..56aca6d 100644 --- a/src/fetch-client-ui/components/SideBar/Collection/index.tsx +++ b/src/fetch-client-ui/components/SideBar/Collection/index.tsx @@ -16,603 +16,629 @@ import { getDays, getMethodClassName, getMethodName, isFolder } from "../util"; import "./style.css"; export interface ICollectionProps { - filterCondition: string; - isLoading: boolean; - selectedItem: { - colId: string; - foldId: string; - itemId: string; - } + filterCondition: string; + isLoading: boolean; + selectedItem: { + colId: string; + foldId: string; + itemId: string; + }, + sort: number; } export const CollectionBar = (props: ICollectionProps) => { - const { collections, variable } = useSelector((state: IRootState) => state.sideBarData); - const { theme } = useSelector((state: IRootState) => state.uiData); - - const [selectedItem, setSelectedItem] = useState(""); - - const moreHeadMenuWrapperRef = useRef({}); - const [currentHeadIndex, _setCurrentHeadIndex] = useState(""); - - const refHeadIndex = useRef(currentHeadIndex); - const setCurrentHeadIndex = (data: string) => { - refHeadIndex.current = data; - _setCurrentHeadIndex(refHeadIndex.current); - }; - - const moreMenuWrapperRef = useRef({}); - const [currentIndex, _setCurrentIndex] = useState(""); - - const refIndex = useRef(currentIndex); - const setCurrentIndex = (data: string) => { - refIndex.current = data; - _setCurrentIndex(refIndex.current); - }; - - const [ddPosition, setPosition] = useState(""); - - const [isCopied, setCopy] = useState(false); - - const styles = { - bottomStyle: { - bottom: ddPosition - } as React.CSSProperties, - }; - - useEffect(() => { - document.addEventListener("mousedown", handleClickOutside, false); - - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.copyItemResponse) { - setCopy(true); - } else if (event.data && event.data.type === responseTypes.pasteItemResponse) { - setCopy(false); - } - }); - - document.addEventListener("keydown", function (e) { - e.stopPropagation(); - if (e.key === 'Escape' && (refIndex.current || refHeadIndex.current)) { - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - }); - - return () => { - document.removeEventListener("mousedown", handleClickOutside, false); - }; - }, []); - - function openMoreMenu(e: any, id: string, isSub: boolean = false) { - e.preventDefault(); - e.stopPropagation(); - openContextMenu(id, isSub); - } - - function openContextMenu(id: string, isSub: boolean) { - if (isSub) { - if (currentIndex === id) { - setCurrentIndex(""); - return; - } - } else { - if (currentHeadIndex === id) { - setCurrentHeadIndex(""); - return; - } - } - - let element = document.getElementById("three-dots-" + id); - if (element) { - let rect = element.getBoundingClientRect(); - let viewportHeight = window.innerHeight; - let total = rect.top + 100; - if (total > viewportHeight) { - setPosition("100%"); - } else { - setPosition(""); - } - } - if (isSub) { - setCurrentIndex(id); - } else { - setCurrentHeadIndex(id); - } - } - - function onRenameCollection(evt: React.MouseEvent, id: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.renameCollectionRequest, data: id }); - setCurrentHeadIndex(""); - } - - function onDeleteCollection(evt: React.MouseEvent, id: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.deleteCollectionRequest, data: id, name: name }); - setCurrentHeadIndex(""); - } - - function onRename(evt: React.MouseEvent, colId: string, historyId: string, folderId: string, isFolder: boolean) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.renameCollectionItemRequest, data: { colId: colId, historyId: historyId, folderId: folderId, isFolder: isFolder } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onCopy(evt: React.MouseEvent, history: IHistory) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.copyItemRequest, data: { history: history } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onPaste(evt: React.MouseEvent, colId: string, folderData: IFolder, isFolder: boolean) { - evt.preventDefault(); - evt.stopPropagation(); - - let folder: IFolder; - - if (isFolder) { - folder = { - id: folderData.id, - name: folderData.name, - createdTime: folderData.createdTime, - type: "folder", - data: [], - settings: folderData.settings ? folderData.settings : InitialSettings - }; - } - - let collection: ICollections = { - id: colId, - createdTime: formatDate(), - name: "Copy", - data: isFolder ? [folder] : [], - variableId: "", - settings: InitialSettings - }; - - vscode.postMessage({ type: requestTypes.pasteItemRequest, data: { col: collection, isFolder: isFolder } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onDelete(evt: React.MouseEvent, colId: string, folderId: string, historyId: string, isFolder: boolean, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.deleteCollectionItemRequest, data: { colId: colId, folderId: folderId, historyId: historyId, isFolder: isFolder, name: name } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onDuplicate(evt: React.MouseEvent, coldId: string, folderId: string, historyId: string, isFolder: boolean) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.duplicateCollectionsRequest, data: { coldId: coldId, folderId: folderId, historyId: historyId, isFolder: isFolder } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onExport(evt: React.MouseEvent, colId: string, hisId: string, folderId: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.exportRequest, data: { colId: colId, hisId: hisId, folderId: folderId, name: name } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onSettings(evt: React.MouseEvent, colId: string, folderId: string, type: string, name: string, varId: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.openColSettingsRequest, data: { colId: colId, folderId: folderId, type: type, name: name, varId: varId } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onAttach(evt: React.MouseEvent, cols: ICollections) { - evt.preventDefault(); - evt.stopPropagation(); - if (!cols.variableId) { - vscode.postMessage({ type: requestTypes.attachVariableRequest, data: { id: cols.id, name: cols.name } }); - } else { - vscode.postMessage({ type: requestTypes.removeVariableRequest, data: { id: cols.id, name: cols.name } }); - } - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onCopyTo(evt: React.MouseEvent, cols: ICollections) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.copyToCollectionsRequest, data: { id: cols.id, name: cols.name.toUpperCase().trim() === "DEFAULT" ? "Default Copy" : cols.name } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function onClear(evt: React.MouseEvent, colId: string, folderId: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.clearRequest, data: { colId: colId, folderId: folderId, name: name } }); - setCurrentHeadIndex(""); - } - - function onClickHistory(evt: React.MouseEvent, colId: string, folderId: string, itemId: string, name: string, variableId: string) { - evt.preventDefault(); - evt.stopPropagation(); - openItem(colId, folderId, itemId, name, variableId, evt.ctrlKey ? true : false); - } - - function onClickNewTab(evt: React.MouseEvent, colId: string, folderId: string, itemId: string, name: string, variableId: string) { - evt.preventDefault(); - evt.stopPropagation(); - openItem(colId, folderId, itemId, name, variableId, true); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function openItem(colId: string, folderId: string, itemId: string, name: string, variableId: string, isNewTab: boolean) { - setSelectedItem(itemId); - vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { colId: colId, folderId: folderId, id: itemId, name: name, varId: variableId, isNewTab: isNewTab } }); - } - - function onRunClick(evt: React.MouseEvent, colId: string, folderId: string, itemId: string, name: string, variableId: string) { - evt.preventDefault(); - evt.stopPropagation(); - setSelectedItem(itemId); - vscode.postMessage({ type: requestTypes.openAndRunItemRequest, data: { colId: colId, folderId: folderId, id: itemId, name: name, varId: variableId, isNewTab: false } }); - setCurrentIndex(""); - setCurrentHeadIndex(""); - } - - function findData(source: any, dest: any) { - let folders = source.data.filter((item: any) => item.data !== undefined); - let histories = source.data.filter((item: any) => item.data === undefined); - - let filteredData = histories?.filter((history: any) => - history.name?.toLowerCase().includes(props.filterCondition) - || history.url?.toLowerCase().includes(props.filterCondition) - || history.method?.toLowerCase().includes(props.filterCondition) - || history.createdTime?.toLowerCase().includes(props.filterCondition) - ); - - if (filteredData?.length > 0) { - dest.data = filteredData; - } else { - dest.data = []; - } - - if (folders.length === 0) { - return dest; - } - - for (let i = 0; i < folders.length; i++) { - let result = findData(folders[i], JSON.parse(JSON.stringify(folders[i]))); - if (result.data.length > 0) { - dest.data = dest.data.concat(result); - } - } - - return dest; - } - - function filterCollections(cols: ICollections[]) { - let filCol: ICollections[] = []; - - for (let i = 0; i < cols.length; i++) { - let result = findData(cols[i], JSON.parse(JSON.stringify(cols[i]))); - if (result.data.length > 0) { - filCol.push(result); - } - } - - return filCol; - } - - - function getCollectionBody() { - if (props.filterCondition) { - return ( - filterCollections(collections) - .map((col, index) => { - return getCollectionItems(col, index); - }) - ); - } else { - return ( - collections.map((col, index) => { - return getCollectionItems(col, index); - }) - ); - } - } - - function getVariableName(varId: string, isFolder: boolean = false) { - const varItem = variable.find(item => item.id === varId); - return
- -
; - } - - function onRunAll(evt: React.MouseEvent, colId: string, folderId: string, name: string, varId: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.runAllUIOpenRequest, data: { colId: colId, folderId: folderId, name: name, varId: varId } }); - setCurrentHeadIndex(""); - } - - function addNewRequest(evt: React.MouseEvent | React.MouseEvent, colId: string, folderId: string) { - evt.preventDefault(); - evt.stopPropagation(); - let newReq: IRequestModel = InitialState; - newReq.id = uuidv4(); - newReq.name = "New Request"; - newReq.url = "localhost"; - newReq.createdTime = formatDate(); - vscode.postMessage({ type: requestTypes.createNewRequest, data: { request: newReq, colId: colId, folderId: folderId } }); - setCurrentHeadIndex(""); - } - - function addNewFolder(evt: React.MouseEvent, colId: string, folderId: string) { - evt.preventDefault(); - evt.stopPropagation(); - let newFolder: IFolder = { - id: uuidv4(), - name: "New Folder", - type: "folder", - createdTime: formatDate(), - data: [], - settings: InitialSettings - }; - - newFolder.settings.auth.authType = "inherit"; - - vscode.postMessage({ type: requestTypes.createNewFolderRequest, data: { folder: newFolder, colId: colId, folderId: folderId } }); - setCurrentHeadIndex(""); - } - - function onColRightClick(e: any, id: string, isSub: boolean = false) { - e.preventDefault(); - e.stopPropagation(); - openContextMenu(id, isSub); - } - - function onItemRightClick(e: any, id: string, isSub: boolean = false) { - e.preventDefault(); - e.stopPropagation(); - openContextMenu(id, isSub); - } - - function getPaddingLeft(level: number) { - const paddingStyle = { - "--b-pl": ((level + 1) * 5) + "px", - "--pl": ((level * 5) + 40) + "px", - "--fpl": (((level + 2) * 5) + 2) + "px", - }; - - return paddingStyle as React.CSSProperties; - } - - useEffect(() => { - setSelectedItem(props.selectedItem.itemId); - if (props.selectedItem.foldId) { - let ele = document.getElementById("folder-" + props.selectedItem.foldId); - if (ele) { - ele.setAttribute("open", "true"); - } - } - - if (props.selectedItem.colId) { - let ele = document.getElementById("collections-" + props.selectedItem.colId); - if (ele) { - ele.setAttribute("open", "true"); - } - } - - if (props.selectedItem.itemId) { - let itemElement = document.getElementById("col-activity-item-" + props.selectedItem.itemId); - let srollPanel = document.querySelector(".activity-items-panel"); - if (itemElement && srollPanel) { - srollPanel.scroll(0, itemElement.offsetTop - 130); - } - } - }, [props.selectedItem]); - - function getThemeColor() { - if (theme === 1) { - return "light-theme-boder"; - } - - return "dark-theme-boder"; - } - - function getFolderItems(cols: ICollections, item: IFolder, variableId: string, level: number) { - return ( -
- onColRightClick(e, item.id)}> -
{item.name}
-
moreHeadMenuWrapperRef.current[item.id] = el}> - {getPlusIconSVG("New Request", "add-req-button", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => addNewRequest(e, cols.id, item.id))} - {getColFolDotMenu("three-dots-" + item.id, "Folder Menu", "col-fol-icon", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => openMoreMenu(e, item.id))} - -
-
{ e.stopPropagation(); e.preventDefault(); }} onContextMenu={(e) => { e.stopPropagation(); e.preventDefault(); }}> New -
- - -
-
-
- -
- - - - {isCopied && } - -
- - -
-
-
- { - <> - { - item.data && item.data.length > 0 && item.data.map((listItem) => { - if (isFolder(listItem)) { - return getFolderItems(cols, (listItem as IFolder), cols.variableId, level + 1); - } - }) - } - { - item.data && item.data.length > 0 && item.data.map((listItem) => { - if (!isFolder(listItem)) { - return (
onItemRightClick(e, listItem.id, true)} onClick={(e) => onClickHistory(e, cols.id, item.id, listItem.id, listItem.name, variableId)}> -
- - -
- {getVariableName(variableId)} -
- -
moreMenuWrapperRef.current[listItem.id] = el}> - { e.stopPropagation(); e.preventDefault(); }} onClick={(e) => openMoreMenu(e, listItem.id, true)} /> - -
- - -
- - - - -
- -
-
-
-
); - } - }) - } - - } -
- ); - } - - function getCollectionItems(item: ICollections, index: number) { - return ( -
- onColRightClick(e, item.id)} > -
{item.name}
-
moreHeadMenuWrapperRef.current[item.id] = el}> - {getPlusIconSVG("New Request", "add-req-button", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => addNewRequest(e, item.id, ""))} - {getColFolDotMenu("three-dots-" + item.id, "collection Menu", "col-fol-icon", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => openMoreMenu(e, item.id))} - -
-
{ e.stopPropagation(); e.preventDefault(); }} onContextMenu={(e) => { e.stopPropagation(); e.preventDefault(); }}> New -
- - -
-
-
- - {index !== 0 &&
} - {index !== 0 && <> - } - -
- - {isCopied && } - - -
- - -
-
-
-
- { - <> - { - item.data && item.data.length > 0 && item.data.map((listItem) => { - if (isFolder(listItem)) { - return getFolderItems(item, (listItem as IFolder), item.variableId, 0); - } - }) - } - { - item.data && item.data.length > 0 && item.data.map((listItem) => { - if (!isFolder(listItem)) { - return ( -
onItemRightClick(e, listItem.id, true)} onClick={(e) => onClickHistory(e, item.id, "", listItem.id, listItem.name, item.variableId)}> -
- - -
- {getVariableName(item.variableId)} -
- -
moreMenuWrapperRef.current[listItem.id] = el}> - { e.stopPropagation(); e.preventDefault(); }} onClick={(e) => openMoreMenu(e, listItem.id, true)} /> - -
- - -
- - - - -
- -
-
-
-
- ); - } - }) - } - - } -
-
- ); - } - - function handleClickOutside(evt: any) { - if (moreHeadMenuWrapperRef.current && moreHeadMenuWrapperRef.current[refHeadIndex.current] && !moreHeadMenuWrapperRef.current[refHeadIndex.current].contains(evt.target)) { - setCurrentHeadIndex(""); - } - - if (moreMenuWrapperRef.current && moreMenuWrapperRef.current[refIndex.current] && !moreMenuWrapperRef.current[refIndex.current].contains(evt.target)) { - setCurrentIndex(""); - } - } - - return ( - <> - { - props.isLoading ? - <> -
-
{"Loading...."}
- - : - collections.length > 0 ? - getCollectionBody() - : -
{"No Collections Available"}
- } - - ); -}; \ No newline at end of file + const { collections, variable } = useSelector((state: IRootState) => state.sideBarData); + const { theme } = useSelector((state: IRootState) => state.uiData); + + const [selectedItem, setSelectedItem] = useState(""); + + const moreHeadMenuWrapperRef = useRef({}); + const [currentHeadIndex, _setCurrentHeadIndex] = useState(""); + + const refHeadIndex = useRef(currentHeadIndex); + const setCurrentHeadIndex = (data: string) => { + refHeadIndex.current = data; + _setCurrentHeadIndex(refHeadIndex.current); + }; + + const moreMenuWrapperRef = useRef({}); + const [currentIndex, _setCurrentIndex] = useState(""); + + const refIndex = useRef(currentIndex); + const setCurrentIndex = (data: string) => { + refIndex.current = data; + _setCurrentIndex(refIndex.current); + }; + + const [ddPosition, setPosition] = useState(""); + + const [isCopied, setCopy] = useState(false); + + const styles = { + bottomStyle: { + bottom: ddPosition + } as React.CSSProperties, + }; + + useEffect(() => { + document.addEventListener("mousedown", handleClickOutside, false); + + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.copyItemResponse) { + setCopy(true); + } else if (event.data && event.data.type === responseTypes.pasteItemResponse) { + setCopy(false); + } + }); + + document.addEventListener("keydown", function (e) { + e.stopPropagation(); + if (e.key === 'Escape' && (refIndex.current || refHeadIndex.current)) { + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + }); + + return () => { + document.removeEventListener("mousedown", handleClickOutside, false); + }; + }, []); + + const [colState, _setColState] = useState(collections); + const refCol = useRef(colState); + const setColState = (data: ICollections[]) => { + refCol.current = data; + _setColState(refCol.current); + }; + + useEffect(() => { + if (props.sort === 0) { + setColState(collections); + } else if (props.sort === 1) { + if (colState?.length > 0) { + setColState([...collections].sort((a, b) => b.name !== "Default" && a.name.localeCompare(b.name))); + } + } else { + if (colState?.length > 0) { + setColState([...collections].sort((a, b) => b.name !== "Default" && b.name.localeCompare(a.name))); + } + } + }, [props.sort, collections, collections.length]); + + function openMoreMenu(e: any, id: string, isSub: boolean = false) { + e.preventDefault(); + e.stopPropagation(); + openContextMenu(id, isSub); + } + + function openContextMenu(id: string, isSub: boolean) { + if (isSub) { + if (currentIndex === id) { + setCurrentIndex(""); + return; + } + } else { + if (currentHeadIndex === id) { + setCurrentHeadIndex(""); + return; + } + } + + let element = document.getElementById("three-dots-" + id); + if (element) { + let rect = element.getBoundingClientRect(); + let viewportHeight = window.innerHeight; + let total = rect.top + 100; + if (total > viewportHeight) { + setPosition("100%"); + } else { + setPosition(""); + } + } + if (isSub) { + setCurrentIndex(id); + } else { + setCurrentHeadIndex(id); + } + } + + function onRenameCollection(evt: React.MouseEvent, id: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.renameCollectionRequest, data: id }); + setCurrentHeadIndex(""); + } + + function onDeleteCollection(evt: React.MouseEvent, id: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.deleteCollectionRequest, data: id, name: name }); + setCurrentHeadIndex(""); + } + + function onRename(evt: React.MouseEvent, colId: string, historyId: string, folderId: string, isFolder: boolean) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.renameCollectionItemRequest, data: { colId: colId, historyId: historyId, folderId: folderId, isFolder: isFolder } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onCopy(evt: React.MouseEvent, history: IHistory) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.copyItemRequest, data: { history: history } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onPaste(evt: React.MouseEvent, colId: string, folderData: IFolder, isFolder: boolean) { + evt.preventDefault(); + evt.stopPropagation(); + + let folder: IFolder; + + if (isFolder) { + folder = { + id: folderData.id, + name: folderData.name, + createdTime: folderData.createdTime, + type: "folder", + data: [], + settings: folderData.settings ? folderData.settings : InitialSettings + }; + } + + let collection: ICollections = { + id: colId, + createdTime: formatDate(), + name: "Copy", + data: isFolder ? [folder] : [], + variableId: "", + settings: InitialSettings + }; + + vscode.postMessage({ type: requestTypes.pasteItemRequest, data: { col: collection, isFolder: isFolder } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onDelete(evt: React.MouseEvent, colId: string, folderId: string, historyId: string, isFolder: boolean, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.deleteCollectionItemRequest, data: { colId: colId, folderId: folderId, historyId: historyId, isFolder: isFolder, name: name } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onDuplicate(evt: React.MouseEvent, coldId: string, folderId: string, historyId: string, isFolder: boolean) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.duplicateCollectionsRequest, data: { coldId: coldId, folderId: folderId, historyId: historyId, isFolder: isFolder } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onExport(evt: React.MouseEvent, colId: string, hisId: string, folderId: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.exportRequest, data: { colId: colId, hisId: hisId, folderId: folderId, name: name } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onSettings(evt: React.MouseEvent, colId: string, folderId: string, type: string, name: string, varId: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.openColSettingsRequest, data: { colId: colId, folderId: folderId, type: type, name: name, varId: varId } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onAttach(evt: React.MouseEvent, cols: ICollections) { + evt.preventDefault(); + evt.stopPropagation(); + if (!cols.variableId) { + vscode.postMessage({ type: requestTypes.attachVariableRequest, data: { id: cols.id, name: cols.name } }); + } else { + vscode.postMessage({ type: requestTypes.removeVariableRequest, data: { id: cols.id, name: cols.name } }); + } + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onCopyTo(evt: React.MouseEvent, cols: ICollections) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.copyToCollectionsRequest, data: { id: cols.id, name: cols.name.toUpperCase().trim() === "DEFAULT" ? "Default Copy" : cols.name } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function onClear(evt: React.MouseEvent, colId: string, folderId: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.clearRequest, data: { colId: colId, folderId: folderId, name: name } }); + setCurrentHeadIndex(""); + } + + function onClickHistory(evt: React.MouseEvent, colId: string, folderId: string, itemId: string, name: string, variableId: string) { + evt.preventDefault(); + evt.stopPropagation(); + openItem(colId, folderId, itemId, name, variableId, evt.ctrlKey ? true : false); + } + + function onClickNewTab(evt: React.MouseEvent, colId: string, folderId: string, itemId: string, name: string, variableId: string) { + evt.preventDefault(); + evt.stopPropagation(); + openItem(colId, folderId, itemId, name, variableId, true); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function openItem(colId: string, folderId: string, itemId: string, name: string, variableId: string, isNewTab: boolean) { + setSelectedItem(itemId); + vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { colId: colId, folderId: folderId, id: itemId, name: name, varId: variableId, isNewTab: isNewTab } }); + } + + function onRunClick(evt: React.MouseEvent, colId: string, folderId: string, itemId: string, name: string, variableId: string) { + evt.preventDefault(); + evt.stopPropagation(); + setSelectedItem(itemId); + vscode.postMessage({ type: requestTypes.openAndRunItemRequest, data: { colId: colId, folderId: folderId, id: itemId, name: name, varId: variableId, isNewTab: false } }); + setCurrentIndex(""); + setCurrentHeadIndex(""); + } + + function findData(source: any, dest: any) { + let folders = source.data.filter((item: any) => item.data !== undefined); + let histories = source.data.filter((item: any) => item.data === undefined); + + let filteredData = histories?.filter((history: any) => + history.name?.toLowerCase().includes(props.filterCondition) + || history.url?.toLowerCase().includes(props.filterCondition) + || history.method?.toLowerCase().includes(props.filterCondition) + || history.createdTime?.toLowerCase().includes(props.filterCondition) + ); + + if (filteredData?.length > 0) { + dest.data = filteredData; + } else { + dest.data = []; + } + + if (folders.length === 0) { + return dest; + } + + for (let i = 0; i < folders.length; i++) { + let result = findData(folders[i], JSON.parse(JSON.stringify(folders[i]))); + if (result.data.length > 0) { + dest.data = dest.data.concat(result); + } + } + + return dest; + } + + function filterCollections(cols: ICollections[]) { + let filCol: ICollections[] = []; + + for (let i = 0; i < cols.length; i++) { + let result = findData(cols[i], JSON.parse(JSON.stringify(cols[i]))); + if (result.data.length > 0) { + filCol.push(result); + } + } + + return filCol; + } + + + function getCollectionBody() { + if (props.filterCondition) { + return ( + filterCollections(colState) + .map((col, index) => { + return getCollectionItems(col, index); + }) + ); + } else { + return ( + colState.map((col, index) => { + return getCollectionItems(col, index); + }) + ); + } + } + + function getVariableName(varId: string, isFolder: boolean = false) { + const varItem = variable.find(item => item.id === varId); + return
+ +
; + } + + function onRunAll(evt: React.MouseEvent, colId: string, folderId: string, name: string, varId: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.runAllUIOpenRequest, data: { colId: colId, folderId: folderId, name: name, varId: varId } }); + setCurrentHeadIndex(""); + } + + function addNewRequest(evt: React.MouseEvent | React.MouseEvent, colId: string, folderId: string) { + evt.preventDefault(); + evt.stopPropagation(); + let newReq: IRequestModel = InitialState; + newReq.id = uuidv4(); + newReq.name = "New Request"; + newReq.url = "localhost"; + newReq.createdTime = formatDate(); + vscode.postMessage({ type: requestTypes.createNewRequest, data: { request: newReq, colId: colId, folderId: folderId } }); + setCurrentHeadIndex(""); + } + + function addNewFolder(evt: React.MouseEvent, colId: string, folderId: string) { + evt.preventDefault(); + evt.stopPropagation(); + let newFolder: IFolder = { + id: uuidv4(), + name: "New Folder", + type: "folder", + createdTime: formatDate(), + data: [], + settings: InitialSettings + }; + + newFolder.settings.auth.authType = "inherit"; + + vscode.postMessage({ type: requestTypes.createNewFolderRequest, data: { folder: newFolder, colId: colId, folderId: folderId } }); + setCurrentHeadIndex(""); + } + + function onColRightClick(e: any, id: string, isSub: boolean = false) { + e.preventDefault(); + e.stopPropagation(); + openContextMenu(id, isSub); + } + + function onItemRightClick(e: any, id: string, isSub: boolean = false) { + e.preventDefault(); + e.stopPropagation(); + openContextMenu(id, isSub); + } + + function getPaddingLeft(level: number) { + const paddingStyle = { + "--b-pl": ((level + 1) * 5) + "px", + "--pl": ((level * 5) + 40) + "px", + "--fpl": (((level + 2) * 5) + 2) + "px", + }; + + return paddingStyle as React.CSSProperties; + } + + useEffect(() => { + setSelectedItem(props.selectedItem.itemId); + if (props.selectedItem.foldId) { + let ele = document.getElementById("folder-" + props.selectedItem.foldId); + if (ele) { + ele.setAttribute("open", "true"); + } + } + + if (props.selectedItem.colId) { + let ele = document.getElementById("collections-" + props.selectedItem.colId); + if (ele) { + ele.setAttribute("open", "true"); + } + } + + if (props.selectedItem.itemId) { + let itemElement = document.getElementById("col-activity-item-" + props.selectedItem.itemId); + let srollPanel = document.querySelector(".activity-items-panel"); + if (itemElement && srollPanel) { + srollPanel.scroll(0, itemElement.offsetTop - 130); + } + } + }, [props.selectedItem]); + + function getThemeColor() { + if (theme === 1) { + return "light-theme-boder"; + } + + return "dark-theme-boder"; + } + + function getFolderItems(cols: ICollections, item: IFolder, variableId: string, level: number) { + return ( +
+ onColRightClick(e, item.id)}> +
{item.name}
+
moreHeadMenuWrapperRef.current[item.id] = el}> + {getPlusIconSVG("New Request", "add-req-button", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => addNewRequest(e, cols.id, item.id))} + {getColFolDotMenu("three-dots-" + item.id, "Folder Menu", "col-fol-icon", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => openMoreMenu(e, item.id))} + +
+
{ e.stopPropagation(); e.preventDefault(); }} onContextMenu={(e) => { e.stopPropagation(); e.preventDefault(); }}> New +
+ + +
+
+
+ +
+ + + + {isCopied && } + +
+ + +
+
+
+ { + <> + { + item.data && item.data.length > 0 && item.data.map((listItem) => { + if (isFolder(listItem)) { + return getFolderItems(cols, (listItem as IFolder), cols.variableId, level + 1); + } + return <>; + }) + } + { + item.data && item.data.length > 0 && item.data.map((listItem) => { + if (!isFolder(listItem)) { + return (
onItemRightClick(e, listItem.id, true)} onClick={(e) => onClickHistory(e, cols.id, item.id, listItem.id, listItem.name, variableId)}> +
+ + +
+ {getVariableName(variableId)} +
+ +
moreMenuWrapperRef.current[listItem.id] = el}> + { e.stopPropagation(); e.preventDefault(); }} onClick={(e) => openMoreMenu(e, listItem.id, true)} /> + +
+ + +
+ + + + +
+ +
+
+
+
); + } + return <>; + }) + } + + } +
+ ); + } + + function getCollectionItems(item: ICollections, index: number) { + return ( +
+ onColRightClick(e, item.id)} > +
{item.name}
+
moreHeadMenuWrapperRef.current[item.id] = el}> + {getPlusIconSVG("New Request", "add-req-button", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => addNewRequest(e, item.id, ""))} + {getColFolDotMenu("three-dots-" + item.id, "collection Menu", "col-fol-icon", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => openMoreMenu(e, item.id))} + +
+
{ e.stopPropagation(); e.preventDefault(); }} onContextMenu={(e) => { e.stopPropagation(); e.preventDefault(); }}> New +
+ + +
+
+
+ + {index !== 0 &&
} + {index !== 0 && <> + } + +
+ + {isCopied && } + + +
+ + +
+
+
+
+ { + <> + { + item.data && item.data.length > 0 && item.data.map((listItem) => { + if (isFolder(listItem)) { + return getFolderItems(item, (listItem as IFolder), item.variableId, 0); + } + return <>; + }) + } + { + item.data && item.data.length > 0 && item.data.map((listItem) => { + if (!isFolder(listItem)) { + return ( +
onItemRightClick(e, listItem.id, true)} onClick={(e) => onClickHistory(e, item.id, "", listItem.id, listItem.name, item.variableId)}> +
+ + +
+ {getVariableName(item.variableId)} +
+ +
moreMenuWrapperRef.current[listItem.id] = el}> + { e.stopPropagation(); e.preventDefault(); }} onClick={(e) => openMoreMenu(e, listItem.id, true)} /> + +
+ + +
+ + + + +
+ +
+
+
+
+ ); + } + return <>; + }) + } + + } +
+
+ ); + } + + function handleClickOutside(evt: any) { + if (moreHeadMenuWrapperRef.current && moreHeadMenuWrapperRef.current[refHeadIndex.current] && !moreHeadMenuWrapperRef.current[refHeadIndex.current].contains(evt.target)) { + setCurrentHeadIndex(""); + } + + if (moreMenuWrapperRef.current && moreMenuWrapperRef.current[refIndex.current] && !moreMenuWrapperRef.current[refIndex.current].contains(evt.target)) { + setCurrentIndex(""); + } + } + + return ( + <> + { + props.isLoading ? + <> +
+
{"Loading...."}
+ + : + colState.length > 0 ? + getCollectionBody() + : +
{"No Collections Available"}
+ } + + ); +}; diff --git a/src/fetch-client-ui/components/SideBar/Collection/style.css b/src/fetch-client-ui/components/SideBar/Collection/style.css index e204346..260f3a0 100644 --- a/src/fetch-client-ui/components/SideBar/Collection/style.css +++ b/src/fetch-client-ui/components/SideBar/Collection/style.css @@ -1,110 +1,112 @@ summary { - word-break : break-all; - padding : 5px; - cursor : pointer; - position : relative; - padding-left: 15px; - font-size : 14px; + word-break : break-all; + padding : 5px; + cursor : pointer; + position : relative; + padding-left: 15px; + font-size : 14px; } summary::-webkit-details-marker { - display: none; + display: none; } summary:before { - position : absolute; - top : 50%; - transform : translateY(-50%); - background-color: transparent; - color : var(--text-color); - display : inline-flex; - flex-shrink : 0; - left : 0.75rem; + position : absolute; + top : 50%; + transform : translateY(-50%); + background-color: transparent; + color : var(--text-color); + display : inline-flex; + flex-shrink : 0; + left : 0.75rem; } summary:hover { - background-color: var(--vscode-dropdown-border); + background-color: var(--vscode-dropdown-border); } details[open] summary { - background-color: var(--vscode-dropdown-border); + background-color: var(--vscode-dropdown-border); } .collection-items:hover .more-icon, .folder-items:hover .more-icon { - display: block; + display: block; } .collection-items { - padding-right: 0 !important; - min-width : 220px; + padding-right : 0 !important; + min-width : 220px; + padding-top : 8px; + padding-bottom: 9px; } .folder-items { - padding-right: 0 !important; + padding-right: 0 !important; } .divider { - border-top: 0.3pt solid var(--border-color); - margin : 1px 12px 1px 12px; - opacity : .6; + border-top: 0.3pt solid var(--border-color); + margin : 1px 12px 1px 12px; + opacity : .6; } details.folder-details-items>summary { - list-style : none; - padding-left : var(--pl); - background-color: transparent !important; + list-style : none; + padding-left : var(--pl); + background-color: transparent !important; } details.folder-details-items>summary:before { - content : "🗀"; - padding-left: var(--b-pl); - color : var(--text-color); + content : "🗀"; + padding-left: var(--b-pl); + color : var(--text-color); } details[open].folder-details-items>summary:before { - content: "🗁"; - color : var(--text-color); + content: "🗁"; + color : var(--text-color); } details.folder-details-items>summary:hover { - background-color: var(--list-hover-background-color) !important; + background-color: var(--list-hover-background-color) !important; } .add-req-button { - color : currentColor; - fill : currentColor; - transform : scale(0.70); - color : currentColor; - margin-right: 5px; - padding : 0 3px 0 3px; - filter : contrast(0.50); + color : currentColor; + fill : currentColor; + transform : scale(0.70); + color : currentColor; + margin-right: 5px; + padding : 0 3px 0 3px; + filter : contrast(0.50); } .add-req-button:hover { - background-color: var(--list-hover-background-color) !important; - border-radius : 3px; - filter : none; + background-color: var(--list-hover-background-color) !important; + border-radius : 3px; + filter : none; } .col-fol-title { - width : 70%; - display: inline-flex; + width : 70%; + display: inline-flex; } .col-fol-icon-panel { - margin-left: 2px; - text-align : right; + margin-left: 2px; + text-align : right; } .col-fol-icon { - transform: scale(0.75); - padding : 0 3px 0 3px; + transform: scale(0.75); + padding : 0 3px 0 3px; } .col-fol-icon:hover { - background-color: var(--list-hover-background-color); - border-radius : 3px; + background-color: var(--list-hover-background-color); + border-radius : 3px; } details, @@ -117,33 +119,33 @@ summary:hover, summary:focus, summary :focus-visible, summary:focus-within { - outline: none; + outline: none; } .sub-menu { - display: none; + display: none; } .parent-menu:hover .sub-menu { - display: block; - left : -88px; - width : 90px !important; - top : 0; + display: block; + left : -88px; + width : 90px !important; + top : 0; } .parent-menu { - padding : 5px 10px; - text-decoration : none; - cursor : pointer; - background-color: var(--background-color); - color : var(--text-color); - outline : none; - border : 3px solid transparent; - border-radius : 0; - text-align : left; + padding : 5px 10px; + text-decoration : none; + cursor : pointer; + background-color: var(--background-color); + color : var(--text-color); + outline : none; + border : 3px solid transparent; + border-radius : 0; + text-align : left; } .parent-menu:hover { - background-color: var(--button-hover-color); - color : var(--button-text-color); -} \ No newline at end of file + background-color: var(--button-hover-color); + color : var(--button-text-color); +} diff --git a/src/fetch-client-ui/components/SideBar/History/index.tsx b/src/fetch-client-ui/components/SideBar/History/index.tsx index bbf2b9d..ae88ed9 100644 --- a/src/fetch-client-ui/components/SideBar/History/index.tsx +++ b/src/fetch-client-ui/components/SideBar/History/index.tsx @@ -1,6 +1,6 @@ import React, { useEffect, useRef, useState } from "react"; -import { ReactComponent as DotsLogo } from '../../../../../icons/dots.svg'; import { useSelector } from "react-redux"; +import { ReactComponent as DotsLogo } from '../../../../../icons/dots.svg'; import { requestTypes } from "../../../../utils/configuration"; import { IRootState } from "../../../reducer/combineReducer"; import vscode from "../../Common/vscodeAPI"; @@ -9,208 +9,208 @@ import { getDays, getMethodClassName, getMethodName } from "../util"; import "./style.css"; export interface IHistoryProps { - filterCondition: string; - isLoading: boolean; - selectedItem: { - itemId: string; - } + filterCondition: string; + isLoading: boolean; + selectedItem: { + itemId: string; + } } export const HistoryBar = (props: IHistoryProps) => { - const { theme } = useSelector((state: IRootState) => state.uiData); - const { history } = useSelector((state: IRootState) => state.sideBarData); - - const [ddPosition, setPosition] = useState(""); - - const [selectedItem, setSelectedItem] = useState(""); - - const [currentIndex, _setCurrentIndex] = useState(-1); - - useEffect(() => { - setSelectedItem(props.selectedItem.itemId); - }, [props.selectedItem]); - - const refIndex = useRef(currentIndex); - const setCurrentIndex = (data: number) => { - refIndex.current = data; - _setCurrentIndex(refIndex.current); - }; - - const moreMenuWrapperRef = useRef([]); - - const styles = { - bottomStyle: { - bottom: ddPosition - } as React.CSSProperties, - }; - - useEffect(() => { - moreMenuWrapperRef.current = moreMenuWrapperRef.current.slice(0, history.length); - }, [history]); - - function openMoreMenu(evt: any, index: number) { - evt.preventDefault(); - evt.stopPropagation(); - openContextMenu(index); - } - - function openContextMenu(index: number) { - if (currentIndex === index) { - setCurrentIndex(-1); - return; - } - - let element = document.getElementById("three-dots-" + index); - if (element) { - let rect = element.getBoundingClientRect(); - let viewportHeight = window.innerHeight; - let total = rect.top + 100; - if (total > viewportHeight) { - setPosition("100%"); - } else { - setPosition(""); - } - } - setCurrentIndex(index); - } - - function onSaveToCollection(evt: React.MouseEvent, id: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.addToCollectionsRequest, data: id }); - setCurrentIndex(-1); - } - - function onRename(evt: React.MouseEvent, id: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.renameHistoryRequest, data: id }); - setCurrentIndex(-1); - } - - function onDelete(evt: React.MouseEvent, id: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.deleteHistoryRequest, data: id, name: name }); - setCurrentIndex(-1); - } - - function onClickHistory(evt: React.MouseEvent, id: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - openItem(id, name, evt.ctrlKey ? true : false); - } - - function onClickNewTab(evt: React.MouseEvent, id: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - openItem(id, name, true); - setCurrentIndex(-1); - } - - function openItem(id: string, name: string, isNewTab: boolean) { - setSelectedItem(id); - vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { id: id, name: name, isNewTab: isNewTab } }); - } - - function onItemRightClick(e: any, index: number) { - e.preventDefault(); - e.stopPropagation(); - openContextMenu(index); - } - - function onRunClick(evt: React.MouseEvent, itemId: string, name: string) { - evt.preventDefault(); - evt.stopPropagation(); - setSelectedItem(itemId); - vscode.postMessage({ type: requestTypes.openAndRunItemRequest, data: { id: itemId, name: name, isNewTab: false } }); - setCurrentIndex(-1); - } - - function getActivityBody() { - if (props.filterCondition) { - return ( - history - .filter(el => el.name?.toLowerCase().includes(props.filterCondition) - || el.url?.toLowerCase().includes(props.filterCondition) - || el.method?.toLowerCase().includes(props.filterCondition) - || el.createdTime?.toLowerCase().includes(props.filterCondition)) - .map((history, index) => { - return getHistoryItems(history, index); - }) - ); - } else { - return ( - history.map((history, index) => { - return getHistoryItems(history, index); - }) - ); - } - } - - function getThemeColor() { - if (theme === 1) { - return "light-theme-boder"; - } - - return "dark-theme-boder"; - } - - function getHistoryItems(history: IHistory, index: number) { - return ( -
onItemRightClick(e, index)} onClick={(e) => onClickHistory(e, history.id, history.name)}> -
- - -
-
- -
moreMenuWrapperRef.current[index] = el}> - openMoreMenu(e, index)} /> - -
- - -
- - - -
-
-
-
- ); - } - - function handleClickOutside(evt: any) { - if (moreMenuWrapperRef.current && moreMenuWrapperRef.current[refIndex.current] && !moreMenuWrapperRef.current[refIndex.current].contains(evt.target)) { - setCurrentIndex(-1); - } - } - - useEffect(() => { - document.addEventListener("mousedown", handleClickOutside, false); - return () => { - document.removeEventListener("mousedown", handleClickOutside, false); - }; - }, []); - - - return ( - <> - { - props.isLoading ? - <> -
-
{"Loading...."}
- - : - history.length > 0 ? - getActivityBody() - : -
{"No History Available"}
- } - - ); -}; \ No newline at end of file + const { theme } = useSelector((state: IRootState) => state.uiData); + const { history } = useSelector((state: IRootState) => state.sideBarData); + + const [ddPosition, setPosition] = useState(""); + + const [selectedItem, setSelectedItem] = useState(""); + + const [currentIndex, _setCurrentIndex] = useState(-1); + + useEffect(() => { + setSelectedItem(props.selectedItem.itemId); + }, [props.selectedItem]); + + const refIndex = useRef(currentIndex); + const setCurrentIndex = (data: number) => { + refIndex.current = data; + _setCurrentIndex(refIndex.current); + }; + + const moreMenuWrapperRef = useRef([]); + + const styles = { + bottomStyle: { + bottom: ddPosition + } as React.CSSProperties, + }; + + useEffect(() => { + moreMenuWrapperRef.current = moreMenuWrapperRef.current.slice(0, history.length); + }, [history]); + + function openMoreMenu(evt: any, index: number) { + evt.preventDefault(); + evt.stopPropagation(); + openContextMenu(index); + } + + function openContextMenu(index: number) { + if (currentIndex === index) { + setCurrentIndex(-1); + return; + } + + let element = document.getElementById("three-dots-" + index); + if (element) { + let rect = element.getBoundingClientRect(); + let viewportHeight = window.innerHeight; + let total = rect.top + 100; + if (total > viewportHeight) { + setPosition("100%"); + } else { + setPosition(""); + } + } + setCurrentIndex(index); + } + + function onSaveToCollection(evt: React.MouseEvent, id: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.addToCollectionsRequest, data: id }); + setCurrentIndex(-1); + } + + function onRename(evt: React.MouseEvent, id: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.renameHistoryRequest, data: id }); + setCurrentIndex(-1); + } + + function onDelete(evt: React.MouseEvent, id: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.deleteHistoryRequest, data: id, name: name }); + setCurrentIndex(-1); + } + + function onClickHistory(evt: React.MouseEvent, id: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + openItem(id, name, evt.ctrlKey ? true : false); + } + + function onClickNewTab(evt: React.MouseEvent, id: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + openItem(id, name, true); + setCurrentIndex(-1); + } + + function openItem(id: string, name: string, isNewTab: boolean) { + setSelectedItem(id); + vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { id: id, name: name, isNewTab: isNewTab } }); + } + + function onItemRightClick(e: any, index: number) { + e.preventDefault(); + e.stopPropagation(); + openContextMenu(index); + } + + function onRunClick(evt: React.MouseEvent, itemId: string, name: string) { + evt.preventDefault(); + evt.stopPropagation(); + setSelectedItem(itemId); + vscode.postMessage({ type: requestTypes.openAndRunItemRequest, data: { id: itemId, name: name, isNewTab: false } }); + setCurrentIndex(-1); + } + + function getActivityBody() { + if (props.filterCondition) { + return ( + history + .filter(el => el.name?.toLowerCase().includes(props.filterCondition) + || el.url?.toLowerCase().includes(props.filterCondition) + || el.method?.toLowerCase().includes(props.filterCondition) + || el.createdTime?.toLowerCase().includes(props.filterCondition)) + .map((history, index) => { + return getHistoryItems(history, index); + }) + ); + } else { + return ( + history.map((history, index) => { + return getHistoryItems(history, index); + }) + ); + } + } + + function getThemeColor() { + if (theme === 1) { + return "light-theme-boder"; + } + + return "dark-theme-boder"; + } + + function getHistoryItems(history: IHistory, index: number) { + return ( +
onItemRightClick(e, index)} onClick={(e) => onClickHistory(e, history.id, history.name)}> +
+ + +
+
+ +
moreMenuWrapperRef.current[index] = el}> + openMoreMenu(e, index)} /> + +
+ + +
+ + + +
+
+
+
+ ); + } + + function handleClickOutside(evt: any) { + if (moreMenuWrapperRef.current && moreMenuWrapperRef.current[refIndex.current] && !moreMenuWrapperRef.current[refIndex.current].contains(evt.target)) { + setCurrentIndex(-1); + } + } + + useEffect(() => { + document.addEventListener("mousedown", handleClickOutside, false); + return () => { + document.removeEventListener("mousedown", handleClickOutside, false); + }; + }, []); + + + return ( + <> + { + props.isLoading ? + <> +
+
{"Loading...."}
+ + : + history.length > 0 ? + getActivityBody() + : +
{"No History Available"}
+ } + + ); +}; diff --git a/src/fetch-client-ui/components/SideBar/History/style.css b/src/fetch-client-ui/components/SideBar/History/style.css index 0d32f3b..7b354f8 100644 --- a/src/fetch-client-ui/components/SideBar/History/style.css +++ b/src/fetch-client-ui/components/SideBar/History/style.css @@ -1,17 +1,17 @@ .no-history-text { - padding: 40px; - font-size: small; - text-align: center; - color: #808080; + padding: 40px; + font-size: small; + text-align: center; + color: #808080; } .loading-history-text { - position: absolute; - left: calc(50% - 45px); - bottom: 50%; - padding: 10px; - font-size: small; - text-align: center; - color: var(--text-color); - margin-left: 15px; -} \ No newline at end of file + position: absolute; + left: calc(50% - 45px); + bottom: 50%; + padding: 10px; + font-size: small; + text-align: center; + color: var(--text-color); + margin-left: 15px; +} diff --git a/src/fetch-client-ui/components/SideBar/Variables/index.tsx b/src/fetch-client-ui/components/SideBar/Variables/index.tsx index 676befa..608624b 100644 --- a/src/fetch-client-ui/components/SideBar/Variables/index.tsx +++ b/src/fetch-client-ui/components/SideBar/Variables/index.tsx @@ -1,184 +1,203 @@ import React, { useEffect, useRef, useState } from "react"; import { useSelector } from "react-redux"; -import { v4 as uuidv4 } from 'uuid'; -import { IRootState } from "../../../reducer/combineReducer"; import { ReactComponent as DotsLogo } from '../../../../../icons/dots.svg'; -import { IVariable } from "../redux/types"; -import vscode from "../../Common/vscodeAPI"; import { requestTypes } from "../../../../utils/configuration"; +import { IRootState } from "../../../reducer/combineReducer"; +import vscode from "../../Common/vscodeAPI"; +import { IVariable } from "../redux/types"; import "./style.css"; export interface IVariableProps { - filterCondition: string; - isLoading: boolean; + filterCondition: string; + isLoading: boolean; + sort: number; } export const VariableSection = (props: IVariableProps) => { - const { variable } = useSelector((state: IRootState) => state.sideBarData); - - const [ddPosition, setPosition] = useState(""); - - const [selectedItem, setSelectedItem] = useState(""); - - const [currentIndex, _setCurrentIndex] = useState(-1); - - const refIndex = useRef(currentIndex); - const setCurrentIndex = (data: number) => { - refIndex.current = data; - _setCurrentIndex(refIndex.current); - }; - - const moreMenuWrapperRef = useRef([]); - - const styles = { - bottomStyle: { - bottom: ddPosition - } as React.CSSProperties, - }; - - function openMoreMenu(evt: any, index: number) { - evt.preventDefault(); - evt.stopPropagation(); - openContextMenu(index); - } - - function openContextMenu(index: number) { - if (currentIndex === index) { - setCurrentIndex(-1); - return; - } - - let element = document.getElementById("three-dots-" + index); - if (element) { - let rect = element.getBoundingClientRect(); - let viewportHeight = window.innerHeight; - let total = rect.top + 100; - if (total > viewportHeight) { - setPosition("100%"); - } else { - setPosition(""); - } - } - setCurrentIndex(index); - } - - function onRename(evt: React.MouseEvent, id: string) { - performOperation(evt, requestTypes.renameVariableRequest, id); - } - - function onDelete(evt: React.MouseEvent, id: string, name: string) { - performOperation(evt, requestTypes.deleteVariableRequest, id, name); - } - - function onExport(evt: React.MouseEvent, vars: IVariable) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.exportVariableRequest, vars: vars }); - setCurrentIndex(-1); - } - - function onClickItem(evt: React.MouseEvent, id: string) { - setSelectedItem(id); - performOperation(evt, requestTypes.openVariableItemRequest, id); - } - - function performOperation(evt: React.MouseEvent, types: string, id: string, name?: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: types, data: id, name: name }); - setCurrentIndex(-1); - } - - function onActive(evt: React.MouseEvent, id: string, status: boolean) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.activeVariableRequest, data: { id: id, status: status } }); - setCurrentIndex(-1); - } - - function onDuplicate(evt: React.MouseEvent, id: string) { - evt.preventDefault(); - evt.stopPropagation(); - vscode.postMessage({ type: requestTypes.duplicateVariableRequest, id: id }); - setCurrentIndex(-1); - } - - function handleClickOutside(evt: any) { - if (moreMenuWrapperRef.current && moreMenuWrapperRef.current[refIndex.current] && !moreMenuWrapperRef.current[refIndex.current].contains(evt.target)) { - setCurrentIndex(-1); - } - } - - useEffect(() => { - document.addEventListener("mousedown", handleClickOutside, false); - - return () => { - document.removeEventListener("mousedown", handleClickOutside, false); - }; - }, []); - - function onItemRightClick(e: any, index: number) { - e.preventDefault(); - e.stopPropagation(); - openContextMenu(index); - } - - function getVariableItems(item: IVariable, index: number) { - return ( -
onItemRightClick(e, index)} onClick={(e) => onClickItem(e, item.id)}> -
- - {index === 0 && } -
moreMenuWrapperRef.current[index] = el}> - openMoreMenu(e, index)} /> - -
- {index !== 0 && <> - } - -
- {index === 0 && !item.isActive && } - -
-
-
-
- ); - } - - function getVariableBody() { - if (props.filterCondition) { - return ( - variable - .filter(el => el.name?.toLowerCase().includes(props.filterCondition)) - .map((item, index) => { - return getVariableItems(item, index); - }) - ); - } else { - return ( - variable.map((item, index) => { - return getVariableItems(item, index); - }) - ); - } - } - - return ( - <> - { - props.isLoading ? - <> -
-
{"Loading...."}
- - : - history.length > 0 ? - getVariableBody() - : -
{"No Variable Available"}
- } - - ); -}; \ No newline at end of file + const { variable } = useSelector((state: IRootState) => state.sideBarData); + + const [ddPosition, setPosition] = useState(""); + const [selectedItem, setSelectedItem] = useState(""); + const [currentIndex, _setCurrentIndex] = useState(-1); + + const refIndex = useRef(currentIndex); + const setCurrentIndex = (data: number) => { + refIndex.current = data; + _setCurrentIndex(refIndex.current); + }; + + const [variableState, _setVariableState] = useState(variable); + const refVariable = useRef(variableState); + const setVariableState = (data: IVariable[]) => { + refVariable.current = data; + _setVariableState(refVariable.current); + }; + + const moreMenuWrapperRef = useRef([]); + + const styles = { + bottomStyle: { + bottom: ddPosition + } as React.CSSProperties, + }; + + function openMoreMenu(evt: any, index: number) { + evt.preventDefault(); + evt.stopPropagation(); + openContextMenu(index); + } + + function openContextMenu(index: number) { + if (currentIndex === index) { + setCurrentIndex(-1); + return; + } + + let element = document.getElementById("three-dots-" + index); + if (element) { + let rect = element.getBoundingClientRect(); + let viewportHeight = window.innerHeight; + let total = rect.top + 100; + if (total > viewportHeight) { + setPosition("100%"); + } else { + setPosition(""); + } + } + setCurrentIndex(index); + } + + function onRename(evt: React.MouseEvent, id: string) { + performOperation(evt, requestTypes.renameVariableRequest, id); + } + + function onDelete(evt: React.MouseEvent, id: string, name: string) { + performOperation(evt, requestTypes.deleteVariableRequest, id, name); + } + + function onExport(evt: React.MouseEvent, vars: IVariable) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.exportVariableRequest, vars: vars }); + setCurrentIndex(-1); + } + + function onClickItem(evt: React.MouseEvent, id: string) { + setSelectedItem(id); + performOperation(evt, requestTypes.openVariableItemRequest, id); + } + + function performOperation(evt: React.MouseEvent, types: string, id: string, name?: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: types, data: id, name: name }); + setCurrentIndex(-1); + } + + function onActive(evt: React.MouseEvent, id: string, status: boolean) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.activeVariableRequest, data: { id: id, status: status } }); + setCurrentIndex(-1); + } + + function onDuplicate(evt: React.MouseEvent, id: string) { + evt.preventDefault(); + evt.stopPropagation(); + vscode.postMessage({ type: requestTypes.duplicateVariableRequest, id: id }); + setCurrentIndex(-1); + } + + function handleClickOutside(evt: any) { + if (moreMenuWrapperRef.current && moreMenuWrapperRef.current[refIndex.current] && !moreMenuWrapperRef.current[refIndex.current].contains(evt.target)) { + setCurrentIndex(-1); + } + } + + useEffect(() => { + document.addEventListener("mousedown", handleClickOutside, false); + + return () => { + document.removeEventListener("mousedown", handleClickOutside, false); + }; + }, []); + + useEffect(() => { + if (props.sort === 0) { + setVariableState(variable); + } else if (props.sort === 1) { + if (variableState?.length > 0) { + setVariableState([...variable].sort((a, b) => b.name !== "Global" && a.name.localeCompare(b.name))); + } + } else { + if (variableState?.length > 0) { + setVariableState([...variable].sort((a, b) => b.name !== "Global" && b.name.localeCompare(a.name))); + } + } + }, [props.sort, variable, variable.length]); + + function onItemRightClick(e: any, index: number) { + e.preventDefault(); + e.stopPropagation(); + openContextMenu(index); + } + + function getVariableItems(item: IVariable, index: number) { + return ( +
onItemRightClick(e, index)} onClick={(e) => onClickItem(e, item.id)}> +
+ + {index === 0 && } +
moreMenuWrapperRef.current[index] = el}> + openMoreMenu(e, index)} /> + +
+ {index !== 0 && <> + } + +
+ {index === 0 && !item.isActive && } + +
+
+
+
+ ); + } + + function getVariableBody() { + if (props.filterCondition) { + return ( + variableState + .filter(el => el.name?.toLowerCase().includes(props.filterCondition)) + .map((item, index) => { + return getVariableItems(item, index); + }) + ); + } else { + return ( + variableState.map((item, index) => { + return getVariableItems(item, index); + }) + ); + } + } + + return ( + <> + { + props.isLoading ? + <> +
+
{"Loading...."}
+ + : + history.length > 0 ? + getVariableBody() + : +
{"No Variable Available"}
+ } + + ); +}; diff --git a/src/fetch-client-ui/components/SideBar/Variables/style.css b/src/fetch-client-ui/components/SideBar/Variables/style.css index 5894a9e..0313a89 100644 --- a/src/fetch-client-ui/components/SideBar/Variables/style.css +++ b/src/fetch-client-ui/components/SideBar/Variables/style.css @@ -1,7 +1,7 @@ .var-item-name { - cursor: pointer; + cursor: pointer; } .variable-row { - display: block !important; -} \ No newline at end of file + display: block !important; +} diff --git a/src/fetch-client-ui/components/SideBar/index.tsx b/src/fetch-client-ui/components/SideBar/index.tsx index d6901f1..c587e73 100644 --- a/src/fetch-client-ui/components/SideBar/index.tsx +++ b/src/fetch-client-ui/components/SideBar/index.tsx @@ -1,299 +1,330 @@ -import { CollectionBar } from "./Collection"; +import React, { useEffect, useRef, useState } from "react"; +import { useDispatch } from "react-redux"; +import { pubSubTypes, requestTypes, responseTypes } from "../../../utils/configuration"; import { getColFolDotMenu } from "../Common/icons"; +import vscode from "../Common/vscodeAPI"; +import { UIActions } from "../MainUI/redux"; +import { CollectionBar } from "./Collection"; import { HistoryBar } from "./History"; -import { ICollections, IHistory, IVariable } from "./redux/types"; -import { pubSubTypes, requestTypes, responseTypes } from "../../../utils/configuration"; import { SideBarActions } from "./redux"; -import { UIActions } from "../MainUI/redux"; -import { useDispatch } from "react-redux"; -import { VariableSection } from "./Variables"; -import React, { useEffect, useRef, useState } from "react"; -import vscode from "../Common/vscodeAPI"; +import { ICollections, IHistory, IVariable } from "./redux/types"; import "./style.css"; +import { VariableSection } from "./Variables"; const SideBar = () => { - const dispatch = useDispatch(); - - const [tabOptions] = useState(["History", "Collection", "Variable"]); - const [selectedTab, setSelectedTab] = useState("History"); - const [menuShow, setMenuShow] = useState(false); - const [filterCondititon, setFilterCondition] = useState(""); - const [isHisLoading, setHisLoading] = useState(true); - const [isColLoading, setColLoading] = useState(true); - const [isVarLoading, setVarLoading] = useState(true); - const [isViewLogOpen, setViewLogOpen] = useState(false); - const [selectedItem, _setSelectedItem] = useState({ colId: "", foldId: "", itemId: "", }); - - const refSelectedItem = useRef(selectedItem); - const setSelectedItem = (data: { colId: string; foldId: string; itemId: string; }) => { - refSelectedItem.current = data; - _setSelectedItem(refSelectedItem.current); - }; - - const wrapperRef = useRef(null); - - function onSelectedTab(tab: string) { - setSelectedTab(tab); - setFilterCondition(""); - } - - function setShowMenu(evt: any) { - evt.preventDefault(); - setMenuShow(!menuShow); - } - - function handleClickOutside(evt: any) { - if (wrapperRef.current && !wrapperRef.current.contains(evt.target)) { - setMenuShow(false); - } - } - - function onClearActivity(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.deleteAllHistoryRequest }); - setMenuShow(false); - } - - function onImportData(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.importRequest }); - setMenuShow(false); - } - - function onImportCurl(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.importCurlRequest }); - setMenuShow(false); - } - - function onImportVariableData(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.importVariableRequest }); - setMenuShow(false); - } - - function onNewVariable(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.newVariableRequest }); - setMenuShow(false); - } - - function onNewCollection(evt: any) { - evt.preventDefault(); - vscode.postMessage({ type: requestTypes.newCollectionRequest }); - setMenuShow(false); - } - - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getAllHistoryResponse) { - dispatch(SideBarActions.SetHistoryAction(event.data.history as IHistory[])); - setHisLoading(false); - } else if (event.data && event.data.type === responseTypes.deleteAllHistoryResponse) { - dispatch(SideBarActions.SetHistoryAction([])); - } else if (event.data && event.data.type === responseTypes.deleteHistoryResponse) { - dispatch(SideBarActions.SetDeleteHistoryAction(event.data.id)); - } else if (event.data && event.data.type === responseTypes.renameHistoryResponse) { - dispatch(SideBarActions.SetRenameHistoryAction(event.data.params.id, event.data.params.name)); - } else if (event.data && event.data.type === responseTypes.newHistoryResponse) { - dispatch(SideBarActions.SetNewHistoryAction(event.data.history as IHistory)); - } else if (event.data && event.data.type === responseTypes.getAllCollectionsResponse) { - dispatch(SideBarActions.SetCollectionAction(event.data.collections as ICollections[])); - setColLoading(false); - } else if (event.data && event.data.type === responseTypes.appendToCollectionsResponse) { - dispatch(SideBarActions.SetHistoryToCollectionAction(event.data.collection as ICollections)); - } else if (event.data && event.data.type === responseTypes.renameCollectionItemResponse) { - if (!event.data.params.name) { - return; - } - dispatch(SideBarActions.SetRenameColItemAction(event.data.params.colId, event.data.params.folderId, event.data.params.historyId, event.data.params.isFolder, event.data.params.name)); - } else if (event.data && event.data.type === responseTypes.deleteCollectionItemResponse) { - dispatch(SideBarActions.SetDeleteColItemAction(event.data.params.colId, event.data.params.folderId, event.data.params.historyId, event.data.params.isFolder)); - } else if (event.data && event.data.type === responseTypes.renameCollectionResponse) { - dispatch(SideBarActions.SetRenameCollectionAction(event.data.params.id, event.data.params.name)); - } else if (event.data && event.data.type === responseTypes.deleteCollectionResponse) { - dispatch(SideBarActions.SetDeleteCollectionAction(event.data.id)); - } else if (event.data && event.data.type === responseTypes.clearResponse) { - dispatch(SideBarActions.SetClearCollectionAction(event.data.id, event.data.folderId)); - } else if (event.data && event.data.type === responseTypes.importResponse) { - dispatch(SideBarActions.SetImportCollectionAction(event.data.data as ICollections)); - } else if (event.data && event.data.type === responseTypes.copyToCollectionsResponse) { - dispatch(SideBarActions.SetCopyToCollectionAction(event.data.data as ICollections)); - } else if (event.data && event.data.type === responseTypes.getAllVariableResponse) { - dispatch(SideBarActions.SetVariableAction(event.data.variable as IVariable[])); - setVarLoading(false); - } else if (event.data && event.data.type === responseTypes.renameVariableResponse) { - dispatch(SideBarActions.SetRenameVariableAction(event.data.params.id, event.data.params.name)); - } else if (event.data && event.data.type === responseTypes.deleteVariableResponse) { - dispatch(SideBarActions.SetDeleteVariablection(event.data.id)); - vscode.postMessage({ type: requestTypes.removeVariableFromColRequest, data: { varId: event.data.id } }); - } else if (event.data && event.data.type === responseTypes.appendToVariableResponse) { - dispatch(SideBarActions.SetNewVariableAction(event.data.collection as IVariable)); - } else if (event.data && event.data.type === responseTypes.attachVariableResponse) { - dispatch(SideBarActions.SetAttachVariableAction(event.data.params.id, event.data.params.varId)); - } else if (event.data && event.data.type === responseTypes.activeVariableResponse) { - dispatch(SideBarActions.SetActiveVariableAction(event.data.params.id, event.data.params.status)); - } else if (event.data && event.data.type === responseTypes.importVariableResponse) { - dispatch(SideBarActions.SetNewVariableAction(event.data.vars)); - } else if (event.data && event.data.type === responseTypes.createNewResponse) { - dispatch(SideBarActions.SetNewRequestToCollectionAction(event.data.item, event.data.id, event.data.folderId)); - vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { colId: event.data.id, folderId: event.data.folderId, id: event.data.item.id, name: event.data.item.name, varId: event.data.variableId } }); - } else if (event.data && event.data.type === responseTypes.createNewFolderResponse) { - dispatch(SideBarActions.SetFolderToCollectionAction(event.data.folder, event.data.colId, event.data.folderId)); - } else if (event.data && event.data.type === requestTypes.selectItemRequest) { - setSelectedItem({ - colId: event.data.colId, - foldId: event.data.folId, - itemId: event.data.id - }); - } else if (event.data && event.data.type === requestTypes.closeItemRequest) { - if (event.data.id && refSelectedItem.current.itemId === event.data.id) { - setSelectedItem({ - colId: "", - foldId: "", - itemId: "" - }); - } - } else if (event.data && event.data.type === responseTypes.themeResponse) { - dispatch(UIActions.SetThemeAction(event.data.theme)); - } else if (event.data && event.data.type === pubSubTypes.themeChanged) { - vscode.postMessage({ type: requestTypes.themeRequest }); - } else if (event.data && event.data.type === responseTypes.updateCollectionHistoryItem) { - if (event.data.colId) { - dispatch(SideBarActions.SetUpdateCollectionItemAction(event.data.item, event.data.colId)); - } - else { - dispatch(SideBarActions.SetUpdateHistoryItemAction(event.data.item)); - } - } - }); - - vscode.postMessage({ type: requestTypes.themeRequest }); - vscode.postMessage({ type: requestTypes.getAllHistoryRequest }); - - setTimeout(() => { - vscode.postMessage({ type: requestTypes.getAllCollectionsRequest }); - }, 1000); - - setTimeout(() => { - vscode.postMessage({ type: requestTypes.getAllVariableRequest }); - }, 1000); - - document.body.style.backgroundColor = "transparent"; - - document.addEventListener("mousedown", handleClickOutside, false); - - return () => { - document.removeEventListener("mousedown", handleClickOutside, false); - }; - }, []); - - function getHistoryMenuItems() { - return ; - } - - function getCollectionsMenuItems() { - return ( - <> - - - - - ); - } - - function getVariableMenuItems() { - return <>; - } - - function onFilterChange(e: any) { - setFilterCondition(e.target.value); - } - - function onViewLogClick(_e: any) { - setViewLogOpen(!isViewLogOpen); - vscode.postMessage({ type: requestTypes.viewLogRequest }); - } - - function getBody() { - return ( -
-
- -
- {getColFolDotMenu("hamburger-menu", "Menu", "hamburger-menu", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => setShowMenu(e))} - {menuShow && (
- {selectedTab === "History" ? getHistoryMenuItems() : selectedTab === "Collection" ? getCollectionsMenuItems() : getVariableMenuItems()} -
)} -
-
-
- { - selectedTab === "History" - ? - - : selectedTab === "Collection" - ? - - : - - } -
- -
- ); - } - - function getTabRender() { - return ( - tabOptions.map((tab) => { - return ( - - ); - }) - ); - } - - function onNewRequestClick() { - vscode.postMessage({ type: requestTypes.newRequest }); - } - - return ( -
-
- -
-
- { - getTabRender() - } -
-
- { - getBody() - } -
-
- ); + const dispatch = useDispatch(); + + const [tabOptions] = useState(["History", "Collection", "Variable"]); + const [selectedTab, setSelectedTab] = useState("History"); + const [menuShow, setMenuShow] = useState(false); + const [filterCondititon, setFilterCondition] = useState(""); + const [isHisLoading, setHisLoading] = useState(true); + const [isColLoading, setColLoading] = useState(true); + const [isVarLoading, setVarLoading] = useState(true); + const [isViewLogOpen, setViewLogOpen] = useState(false); + const [selectedItem, _setSelectedItem] = useState({ colId: "", foldId: "", itemId: "", }); + const [colSort, setColSort] = useState(0); + const [varSort, setVarSort] = useState(0); + + const refSelectedItem = useRef(selectedItem); + const setSelectedItem = (data: { colId: string; foldId: string; itemId: string; }) => { + refSelectedItem.current = data; + _setSelectedItem(refSelectedItem.current); + }; + + const wrapperRef = useRef(null); + + function onSelectedTab(tab: string) { + setSelectedTab(tab); + setFilterCondition(""); + } + + function setShowMenu(evt: any) { + evt.preventDefault(); + setMenuShow(!menuShow); + } + + function handleClickOutside(evt: any) { + if (wrapperRef.current && !wrapperRef.current.contains(evt.target)) { + setMenuShow(false); + } + } + + function onClearActivity(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.deleteAllHistoryRequest }); + setMenuShow(false); + } + + function onImportData(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.importRequest }); + setMenuShow(false); + } + + function onBulkExportData(evt: any, type: string) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.bulkExportRequest, data: { type: type } }); + setMenuShow(false); + } + + function onImportCurl(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.importCurlRequest }); + setMenuShow(false); + } + + function onImportVariableData(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.importVariableRequest }); + setMenuShow(false); + } + + function onVariableSort(evt: any) { + evt.preventDefault(); + setVarSort((varSort === 0 || varSort === 2) ? 1 : 2); + setMenuShow(false); + } + + function onColSort(evt: any) { + evt.preventDefault(); + setColSort((colSort === 0 || colSort === 2) ? 1 : 2); + setMenuShow(false); + } + + function onNewVariable(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.newVariableRequest }); + setMenuShow(false); + } + + function onNewCollection(evt: any) { + evt.preventDefault(); + vscode.postMessage({ type: requestTypes.newCollectionRequest }); + setMenuShow(false); + } + + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getAllHistoryResponse) { + dispatch(SideBarActions.SetHistoryAction(event.data.history as IHistory[])); + setHisLoading(false); + } else if (event.data && event.data.type === responseTypes.deleteAllHistoryResponse) { + dispatch(SideBarActions.SetHistoryAction([])); + } else if (event.data && event.data.type === responseTypes.deleteHistoryResponse) { + dispatch(SideBarActions.SetDeleteHistoryAction(event.data.id)); + } else if (event.data && event.data.type === responseTypes.renameHistoryResponse) { + dispatch(SideBarActions.SetRenameHistoryAction(event.data.params.id, event.data.params.name)); + } else if (event.data && event.data.type === responseTypes.newHistoryResponse) { + dispatch(SideBarActions.SetNewHistoryAction(event.data.history as IHistory)); + } else if (event.data && event.data.type === responseTypes.getAllCollectionsResponse) { + dispatch(SideBarActions.SetCollectionAction(event.data.collections as ICollections[])); + setColLoading(false); + } else if (event.data && event.data.type === responseTypes.appendToCollectionsResponse) { + dispatch(SideBarActions.SetHistoryToCollectionAction(event.data.collection as ICollections)); + } else if (event.data && event.data.type === responseTypes.renameCollectionItemResponse) { + if (!event.data.params.name) { + return; + } + dispatch(SideBarActions.SetRenameColItemAction(event.data.params.colId, event.data.params.folderId, event.data.params.historyId, event.data.params.isFolder, event.data.params.name)); + } else if (event.data && event.data.type === responseTypes.deleteCollectionItemResponse) { + dispatch(SideBarActions.SetDeleteColItemAction(event.data.params.colId, event.data.params.folderId, event.data.params.historyId, event.data.params.isFolder)); + } else if (event.data && event.data.type === responseTypes.renameCollectionResponse) { + dispatch(SideBarActions.SetRenameCollectionAction(event.data.params.id, event.data.params.name)); + } else if (event.data && event.data.type === responseTypes.deleteCollectionResponse) { + dispatch(SideBarActions.SetDeleteCollectionAction(event.data.id)); + } else if (event.data && event.data.type === responseTypes.clearResponse) { + dispatch(SideBarActions.SetClearCollectionAction(event.data.id, event.data.folderId)); + } else if (event.data && event.data.type === responseTypes.importResponse) { + dispatch(SideBarActions.SetImportCollectionAction(event.data.data as ICollections)); + } else if (event.data && event.data.type === responseTypes.copyToCollectionsResponse) { + dispatch(SideBarActions.SetCopyToCollectionAction(event.data.data as ICollections)); + } else if (event.data && event.data.type === responseTypes.getAllVariableResponse) { + dispatch(SideBarActions.SetVariableAction(event.data.variable as IVariable[])); + setVarLoading(false); + } else if (event.data && event.data.type === responseTypes.renameVariableResponse) { + dispatch(SideBarActions.SetRenameVariableAction(event.data.params.id, event.data.params.name)); + } else if (event.data && event.data.type === responseTypes.deleteVariableResponse) { + dispatch(SideBarActions.SetDeleteVariablection(event.data.id)); + vscode.postMessage({ type: requestTypes.removeVariableFromColRequest, data: { varId: event.data.id } }); + } else if (event.data && event.data.type === responseTypes.appendToVariableResponse) { + dispatch(SideBarActions.SetNewVariableAction(event.data.collection as IVariable)); + } else if (event.data && event.data.type === responseTypes.attachVariableResponse) { + dispatch(SideBarActions.SetAttachVariableAction(event.data.params.id, event.data.params.varId)); + } else if (event.data && event.data.type === responseTypes.activeVariableResponse) { + dispatch(SideBarActions.SetActiveVariableAction(event.data.params.id, event.data.params.status)); + } else if (event.data && event.data.type === responseTypes.importVariableResponse) { + dispatch(SideBarActions.SetNewVariableAction(event.data.vars)); + } else if (event.data && event.data.type === responseTypes.createNewResponse) { + dispatch(SideBarActions.SetNewRequestToCollectionAction(event.data.item, event.data.id, event.data.folderId)); + vscode.postMessage({ type: requestTypes.openHistoryItemRequest, data: { colId: event.data.id, folderId: event.data.folderId, id: event.data.item.id, name: event.data.item.name, varId: event.data.variableId } }); + } else if (event.data && event.data.type === responseTypes.createNewFolderResponse) { + dispatch(SideBarActions.SetFolderToCollectionAction(event.data.folder, event.data.colId, event.data.folderId)); + } else if (event.data && event.data.type === requestTypes.selectItemRequest) { + setSelectedItem({ + colId: event.data.colId, + foldId: event.data.folId, + itemId: event.data.id + }); + } else if (event.data && event.data.type === requestTypes.closeItemRequest) { + if (event.data.id && refSelectedItem.current.itemId === event.data.id) { + setSelectedItem({ + colId: "", + foldId: "", + itemId: "" + }); + } + } else if (event.data && event.data.type === responseTypes.themeResponse) { + dispatch(UIActions.SetThemeAction(event.data.theme)); + } else if (event.data && event.data.type === pubSubTypes.themeChanged) { + vscode.postMessage({ type: requestTypes.themeRequest }); + } else if (event.data && event.data.type === responseTypes.updateCollectionHistoryItem) { + if (event.data.colId) { + dispatch(SideBarActions.SetUpdateCollectionItemAction(event.data.item, event.data.colId)); + } + else { + dispatch(SideBarActions.SetUpdateHistoryItemAction(event.data.item)); + } + } + }); + + vscode.postMessage({ type: requestTypes.themeRequest }); + vscode.postMessage({ type: requestTypes.getAllHistoryRequest }); + + setTimeout(() => { + vscode.postMessage({ type: requestTypes.getAllCollectionsRequest }); + }, 1000); + + setTimeout(() => { + vscode.postMessage({ type: requestTypes.getAllVariableRequest }); + }, 1000); + + document.body.style.backgroundColor = "transparent"; + + document.addEventListener("mousedown", handleClickOutside, false); + + return () => { + document.removeEventListener("mousedown", handleClickOutside, false); + }; + }, []); + + function getHistoryMenuItems() { + return ; + } + + function getCollectionsMenuItems() { + return ( + <> + + + + +
+ + + ); + } + + function getVariableMenuItems() { + return ( + <> + + + +
+ + + ); + } + + function onFilterChange(e: any) { + setFilterCondition(e.target.value); + } + + function onViewLogClick(_e: any) { + setViewLogOpen(!isViewLogOpen); + vscode.postMessage({ type: requestTypes.viewLogRequest }); + } + + function getBody() { + return ( +
+
+ +
+ {getColFolDotMenu("hamburger-menu", "Menu", "hamburger-menu", (e) => { e.stopPropagation(); e.preventDefault(); }, (e) => setShowMenu(e))} + {menuShow && (
+ {selectedTab === "History" ? getHistoryMenuItems() : selectedTab === "Collection" ? getCollectionsMenuItems() : getVariableMenuItems()} +
)} +
+
+
+ { + selectedTab === "History" + ? + + : selectedTab === "Collection" + ? + + : + + } +
+ +
+ ); + } + + function getTabRender() { + return ( + tabOptions.map((tab) => { + return ( + + ); + }) + ); + } + + function onNewRequestClick() { + vscode.postMessage({ type: requestTypes.newRequest }); + } + + return ( +
+
+ +
+
+ { + getTabRender() + } +
+
+ { + getBody() + } +
+
+ ); }; -export default SideBar; \ No newline at end of file +export default SideBar; diff --git a/src/fetch-client-ui/components/SideBar/redux/actions.ts b/src/fetch-client-ui/components/SideBar/redux/actions.ts index 6774de3..b5e4d4d 100644 --- a/src/fetch-client-ui/components/SideBar/redux/actions.ts +++ b/src/fetch-client-ui/components/SideBar/redux/actions.ts @@ -1,236 +1,236 @@ import { - FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE, FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE, FETCH_CLIENT_SET_CLEAR_COLLECTION, - FETCH_CLIENT_SET_COLLECTION, FETCH_CLIENT_SET_COPY_TO_COLLECTION, FETCH_CLIENT_SET_DELETE_COLLECTION, - FETCH_CLIENT_SET_DELETE_COL_ITEM, FETCH_CLIENT_SET_DELETE_HISTORY, FETCH_CLIENT_SET_DELETE_VARIABLE, - FETCH_CLIENT_SET_HISTORY, FETCH_CLIENT_SET_IMPORT_COLLECTION, FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION, - FETCH_CLIENT_SET_NEW_HISTORY, FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION, FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION, - FETCH_CLIENT_SET_NEW_VARIABLE, FETCH_CLIENT_SET_RENAME_COLLECTION, FETCH_CLIENT_SET_RENAME_COL_ITEM, - FETCH_CLIENT_SET_RENAME_HISTORY, FETCH_CLIENT_SET_RENAME_VARIABLE, FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM, FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM, FETCH_CLIENT_SET_VARIABLE, - ICollections, IFolder, IHistory, IVariable, SideBarActionTypes + FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE, FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE, FETCH_CLIENT_SET_CLEAR_COLLECTION, + FETCH_CLIENT_SET_COLLECTION, FETCH_CLIENT_SET_COPY_TO_COLLECTION, FETCH_CLIENT_SET_DELETE_COLLECTION, + FETCH_CLIENT_SET_DELETE_COL_ITEM, FETCH_CLIENT_SET_DELETE_HISTORY, FETCH_CLIENT_SET_DELETE_VARIABLE, + FETCH_CLIENT_SET_HISTORY, FETCH_CLIENT_SET_IMPORT_COLLECTION, FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION, + FETCH_CLIENT_SET_NEW_HISTORY, FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION, FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION, + FETCH_CLIENT_SET_NEW_VARIABLE, FETCH_CLIENT_SET_RENAME_COLLECTION, FETCH_CLIENT_SET_RENAME_COL_ITEM, + FETCH_CLIENT_SET_RENAME_HISTORY, FETCH_CLIENT_SET_RENAME_VARIABLE, FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM, FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM, FETCH_CLIENT_SET_VARIABLE, + ICollections, IFolder, IHistory, IVariable, SideBarActionTypes } from "./types"; export const SetHistoryAction = (value: IHistory[]): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_HISTORY, - payload: { - history: value - } - }; + return { + type: FETCH_CLIENT_SET_HISTORY, + payload: { + history: value + } + }; }; export const SetNewHistoryAction = (value: IHistory): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_NEW_HISTORY, - payload: { - history: value - } - }; + return { + type: FETCH_CLIENT_SET_NEW_HISTORY, + payload: { + history: value + } + }; }; export const SetHistoryToCollectionAction = (value: ICollections): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION, - payload: { - collection: value - } - }; + return { + type: FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION, + payload: { + collection: value + } + }; }; export const SetDeleteHistoryAction = (value: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_DELETE_HISTORY, - payload: { - id: value - } - }; + return { + type: FETCH_CLIENT_SET_DELETE_HISTORY, + payload: { + id: value + } + }; }; export const SetRenameHistoryAction = (value: string, value1: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_RENAME_HISTORY, - payload: { - id: value, - name: value1 - } - }; + return { + type: FETCH_CLIENT_SET_RENAME_HISTORY, + payload: { + id: value, + name: value1 + } + }; }; export const SetCollectionAction = (value: ICollections[]): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_COLLECTION, - payload: { - collections: value - } - }; + return { + type: FETCH_CLIENT_SET_COLLECTION, + payload: { + collections: value + } + }; }; export const SetRenameColItemAction = (value: string, value1: string, value2: string, value3: boolean, value4: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_RENAME_COL_ITEM, - payload: { - colId: value, - folderId: value1, - historyId: value2, - isFolder: value3, - name: value4 - } - }; + return { + type: FETCH_CLIENT_SET_RENAME_COL_ITEM, + payload: { + colId: value, + folderId: value1, + historyId: value2, + isFolder: value3, + name: value4 + } + }; }; export const SetDeleteColItemAction = (value: string, value1: string, value2: string, value3: boolean): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_DELETE_COL_ITEM, - payload: { - colId: value, - folderId: value1, - historyId: value2, - isFolder: value3 - } - }; + return { + type: FETCH_CLIENT_SET_DELETE_COL_ITEM, + payload: { + colId: value, + folderId: value1, + historyId: value2, + isFolder: value3 + } + }; }; export const SetRenameCollectionAction = (value: string, value1: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_RENAME_COLLECTION, - payload: { - colId: value, - name: value1 - } - }; + return { + type: FETCH_CLIENT_SET_RENAME_COLLECTION, + payload: { + colId: value, + name: value1 + } + }; }; export const SetDeleteCollectionAction = (value: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_DELETE_COLLECTION, - payload: { - colId: value, - } - }; + return { + type: FETCH_CLIENT_SET_DELETE_COLLECTION, + payload: { + colId: value, + } + }; }; export const SetClearCollectionAction = (value: string, value1: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_CLEAR_COLLECTION, - payload: { - colId: value, - folderId: value1 - } - }; + return { + type: FETCH_CLIENT_SET_CLEAR_COLLECTION, + payload: { + colId: value, + folderId: value1 + } + }; }; export const SetImportCollectionAction = (value: ICollections): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_IMPORT_COLLECTION, - payload: { - collection: value, - } - }; + return { + type: FETCH_CLIENT_SET_IMPORT_COLLECTION, + payload: { + collection: value, + } + }; }; export const SetCopyToCollectionAction = (value: ICollections): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_COPY_TO_COLLECTION, - payload: { - collection: value, - } - }; + return { + type: FETCH_CLIENT_SET_COPY_TO_COLLECTION, + payload: { + collection: value, + } + }; }; export const SetDeleteVariablection = (value: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_DELETE_VARIABLE, - payload: { - varId: value - } - }; + return { + type: FETCH_CLIENT_SET_DELETE_VARIABLE, + payload: { + varId: value + } + }; }; export const SetRenameVariableAction = (value: string, value1: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_RENAME_VARIABLE, - payload: { - varId: value, - name: value1 - } - }; + return { + type: FETCH_CLIENT_SET_RENAME_VARIABLE, + payload: { + varId: value, + name: value1 + } + }; }; export const SetVariableAction = (value: IVariable[]): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_VARIABLE, - payload: { - variable: value, - } - }; + return { + type: FETCH_CLIENT_SET_VARIABLE, + payload: { + variable: value, + } + }; }; export const SetNewVariableAction = (value: IVariable): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_NEW_VARIABLE, - payload: { - variable: value, - } - }; + return { + type: FETCH_CLIENT_SET_NEW_VARIABLE, + payload: { + variable: value, + } + }; }; export const SetAttachVariableAction = (value: string, value1: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE, - payload: { - colId: value, - varId: value1 - } - }; + return { + type: FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE, + payload: { + colId: value, + varId: value1 + } + }; }; export const SetActiveVariableAction = (value: string, value1: boolean): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE, - payload: { - varId: value, - status: value1 - } - }; + return { + type: FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE, + payload: { + varId: value, + status: value1 + } + }; }; export const SetNewRequestToCollectionAction = (value: IHistory, value1: string, value2: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION, - payload: { - item: value, - id: value1, - folId: value2, - } - }; + return { + type: FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION, + payload: { + item: value, + id: value1, + folId: value2, + } + }; }; export const SetFolderToCollectionAction = (value: IFolder, value1: string, value2: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION, - payload: { - folder: value, - colId: value1, - folderId: value2 - } - }; + return { + type: FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION, + payload: { + folder: value, + colId: value1, + folderId: value2 + } + }; }; export const SetUpdateCollectionItemAction = (value: IHistory, value1: string): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM, - payload: { - item: value, - colId: value1 - } - }; + return { + type: FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM, + payload: { + item: value, + colId: value1 + } + }; }; export const SetUpdateHistoryItemAction = (value: IHistory): SideBarActionTypes => { - return { - type: FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM, - payload: { - item: value - } - }; + return { + type: FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM, + payload: { + item: value + } + }; }; diff --git a/src/fetch-client-ui/components/SideBar/redux/index.ts b/src/fetch-client-ui/components/SideBar/redux/index.ts index 3cce292..4737076 100644 --- a/src/fetch-client-ui/components/SideBar/redux/index.ts +++ b/src/fetch-client-ui/components/SideBar/redux/index.ts @@ -3,6 +3,6 @@ import { SideBarReducer } from "./reducer"; export { - SideBarActions, - SideBarReducer + SideBarActions, + SideBarReducer }; diff --git a/src/fetch-client-ui/components/SideBar/redux/reducer.ts b/src/fetch-client-ui/components/SideBar/redux/reducer.ts index 891a171..4245644 100644 --- a/src/fetch-client-ui/components/SideBar/redux/reducer.ts +++ b/src/fetch-client-ui/components/SideBar/redux/reducer.ts @@ -1,380 +1,380 @@ import { InitialAuth, InitialPreFetch, InitialRequestHeaders } from "../../RequestUI/redux/reducer"; import { isFolder } from "../util"; import { - FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE, FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE, FETCH_CLIENT_SET_CLEAR_COLLECTION, - FETCH_CLIENT_SET_COLLECTION, FETCH_CLIENT_SET_COPY_TO_COLLECTION, FETCH_CLIENT_SET_DELETE_COLLECTION, - FETCH_CLIENT_SET_DELETE_COL_ITEM, FETCH_CLIENT_SET_DELETE_HISTORY, FETCH_CLIENT_SET_DELETE_VARIABLE, FETCH_CLIENT_SET_HISTORY, - FETCH_CLIENT_SET_IMPORT_COLLECTION, FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION, FETCH_CLIENT_SET_NEW_HISTORY, - FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION, FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION, FETCH_CLIENT_SET_NEW_VARIABLE, - FETCH_CLIENT_SET_RENAME_COLLECTION, FETCH_CLIENT_SET_RENAME_COL_ITEM, FETCH_CLIENT_SET_RENAME_HISTORY, - FETCH_CLIENT_SET_RENAME_VARIABLE, FETCH_CLIENT_SET_VARIABLE, - ICollections, ISettings, IFolder, IHistory, ISideBarModel, IVariable, SideBarActionTypes, - FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM, - FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM + FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE, FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE, FETCH_CLIENT_SET_CLEAR_COLLECTION, + FETCH_CLIENT_SET_COLLECTION, FETCH_CLIENT_SET_COPY_TO_COLLECTION, FETCH_CLIENT_SET_DELETE_COLLECTION, + FETCH_CLIENT_SET_DELETE_COL_ITEM, FETCH_CLIENT_SET_DELETE_HISTORY, FETCH_CLIENT_SET_DELETE_VARIABLE, FETCH_CLIENT_SET_HISTORY, + FETCH_CLIENT_SET_IMPORT_COLLECTION, FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION, FETCH_CLIENT_SET_NEW_HISTORY, + FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION, FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION, FETCH_CLIENT_SET_NEW_VARIABLE, + FETCH_CLIENT_SET_RENAME_COLLECTION, FETCH_CLIENT_SET_RENAME_COL_ITEM, FETCH_CLIENT_SET_RENAME_HISTORY, + FETCH_CLIENT_SET_RENAME_VARIABLE, FETCH_CLIENT_SET_VARIABLE, + ICollections, ISettings, IFolder, IHistory, ISideBarModel, IVariable, SideBarActionTypes, + FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM, + FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM } from "./types"; export const InitialSettings: ISettings = { - auth: InitialAuth, - preFetch: InitialPreFetch, - headers: InitialRequestHeaders + auth: InitialAuth, + preFetch: InitialPreFetch, + headers: InitialRequestHeaders }; export const InitialState: ISideBarModel = { - history: [], - collections: [], - variable: [] + history: [], + collections: [], + variable: [] }; export const SideBarReducer: (state?: ISideBarModel, - action?: SideBarActionTypes) => ISideBarModel = - (state: ISideBarModel = InitialState, - action: SideBarActionTypes = {} as SideBarActionTypes): ISideBarModel => { - switch (action.type) { - case FETCH_CLIENT_SET_HISTORY: { - return { - ...state, - history: action.payload.history, - }; - } - case FETCH_CLIENT_SET_COLLECTION: { - return { - ...state, - collections: action.payload.collections, - }; - } - case FETCH_CLIENT_SET_DELETE_HISTORY: { - return { - ...state, - history: deleteHistoryFromState(action.payload.id, state.history), - }; - } - case FETCH_CLIENT_SET_RENAME_HISTORY: { - return { - ...state, - history: renameHistoryFromState(action.payload.id, action.payload.name, state.history), - }; - } - case FETCH_CLIENT_SET_NEW_HISTORY: { - return { - ...state, - history: [action.payload.history, ...state.history], - }; - } - case FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION: { - return { - ...state, - collections: appendToCollectionState(action.payload.collection, state.collections), - }; - } - case FETCH_CLIENT_SET_RENAME_COL_ITEM: { - return { - ...state, - collections: renameColItemFromState(action.payload.colId, action.payload.folderId, action.payload.historyId, action.payload.name, action.payload.isFolder, state.collections), - }; - } - case FETCH_CLIENT_SET_DELETE_COL_ITEM: { - return { - ...state, - collections: deleteColItemFromState(action.payload.colId, action.payload.folderId, action.payload.historyId, action.payload.isFolder, state.collections), - }; - } - case FETCH_CLIENT_SET_RENAME_COLLECTION: { - return { - ...state, - collections: renameCollectionFromState(action.payload.colId, action.payload.name, state.collections), - }; - } - case FETCH_CLIENT_SET_DELETE_COLLECTION: { - return { - ...state, - collections: deleteCollectionFromState(action.payload.colId, state.collections), - }; - } - case FETCH_CLIENT_SET_CLEAR_COLLECTION: { - return { - ...state, - collections: clearCollectionFromState(action.payload.colId, action.payload.folderId, state.collections), - }; - } - case FETCH_CLIENT_SET_IMPORT_COLLECTION: { - return { - ...state, - collections: importCollectionToState(action.payload.collection, state.collections), - }; - } - case FETCH_CLIENT_SET_COPY_TO_COLLECTION: { - return { - ...state, - collections: copyToCollectionToState(action.payload.collection, state.collections), - }; - } - case FETCH_CLIENT_SET_RENAME_VARIABLE: { - return { - ...state, - variable: renameVariableFromState(action.payload.varId, action.payload.name, state.variable), - }; - } - case FETCH_CLIENT_SET_VARIABLE: { - return { - ...state, - variable: action.payload.variable, - }; - } - case FETCH_CLIENT_SET_DELETE_VARIABLE: { - return { - ...state, - variable: deleteVariableFromState(action.payload.varId, state.variable), - }; - } - case FETCH_CLIENT_SET_NEW_VARIABLE: { - return { - ...state, - variable: [...state.variable, action.payload.variable], - }; - } - case FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE: { - return { - ...state, - collections: attachVariableFromState(action.payload.colId, action.payload.varId, state.collections), - }; - } - case FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE: { - return { - ...state, - variable: updateStatusVariableFromState(action.payload.varId, action.payload.status, state.variable) - }; - } - case FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION: { - return { - ...state, - collections: appendRequestToCollectionState(action.payload.item, action.payload.id, action.payload.folId, state.collections) - }; - } - case FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION: { - return { - ...state, - collections: appendRequestToCollectionState(action.payload.folder, action.payload.colId, action.payload.folderId, state.collections) - }; - } - case FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM: { - return { - ...state, - collections: updateItemInCollectionState(action.payload.item, action.payload.colId, state.collections) - }; - } - case FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM: { - return { - ...state, - history: updateItemInHistoryState(action.payload.item, state.history) - }; - } - default: { - return state; - } - } - }; + action?: SideBarActionTypes) => ISideBarModel = + (state: ISideBarModel = InitialState, + action: SideBarActionTypes = {} as SideBarActionTypes): ISideBarModel => { + switch (action.type) { + case FETCH_CLIENT_SET_HISTORY: { + return { + ...state, + history: action.payload.history, + }; + } + case FETCH_CLIENT_SET_COLLECTION: { + return { + ...state, + collections: action.payload.collections, + }; + } + case FETCH_CLIENT_SET_DELETE_HISTORY: { + return { + ...state, + history: deleteHistoryFromState(action.payload.id, state.history), + }; + } + case FETCH_CLIENT_SET_RENAME_HISTORY: { + return { + ...state, + history: renameHistoryFromState(action.payload.id, action.payload.name, state.history), + }; + } + case FETCH_CLIENT_SET_NEW_HISTORY: { + return { + ...state, + history: [action.payload.history, ...state.history], + }; + } + case FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION: { + return { + ...state, + collections: appendToCollectionState(action.payload.collection, state.collections), + }; + } + case FETCH_CLIENT_SET_RENAME_COL_ITEM: { + return { + ...state, + collections: renameColItemFromState(action.payload.colId, action.payload.folderId, action.payload.historyId, action.payload.name, action.payload.isFolder, state.collections), + }; + } + case FETCH_CLIENT_SET_DELETE_COL_ITEM: { + return { + ...state, + collections: deleteColItemFromState(action.payload.colId, action.payload.folderId, action.payload.historyId, action.payload.isFolder, state.collections), + }; + } + case FETCH_CLIENT_SET_RENAME_COLLECTION: { + return { + ...state, + collections: renameCollectionFromState(action.payload.colId, action.payload.name, state.collections), + }; + } + case FETCH_CLIENT_SET_DELETE_COLLECTION: { + return { + ...state, + collections: deleteCollectionFromState(action.payload.colId, state.collections), + }; + } + case FETCH_CLIENT_SET_CLEAR_COLLECTION: { + return { + ...state, + collections: clearCollectionFromState(action.payload.colId, action.payload.folderId, state.collections), + }; + } + case FETCH_CLIENT_SET_IMPORT_COLLECTION: { + return { + ...state, + collections: importCollectionToState(action.payload.collection, state.collections), + }; + } + case FETCH_CLIENT_SET_COPY_TO_COLLECTION: { + return { + ...state, + collections: copyToCollectionToState(action.payload.collection, state.collections), + }; + } + case FETCH_CLIENT_SET_RENAME_VARIABLE: { + return { + ...state, + variable: renameVariableFromState(action.payload.varId, action.payload.name, state.variable), + }; + } + case FETCH_CLIENT_SET_VARIABLE: { + return { + ...state, + variable: action.payload.variable, + }; + } + case FETCH_CLIENT_SET_DELETE_VARIABLE: { + return { + ...state, + variable: deleteVariableFromState(action.payload.varId, state.variable), + }; + } + case FETCH_CLIENT_SET_NEW_VARIABLE: { + return { + ...state, + variable: [...state.variable, action.payload.variable], + }; + } + case FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE: { + return { + ...state, + collections: attachVariableFromState(action.payload.colId, action.payload.varId, state.collections), + }; + } + case FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE: { + return { + ...state, + variable: updateStatusVariableFromState(action.payload.varId, action.payload.status, state.variable) + }; + } + case FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION: { + return { + ...state, + collections: appendRequestToCollectionState(action.payload.item, action.payload.id, action.payload.folId, state.collections) + }; + } + case FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION: { + return { + ...state, + collections: appendRequestToCollectionState(action.payload.folder, action.payload.colId, action.payload.folderId, state.collections) + }; + } + case FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM: { + return { + ...state, + collections: updateItemInCollectionState(action.payload.item, action.payload.colId, state.collections) + }; + } + case FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM: { + return { + ...state, + history: updateItemInHistoryState(action.payload.item, state.history) + }; + } + default: { + return state; + } + } + }; function deleteHistoryFromState(id: string, history: IHistory[]): IHistory[] { - const { found, index } = findItemById(id, history); - if (!found) { return history; } - history.splice(index, 1); - return history; + const { found, index } = findItemById(id, history); + if (!found) { return history; } + history.splice(index, 1); + return history; } function renameHistoryFromState(id: string, name: string, history: IHistory[]): IHistory[] { - const { found, index } = findItemById(id, history); - if (!found) { return history; } - history[index].name = name; - return history; + const { found, index } = findItemById(id, history); + if (!found) { return history; } + history[index].name = name; + return history; } function findItemById(id: string, items: IHistory[] | ICollections[] | IVariable[]): { found: boolean, index: number } { - let findIndex: number = -1; - let found = items.some(function (item: IHistory | ICollections | IVariable, index: number) { findIndex = index; return item.id === id; }); - return { found: found, index: findIndex }; + let findIndex: number = -1; + let found = items.some(function (item: IHistory | ICollections | IVariable, index: number) { findIndex = index; return item.id === id; }); + return { found: found, index: findIndex }; } function appendToCollectionState(item: ICollections, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(item.id, cols); - if (found) { - cols[index] = item; - } else { - cols.push(item); - } - - return cols; + const { found, index } = findItemById(item.id, cols); + if (found) { + cols[index] = item; + } else { + cols.push(item); + } + + return cols; } function renameColItemFromState(colId: string, folderId: string, historyId: string, name: string, _isFolder: boolean, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(colId, cols); - if (found) { - let item = findItem(cols[index], historyId ? historyId : folderId); - if (item) { - item.name = name; - } - } - - return cols; + const { found, index } = findItemById(colId, cols); + if (found) { + let item = findItem(cols[index], historyId ? historyId : folderId); + if (item) { + item.name = name; + } + } + + return cols; } function deleteColItemFromState(colId: string, folderId: string, historyId: string, isFolder: boolean, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(colId, cols); - if (found) { - deleteItem(cols[index], isFolder ? folderId : historyId); - } + const { found, index } = findItemById(colId, cols); + if (found) { + deleteItem(cols[index], isFolder ? folderId : historyId); + } - return cols; + return cols; } function renameCollectionFromState(id: string, name: string, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(id, cols); - if (!found) { return cols; } - cols[index].name = name; - return cols; + const { found, index } = findItemById(id, cols); + if (!found) { return cols; } + cols[index].name = name; + return cols; } function deleteCollectionFromState(id: string, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(id, cols); - if (!found) { return cols; } - cols.splice(index, 1); - return cols; + const { found, index } = findItemById(id, cols); + if (!found) { return cols; } + cols.splice(index, 1); + return cols; } function clearCollectionFromState(id: string, folderId: string, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(id, cols); - - if (found) { - if (folderId) { - let item = findItem(cols[index], folderId); - item.data.length = 0; - } else { - cols[index].data.length = 0; - } - } - - return cols; + const { found, index } = findItemById(id, cols); + + if (found) { + if (folderId) { + let item = findItem(cols[index], folderId); + item.data.length = 0; + } else { + cols[index].data.length = 0; + } + } + + return cols; } function importCollectionToState(item: ICollections, cols: ICollections[]): ICollections[] { - cols = cols.concat(item); - return cols; + cols = cols.concat(item); + return cols; } function copyToCollectionToState(item: ICollections, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(item.id, cols); - if (found) { - cols.splice(index, 1, item); - } else { - cols.push(item); - } - return cols; + const { found, index } = findItemById(item.id, cols); + if (found) { + cols.splice(index, 1, item); + } else { + cols.push(item); + } + return cols; } function renameVariableFromState(id: string, name: string, vars: IVariable[]): IVariable[] { - const { found, index } = findItemById(id, vars); - if (!found) { return vars; } - vars[index].name = name; - return vars; + const { found, index } = findItemById(id, vars); + if (!found) { return vars; } + vars[index].name = name; + return vars; } function deleteVariableFromState(id: string, vars: IVariable[]): IVariable[] { - const { found, index } = findItemById(id, vars); - if (!found) { return vars; } - vars.splice(index, 1); - return vars; + const { found, index } = findItemById(id, vars); + if (!found) { return vars; } + vars.splice(index, 1); + return vars; } function attachVariableFromState(colId: string, varId: string, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(colId, cols); - if (!found) { return cols; } - cols[index].variableId = varId; - return cols; + const { found, index } = findItemById(colId, cols); + if (!found) { return cols; } + cols[index].variableId = varId; + return cols; } function updateStatusVariableFromState(_id: string, status: boolean, vars: IVariable[]): IVariable[] { - vars[0].isActive = status; - return vars; + vars[0].isActive = status; + return vars; } function appendRequestToCollectionState(item: IHistory | IFolder, colId: string, folderId: string, cols: ICollections[]): ICollections[] { - const { found, index } = findItemById(colId, cols); - if (found) { - if (folderId) { - let folder = findItem(cols[index], folderId); - if (folder) { - folder.data.push(item); - } - } else { - cols[index].data.push(item); - } - } - - return cols; + const { found, index } = findItemById(colId, cols); + if (found) { + if (folderId) { + let folder = findItem(cols[index], folderId); + if (folder) { + folder.data.push(item); + } + } else { + cols[index].data.push(item); + } + } + + return cols; } function updateItemInCollectionState(item: IHistory, colId: string, cols: ICollections[]): ICollections[] { - let { found, index } = findItemById(colId, cols); - if (found) { - cols[index] = updateItem(cols[index], item.id, item); - } - return cols; + let { found, index } = findItemById(colId, cols); + if (found) { + cols[index] = updateItem(cols[index], item.id, item); + } + return cols; } function updateItemInHistoryState(item: IHistory, items: IHistory[]): IHistory[] { - let { found, index } = findItemById(item.id, items); - if (found) { - items[index] = item; - } + let { found, index } = findItemById(item.id, items); + if (found) { + items[index] = item; + } - return items; + return items; } function findItem(source: any, searchId: string) { - let pos = source.data.findIndex((el: any) => el.id === searchId); - - if (pos !== -1) { - return source.data[pos]; - } - - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - const result = findItem(source.data[i], searchId); - if (result) { - return result; - } - } - } + let pos = source.data.findIndex((el: any) => el.id === searchId); + + if (pos !== -1) { + return source.data[pos]; + } + + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + const result = findItem(source.data[i], searchId); + if (result) { + return result; + } + } + } } function deleteItem(source: any, id: string) { - let pos = source.data.findIndex((el: any) => el.id === id); + let pos = source.data.findIndex((el: any) => el.id === id); - if (pos !== -1) { - source.data.splice(pos, 1); - } + if (pos !== -1) { + source.data.splice(pos, 1); + } - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - deleteItem(source.data[i], id); - } - } + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + deleteItem(source.data[i], id); + } + } } function updateItem(source: any, id: string, item: IHistory): any { - let pos = source.data.findIndex((el: any) => el.id === id); + let pos = source.data.findIndex((el: any) => el.id === id); - if (pos !== -1) { - source.data[pos] = item; - return source; - } + if (pos !== -1) { + source.data[pos] = item; + return source; + } - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - updateItem(source.data[i], id, item); - } - } + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + updateItem(source.data[i], id, item); + } + } - return source; + return source; } diff --git a/src/fetch-client-ui/components/SideBar/redux/types.ts b/src/fetch-client-ui/components/SideBar/redux/types.ts index 4c637e9..e40079b 100644 --- a/src/fetch-client-ui/components/SideBar/redux/types.ts +++ b/src/fetch-client-ui/components/SideBar/redux/types.ts @@ -2,49 +2,49 @@ import { ITableData } from "../../Common/Table/types"; import { IAuth, IPreFetch } from "../../RequestUI/redux/types"; export interface IHistory { - id: string; - method: string; - name: string; - url: string; - createdTime: string; + id: string; + method: string; + name: string; + url: string; + createdTime: string; } export interface ISettings { - auth: IAuth; - preFetch?: IPreFetch; - headers?: ITableData[]; + auth: IAuth; + preFetch?: IPreFetch; + headers?: ITableData[]; } export interface ICollections { - id: string; - name: string; - createdTime: string; - data?: (IHistory | IFolder)[]; - variableId: string; - settings: ISettings; + id: string; + name: string; + createdTime: string; + data?: (IHistory | IFolder)[]; + variableId: string; + settings: ISettings; } export interface IFolder { - id: string; - name: string; - createdTime: string; - type: "folder"; - data?: (IHistory | IFolder)[]; - settings: ISettings; + id: string; + name: string; + createdTime: string; + type: "folder"; + data?: (IHistory | IFolder)[]; + settings: ISettings; } export interface IVariable { - id: string; - name: string; - createdTime: string; - isActive: boolean; - data: ITableData[]; + id: string; + name: string; + createdTime: string; + isActive: boolean; + data: ITableData[]; } export interface ISideBarModel { - history: IHistory[]; - collections: ICollections[]; - variable: IVariable[]; + history: IHistory[]; + collections: ICollections[]; + variable: IVariable[]; } export const FETCH_CLIENT_SET_HISTORY: "FETCH_CLIENT_SET_HISTORY" = "FETCH_CLIENT_SET_HISTORY"; @@ -74,199 +74,199 @@ export const FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM: "FETCH_CLIENT_SET_UPDATE_HIST export interface ISetHistory { - type: typeof FETCH_CLIENT_SET_HISTORY; - payload: { - history: IHistory[]; - }; + type: typeof FETCH_CLIENT_SET_HISTORY; + payload: { + history: IHistory[]; + }; } export interface ISetNewHistory { - type: typeof FETCH_CLIENT_SET_NEW_HISTORY; - payload: { - history: IHistory; - }; + type: typeof FETCH_CLIENT_SET_NEW_HISTORY; + payload: { + history: IHistory; + }; } export interface ISetCollection { - type: typeof FETCH_CLIENT_SET_COLLECTION; - payload: { - collections: ICollections[]; - }; + type: typeof FETCH_CLIENT_SET_COLLECTION; + payload: { + collections: ICollections[]; + }; } export interface ISetHistoryToCollection { - type: typeof FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION; - payload: { - collection: ICollections; - }; + type: typeof FETCH_CLIENT_SET_NEW_HISTORY_TO_COLLECTION; + payload: { + collection: ICollections; + }; } export interface ISetDeleteHistory { - type: typeof FETCH_CLIENT_SET_DELETE_HISTORY; - payload: { - id: string; - }; + type: typeof FETCH_CLIENT_SET_DELETE_HISTORY; + payload: { + id: string; + }; } export interface ISetRenameHistory { - type: typeof FETCH_CLIENT_SET_RENAME_HISTORY; - payload: { - id: string; - name: string; - }; + type: typeof FETCH_CLIENT_SET_RENAME_HISTORY; + payload: { + id: string; + name: string; + }; } export interface ISetRenameColItem { - type: typeof FETCH_CLIENT_SET_RENAME_COL_ITEM; - payload: { - colId: string; - folderId: string; - historyId: string; - isFolder: boolean; - name: string; - }; + type: typeof FETCH_CLIENT_SET_RENAME_COL_ITEM; + payload: { + colId: string; + folderId: string; + historyId: string; + isFolder: boolean; + name: string; + }; } export interface ISetDeleteColItem { - type: typeof FETCH_CLIENT_SET_DELETE_COL_ITEM; - payload: { - colId: string; - folderId: string; - historyId: string; - isFolder: boolean; - }; + type: typeof FETCH_CLIENT_SET_DELETE_COL_ITEM; + payload: { + colId: string; + folderId: string; + historyId: string; + isFolder: boolean; + }; } export interface ISetRenameCollection { - type: typeof FETCH_CLIENT_SET_RENAME_COLLECTION; - payload: { - colId: string; - name: string; - }; + type: typeof FETCH_CLIENT_SET_RENAME_COLLECTION; + payload: { + colId: string; + name: string; + }; } export interface ISetDeleteCollection { - type: typeof FETCH_CLIENT_SET_DELETE_COLLECTION; - payload: { - colId: string; - }; + type: typeof FETCH_CLIENT_SET_DELETE_COLLECTION; + payload: { + colId: string; + }; } export interface ISetClearCollection { - type: typeof FETCH_CLIENT_SET_CLEAR_COLLECTION; - payload: { - colId: string; - folderId: string; - }; + type: typeof FETCH_CLIENT_SET_CLEAR_COLLECTION; + payload: { + colId: string; + folderId: string; + }; } export interface ISetImportCollection { - type: typeof FETCH_CLIENT_SET_IMPORT_COLLECTION; - payload: { - collection: ICollections; - }; + type: typeof FETCH_CLIENT_SET_IMPORT_COLLECTION; + payload: { + collection: ICollections; + }; } export interface ISetCopyToCollection { - type: typeof FETCH_CLIENT_SET_COPY_TO_COLLECTION; - payload: { - collection: ICollections; - }; + type: typeof FETCH_CLIENT_SET_COPY_TO_COLLECTION; + payload: { + collection: ICollections; + }; } export interface ISetVariable { - type: typeof FETCH_CLIENT_SET_VARIABLE; - payload: { - variable: IVariable[]; - }; + type: typeof FETCH_CLIENT_SET_VARIABLE; + payload: { + variable: IVariable[]; + }; } export interface ISetDeleteVariable { - type: typeof FETCH_CLIENT_SET_DELETE_VARIABLE; - payload: { - varId: string; - }; + type: typeof FETCH_CLIENT_SET_DELETE_VARIABLE; + payload: { + varId: string; + }; } export interface ISetRenameVariable { - type: typeof FETCH_CLIENT_SET_RENAME_VARIABLE; - payload: { - varId: string; - name: string; - }; + type: typeof FETCH_CLIENT_SET_RENAME_VARIABLE; + payload: { + varId: string; + name: string; + }; } export interface ISetNewVariable { - type: typeof FETCH_CLIENT_SET_NEW_VARIABLE; - payload: { - variable: IVariable; - }; + type: typeof FETCH_CLIENT_SET_NEW_VARIABLE; + payload: { + variable: IVariable; + }; } export interface ISetUpdateVariable { - type: typeof FETCH_CLIENT_SET_UPDATE_VARIABLE; - payload: { - variable: IVariable; - }; + type: typeof FETCH_CLIENT_SET_UPDATE_VARIABLE; + payload: { + variable: IVariable; + }; } export interface ISetUpdateVariable { - type: typeof FETCH_CLIENT_SET_UPDATE_VARIABLE; - payload: { - variable: IVariable; - }; + type: typeof FETCH_CLIENT_SET_UPDATE_VARIABLE; + payload: { + variable: IVariable; + }; } export interface ISetAttachVariable { - type: typeof FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE; - payload: { - colId: string; - varId: string; - }; + type: typeof FETCH_CLIENT_SET_ATTACH_DETACH_VARIABLE; + payload: { + colId: string; + varId: string; + }; } export interface ISetActiveVariable { - type: typeof FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE; - payload: { - varId: string; - status: boolean; - }; + type: typeof FETCH_CLIENT_SET_ACTIVE_INACTIVE_VARIABLE; + payload: { + varId: string; + status: boolean; + }; } export interface ISetNewRequestToCollection { - type: typeof FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION; - payload: { - item: IHistory; - id: string; - folId: string; - }; + type: typeof FETCH_CLIENT_SET_NEW_REQUEST_TO_COLLECTION; + payload: { + item: IHistory; + id: string; + folId: string; + }; } export interface ISetNewFolderToCollection { - type: typeof FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION; - payload: { - folder: IFolder; - colId: string; - folderId: string; - }; + type: typeof FETCH_CLIENT_SET_NEW_FOLDER_TO_COLLECTION; + payload: { + folder: IFolder; + colId: string; + folderId: string; + }; } export interface ISetUpdateCollectionItem { - type: typeof FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM; - payload: { - item: IHistory; - colId: string; - }; + type: typeof FETCH_CLIENT_SET_UPDATE_COLLECTION_ITEM; + payload: { + item: IHistory; + colId: string; + }; } export interface ISetUpdateHistoryItem { - type: typeof FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM; - payload: { - item: IHistory; - }; + type: typeof FETCH_CLIENT_SET_UPDATE_HISTORY_ITEM; + payload: { + item: IHistory; + }; } export type SideBarActionTypes = | ISetHistory | ISetCollection | ISetDeleteHistory | ISetRenameHistory | ISetNewHistory | ISetHistoryToCollection | - ISetRenameColItem | ISetDeleteColItem | ISetRenameCollection | ISetDeleteCollection | ISetClearCollection | ISetImportCollection | - ISetCopyToCollection | ISetVariable | ISetDeleteVariable | ISetRenameVariable | ISetNewVariable | ISetUpdateVariable | ISetAttachVariable | ISetActiveVariable | ISetNewRequestToCollection | - ISetNewFolderToCollection | ISetUpdateCollectionItem | ISetUpdateHistoryItem; \ No newline at end of file + ISetRenameColItem | ISetDeleteColItem | ISetRenameCollection | ISetDeleteCollection | ISetClearCollection | ISetImportCollection | + ISetCopyToCollection | ISetVariable | ISetDeleteVariable | ISetRenameVariable | ISetNewVariable | ISetUpdateVariable | ISetAttachVariable | ISetActiveVariable | ISetNewRequestToCollection | + ISetNewFolderToCollection | ISetUpdateCollectionItem | ISetUpdateHistoryItem; diff --git a/src/fetch-client-ui/components/SideBar/style.css b/src/fetch-client-ui/components/SideBar/style.css index 83dd13b..4b69515 100644 --- a/src/fetch-client-ui/components/SideBar/style.css +++ b/src/fetch-client-ui/components/SideBar/style.css @@ -1,322 +1,322 @@ .sidebar-tab-menu { - float : left; - padding : 10px; - background-color: transparent; - color : var(--text-color); - border : 0; - cursor : pointer; + float : left; + padding : 10px; + background-color: transparent; + color : var(--text-color); + border : 0; + cursor : pointer; } .sidebar-tab-menu-settings { - padding : 10px 20px 10px 20px; + padding : 10px 20px 10px 20px; } .selected { - border-bottom: 2.5px solid var(--button-background-color) !important; + border-bottom: 2.5px solid var(--button-background-color) !important; } .sidebar-panel-tabs { - display : flex; - justify-content: space-around; - border-bottom : 1px solid var(--vscode-sideBarSectionHeader-border); + display : flex; + justify-content: space-around; + border-bottom : 1px solid var(--vscode-sideBarSectionHeader-border); } .sidebar-panel { - height : calc(100vh - 131px); - width : 100%; - display: block; - padding: 0; + height : calc(100vh - 131px); + width : 100%; + display: block; + padding: 0; } .sidebar-body { - font-size: smaller; - height : 100%; + font-size: smaller; + height : 100%; } .activity-items-panel { - height : calc(100% - 30px); - overflow-y: auto; - overflow-x: hidden; - cursor : pointer; + height : calc(100% - 30px); + overflow-y: auto; + overflow-x: hidden; + cursor : pointer; } .activity-items { - padding: 0 5px 5px; - cursor : pointer; + padding: 0 5px 5px; + cursor : pointer; } .dark-theme-boder { - border-bottom: 0.25px solid #343434; + border-bottom: 0.25px solid #343434; } .light-theme-boder { - border-bottom: 0.25px solid #cbcbcb; + border-bottom: 0.25px solid #cbcbcb; } .folder-activity-items { - padding-left: var(--fpl) !important; + padding-left: var(--fpl) !important; } .activity-items:hover, .folder-activity-items:hover { - background-color: var(--list-hover-background-color); + background-color: var(--list-hover-background-color); } .activity-method { - display : block; - width : fit-content; - padding : 2px 5px 0; - border-radius: 5px; - height : 15px; - text-align : center; - font-weight : bold; - font-size : smaller; - cursor : pointer; - color : var(--button-text-color); + display : block; + width : fit-content; + padding : 2px 5px 0; + border-radius: 5px; + height : 15px; + text-align : center; + font-weight : bold; + font-size : smaller; + cursor : pointer; + color : var(--button-text-color); } .pass { - background-color: rgb(2, 151, 2); + background-color: rgb(2, 151, 2); } .get-mtd { - background-color: rgb(2, 151, 2); + background-color: rgb(2, 151, 2); } .post-mtd { - background-color: #c5830b; + background-color: #c5830b; } .put-mtd { - background-color: #247bc1; + background-color: #247bc1; } .patch-mtd { - background-color: #767676; + background-color: #767676; } .delete-mtd { - background-color: #bd2b2b; + background-color: #bd2b2b; } .other-mtd { - background-color: #404040; + background-color: #404040; } .disabled-mtd { - background-color: var(--input-unchecked); + background-color: var(--input-unchecked); } .activity-item-row-1 { - padding: 10px 10px 5px; - display: flex; - cursor : pointer; + padding: 10px 10px 5px; + display: flex; + cursor : pointer; } .activity-url { - padding-left: 6px; - cursor : pointer; - word-break : break-word; + padding-left: 6px; + cursor : pointer; + word-break : break-word; } .activity-item-row-2 { - padding: 0 5px 2px 10px; - color : gray; - cursor : pointer; + padding: 0 5px 2px 10px; + color : gray; + cursor : pointer; } .activity-item-row-2 label { - cursor: pointer; + cursor: pointer; } .activity-search { - background-color: transparent; - color : var(--text-color); - border : 1px solid gray; - outline : none; - border-radius : 5px; - padding : 5px 10px; - margin : 10px 2px 5px 10px; - width : 80%; + background-color: transparent; + color : var(--text-color); + border : 1px solid gray; + outline : none; + border-radius : 5px; + padding : 5px 10px; + margin : 10px 2px 5px 10px; + width : 80%; } .activity-search:focus { - outline: none; + outline: none; } .activity-filter { - display: flex; + display: flex; } .hamburger-menu-panel { - padding: 15px 5px 0; + padding: 15px 5px 0; } .hamburger-menu { - width : 16px; - height: 16px; - cursor: pointer; + width : 16px; + height: 16px; + cursor: pointer; } .hamburger-menu path { - fill: var(--text-color); + fill: var(--text-color); } .dropdown { - position: relative; - display : inline-block; + position: relative; + display : inline-block; } .dropdown-content { - display : none; - position : absolute; - width : 125px; - overflow : auto; - box-shadow : 10px 8px 16px 0 rgba(0, 0, 0, 0.4); - right : 0; - z-index : 1; - /* border-radius: 5px; */ - color : var(--text-color); - background-color: var(--background-color); - border : 1px solid var(--border-color); - top : 32px; + display : none; + position : absolute; + width : 125px; + overflow : auto; + box-shadow : 10px 8px 16px 0 rgba(0, 0, 0, 0.4); + right : 0; + z-index : 1; + /* border-radius: 5px; */ + color : var(--text-color); + background-color: var(--background-color); + border : 1px solid var(--border-color); + top : 32px; } .dropdown-content button, .dropdown-more button { - padding : 5px 10px; - text-decoration : none; - width : 100%; - cursor : pointer; - background-color: var(--background-color); - color : var(--text-color); - outline : none; - border : 3px solid transparent; - border-radius : 0; - text-align : left; + padding : 5px 10px; + text-decoration : none; + width : 100%; + cursor : pointer; + background-color: var(--background-color); + color : var(--text-color); + outline : none; + border : 3px solid transparent; + border-radius : 0; + text-align : left; } .dropdown-content button:hover, .dropdown button:hover, .dropdown-more button:hover { - background-color: var(--button-hover-color); - color : var(--button-text-color); + background-color: var(--button-hover-color); + color : var(--button-text-color); } .show { - display: block; + display: block; } .more-icon { - float : right; - display : none; - /* padding-top: 2px; */ + float : right; + display : none; + /* padding-top: 2px; */ } .plus-icon { - height : 14px; - width : 14px; - fill : currentColor; - stroke : currentColor; - stroke : currentcolor; - stroke-linecap : round; - stroke-linejoin: round; - stroke-width : 1.5; + height : 14px; + width : 14px; + fill : currentColor; + stroke : currentColor; + stroke : currentcolor; + stroke-linecap : round; + stroke-linejoin: round; + stroke-width : 1.5; } .activity-items:hover .more-icon { - display: block; + display: block; } .display-block { - position: relative; - display : inline-block; + position: relative; + display : inline-block; } .dd-input { - display: none; + display: none; } .dropdown-more { - position : absolute; - width : 140px; - box-shadow : 10px 8px 16px 0px rgba(0, 0, 0, 0.4); - z-index : 1; - color : var(--text-color); - background-color: var(--background-color); - border : 1px solid var(--border-color); - text-align : left; - right : 0; + position : absolute; + width : 140px; + box-shadow : 10px 8px 16px 0px rgba(0, 0, 0, 0.4); + z-index : 1; + color : var(--text-color); + background-color: var(--background-color); + border : 1px solid var(--border-color); + text-align : left; + right : 0; } .dd-input+.dropdown-more { - display: none; + display: none; } .dd-input:checked+.dropdown-more { - display: block; + display: block; } .new-request-button { - border : 0; - box-sizing : border-box; - display : flex; - width : 100%; - padding : 4px; - text-align : center; - cursor : pointer; - justify-content : center; - align-items : center; - max-width : 300px; - color : var(--button-text-color); - background-color: var(--button-background-color); - height : 26px; + border : 0; + box-sizing : border-box; + display : flex; + width : 100%; + padding : 4px; + text-align : center; + cursor : pointer; + justify-content : center; + align-items : center; + max-width : 300px; + color : var(--button-text-color); + background-color: var(--button-background-color); + height : 26px; } .new-request-button:hover { - background-color: var(--button-hover-color); + background-color: var(--button-hover-color); } .new-request-panel { - margin : 0 auto; - max-width : 300px; - transition: max-width .2s ease-out; - padding : 10px 20px 1em; + margin : 0 auto; + max-width : 300px; + transition: max-width .2s ease-out; + padding : 10px 20px 1em; } .sidebar-panel-body { - height: 100%; + height: 100%; } .selected-item { - border-left : 3px solid var(--button-background-color); - background-color: var(--list-hover-background-color); + border-left : 3px solid var(--button-background-color); + background-color: var(--list-hover-background-color); } .bottom-menu-panel { - padding : 5px; - height : 20px; - background-color: var(--vscode-dropdown-border); + padding : 5px; + height : 20px; + background-color: var(--vscode-dropdown-border); } .view-log { - align-items : center; - flex-direction : row; - cursor : pointer; - display : flex; - justify-content: center; - color : var(--text-color); + align-items : center; + flex-direction : row; + cursor : pointer; + display : flex; + justify-content: center; + color : var(--text-color); } .log-span { - font-size: 13px; + font-size: 13px; } .view-log:hover { - color: var(--vscode-textLink-activeForeground); + color: var(--vscode-textLink-activeForeground); } .log-icon { - transform: scale(0.3); -} \ No newline at end of file + transform: scale(0.3); +} diff --git a/src/fetch-client-ui/components/SideBar/util.ts b/src/fetch-client-ui/components/SideBar/util.ts index bc6a211..1c4daa6 100644 --- a/src/fetch-client-ui/components/SideBar/util.ts +++ b/src/fetch-client-ui/components/SideBar/util.ts @@ -1,65 +1,63 @@ -import { IFolder, IHistory } from "./redux/types"; - export function getDays(date1: string, date2: Date) { - const _MS_PER_DAY = 1000 * 60 * 60 * 24; - - let dateFormat = new Date(date1); - const utc1 = Date.UTC(dateFormat.getFullYear(), dateFormat.getMonth(), dateFormat.getDate()); - const utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()); - - const diffDays = Math.floor((utc2 - utc1) / _MS_PER_DAY); - - if (diffDays === 0) { - return "Today"; - } - if (diffDays === 1) { - return "Yesterday"; - } - if (diffDays > 365) { - let year = Math.floor(diffDays / 365); - return year + (year > 1 ? " years ago" : " year ago"); - } - if (diffDays > 30) { - let month = Math.floor(diffDays / 30); - return month + (month > 1 ? " months ago" : " month ago"); - } - if (diffDays > 7) { - let week = Math.floor(diffDays / 7); - return week + (week > 1 ? " weeks ago" : " week ago"); - } - return diffDays + " days ago"; + const _MS_PER_DAY = 1000 * 60 * 60 * 24; + + let dateFormat = new Date(date1); + const utc1 = Date.UTC(dateFormat.getFullYear(), dateFormat.getMonth(), dateFormat.getDate()); + const utc2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()); + + const diffDays = Math.floor((utc2 - utc1) / _MS_PER_DAY); + + if (diffDays === 0) { + return "Today"; + } + if (diffDays === 1) { + return "Yesterday"; + } + if (diffDays > 365) { + let year = Math.floor(diffDays / 365); + return year + (year > 1 ? " years ago" : " year ago"); + } + if (diffDays > 30) { + let month = Math.floor(diffDays / 30); + return month + (month > 1 ? " months ago" : " month ago"); + } + if (diffDays > 7) { + let week = Math.floor(diffDays / 7); + return week + (week > 1 ? " weeks ago" : " week ago"); + } + return diffDays + " days ago"; } export function getMethodClassName(method: string, disabled?: boolean) { - if (disabled !== undefined && disabled !== null && disabled === false) { - return "disabled-mtd"; - } - - switch (method) { - case "GET": - return "get-mtd"; - case "POST": - return "post-mtd"; - case "PUT": - return "put-mtd"; - case "PATCH": - return "patch-mtd"; - case "DELETE": - return "delete-mtd"; - default: - return "other-mtd"; - } + if (disabled !== undefined && disabled !== null && disabled === false) { + return "disabled-mtd"; + } + + switch (method) { + case "GET": + return "get-mtd"; + case "POST": + return "post-mtd"; + case "PUT": + return "put-mtd"; + case "PATCH": + return "patch-mtd"; + case "DELETE": + return "delete-mtd"; + default: + return "other-mtd"; + } } export function getMethodName(method: string) { - if (method === "OPTIONS") { - return "OPT"; - } + if (method === "OPTIONS") { + return "OPT"; + } - return method; + return method; } export function isFolder(item: any): boolean { - return item.data !== undefined; -} \ No newline at end of file + return item.data !== undefined; +} diff --git a/src/fetch-client-ui/components/TestUI/TestPanel/consts.ts b/src/fetch-client-ui/components/TestUI/TestPanel/consts.ts index 8b935c7..c4e7311 100644 --- a/src/fetch-client-ui/components/TestUI/TestPanel/consts.ts +++ b/src/fetch-client-ui/components/TestUI/TestPanel/consts.ts @@ -1,122 +1,122 @@ export const ActionsParametersMapping = { - "Content-Type": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "contains", value: "contains" }, - { name: "regex", value: "regex" }, - ] - }, - "Content-Length": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "regex", value: "regex" }, - ] - }, - "Content-Encoding": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "regex", value: "regex" }, - ] - }, - "Header": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "contains", value: "contains" }, - { name: "type", value: "type" }, - { name: "regex", value: "regex" }, - ] - }, - "Response Code": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "<", value: "<" }, - { name: "<=", value: "<=" }, - { name: ">", value: ">" }, - { name: ">=", value: ">=" }, - { name: "regex", value: "regex" }, - ] - }, - "Response Body": { - "action": [ - { name: "select", value: "", }, - { name: "isJSON", value: "isJSON" }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "contains", value: "contains" }, - { name: "regex", value: "regex" }, - ] - }, - "Response Time": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "<", value: "<" }, - { name: "<=", value: "<=" }, - { name: ">", value: ">" }, - { name: ">=", value: ">=" }, - ] - }, - "JSON": { - "action": [ - { name: "select", value: "", }, - { name: "equal", value: "equal" }, - { name: "notEqual", value: "notEqual" }, - { name: "<", value: "<" }, - { name: "<=", value: "<=" }, - { name: ">", value: ">" }, - { name: ">=", value: ">=" }, - { name: "contains", value: "contains" }, - { name: "notContains", value: "notContains" }, - { name: "length", value: "length" }, - { name: "type", value: "type" }, - { name: "regex", value: "regex" }, - ] - }, + "Content-Type": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "contains", value: "contains" }, + { name: "regex", value: "regex" }, + ] + }, + "Content-Length": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "regex", value: "regex" }, + ] + }, + "Content-Encoding": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "regex", value: "regex" }, + ] + }, + "Header": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "contains", value: "contains" }, + { name: "type", value: "type" }, + { name: "regex", value: "regex" }, + ] + }, + "Response Code": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "<", value: "<" }, + { name: "<=", value: "<=" }, + { name: ">", value: ">" }, + { name: ">=", value: ">=" }, + { name: "regex", value: "regex" }, + ] + }, + "Response Body": { + "action": [ + { name: "select", value: "", }, + { name: "isJSON", value: "isJSON" }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "contains", value: "contains" }, + { name: "regex", value: "regex" }, + ] + }, + "Response Time": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "<", value: "<" }, + { name: "<=", value: "<=" }, + { name: ">", value: ">" }, + { name: ">=", value: ">=" }, + ] + }, + "JSON": { + "action": [ + { name: "select", value: "", }, + { name: "equal", value: "equal" }, + { name: "notEqual", value: "notEqual" }, + { name: "<", value: "<" }, + { name: "<=", value: "<=" }, + { name: ">", value: ">" }, + { name: ">=", value: ">=" }, + { name: "contains", value: "contains" }, + { name: "notContains", value: "notContains" }, + { name: "length", value: "length" }, + { name: "type", value: "type" }, + { name: "regex", value: "regex" }, + ] + }, }; export const ParametersModelMapping = { - "Response Code": "response.status", - "Response Body": "response.responseData", - "Response Time": "response.duration", - "Content-Type": "headers.Content-Type", - "Content-Length": "headers.Content-Length", - "Content-Encoding": "headers.Content-Encoding", - "Header": "headers.[specific]", - "JSON": "responseData.[specific]", - "Variable": "variable" + "Response Code": "response.status", + "Response Body": "response.responseData", + "Response Time": "response.duration", + "Content-Type": "headers.Content-Type", + "Content-Length": "headers.Content-Length", + "Content-Encoding": "headers.Content-Encoding", + "Header": "headers.[specific]", + "JSON": "responseData.[specific]", + "Variable": "variable" }; export const TestCaseParameters = [ - { name: "select", value: "", }, - { name: "Content-Type", value: "Content-Type", }, - { name: "Content-Length", value: "Content-Length", }, - { name: "Content-Encoding", value: "Content-Encoding", }, - { name: "Header", value: "Header", }, - { name: "ResponseCode", value: "Response Code", }, - { name: "ResponseBody", value: "Response Body", }, - { name: "ResponseTime", value: "Response Time", }, - { name: "Json Query", value: "JSON", } + { name: "select", value: "", }, + { name: "Content-Type", value: "Content-Type", }, + { name: "Content-Length", value: "Content-Length", }, + { name: "Content-Encoding", value: "Content-Encoding", }, + { name: "Header", value: "Header", }, + { name: "ResponseCode", value: "Response Code", }, + { name: "ResponseBody", value: "Response Body", }, + { name: "ResponseTime", value: "Response Time", }, + { name: "Json Query", value: "JSON", } ]; export const TestValueSuggestions = [ - "string", - "boolean", - "number", - "object", - "array", - "true", - "false", - "null", - "undefined" -]; \ No newline at end of file + "string", + "boolean", + "number", + "object", + "array", + "true", + "false", + "null", + "undefined" +]; diff --git a/src/fetch-client-ui/components/TestUI/TestPanel/helper.ts b/src/fetch-client-ui/components/TestUI/TestPanel/helper.ts index 12ad43f..4308e10 100644 --- a/src/fetch-client-ui/components/TestUI/TestPanel/helper.ts +++ b/src/fetch-client-ui/components/TestUI/TestPanel/helper.ts @@ -7,288 +7,288 @@ import { IVariable } from "../../SideBar/redux/types"; import { ParametersModelMapping } from "./consts"; export function setVariable(variable: IVariable, setVar: ISetVar[], responseValue: IReponseModel): IVariable { - let actualValue: any; - let index = -1; - - if (setVar.length > 0) { - setVar.forEach(item => { - index = -1; - actualValue = null; - if (item.parameter === "Header") { - actualValue = findHeader(responseValue.headers, item.key); - if (actualValue) { - index = variable.data.findIndex(d => d.key === item.variableName); - if (index === -1) { - variable.data.push({ - isChecked: true, - key: item.variableName, - value: actualValue - }); - } else { - variable.data[index] = { - isChecked: true, - key: item.variableName, - value: actualValue - }; - } - } - } else if (item.parameter === "Cookie") { - actualValue = findCookie(responseValue.cookies, item.key); - if (actualValue) { - index = variable.data.findIndex(d => d.key === item.variableName); - if (index === -1) { - variable.data.push({ - isChecked: true, - key: item.variableName, - value: actualValue - }); - } else { - variable.data[index] = { - isChecked: true, - key: item.variableName, - value: actualValue - }; - } - } - } else { - let mapping = ParametersModelMapping[item.parameter]; - if (mapping) { - mapping = mapping.replace("[specific]", item.key); - let responseData; - try { - responseData = JSON.parse(responseValue.response.responseData); - } catch { - responseData = ""; - } - actualValue = findValueInResponse(responseData, mapping.replace("responseData.", "")); - } - if (actualValue) { - index = variable.data.findIndex(d => d.key === item.variableName); - if (index === -1) { - variable.data.push({ - isChecked: true, - key: item.variableName, - value: actualValue - }); - } else { - variable.data[index] = { - isChecked: true, - key: item.variableName, - value: actualValue - }; - } - } - } - }); - } - - return variable; + let actualValue: any; + let index = -1; + + if (setVar.length > 0) { + setVar.forEach(item => { + index = -1; + actualValue = null; + if (item.parameter === "Header") { + actualValue = findHeader(responseValue.headers, item.key); + if (actualValue) { + index = variable.data.findIndex(d => d.key === item.variableName); + if (index === -1) { + variable.data.push({ + isChecked: true, + key: item.variableName, + value: actualValue + }); + } else { + variable.data[index] = { + isChecked: true, + key: item.variableName, + value: actualValue + }; + } + } + } else if (item.parameter === "Cookie") { + actualValue = findCookie(responseValue.cookies, item.key); + if (actualValue) { + index = variable.data.findIndex(d => d.key === item.variableName); + if (index === -1) { + variable.data.push({ + isChecked: true, + key: item.variableName, + value: actualValue + }); + } else { + variable.data[index] = { + isChecked: true, + key: item.variableName, + value: actualValue + }; + } + } + } else { + let mapping = ParametersModelMapping[item.parameter]; + if (mapping) { + mapping = mapping.replace("[specific]", item.key); + let responseData; + try { + responseData = JSON.parse(responseValue.response.responseData); + } catch { + responseData = ""; + } + actualValue = findValueInResponse(responseData, mapping.replace("responseData.", "")); + } + if (actualValue) { + index = variable.data.findIndex(d => d.key === item.variableName); + if (index === -1) { + variable.data.push({ + isChecked: true, + key: item.variableName, + value: actualValue + }); + } else { + variable.data[index] = { + isChecked: true, + key: item.variableName, + value: actualValue + }; + } + } + } + }); + } + + return variable; } export function executeTests(testData: ITest[], responseValue: IReponseModel, variableData: ITableData[]): ITestResult[] { - let actualValue: any; - let testResults: ITestResult[] = []; - let varData = {}; - let tests: ITest[]; - - if (variableData?.length > 0) { - variableData.forEach(item => { - varData[item.key] = item.value; - }); - let copy = JSON.parse(JSON.stringify(testData)); - tests = replaceTestWithVariable(copy, varData); - } else { - tests = testData; - } - - for (let i = 0; i < tests.length; i++) { - - if (tests[i].parameter === "") { - continue; - } - - if (tests[i].parameter === "noCondition") { - let testResult: ITestResult = { - test: tests[i].parameter, - actualValue: "", - result: true - }; - - testResults.push(testResult); - - continue; - } - - let mapping = ParametersModelMapping[tests[i].parameter]; - if (mapping === "") { - continue; - } - - if (mapping.includes("[specific]")) { - mapping = mapping.replace("[specific]", tests[i].customParameter); - } - - if (mapping.includes("response.")) { - actualValue = findValueInResponse(responseValue, mapping); - } else if (mapping.includes("responseData.")) { - let responseData; - try { - responseData = JSON.parse(responseValue.response.responseData); - } catch { - responseData = ""; - } - actualValue = findValueInResponse(responseData, mapping.replace("responseData.", "")); - } else if (mapping.includes("variable")) { - let item = variableData?.find(t => t.key === tests[i].expectedValue.replace("{{", "").replace("}}", "").trim()); - actualValue = item?.value; - } else { - actualValue = findHeader(responseValue.headers, mapping.replace("headers.", "")); - } - - if (tests[i].action === "length") { - actualValue = actualValue ? actualValue.length : 0; - } - - if (tests[i].action === "type") { - if (Array.isArray(actualValue) || Object.prototype.toString.call(actualValue) === '[object Array]') { - actualValue = "array"; - } else { - actualValue = actualValue ? typeof (actualValue) : undefined; - } - } - - let testResult: ITestResult = { - test: tests[i].parameter + (tests[i].customParameter ? " (" + tests[i].customParameter + ")" : "") + " " + getLinkedWord(tests[i].action) + tests[i].expectedValue, - actualValue: actualValue === undefined ? "undefined" : (actualValue === null ? "null" : actualValue), - result: executeTestCase(tests[i].action, actualValue, tests[i].expectedValue === "null" ? null : tests[i].expectedValue) - }; - - testResults.push(testResult); - } - - return testResults; + let actualValue: any; + let testResults: ITestResult[] = []; + let varData = {}; + let tests: ITest[]; + + if (variableData?.length > 0) { + variableData.forEach(item => { + varData[item.key] = item.value; + }); + let copy = JSON.parse(JSON.stringify(testData)); + tests = replaceTestWithVariable(copy, varData); + } else { + tests = testData; + } + + for (let i = 0; i < tests.length; i++) { + + if (tests[i].parameter === "") { + continue; + } + + if (tests[i].parameter === "noCondition") { + let testResult: ITestResult = { + test: tests[i].parameter, + actualValue: "", + result: true + }; + + testResults.push(testResult); + + continue; + } + + let mapping = ParametersModelMapping[tests[i].parameter]; + if (mapping === "") { + continue; + } + + if (mapping.includes("[specific]")) { + mapping = mapping.replace("[specific]", tests[i].customParameter); + } + + if (mapping.includes("response.")) { + actualValue = findValueInResponse(responseValue, mapping); + } else if (mapping.includes("responseData.")) { + let responseData; + try { + responseData = JSON.parse(responseValue.response.responseData); + } catch { + responseData = ""; + } + actualValue = findValueInResponse(responseData, mapping.replace("responseData.", "")); + } else if (mapping.includes("variable")) { + let item = variableData?.find(t => t.key === tests[i].expectedValue.replace("{{", "").replace("}}", "").trim()); + actualValue = item?.value; + } else { + actualValue = findHeader(responseValue.headers, mapping.replace("headers.", "")); + } + + if (tests[i].action === "length") { + actualValue = actualValue ? actualValue.length : 0; + } + + if (tests[i].action === "type") { + if (Array.isArray(actualValue) || Object.prototype.toString.call(actualValue) === '[object Array]') { + actualValue = "array"; + } else { + actualValue = actualValue ? typeof (actualValue) : undefined; + } + } + + let testResult: ITestResult = { + test: tests[i].parameter + (tests[i].customParameter ? " (" + tests[i].customParameter + ")" : "") + " " + getLinkedWord(tests[i].action) + tests[i].expectedValue, + actualValue: actualValue === undefined ? "undefined" : (actualValue === null ? "null" : actualValue), + result: executeTestCase(tests[i].action, actualValue, tests[i].expectedValue === "null" ? null : tests[i].expectedValue) + }; + + testResults.push(testResult); + } + + return testResults; } function getLinkedWord(action: string) { - if (action === "type" || action === "length") { - return action + " is "; - } + if (action === "type" || action === "length") { + return action + " is "; + } - if (action === "contains") { - return "contains "; - } + if (action === "contains") { + return "contains "; + } - if (action === "regex") { - return " match with regex "; - } + if (action === "regex") { + return " match with regex "; + } - return action + " to "; + return action + " to "; } function executeTestCase(action: string, actualValue: string | number | undefined | null, expectedValue: string | number | undefined | null): boolean { - switch (action) { - case "equal": - return actualValue == expectedValue; - case "notEqual": - return actualValue != expectedValue; - case "contains": - return (actualValue?.toString()).includes(expectedValue?.toString()); - case "notContains": - return !((actualValue?.toString()).includes(expectedValue?.toString())); - case "<": - return actualValue < expectedValue; - case "<=": - return actualValue <= expectedValue; - case ">": - return actualValue > expectedValue; - case ">=": - return actualValue >= expectedValue; - case "length": - return actualValue == expectedValue; - case "type": - return actualValue == (expectedValue?.toString().trim().toLocaleLowerCase() === "undefined" ? undefined : expectedValue); - case "isJSON": - return isJson(actualValue) === (expectedValue ? expectedValue : "true"); - case "regex": - return checkRegexMatch(expectedValue?.toString(), actualValue); - case "empty": - return actualValue === "" || actualValue === null || actualValue === undefined; - case "notEmpty": - return actualValue !== "" && actualValue !== null && actualValue !== undefined; - } - - return false; + switch (action) { + case "equal": + return actualValue == expectedValue; + case "notEqual": + return actualValue != expectedValue; + case "contains": + return (actualValue?.toString()).includes(expectedValue?.toString()); + case "notContains": + return !((actualValue?.toString()).includes(expectedValue?.toString())); + case "<": + return actualValue < expectedValue; + case "<=": + return actualValue <= expectedValue; + case ">": + return actualValue > expectedValue; + case ">=": + return actualValue >= expectedValue; + case "length": + return actualValue == expectedValue; + case "type": + return actualValue == (expectedValue?.toString().trim().toLocaleLowerCase() === "undefined" ? undefined : expectedValue); + case "isJSON": + return isJson(actualValue) === (expectedValue ? expectedValue : "true"); + case "regex": + return checkRegexMatch(expectedValue?.toString(), actualValue); + case "empty": + return actualValue === "" || actualValue === null || actualValue === undefined; + case "notEmpty": + return actualValue !== "" && actualValue !== null && actualValue !== undefined; + } + + return false; } function checkRegexMatch(regex: string, value: string | number | undefined | null): boolean { - if (!regex) { - return false; - } - - try { - value = value ? value.toString() : ""; - let re = new RegExp(regex, "gm"); - return re.test(value); - } catch { - return false; - } + if (!regex) { + return false; + } + + try { + value = value ? value.toString() : ""; + let re = new RegExp(regex, "gm"); + return re.test(value); + } catch { + return false; + } } function findHeader(headers: ITableData[], headerValue: string): string { - try { - let selectedHeader = headers.find(header => header.key.trim().toUpperCase() === headerValue.trim().toUpperCase()); - return selectedHeader ? selectedHeader.value : ""; - } - catch { - return ""; - } + try { + let selectedHeader = headers.find(header => header.key.trim().toUpperCase() === headerValue.trim().toUpperCase()); + return selectedHeader ? selectedHeader.value : ""; + } + catch { + return ""; + } } function findCookie(cookies: ITableData[], cookieValue: string): string { - try { - let selectedCookie = cookies.find(header => header.key.trim().toUpperCase() === cookieValue.trim().toUpperCase()); - return selectedCookie ? selectedCookie.value : ""; - } - catch { - return ""; - } + try { + let selectedCookie = cookies.find(header => header.key.trim().toUpperCase() === cookieValue.trim().toUpperCase()); + return selectedCookie ? selectedCookie.value : ""; + } + catch { + return ""; + } } function findValueInResponse(responseValue: any, path: string) { - try { - path = path.replace(/\[(\w+)\]/g, '.$1'); - path = path.replace(/^\./, ''); - var a = path.split('.'); - for (var i = 0, n = a.length; i < n; ++i) { - var k = a[i]; - responseValue = responseValue[k] ? responseValue[k] : (responseValue[k.toLowerCase()] ? responseValue[k.toLowerCase()] : (responseValue[k.toUpperCase()] ? responseValue[k.toUpperCase()] : "")); - if (!responseValue) { - return ""; - } - } - return responseValue; - } catch { - return ""; - } + try { + path = path.replace(/\[(\w+)\]/g, '.$1'); + path = path.replace(/^\./, ''); + var a = path.split('.'); + for (var i = 0, n = a.length; i < n; ++i) { + var k = a[i]; + responseValue = responseValue[k] ? responseValue[k] : (responseValue[k.toLowerCase()] ? responseValue[k.toLowerCase()] : (responseValue[k.toUpperCase()] ? responseValue[k.toUpperCase()] : "")); + if (!responseValue) { + return ""; + } + } + return responseValue; + } catch { + return ""; + } } export function replaceTestWithVariable(tests: ITest[], varData: any): ITest[] { - tests.forEach(test => { - if (test.parameter !== "Variable") { - test.customParameter = replaceDataWithVariable(test.customParameter, varData); - test.expectedValue = replaceDataWithVariable(test.expectedValue, varData); - } - }); - - return tests; + tests.forEach(test => { + if (test.parameter !== "Variable") { + test.customParameter = replaceDataWithVariable(test.customParameter, varData); + test.expectedValue = replaceDataWithVariable(test.expectedValue, varData); + } + }); + + return tests; } export function isJson(str: any): string { - try { - JSON.parse(str); - } catch (e) { - return "false"; - } - return "true"; -} \ No newline at end of file + try { + JSON.parse(str); + } catch (e) { + return "false"; + } + return "true"; +} diff --git a/src/fetch-client-ui/components/TestUI/TestPanel/index.tsx b/src/fetch-client-ui/components/TestUI/TestPanel/index.tsx index 24a03da..ecdb00b 100644 --- a/src/fetch-client-ui/components/TestUI/TestPanel/index.tsx +++ b/src/fetch-client-ui/components/TestUI/TestPanel/index.tsx @@ -1,197 +1,197 @@ import React from "react"; -import { ReactComponent as BinLogo } from '../../../../../icons/bin.svg'; import { useDispatch, useSelector } from "react-redux"; +import { ReactComponent as BinLogo } from '../../../../../icons/bin.svg'; import { IRootState } from "../../../reducer/combineReducer"; +import { Autocomplete } from "../../Common/Autocomplete/Autocomplete"; +import { HerdersValues } from "../../Common/Table/types"; +import { TextEditor } from "../../Common/TextEditor/TextEditor"; import { Actions } from "../../RequestUI/redux"; import { ITest } from "../../RequestUI/redux/types"; import { ActionsParametersMapping, TestCaseParameters, TestValueSuggestions } from "./consts"; import "./style.css"; -import { TextEditor } from "../../Common/TextEditor/TextEditor"; -import { Autocomplete } from "../../Common/Autocomplete/Autocomplete"; -import { HerdersValues } from "../../Common/Table/types"; export const TestPanel = () => { - const dispatch = useDispatch(); - - const { tests } = useSelector((state: IRootState) => state.requestData); - const { selectedVariable } = useSelector((state: IRootState) => state.variableData); - - const onSelectItem = (value: string, index: number, type: string) => { - let newRow: ITest = { - parameter: "", - action: "", - expectedValue: "", - customParameter: "" - }; - - let localTable = addValue(value, index, type); - - if (index === tests.length - 1 && (((localTable[index].parameter === "Header" || localTable[index].parameter === "JSON") && localTable[index].customParameter) || (localTable[index].parameter !== "Header" && localTable[index].parameter !== "JSON")) && localTable[index].action) { - localTable.push(newRow); - } - - dispatch(Actions.SetTestAction(localTable)); - }; - - const onSelect = (event: React.ChangeEvent | React.ChangeEvent, index: number, type: string) => { - onSelectItem(event.target.value, index, type); - }; - - function onDelete(index: number) { - let localTable = [...tests]; - localTable.splice(index, 1); - dispatch(Actions.SetTestAction(localTable)); - } - - const addValue = (value: string, index: number, selectType: string): ITest[] => { - let localTable = [...tests]; - let rowData = localTable[index]; - localTable[index] = { - parameter: selectType === "parameter" ? value : rowData.parameter, - action: selectType === "action" ? value : rowData.action, - expectedValue: selectType === "expectedValue" ? value : rowData.expectedValue, - customParameter: selectType === "customParameter" ? value : rowData.customParameter - }; - - return localTable; - }; - - function getParameterList(row: ITest, index: number) { - return ( - <> - { - row.parameter === "Header" || row.parameter === "JSON" ? - selectedVariable.id && item.key)} - placeholder={row.parameter === "Header" ? "header name" : "ex: data or data.id"} - onChange={(val) => onSelectItem(val, index, "customParameter")} - value={row.customParameter} - focus={true} - /> - : - - } - - ); - } - - function getActionList(row: ITest, index: number) { - let parameter = ActionsParametersMapping[row.parameter]; - let actionList: any; - - if (parameter) { - actionList = row.parameter ? parameter["action"] : {}; - } - else { - actionList = {}; - } - - return ( - - ); - } - - const tableRow = (row: ITest, index: number) => { - return ( -
- - - - - - ); - }; - - const makeTable = (data: ITest[]) => { - return ( - data.map((item: ITest, index: number) => { - return tableRow(item, index); - }) - ); - }; - - return ( -
- {getParameterList(row, index)} - - {getActionList(row, index)} - - onSelectItem(val, index, "expectedValue")} - suggestions={[...HerdersValues, ...TestValueSuggestions]} - disabled={row.parameter !== "" && row.action !== "" ? false : true} - placeholder={row.parameter !== "" && row.action !== "" ? "value" : ""} - selectedVariable={selectedVariable} - /> - - {index !== tests.length - 1 ? - onDelete(index)} /> - : - <> - } -
- - - - - - - - - - { - makeTable(tests) - } - -
ParameterActionTest Value
- ); -}; \ No newline at end of file + const dispatch = useDispatch(); + + const { tests } = useSelector((state: IRootState) => state.requestData); + const { selectedVariable } = useSelector((state: IRootState) => state.variableData); + + const onSelectItem = (value: string, index: number, type: string) => { + let newRow: ITest = { + parameter: "", + action: "", + expectedValue: "", + customParameter: "" + }; + + let localTable = addValue(value, index, type); + + if (index === tests.length - 1 && (((localTable[index].parameter === "Header" || localTable[index].parameter === "JSON") && localTable[index].customParameter) || (localTable[index].parameter !== "Header" && localTable[index].parameter !== "JSON")) && localTable[index].action) { + localTable.push(newRow); + } + + dispatch(Actions.SetTestAction(localTable)); + }; + + const onSelect = (event: React.ChangeEvent | React.ChangeEvent, index: number, type: string) => { + onSelectItem(event.target.value, index, type); + }; + + function onDelete(index: number) { + let localTable = [...tests]; + localTable.splice(index, 1); + dispatch(Actions.SetTestAction(localTable)); + } + + const addValue = (value: string, index: number, selectType: string): ITest[] => { + let localTable = [...tests]; + let rowData = localTable[index]; + localTable[index] = { + parameter: selectType === "parameter" ? value : rowData.parameter, + action: selectType === "action" ? value : rowData.action, + expectedValue: selectType === "expectedValue" ? value : rowData.expectedValue, + customParameter: selectType === "customParameter" ? value : rowData.customParameter + }; + + return localTable; + }; + + function getParameterList(row: ITest, index: number) { + return ( + <> + { + row.parameter === "Header" || row.parameter === "JSON" ? + selectedVariable.id && item.key)} + placeholder={row.parameter === "Header" ? "header name" : "ex: data or data.id"} + onChange={(val) => onSelectItem(val, index, "customParameter")} + value={row.customParameter} + focus={true} + /> + : + + } + + ); + } + + function getActionList(row: ITest, index: number) { + let parameter = ActionsParametersMapping[row.parameter]; + let actionList: any; + + if (parameter) { + actionList = row.parameter ? parameter["action"] : {}; + } + else { + actionList = {}; + } + + return ( + + ); + } + + const tableRow = (row: ITest, index: number) => { + return ( + + + {getParameterList(row, index)} + + + {getActionList(row, index)} + + + onSelectItem(val, index, "expectedValue")} + suggestions={[...HerdersValues, ...TestValueSuggestions]} + disabled={row.parameter !== "" && row.action !== "" ? false : true} + placeholder={row.parameter !== "" && row.action !== "" ? "value" : ""} + selectedVariable={selectedVariable} + /> + + + {index !== tests.length - 1 ? + onDelete(index)} /> + : + <> + } + + + ); + }; + + const makeTable = (data: ITest[]) => { + return ( + data.map((item: ITest, index: number) => { + return tableRow(item, index); + }) + ); + }; + + return ( + + + + + + + + + + + { + makeTable(tests) + } + +
ParameterActionTest Value
+ ); +}; diff --git a/src/fetch-client-ui/components/TestUI/TestPanel/style.css b/src/fetch-client-ui/components/TestUI/TestPanel/style.css index 2fa44b7..9ca71a3 100644 --- a/src/fetch-client-ui/components/TestUI/TestPanel/style.css +++ b/src/fetch-client-ui/components/TestUI/TestPanel/style.css @@ -1,12 +1,12 @@ .test-table { - border-collapse: collapse; - width : 100%; - margin-top : 10px; - table-layout : fixed; + border-collapse: collapse; + width : 100%; + margin-top : 10px; + table-layout : fixed; } .test-table thead { - background-color: var(--list-hover-background-color); + background-color: var(--list-hover-background-color); } .test-table, @@ -15,21 +15,21 @@ .test-table td, .test-table th, .test-table tr { - border: var(--border-size) solid var(--border-color) !important; + border: var(--border-size) solid var(--border-color) !important; } .testvalue-text, .test-parameter-select, .test-action-select, .parameter-value-text { - background-color: transparent; - border : 0; - box-sizing : border-box; - color : var(--text-color); - font-size : var(--font-size); - outline : none; - padding : 10px; - width : 100%; + background-color: transparent; + border : 0; + box-sizing : border-box; + color : var(--text-color); + font-size : var(--font-size); + outline : none; + padding : 10px; + width : 100%; } .testvalue-text:focus, @@ -40,28 +40,28 @@ .test-parameter-select:hover, .test-action-select:hover, .parameter-value-text:hover { - outline: none; + outline: none; } .test-parameter-select option, .test-action-select option { - color: black; + color: black; } select:required:invalid { - color: gray; + color: gray; } option[value=""][disabled] { - display: none; + display: none; } .test-action-cell { - text-align: center; - width: 50px; + text-align: center; + width: 50px; } .test-table>tbody>tr:hover .DraftEditor-editorContainer, .test-table>tbody>tr:focus .DraftEditor-editorContainer { - background-color: var(--list-hover-background-color) !important; -} \ No newline at end of file + background-color: var(--list-hover-background-color) !important; +} diff --git a/src/fetch-client-ui/components/TestUI/TestResult/index.tsx b/src/fetch-client-ui/components/TestUI/TestResult/index.tsx index de3e8f9..3e5ccde 100644 --- a/src/fetch-client-ui/components/TestUI/TestResult/index.tsx +++ b/src/fetch-client-ui/components/TestUI/TestResult/index.tsx @@ -6,97 +6,97 @@ import "./style.css"; export const TestResult = () => { - const { response, testResults } = useSelector((state: IRootState) => state.responseData); + const { response, testResults } = useSelector((state: IRootState) => state.responseData); - const tableRow = (row: ITestResult, index: number) => { - if (row.test === "") { - return; - } - return ( - - -
- {row.test} -
- - -
- {row.actualValue?.length > 50 ? showMoreContent(row.actualValue) : row.actualValue} -
- - - - - - ); - }; + const tableRow = (row: ITestResult, index: number) => { + if (row.test === "") { + return <>; + } + return ( + + +
+ {row.test} +
+ + +
+ {row.actualValue?.length > 50 ? showMoreContent(row.actualValue) : row.actualValue} +
+ + + + + + ); + }; - function showMoreContent(value: string) { - return ( - <> -
- {value} -
- - - ); - } + function showMoreContent(value: string) { + return ( + <> +
+ {value} +
+ + + ); + } - function onShowMoreClick(e: React.MouseEvent) { - e.preventDefault(); - e.stopPropagation(); + function onShowMoreClick(e: React.MouseEvent) { + e.preventDefault(); + e.stopPropagation(); - if (e.currentTarget.innerText === "Show More") { - e.currentTarget.previousElementSibling.classList.remove("short-content"); - e.currentTarget.innerHTML = "Show Less"; - } else { - e.currentTarget.previousElementSibling.classList.add("short-content"); - e.currentTarget.innerHTML = "Show More"; - } - } + if (e.currentTarget.innerText === "Show More") { + e.currentTarget.previousElementSibling.classList.remove("short-content"); + e.currentTarget.innerHTML = "Show Less"; + } else { + e.currentTarget.previousElementSibling.classList.add("short-content"); + e.currentTarget.innerHTML = "Show More"; + } + } - const makeTable = (data: ITestResult[]) => { - return ( - data.map((item: ITestResult, index: number) => { - return tableRow(item, index); - }) - ); - }; + const makeTable = (data: ITestResult[]) => { + return ( + data.map((item: ITestResult, index: number) => { + return tableRow(item, index); + }) + ); + }; - return ( - <> - { - testResults.length > 0 && response.status !== 0 - ? - <> - - Total : {testResults.length} - Passed : {testResults.filter(i => i.result === true).length} - Failed : {testResults.filter(i => i.result === false).length} - -
- - - - - - - - - - {makeTable(testResults)} - -
TestActual ValueResult
-
- - : - <> -
-
- - } - - ); -}; \ No newline at end of file + return ( + <> + { + testResults.length > 0 && response.status !== 0 + ? + <> + + Total : {testResults.length} + Passed : {testResults.filter(i => i.result === true).length} + Failed : {testResults.filter(i => i.result === false).length} + +
+ + + + + + + + + + {makeTable(testResults)} + +
TestActual ValueResult
+
+ + : + <> +
+
+ + } + + ); +}; diff --git a/src/fetch-client-ui/components/TestUI/TestResult/style.css b/src/fetch-client-ui/components/TestUI/TestResult/style.css index 6b646b6..4a9416d 100644 --- a/src/fetch-client-ui/components/TestUI/TestResult/style.css +++ b/src/fetch-client-ui/components/TestUI/TestResult/style.css @@ -1,18 +1,18 @@ .test-result-table { - border-collapse: collapse; - width : 100%; - margin-top : 10px; + border-collapse: collapse; + width : 100%; + margin-top : 10px; } /* .test-result-table, td, th, tr { - border: var(--border-size) solid var(--border-color); + border: var(--border-size) solid var(--border-color); } */ .test-result-table thead { - background-color: var(--list-hover-background-color); + background-color: var(--list-hover-background-color); } .test-result-table, @@ -21,98 +21,98 @@ tr { .test-result-table td, .test-result-table th, .test-result-table tr { - border: var(--border-size) solid var(--border-color); + border: var(--border-size) solid var(--border-color); } tbody>tr:hover { - background-color: var(--list-hover-background-color); + background-color: var(--list-hover-background-color); } .test-result-table-input { - background-color: transparent; - border : 0; - box-sizing : border-box; - color : var(--text-color); - font-size : var(--font-size); - outline : none; - padding : 10px; - width : 100%; - text-overflow : ellipsis; + background-color: transparent; + border : 0; + box-sizing : border-box; + color : var(--text-color); + font-size : var(--font-size); + outline : none; + padding : 10px; + width : 100%; + text-overflow : ellipsis; } .test-result-test-case-col { - width : 50%; - vertical-align: top; + width : 50%; + vertical-align: top; } .test-result-actual-val-col { - width : 40%; - vertical-align: top; + width : 40%; + vertical-align: top; } .center-text { - text-align: center; + text-align: center; } .top-align { - vertical-align: top; + vertical-align: top; } .test-result-label { - display : block; - width : 50px; - border-radius: 3px; - height : 23px; - margin : 5px; - padding : 4px 0 0; - text-align : center; - font-weight : bold; + display : block; + width : 50px; + border-radius: 3px; + height : 23px; + margin : 5px; + padding : 4px 0 0; + text-align : center; + font-weight : bold; } .pass { - background-color: rgb(2, 151, 2); - color : var(--button-text-color); + background-color: rgb(2, 151, 2); + color : var(--button-text-color); } .fail { - background-color: rgb(240, 22, 22); - color : var(--button-text-color); + background-color: rgb(240, 22, 22); + color : var(--button-text-color); } .short-content { - height : 50px; - overflow : hidden; - text-overflow: ellipsis; - margin-bottom: 10px; + height : 50px; + overflow : hidden; + text-overflow: ellipsis; + margin-bottom: 10px; } .show-more-btn { - background : transparent; - border : 0; - color : var(--button-background-color); - text-align : center; - float : right; - margin-bottom: 2px; - cursor : pointer; + background : transparent; + border : 0; + color : var(--button-background-color); + text-align : center; + float : right; + margin-bottom: 2px; + cursor : pointer; } .show-more-btn:hover { - color: var(--button-hover-color); + color: var(--button-hover-color); } .test-result-title { - font-size: 14px; - display : block; - margin : 5px 10px 5px 0; - padding : 5px 10px 5px 0; + font-size: 14px; + display : block; + margin : 5px 10px 5px 0; + padding : 5px 10px 5px 0; } .test-result-title-panel { - display : flex; - font-weight: 400; + display : flex; + font-weight: 400; } .test-result-panel { - padding-right : 5px; - padding-bottom: 5px; -} \ No newline at end of file + padding-right : 5px; + padding-bottom: 5px; +} diff --git a/src/fetch-client-ui/components/Variables/index.tsx b/src/fetch-client-ui/components/Variables/index.tsx index 2565d09..f9745f5 100644 --- a/src/fetch-client-ui/components/Variables/index.tsx +++ b/src/fetch-client-ui/components/Variables/index.tsx @@ -1,187 +1,203 @@ import React, { useEffect, useState } from "react"; +import { v4 as uuidv4 } from 'uuid'; import { requestTypes, responseTypes } from "../../../utils/configuration"; +import { formatDate } from "../../../utils/helper"; import { Table } from "../Common/Table/Table"; import { ITableData } from "../Common/Table/types"; import vscode from "../Common/vscodeAPI"; import { IVariable } from "../SideBar/redux/types"; -import { v4 as uuidv4 } from 'uuid'; import "./style.css"; -import { formatDate } from "../../../utils/helper"; export interface IVariableProps { - index?: number; + index?: number; } -const Variables = (props: IVariableProps) => { - - const [isDone, setDone] = useState(false); - const [isNew, setNew] = useState(true); - const [enabled, setEnabled] = useState(true); - const [errors, setErrors] = useState({}); - const [defaultGlobal, setDefaultGlobal] = useState(false); - const [variableItem, setVariableItem] = useState(null); - const [duplicates, setDuplicates] = useState([]); - - const [collectionNames, setCollectionNames] = useState([]); - - function onRowAdd(event: React.ChangeEvent, index: number, isKey: boolean = true) { - let newRow: ITableData = { - isChecked: false, - key: "", - value: "" - }; - - let localTable = addValue(event.target.value, index, isKey); - - if (localTable[index].key && localTable[index].value) { - localTable.push(newRow); - } - - setVariableItem({ ...variableItem, data: localTable }); - setDone(false); - } - - function onRowUpdate(event: React.ChangeEvent, index: number, isKey: boolean = true) { - let localTable = addValue(event.target.value, index, isKey); - setVariableItem({ ...variableItem, data: localTable }); - setDone(false); - } - - const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { - let localTable = [...variableItem.data]; - let rowData = localTable[index]; - localTable[index] = { - isChecked: true, - key: isKey ? value : rowData.key, - value: !isKey ? value : rowData.value - }; - - return localTable; - }; - - - function deleteParam(index: number) { - let localTable = [...variableItem.data]; - localTable.splice(index, 1); - setVariableItem({ ...variableItem, data: localTable }); - setDone(false); - } - - useEffect(() => { - window.addEventListener("message", (event) => { - if (event.data && event.data.type === responseTypes.getVariableItemResponse) { - let varItem = event.data.data[0] as IVariable; - varItem.data.push({ isChecked: false, key: "", value: "", }); - setVariableItem(varItem); - setDefaultGlobal(varItem.name.toUpperCase().trim() === "GLOBAL"); - setEnabled(false); - } else if (event.data && (event.data.type === responseTypes.saveVariableResponse || event.data.type === responseTypes.updateVariableResponse)) { - setDone(true); - } else if (event.data && (event.data.type === responseTypes.getAttachedColIdsResponse)) { - setCollectionNames(event.data.colNames); - } - }); - - let id = document.title.split("@:@")[1]; - if (id !== "undefined") { - vscode.postMessage({ type: requestTypes.getVariableItemRequest, data: { id: id, isGlobal: false } }); - setNew(false); - } else { - setVariableItem({ - id: uuidv4(), - name: "", - isActive: true, - createdTime: formatDate(), - data: [{ - isChecked: false, - key: "", - value: "", - }] - }); - } - }, []); - - function onSubmitClick() { - let duplicates = variableItem.data.map((item) => { - return item.key.trim(); - }).filter((item, index, self) => self.indexOf(item) !== index); - - if (duplicates.length > 0) { - setDuplicates(duplicates); - } else { - setDuplicates([]); - let localVar = { ...variableItem }; - localVar.data = localVar.data.filter(item => item.key); - vscode.postMessage({ type: isNew ? requestTypes.saveVariableRequest : requestTypes.updateVariableRequest, data: localVar }); - } - } - - function isDisabled(): boolean { - if (!variableItem.name) { - return true; - } - - if (!defaultGlobal && variableItem.name.toUpperCase().trim() === "GLOBAL") { - return true; - } - - return false; - } - - function onNameChange(event: any) { - setVariableItem({ ...variableItem, name: event.target.value }); - setErrors({ ...errors, "varName": (event.target.value ? (event.target.value.toUpperCase().trim() === "GLOBAL" ? "Variable name should not be 'Global'" : "") : "Cannot be empty") }); - } - - return ( -
-
Variables
- { - variableItem ? - <> -
- - { - errors["varName"] &&
{errors["varName"]}
- } -
-
- - - {collectionNames.length > 0 ? -
- - -
- : - <>} -
- -
-
- {isDone && ({`Variables ${isNew ? `added` : `updated`} successfully`})} - {duplicates.length > 0 && ({`Duplicate Variables : ${duplicates.join(", ")}`})} -
- - : - <> - } - - ); +const Variables = (_props: IVariableProps) => { + + const [isDone, setDone] = useState(false); + const [isNew, setNew] = useState(true); + const [enabled, setEnabled] = useState(true); + const [errors, setErrors] = useState({}); + const [defaultGlobal, setDefaultGlobal] = useState(false); + const [variableItem, setVariableItem] = useState(null); + const [duplicates, setDuplicates] = useState([]); + + const [collectionNames, setCollectionNames] = useState([]); + const [viewVariables, setViewVariables] = useState(false); + + function onRowAdd(event: React.ChangeEvent, index: number, isKey: boolean = true) { + let newRow: ITableData = { + isChecked: false, + key: "", + value: "" + }; + + let localTable = addValue(event.target.value, index, isKey); + + if (localTable[index].key && localTable[index].value) { + localTable.push(newRow); + } + + setVariableItem({ ...variableItem, data: localTable }); + setDone(false); + } + + function onRowUpdate(event: React.ChangeEvent, index: number, isKey: boolean = true) { + let localTable = addValue(event.target.value, index, isKey); + setVariableItem({ ...variableItem, data: localTable }); + setDone(false); + } + + const addValue = (value: string, index: number, isKey: boolean): ITableData[] => { + let localTable = [...variableItem.data]; + let rowData = localTable[index]; + localTable[index] = { + isChecked: true, + key: isKey ? value : rowData.key, + value: !isKey ? value : rowData.value + }; + + return localTable; + }; + + + function deleteParam(index: number) { + let localTable = [...variableItem.data]; + localTable.splice(index, 1); + setVariableItem({ ...variableItem, data: localTable }); + setDone(false); + } + + useEffect(() => { + window.addEventListener("message", (event) => { + if (event.data && event.data.type === responseTypes.getVariableItemResponse) { + let varItem = event.data.data[0] as IVariable; + varItem.data.push({ isChecked: false, key: "", value: "", }); + setVariableItem(varItem); + setDefaultGlobal(varItem.name.toUpperCase().trim() === "GLOBAL"); + setEnabled(false); + } else if (event.data && (event.data.type === responseTypes.saveVariableResponse || event.data.type === responseTypes.updateVariableResponse)) { + setDone(true); + } else if (event.data && (event.data.type === responseTypes.getAttachedColIdsResponse)) { + setCollectionNames(event.data.colNames); + } + }); + + let id = document.title.split("@:@")[1]; + if (id !== "undefined") { + vscode.postMessage({ type: requestTypes.getVariableItemRequest, data: { id: id, isGlobal: false } }); + setNew(false); + } else { + setVariableItem({ + id: uuidv4(), + name: "", + isActive: true, + createdTime: formatDate(), + data: [{ + isChecked: false, + key: "", + value: "", + }] + }); + } + }, []); + + function onSubmitClick() { + let duplicates = variableItem.data.map((item) => { + return item.key.trim(); + }).filter((item, index, self) => self.indexOf(item) !== index); + + if (duplicates.length > 0) { + setDuplicates(duplicates); + } else { + setDuplicates([]); + let localVar = { ...variableItem }; + localVar.data = localVar.data.filter(item => item.key); + vscode.postMessage({ type: isNew ? requestTypes.saveVariableRequest : requestTypes.updateVariableRequest, data: localVar }); + } + } + + function isDisabled(): boolean { + if (!variableItem.name) { + return true; + } + + if (!defaultGlobal && variableItem.name.toUpperCase().trim() === "GLOBAL") { + return true; + } + + return false; + } + + function onNameChange(event: any) { + setVariableItem({ ...variableItem, name: event.target.value }); + setErrors({ ...errors, "varName": (event.target.value ? (event.target.value.toUpperCase().trim() === "GLOBAL" ? "Variable name should not be 'Global'" : "") : "Cannot be empty") }); + } + + function onSelectChange(evt: React.ChangeEvent) { + setViewVariables(evt.currentTarget.checked); + } + + return ( +
+
Variables
+ { + variableItem ? + <> +
+ + { + errors["varName"] &&
{errors["varName"]}
+ } +
+
+ +
+
+
+ + { + collectionNames.length > 0 ? +
+ + +
+ : + <> + } +
+ +
+
+ {isDone && ({`Variables ${isNew ? `added` : `updated`} successfully`})} + {duplicates.length > 0 && ({`Duplicate Variables : ${duplicates.join(", ")}`})} +
+ + : + <> + } + + ); }; -export default Variables; \ No newline at end of file +export default Variables; diff --git a/src/fetch-client-ui/components/Variables/redux/actions.ts b/src/fetch-client-ui/components/Variables/redux/actions.ts index c3bf124..00fb691 100644 --- a/src/fetch-client-ui/components/Variables/redux/actions.ts +++ b/src/fetch-client-ui/components/Variables/redux/actions.ts @@ -2,37 +2,37 @@ import { IVariable } from "../../SideBar/redux/types"; import { FETCH_CLIENT_SET_LOCAL_CHANGE, FETCH_CLIENT_SET_REQ_ALL_VARIABLES, FETCH_CLIENT_SET_REQ_VARIABLE, FETCH_CLIENT_SET_SETVAR_CHANGE, VariableActionTypes } from "./types"; export const SetReqVariableAction = (value: IVariable): VariableActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_VARIABLE, - payload: { - variable: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_VARIABLE, + payload: { + variable: value + } + }; }; export const SetReqAllVariableAction = (value: IVariable[]): VariableActionTypes => { - return { - type: FETCH_CLIENT_SET_REQ_ALL_VARIABLES, - payload: { - variables: value - } - }; + return { + type: FETCH_CLIENT_SET_REQ_ALL_VARIABLES, + payload: { + variables: value + } + }; }; export const SetReqLocalChangeAction = (value: boolean): VariableActionTypes => { - return { - type: FETCH_CLIENT_SET_LOCAL_CHANGE, - payload: { - change: value - } - }; + return { + type: FETCH_CLIENT_SET_LOCAL_CHANGE, + payload: { + change: value + } + }; }; export const SetReqVarChangeAction = (value: boolean): VariableActionTypes => { - return { - type: FETCH_CLIENT_SET_SETVAR_CHANGE, - payload: { - setVarChanged: value - } - }; + return { + type: FETCH_CLIENT_SET_SETVAR_CHANGE, + payload: { + setVarChanged: value + } + }; }; diff --git a/src/fetch-client-ui/components/Variables/redux/index.ts b/src/fetch-client-ui/components/Variables/redux/index.ts index d467013..f989d2a 100644 --- a/src/fetch-client-ui/components/Variables/redux/index.ts +++ b/src/fetch-client-ui/components/Variables/redux/index.ts @@ -3,6 +3,6 @@ import { VariableReducer } from "./reducer"; export { - VariableActions, - VariableReducer + VariableActions, + VariableReducer }; diff --git a/src/fetch-client-ui/components/Variables/redux/reducer.ts b/src/fetch-client-ui/components/Variables/redux/reducer.ts index 9ede556..087f005 100644 --- a/src/fetch-client-ui/components/Variables/redux/reducer.ts +++ b/src/fetch-client-ui/components/Variables/redux/reducer.ts @@ -1,56 +1,56 @@ import { FETCH_CLIENT_SET_LOCAL_CHANGE, FETCH_CLIENT_SET_REQ_ALL_VARIABLES, FETCH_CLIENT_SET_REQ_VARIABLE, FETCH_CLIENT_SET_SETVAR_CHANGE, IVariableModel, VariableActionTypes } from "./types"; export const InitialState: IVariableModel = { - variables: [], - selectedVariable: { - id: "", - name: "", - createdTime: "", - isActive: false, - data: [] - }, - isLocalChange: false, - setVarChanged: false + variables: [], + selectedVariable: { + id: "", + name: "", + createdTime: "", + isActive: false, + data: [] + }, + isLocalChange: false, + setVarChanged: false }; export const VariableReducer: (state?: IVariableModel, - action?: VariableActionTypes) => IVariableModel = - (state: IVariableModel = InitialState, - action: VariableActionTypes = {} as VariableActionTypes): IVariableModel => { - switch (action.type) { - case FETCH_CLIENT_SET_REQ_VARIABLE: { - return { - ...state, - selectedVariable: { - ...state.selectedVariable, - id: action.payload.variable.id, - name: action.payload.variable.name, - createdTime: action.payload.variable.createdTime, - isActive: action.payload.variable.isActive, - data: action.payload.variable.data, - } - }; - } - case FETCH_CLIENT_SET_REQ_ALL_VARIABLES: { - return { - ...state, - variables: action.payload.variables - }; - } - case FETCH_CLIENT_SET_LOCAL_CHANGE: { - return { - ...state, - isLocalChange: action.payload.change - }; - } - case FETCH_CLIENT_SET_SETVAR_CHANGE: { - return { - ...state, - setVarChanged: action.payload.setVarChanged - }; - } - default: { - return state; - } - } - }; + action?: VariableActionTypes) => IVariableModel = + (state: IVariableModel = InitialState, + action: VariableActionTypes = {} as VariableActionTypes): IVariableModel => { + switch (action.type) { + case FETCH_CLIENT_SET_REQ_VARIABLE: { + return { + ...state, + selectedVariable: { + ...state.selectedVariable, + id: action.payload.variable.id, + name: action.payload.variable.name, + createdTime: action.payload.variable.createdTime, + isActive: action.payload.variable.isActive, + data: action.payload.variable.data, + } + }; + } + case FETCH_CLIENT_SET_REQ_ALL_VARIABLES: { + return { + ...state, + variables: action.payload.variables + }; + } + case FETCH_CLIENT_SET_LOCAL_CHANGE: { + return { + ...state, + isLocalChange: action.payload.change + }; + } + case FETCH_CLIENT_SET_SETVAR_CHANGE: { + return { + ...state, + setVarChanged: action.payload.setVarChanged + }; + } + default: { + return state; + } + } + }; diff --git a/src/fetch-client-ui/components/Variables/redux/types.ts b/src/fetch-client-ui/components/Variables/redux/types.ts index 6fb8468..1fb2f1a 100644 --- a/src/fetch-client-ui/components/Variables/redux/types.ts +++ b/src/fetch-client-ui/components/Variables/redux/types.ts @@ -6,38 +6,38 @@ export const FETCH_CLIENT_SET_LOCAL_CHANGE: "FETCH_CLIENT_SET_LOCAL_CHANGE" = "F export const FETCH_CLIENT_SET_SETVAR_CHANGE: "FETCH_CLIENT_SET_SETVAR_CHANGE" = "FETCH_CLIENT_SET_SETVAR_CHANGE"; export interface IVariableModel { - variables: IVariable[]; - selectedVariable: IVariable; - isLocalChange: boolean; - setVarChanged: boolean; + variables: IVariable[]; + selectedVariable: IVariable; + isLocalChange: boolean; + setVarChanged: boolean; } export interface ISetReqVariable { - type: typeof FETCH_CLIENT_SET_REQ_VARIABLE; - payload: { - variable: IVariable; - }; + type: typeof FETCH_CLIENT_SET_REQ_VARIABLE; + payload: { + variable: IVariable; + }; } export interface ISetReqAllVariable { - type: typeof FETCH_CLIENT_SET_REQ_ALL_VARIABLES; - payload: { - variables: IVariable[]; - }; + type: typeof FETCH_CLIENT_SET_REQ_ALL_VARIABLES; + payload: { + variables: IVariable[]; + }; } export interface ISetLocalChange { - type: typeof FETCH_CLIENT_SET_LOCAL_CHANGE; - payload: { - change: boolean; - }; + type: typeof FETCH_CLIENT_SET_LOCAL_CHANGE; + payload: { + change: boolean; + }; } export interface ISetVarChange { - type: typeof FETCH_CLIENT_SET_SETVAR_CHANGE; - payload: { - setVarChanged: boolean; - }; + type: typeof FETCH_CLIENT_SET_SETVAR_CHANGE; + payload: { + setVarChanged: boolean; + }; } -export type VariableActionTypes = | ISetReqVariable | ISetReqAllVariable | ISetLocalChange | ISetVarChange; \ No newline at end of file +export type VariableActionTypes = | ISetReqVariable | ISetReqAllVariable | ISetLocalChange | ISetVarChange; diff --git a/src/fetch-client-ui/components/Variables/resToVar.tsx b/src/fetch-client-ui/components/Variables/resToVar.tsx index 8062473..24ae258 100644 --- a/src/fetch-client-ui/components/Variables/resToVar.tsx +++ b/src/fetch-client-ui/components/Variables/resToVar.tsx @@ -1,170 +1,170 @@ import React from "react"; -import { ReactComponent as BinLogo } from '../../../../icons/bin.svg'; import { useDispatch, useSelector } from "react-redux"; +import { ReactComponent as BinLogo } from '../../../../icons/bin.svg'; import { IRootState } from "../../reducer/combineReducer"; -import { ISetVar } from "../RequestUI/redux/types"; import { Actions } from "../RequestUI/redux"; -import "./style.css"; +import { ISetVar } from "../RequestUI/redux/types"; import { VariableActions } from "./redux"; +import "./style.css"; const ResToVariables = () => { - const dispatch = useDispatch(); - - const { variables, selectedVariable, setVarChanged } = useSelector((state: IRootState) => state.variableData); - const { setvar } = useSelector((state: IRootState) => state.requestData); - - function onRowAdd(event: React.ChangeEvent | React.ChangeEvent, index: number, type: string) { - let newRow: ISetVar = { - parameter: "", - key: "", - variableName: "" - }; - - let localTable = addValue(event.target.value, index, type); - - if (localTable[index].parameter && localTable[index].key && localTable[index].variableName) { - localTable.push(newRow); - } - - dispatch(Actions.SetVarAction(localTable)); - - if (!setVarChanged) { - dispatch(VariableActions.SetReqVarChangeAction(true)); - } - } - - function onRowUpdate(event: React.ChangeEvent | React.ChangeEvent, index: number, type: string) { - let localTable = addValue(event.target.value, index, type); - dispatch(Actions.SetVarAction(localTable)); - - if (!setVarChanged) { - dispatch(VariableActions.SetReqVarChangeAction(true)); - } - } - - const addValue = (value: string, index: number, type: string): ISetVar[] => { - let localTable = [...setvar]; - let rowData = localTable[index]; - localTable[index] = { - parameter: type === "parameter" ? value : rowData.parameter, - key: type === "key" ? value : rowData.key, - variableName: type === "variableName" ? value : rowData.variableName - }; - - return localTable; - }; - - function onDelete(index: number) { - let localValue = [...setvar]; - localValue.splice(index, 1); - if ((localValue.length === 0) || (localValue[localValue.length - 1].parameter && localValue[localValue.length - 1].key && localValue[localValue.length - 1].variableName)) { - let newRow: ISetVar = { - parameter: "", - key: "", - variableName: "" - }; - localValue.push(newRow); - } - - dispatch(Actions.SetVarAction(localValue)); - } - - const tableRow = (row: ISetVar, index: number) => { - return ( - - - - - - - ); - }; - - const makeTable = (data: ISetVar[]) => { - return ( - data.map((item: ISetVar, index: number) => { - return tableRow(item, index); - }) - ); - }; - - return ( - variables && variables.length > 0 - ? -
-
- Variable : - {selectedVariable.name} -
-
-
- - - index === setvar.length - 1 ? onRowAdd(event, index, "key") : onRowUpdate(event, index, "key")} - placeholder={row.parameter ? row.parameter === "Header" ? "header name" : row.parameter === "Cookie" ? "cookie name" : "json data" : "value"} - /> - - index === setvar.length - 1 ? onRowAdd(event, index, "variableName") : onRowUpdate(event, index, "variableName")} - placeholder="variable name" - /> - - { - row.parameter || row.key || row.variableName ? - onDelete(index)} /> - : - <> - } -
- - - - - - - - - - { - makeTable(setvar) - } - -
ParameterValueVariable Name
-
- {"Note : "}{"Enter the variable name without {{ and }}"} -
-
- : - <> - ); + const dispatch = useDispatch(); + + const { variables, selectedVariable, setVarChanged } = useSelector((state: IRootState) => state.variableData); + const { setvar } = useSelector((state: IRootState) => state.requestData); + + function onRowAdd(event: React.ChangeEvent | React.ChangeEvent, index: number, type: string) { + let newRow: ISetVar = { + parameter: "", + key: "", + variableName: "" + }; + + let localTable = addValue(event.target.value, index, type); + + if (localTable[index].parameter && localTable[index].key && localTable[index].variableName) { + localTable.push(newRow); + } + + dispatch(Actions.SetVarAction(localTable)); + + if (!setVarChanged) { + dispatch(VariableActions.SetReqVarChangeAction(true)); + } + } + + function onRowUpdate(event: React.ChangeEvent | React.ChangeEvent, index: number, type: string) { + let localTable = addValue(event.target.value, index, type); + dispatch(Actions.SetVarAction(localTable)); + + if (!setVarChanged) { + dispatch(VariableActions.SetReqVarChangeAction(true)); + } + } + + const addValue = (value: string, index: number, type: string): ISetVar[] => { + let localTable = [...setvar]; + let rowData = localTable[index]; + localTable[index] = { + parameter: type === "parameter" ? value : rowData.parameter, + key: type === "key" ? value : rowData.key, + variableName: type === "variableName" ? value : rowData.variableName + }; + + return localTable; + }; + + function onDelete(index: number) { + let localValue = [...setvar]; + localValue.splice(index, 1); + if ((localValue.length === 0) || (localValue[localValue.length - 1].parameter && localValue[localValue.length - 1].key && localValue[localValue.length - 1].variableName)) { + let newRow: ISetVar = { + parameter: "", + key: "", + variableName: "" + }; + localValue.push(newRow); + } + + dispatch(Actions.SetVarAction(localValue)); + } + + const tableRow = (row: ISetVar, index: number) => { + return ( + + + + + + index === setvar.length - 1 ? onRowAdd(event, index, "key") : onRowUpdate(event, index, "key")} + placeholder={row.parameter ? row.parameter === "Header" ? "header name" : row.parameter === "Cookie" ? "cookie name" : "json data" : "value"} + /> + + + index === setvar.length - 1 ? onRowAdd(event, index, "variableName") : onRowUpdate(event, index, "variableName")} + placeholder="variable name" + /> + + + { + row.parameter || row.key || row.variableName ? + onDelete(index)} /> + : + <> + } + + + ); + }; + + const makeTable = (data: ISetVar[]) => { + return ( + data.map((item: ISetVar, index: number) => { + return tableRow(item, index); + }) + ); + }; + + return ( + variables && variables.length > 0 + ? +
+
+ Variable : + {selectedVariable.name} +
+
+ + + + + + + + + + + { + makeTable(setvar) + } + +
ParameterValueVariable Name
+
+ {"Note : "}{"Enter the variable name without {{ and }}"} +
+
+ : + <> + ); }; export default ResToVariables; diff --git a/src/fetch-client-ui/components/Variables/style.css b/src/fetch-client-ui/components/Variables/style.css index 9092049..7817e50 100644 --- a/src/fetch-client-ui/components/Variables/style.css +++ b/src/fetch-client-ui/components/Variables/style.css @@ -1,131 +1,143 @@ .variable-panel { - padding: 25px 50px; - margin : 0 auto; - height : 91%; + padding: 25px 50px; + margin : 0 auto; + height : 91%; } .var-header { - font-style: normal; - font-size : x-large; - text-align: center; + font-style: normal; + font-size : x-large; + text-align: center; } .var-btn-panel { - margin-top: 20px; + margin-top: 20px; } .variable-panel-name { - margin-top: 20px; - display : flex; - width : 90%; + margin-top: 20px; + display : flex; + width : 90%; } .variable-text-label { - width : 55px; - display : flex; - align-items: center; + width : 55px; + display : flex; + align-items: center; } .variable-text { - color : var(--text-color); - border : 1px solid var(--border-color); - background-color: transparent; - outline : 0; - height : 30px; - width : 50%; - padding : 0 10px 0 10px; + color : var(--text-color); + border : 1px solid var(--border-color); + background-color: transparent; + outline : 0; + height : 30px; + width : 50%; + padding : 0 10px 0 10px; } .variable-text:disabled, .variable-text[disabled], .variable-text:disabled:hover, .variable-text[disabled]:hover { - background-color: var(--list-hover-background-color); - cursor : not-allowed; + background-color: var(--list-hover-background-color); + cursor : not-allowed; } .variable-text:focus { - outline: none; + outline: none; } .var-tbl-panel { - margin-top : 10px; - max-height : calc(100% - 185px); - overflow : scroll; - padding-right: 5px; + margin-top : 10px; + max-height : calc(100% - 185px); + overflow : scroll; + padding-right: 5px; } .variable-col-panel { - margin-top: 10px; + margin-top: 10px; } .variable-col-label, .variable-col-list-label { - font-size: medium !important; + font-size: medium !important; } .variable-col-list-label { - color: var(--button-background-color) !important; + color: var(--button-background-color) !important; } .var-name-valid { - margin-left: 10px; - padding-top: 5px; + margin-left: 10px; + padding-top: 5px; } .var-error { - font-weight: bolder; + font-weight: bolder; } .addto-var-label { - font-weight : 500; - color : var(--text-color); - padding-right: 20px; - width : fit-content; - padding-top : 8px; + font-weight : 500; + color : var(--text-color); + padding-right: 20px; + width : fit-content; + padding-top : 8px; } .addto-var-select { - background-color: var(--background-color); - box-sizing : border-box; - color : var(--text-color); - font-size : small; - outline : none; - padding : 10px; - width : 50%; + background-color: var(--background-color); + box-sizing : border-box; + color : var(--text-color); + font-size : small; + outline : none; + padding : 10px; + width : 50%; } .addto-var-select:focus { - outline: none; + outline: none; } .addto-var-select:required:invalid { - color: var(--input-unchecked); + color: var(--input-unchecked); } .addto-var-select option[value=""][disabled] { - display: none; + display: none; } .addto-var-select option { - color : var(--text-color) !important; - background: var(--background-color) !important; + color : var(--text-color) !important; + background: var(--background-color) !important; } .set-variable-panel { - padding: 0 5px 5px 5px; - width : 100%; + padding: 0 5px 5px 5px; + width : 100%; } .set-variable-panel-name { - display: flex; - width : 100%; + display: flex; + width : 100%; } .addto-var-label-note { - padding-top: 10px; + padding-top: 10px; } .remove-overflow { - overflow: unset !important; + overflow: unset !important; +} + +.view-variable { + margin-left: auto; + margin-right: 0; + padding-right: 25px; +} + +.view-variable-panel-name { + margin-top: 20px; + display : flex; + width : 100%; } diff --git a/src/fetch-client-ui/index.css b/src/fetch-client-ui/index.css index 05be3b0..f072a4d 100644 --- a/src/fetch-client-ui/index.css +++ b/src/fetch-client-ui/index.css @@ -1,56 +1,56 @@ body { - margin: 0; + margin: 0; - --background-color: var(--vscode-editor-background); - --editor-text-color: var(--vscode-input-foreground); - --border-color: gray; - --border-size: 0.5px; - --button-text-color: var(--vscode-button-foreground); - --button-background-color: var(--vscode-button-background); - --button-hover-color: var(--vscode-button-hoverBackground); - --font-size: var(--vscode-font-size); - --font-weight: var(--vscode-font-weight); - --font-family: var(--vscode-font-family); - --input-background-color: var(--vscode-input-background); - --input-focus: var(--vscode-input-background); - --input-hover: var(--vscode-input-background); - --input-unchecked: #808080; - --text-color: var(--vscode-foreground); - --list-hover-background-color: var(--vscode-list-hoverBackground); - --required-color: red; + --background-color: var(--vscode-editor-background); + --editor-text-color: var(--vscode-input-foreground); + --border-color: gray; + --border-size: 0.5px; + --button-text-color: var(--vscode-button-foreground); + --button-background-color: var(--vscode-button-background); + --button-hover-color: var(--vscode-button-hoverBackground); + --font-size: var(--vscode-font-size); + --font-weight: var(--vscode-font-weight); + --font-family: var(--vscode-font-family); + --input-background-color: var(--vscode-input-background); + --input-focus: var(--vscode-input-background); + --input-hover: var(--vscode-input-background); + --input-unchecked: #808080; + --text-color: var(--vscode-foreground); + --list-hover-background-color: var(--vscode-list-hoverBackground); + --required-color: red; } code { - font-size: var(--vscode-editor-font-size); - font-family: var(--vscode-editor-font-family); + font-size: var(--vscode-editor-font-size); + font-family: var(--vscode-editor-font-family); } .spinner.loading { - padding: 50px; - text-align: center; + padding: 50px; + text-align: center; } .spinner.loading:before { - content: ""; - height: 25px; - width: 25px; - margin: -15px auto auto -15px; - position: absolute; - bottom: 50%; - left: calc(50% - 45px); - border-width: 3px; - border-style: solid; - border-color: #2180c0 #ccc #ccc; - border-radius: 100%; - animation: rotation .7s infinite linear; + content: ""; + height: 25px; + width: 25px; + margin: -15px auto auto -15px; + position: absolute; + bottom: 50%; + left: calc(50% - 45px); + border-width: 3px; + border-style: solid; + border-color: #2180c0 #ccc #ccc; + border-radius: 100%; + animation: rotation .7s infinite linear; } @keyframes rotation { - from { - transform: rotate(0deg); - } + from { + transform: rotate(0deg); + } - to { - transform: rotate(359deg); - } -} \ No newline at end of file + to { + transform: rotate(359deg); + } +} diff --git a/src/fetch-client-ui/index.tsx b/src/fetch-client-ui/index.tsx index bc82a56..f3257f2 100644 --- a/src/fetch-client-ui/index.tsx +++ b/src/fetch-client-ui/index.tsx @@ -8,10 +8,10 @@ import { StateAndRouterProvider } from './store/stateAndRouterProvider'; const store = getAppStore(); ReactDOM.render( - - - - - , - document.getElementById('root') -); \ No newline at end of file + + + + + , + document.getElementById('root') +); diff --git a/src/fetch-client-ui/reducer/combineReducer.ts b/src/fetch-client-ui/reducer/combineReducer.ts index c748647..36a3764 100644 --- a/src/fetch-client-ui/reducer/combineReducer.ts +++ b/src/fetch-client-ui/reducer/combineReducer.ts @@ -5,6 +5,7 @@ import { UIReducer } from "../components/MainUI/redux/reducer"; import { ICommonConfig } from "../components/MainUI/redux/types"; import { ReqColReducer } from "../components/RequestUI/redux/colReducer"; import { RequestReducer } from "../components/RequestUI/redux/reducer"; +import { ReqSettingsReducer } from "../components/RequestUI/redux/reqSettingsReducer"; import { IReqColModel, IReqSettings, IRequestModel } from "../components/RequestUI/redux/types"; import { ResponseReducer } from "../components/ResponseUI/redux"; import { IReponseModel } from "../components/ResponseUI/redux/types"; @@ -12,29 +13,28 @@ import { SideBarReducer } from "../components/SideBar/redux"; import { ISideBarModel } from "../components/SideBar/redux/types"; import { VariableReducer } from "../components/Variables/redux/reducer"; import { IVariableModel } from "../components/Variables/redux/types"; -import { ReqSettingsReducer } from "../components/RequestUI/redux/reqSettingsReducer"; export interface IRootState { - requestData: IRequestModel, - responseData: IReponseModel, - uiData: ICommonConfig, - sideBarData: ISideBarModel, - variableData: IVariableModel, - cookieData: ICookiesModel, - reqColData: IReqColModel, - reqSettings: IReqSettings + requestData: IRequestModel, + responseData: IReponseModel, + uiData: ICommonConfig, + sideBarData: ISideBarModel, + variableData: IVariableModel, + cookieData: ICookiesModel, + reqColData: IReqColModel, + reqSettings: IReqSettings } const createRootReducer: () => Reducer = - (): Reducer => combineReducers({ - requestData: RequestReducer, - responseData: ResponseReducer, - uiData: UIReducer, - sideBarData: SideBarReducer, - variableData: VariableReducer, - cookieData: CookieReducer, - reqColData: ReqColReducer, - reqSettings: ReqSettingsReducer - }); + (): Reducer => combineReducers({ + requestData: RequestReducer, + responseData: ResponseReducer, + uiData: UIReducer, + sideBarData: SideBarReducer, + variableData: VariableReducer, + cookieData: CookieReducer, + reqColData: ReqColReducer, + reqSettings: ReqSettingsReducer + }); -export default createRootReducer; \ No newline at end of file +export default createRootReducer; diff --git a/src/fetch-client-ui/reportWebVitals.ts b/src/fetch-client-ui/reportWebVitals.ts index 49a2a16..6fe8bad 100644 --- a/src/fetch-client-ui/reportWebVitals.ts +++ b/src/fetch-client-ui/reportWebVitals.ts @@ -1,15 +1,15 @@ import { ReportHandler } from 'web-vitals'; const reportWebVitals = (onPerfEntry?: ReportHandler) => { - if (onPerfEntry && onPerfEntry instanceof Function) { - import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { - getCLS(onPerfEntry); - getFID(onPerfEntry); - getFCP(onPerfEntry); - getLCP(onPerfEntry); - getTTFB(onPerfEntry); - }); - } + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } }; export default reportWebVitals; diff --git a/src/fetch-client-ui/store/appStore.ts b/src/fetch-client-ui/store/appStore.ts index 84c9368..831bd69 100644 --- a/src/fetch-client-ui/store/appStore.ts +++ b/src/fetch-client-ui/store/appStore.ts @@ -3,6 +3,6 @@ import thunk from "redux-thunk"; import createRootReducer, { IRootState } from "../reducer/combineReducer"; export const composeStore = (): any => - compose(applyMiddleware(thunk)); + compose(applyMiddleware(thunk)); export const getAppStore = (): Store => createStore(createRootReducer(), composeStore()); diff --git a/src/fetch-client-ui/store/stateAndRouterProvider.tsx b/src/fetch-client-ui/store/stateAndRouterProvider.tsx index 6fcbd84..2abedab 100644 --- a/src/fetch-client-ui/store/stateAndRouterProvider.tsx +++ b/src/fetch-client-ui/store/stateAndRouterProvider.tsx @@ -4,14 +4,14 @@ import { Store } from "redux"; import { IChildrenProp } from "./types"; interface IProps extends IChildrenProp { - store: Store; + store: Store; } export const StateAndRouterProvider: React.FC = (props: IProps) => { - return ( - - {props.children} - - ); + return ( + + {props.children} + + ); }; diff --git a/src/fetch-client-ui/store/types.ts b/src/fetch-client-ui/store/types.ts index 71a9de7..e15daa4 100644 --- a/src/fetch-client-ui/store/types.ts +++ b/src/fetch-client-ui/store/types.ts @@ -4,9 +4,9 @@ import { ReactChild, ReactPortal, Children } from "react"; type Children = ReactChild | Array | ReactPortal; export interface IChildrenProp { - children: Children; + children: Children; } export interface IElementProps { - className: string; + className: string; } diff --git a/src/utils/LocalStorageService.ts b/src/utils/LocalStorageService.ts index 259a1e6..c6e4e19 100644 --- a/src/utils/LocalStorageService.ts +++ b/src/utils/LocalStorageService.ts @@ -1,14 +1,14 @@ import { Memento } from "vscode"; export class LocalStorageService { - - constructor(private storage: Memento) { } - - public getValue(key : string) : T{ - return this.storage.get(key, null); - } - - public setValue(key : string, value : T){ - this.storage.update(key, value ); - } -} \ No newline at end of file + + constructor(private storage: Memento) { } + + public getValue(key : string) : T{ + return this.storage.get(key, null); + } + + public setValue(key : string, value : T){ + this.storage.update(key, value ); + } +} diff --git a/src/utils/PreFetchRunner.ts b/src/utils/PreFetchRunner.ts index 711e4e6..c1113ae 100644 --- a/src/utils/PreFetchRunner.ts +++ b/src/utils/PreFetchRunner.ts @@ -5,117 +5,117 @@ import { ISettings, IVariable } from "../fetch-client-ui/components/SideBar/redu import { executeTests, setVariable } from "../fetch-client-ui/components/TestUI/TestPanel/helper"; import { GetParentSettingsSync, GetVariableByColId } from "./db/collectionDBUtil"; import { GetRequestItem } from "./db/mainDBUtil"; -import { GetVariableByIdSync, UpdateVariable, UpdateVariableSync } from "./db/varDBUtil"; +import { GetVariableByIdSync, UpdateVariableSync } from "./db/varDBUtil"; import { apiFetch, FetchConfig } from "./fetchUtil"; export class PreFetchRunner { - private readonly fetchConfig: FetchConfig; - private executingRequests: string[] = []; - private allow: boolean = true; - private response: IReponseModel = { - response: JSON.parse(JSON.stringify(InitialResponse)), - headers: [], - cookies: [], - loading: false, - testResults: [] - }; - public message: string = ""; - - - constructor(fetchConfig: FetchConfig, reqId: string) { - this.executingRequests.push(reqId); - this.fetchConfig = fetchConfig; - } - - RunPreRequests = async (preFetch: IPreFetch, fetchIndex: number, reqIndex: number, parentName: string, isCollectionPreRequest: boolean) => { - let request: IRequestModel; - let parentSettings: ISettings; - let updateVariable: IVariable; - - if (!this.allow) { - return; - } - - let item = this.executingRequests.find(i => i === preFetch.requests[reqIndex].reqId); - - if (item) { - this.allow = false; - this.message = `Circular Dependency in Request ${parentName}`; - return; - } else { - this.executingRequests.push(preFetch.requests[reqIndex].reqId); - } - - for (let i = 0; i < preFetch.requests.length && this.allow; i++) { - reqIndex = i; - if (i > 0 && request?.id) { - let condition = preFetch.requests[i].condition; - for (let j = 0; j < condition.length; j++) { - if (!condition[j].parameter || !condition[j].action) { - break; - } - let testResult = executeTests(condition, this.response, updateVariable?.data); - if (testResult.findIndex(i => i.result === false) !== -1) { - this.allow = false; - this.message = `'Condition ${reqIndex}' failed in 'Pre-Request ${reqIndex}' in the Request '${parentName}'`; - return; - } - } - } - - let reqId = preFetch.requests[i].reqId; - let parentId = preFetch.requests[i].parentId; - let colId = preFetch.requests[i].colId; - - if (!reqId) { - return; - } - - let varId = await GetVariableByColId(colId); - let variable = await GetVariableByIdSync(varId); - - if (parentId === colId) { - parentSettings = await GetParentSettingsSync(colId, ""); - } else { - parentSettings = await GetParentSettingsSync(colId, parentId); - } - - request = await GetRequestItem(reqId); - - if (request && this.allow) { - if (request.preFetch?.requests?.length > 0 && !isCollectionPreRequest) { - await this.RunPreRequests(request.preFetch, fetchIndex + 1, 0, request.name, isCollectionPreRequest); - if (!this.allow) { - return; - } - let index = this.executingRequests.findIndex(i => i === reqId); - if (index !== -1) { - this.executingRequests.splice(index); - } - let res = await apiFetch(request, variable?.data, parentSettings, null, this.fetchConfig); - this.response.response = res.response; - this.response.headers = res.headers; - this.response.cookies = res.cookies; - updateVariable = await this.updateVariable(request, variable); - } else { - let res = await apiFetch(request, variable?.data, parentSettings, null, this.fetchConfig); - this.response.response = res.response; - this.response.headers = res.headers; - this.response.cookies = res.cookies; - updateVariable = await this.updateVariable(request, variable); - } - } - } - }; - - updateVariable = async (request: IRequestModel, variable: IVariable): Promise => { - if (this.response.response.status !== 0 && this.response.response.status <= 399 && request.setvar.length - 1 > 0 && variable?.id) { - let variables = setVariable(variable, request.setvar, this.response); - let variableResult = await UpdateVariableSync(variables); - return variableResult; - } - return variable; - }; + private readonly fetchConfig: FetchConfig; + private executingRequests: string[] = []; + private allow: boolean = true; + private response: IReponseModel = { + response: JSON.parse(JSON.stringify(InitialResponse)), + headers: [], + cookies: [], + loading: false, + testResults: [] + }; + public message: string = ""; + + + constructor(fetchConfig: FetchConfig, reqId: string) { + this.executingRequests.push(reqId); + this.fetchConfig = fetchConfig; + } + + RunPreRequests = async (preFetch: IPreFetch, fetchIndex: number, reqIndex: number, parentName: string, isCollectionPreRequest: boolean) => { + let request: IRequestModel; + let parentSettings: ISettings; + let updateVariable: IVariable; + + if (!this.allow) { + return; + } + + let item = this.executingRequests.find(i => i === preFetch.requests[reqIndex].reqId); + + if (item) { + this.allow = false; + this.message = `Circular Dependency in Request ${parentName}`; + return; + } else { + this.executingRequests.push(preFetch.requests[reqIndex].reqId); + } + + for (let i = 0; i < preFetch.requests.length && this.allow; i++) { + reqIndex = i; + if (i > 0 && request?.id) { + let condition = preFetch.requests[i].condition; + for (let j = 0; j < condition.length; j++) { + if (!condition[j].parameter || !condition[j].action) { + break; + } + let testResult = executeTests(condition, this.response, updateVariable?.data); + if (testResult.findIndex(i => i.result === false) !== -1) { + this.allow = false; + this.message = `'Condition ${reqIndex}' failed in 'Pre-Request ${reqIndex}' in the Request '${parentName}'`; + return; + } + } + } + + let reqId = preFetch.requests[i].reqId; + let parentId = preFetch.requests[i].parentId; + let colId = preFetch.requests[i].colId; + + if (!reqId) { + return; + } + + let varId = await GetVariableByColId(colId); + let variable = await GetVariableByIdSync(varId); + + if (parentId === colId) { + parentSettings = await GetParentSettingsSync(colId, ""); + } else { + parentSettings = await GetParentSettingsSync(colId, parentId); + } + + request = await GetRequestItem(reqId); + + if (request && this.allow) { + if (request.preFetch?.requests?.length > 0 && !isCollectionPreRequest) { + await this.RunPreRequests(request.preFetch, fetchIndex + 1, 0, request.name, isCollectionPreRequest); + if (!this.allow) { + return; + } + let index = this.executingRequests.findIndex(i => i === reqId); + if (index !== -1) { + this.executingRequests.splice(index); + } + let res = await apiFetch(request, variable?.data, parentSettings, null, this.fetchConfig); + this.response.response = res.response; + this.response.headers = res.headers; + this.response.cookies = res.cookies; + updateVariable = await this.updateVariable(request, variable); + } else { + let res = await apiFetch(request, variable?.data, parentSettings, null, this.fetchConfig); + this.response.response = res.response; + this.response.headers = res.headers; + this.response.cookies = res.cookies; + updateVariable = await this.updateVariable(request, variable); + } + } + } + }; + + updateVariable = async (request: IRequestModel, variable: IVariable): Promise => { + if (this.response.response.status !== 0 && this.response.response.status <= 399 && request.setvar.length - 1 > 0 && variable?.id) { + let variables = setVariable(variable, request.setvar, this.response); + let variableResult = await UpdateVariableSync(variables); + return variableResult; + } + return variable; + }; } diff --git a/src/utils/PubSub.ts b/src/utils/PubSub.ts index 187ea7d..4ff13ae 100644 --- a/src/utils/PubSub.ts +++ b/src/utils/PubSub.ts @@ -1,76 +1,76 @@ export interface IPubSubMessage { - messageType: string; - message?: any; + messageType: string; + message?: any; } export interface Subscription { - unsubscribe(): void; + unsubscribe(): void; } export type Consumer = (value: T) => any; export interface Publisher { - subscribe(consumer: Consumer): Subscription; + subscribe(consumer: Consumer): Subscription; } const EMPTY_SUBSCRIPTION: Subscription = { - unsubscribe: () => undefined, + unsubscribe: () => undefined, }; export class PubSub implements Publisher { - private consumers: Map>; + private consumers: Map>; - constructor() { - this.consumers = new Map>(); - } + constructor() { + this.consumers = new Map>(); + } - /** A number of subscribed consumers. */ - get size(): number { - return this.consumers.size; - } + /** A number of subscribed consumers. */ + get size(): number { + return this.consumers.size; + } - /** Subscribes a consumer of values. */ - subscribe(consumer: Consumer): Subscription { - if (!consumer) { - return EMPTY_SUBSCRIPTION; - } - const consumerKey = Object.create(null); - this.consumers.set(consumerKey, consumer); - return new EmitterSubscription(this.consumers, consumerKey); - } + /** Subscribes a consumer of values. */ + subscribe(consumer: Consumer): Subscription { + if (!consumer) { + return EMPTY_SUBSCRIPTION; + } + const consumerKey = Object.create(null); + this.consumers.set(consumerKey, consumer); + return new EmitterSubscription(this.consumers, consumerKey); + } - /** Publish a value to subscribed consumers. */ - publish(value: T) { - if (this.consumers.size === 0) { - return; - } - this.consumers.forEach((consumer) => { - consumer(value); - }); - } + /** Publish a value to subscribed consumers. */ + publish(value: T) { + if (this.consumers.size === 0) { + return; + } + this.consumers.forEach((consumer) => { + consumer(value); + }); + } - /** Removes all subscribed consumers. */ - clear() { - this.consumers.clear(); - this.consumers = new Map>(); - } + /** Removes all subscribed consumers. */ + clear() { + this.consumers.clear(); + this.consumers = new Map>(); + } } class EmitterSubscription implements Subscription { - private consumers: Map> | undefined; - private consumerKey: object | undefined; + private consumers: Map> | undefined; + private consumerKey: object | undefined; - constructor(consumers: Map>, consumerKey: object) { - this.consumers = consumers; - this.consumerKey = consumerKey; - } + constructor(consumers: Map>, consumerKey: object) { + this.consumers = consumers; + this.consumerKey = consumerKey; + } - unsubscribe(): void { - if (this.consumers && this.consumerKey) { - this.consumers.delete(this.consumerKey); - } + unsubscribe(): void { + if (this.consumers && this.consumerKey) { + this.consumers.delete(this.consumerKey); + } - this.consumers = undefined; - this.consumerKey = undefined; - } -} \ No newline at end of file + this.consumers = undefined; + this.consumerKey = undefined; + } +} diff --git a/src/utils/configuration.ts b/src/utils/configuration.ts index a81a9bf..b62329d 100644 --- a/src/utils/configuration.ts +++ b/src/utils/configuration.ts @@ -1,177 +1,183 @@ export const requestTypes = { - activeVariableRequest: "activeVariableRequest", - addToCollectionsRequest: "addToCollectionsRequest", - apiRequest: "apiRequest", - attachVariableRequest: "attachVariableRequest", - cancelRequest: "cancelRequest", - clearRequest: "clearRequest", - closeItemRequest: "closeItemRequest", - configRequest: "configRequest", - convertCurlToJsonRequest: "convertCurlToJsonRequest", - copyItemRequest: "copyItemRequest", - copyToCollectionsRequest: "copyToCollectionsRequest", - createNewFolderRequest: "createNewFolderRequest", - createNewRequest: "createNewRequest", - deleteAllCookieRequest: "deleteAllCookieRequest", - deleteAllHistoryRequest: "deleteAllHistoryRequest", - deleteCollectionItemRequest: "deleteCollectionItemRequest", - deleteCollectionRequest: "deleteCollectionRequest", - deleteCookieByIdRequest: "deleteCookieByIdRequest", - deleteHistoryRequest: "deleteHistoryRequest", - deleteVariableRequest: "deleteVariableRequest", - downloadFileTypeRequest: "downloadFileTypeRequest", - downloadLargeFileRequest: "downloadLargeFileRequest", - duplicateCollectionsRequest: "duplicateCollectionsRequest", - duplicateVariableRequest: "duplicateVariableRequest", - exportRequest: "exportRequest", - exportRunTestCSVRequest: "exportRunTestCSVRequest", - exportRunTestJsonRequest: "exportRunTestJsonRequest", - exportVariableRequest: "exportVariableRequest", - formDataFileRequest: "formDataFileRequest", - getAllCollectionNameRequest: "getAllCollectionNameRequest", - getAllCollectionsRequest: "getAllCollectionsRequest", - getAllCookiesRequest: "getAllCookiesRequest", - getAllHistoryRequest: "getAllHistoryRequest", - getAllVariableRequest: "getAllVariableRequest", - getAttachedColIdsRequest: "getAttachedColIdsRequest", - getCollectionsByIdRequest: "getCollectionsByIdRequest", - getCollectionsByIdWithPathRequest: "getCollectionsByIdWithPathRequest", - getColSettingsRequest: "getColSettingsRequest", - getCookiesByIdRequest: "getCookiesByIdRequest", - getErrorLogRequest: "getErrorLogRequest", - getHistoryItemRequest: "getHistoryItemRequest", - getOpenAndRunItemDataRequest: "getOpenAndRunItemDataRequest", - getParentSettingsRequest: "getParentSettingsRequest", - getRunItemDataRequest: "getRunItemDataRequest", - getVariableItemRequest: "getVariableItemRequest", - importCurlRequest: "importCurlRequest", - importRequest: "importRequest", - importVariableRequest: "importVariableRequest", - layoutConfigRequest: "layoutConfigRequest", - multipleApiRequest: "multipleApiRequest", - newCollectionRequest: "newCollectionRequest", - newRequest: "newRequest", - newVariableRequest: "newVariableRequest", - openAndRunItemRequest: "openAndRunItemRequest", - openColSettingsRequest: "openColSettingsRequest", - openExistingItemRequest: "openExistingItemRequest", - openHistoryItemRequest: "openHistoryItemRequest", - openManageCookiesRequest: "openManageCookiesRequest", - openRunRequest: "openRunRequest", - openSetToVariableUIRequest: "openSetToVariableUIRequest", - openVariableItemRequest: "openVariableItemRequest", - pasteItemRequest: "pasteItemRequest", - readFileRequest: "readFileRequest", - removeVariableFromColRequest: "removeVariableFromColRequest", - removeVariableRequest: "removeVariableRequest", - renameCollectionItemRequest: "renameCollectionItemRequest", - renameCollectionRequest: "renameCollectionRequest", - renameHistoryRequest: "renameHistoryRequest", - renameVariableRequest: "renameVariableRequest", - runAllRequest: "runAllRequest", - runAllUIOpenRequest: "runAllUIOpenRequest", - runCurlRequest: "runCurlRequest", - saveColSettingsRequest: "saveColSettingsRequest", - saveCookieRequest: "saveCookieRequest", - saveRequest: "saveRequest", - saveResponseRequest: "saveResponseRequest", - saveTestResponseRequest: "saveTestResponseRequest", - saveVariableRequest: "saveVariableRequest", - selectFileRequest: "selectFileRequest", - selectItemRequest: "selectItemRequest", - setToVariableRequest: "setToVariableRequest", - themeRequest: "themeRequest", - tokenRequest: "tokenRequest", - updateVariableRequest: "updateVariableRequest", - viewLogRequest: "viewLogRequest" + activeVariableRequest: "activeVariableRequest", + addToCollectionsRequest: "addToCollectionsRequest", + apiRequest: "apiRequest", + attachVariableRequest: "attachVariableRequest", + bulkExportRequest: "bulkExportRequest", + bulkColExportRequest: "bulkColExportRequest", + cancelRequest: "cancelRequest", + clearRequest: "clearRequest", + closeItemRequest: "closeItemRequest", + configRequest: "configRequest", + convertCurlToJsonRequest: "convertCurlToJsonRequest", + copyItemRequest: "copyItemRequest", + copyToCollectionsRequest: "copyToCollectionsRequest", + createNewFolderRequest: "createNewFolderRequest", + createNewRequest: "createNewRequest", + deleteAllCookieRequest: "deleteAllCookieRequest", + deleteAllHistoryRequest: "deleteAllHistoryRequest", + deleteCollectionItemRequest: "deleteCollectionItemRequest", + deleteCollectionRequest: "deleteCollectionRequest", + deleteCookieByIdRequest: "deleteCookieByIdRequest", + deleteHistoryRequest: "deleteHistoryRequest", + deleteVariableRequest: "deleteVariableRequest", + downloadFileTypeRequest: "downloadFileTypeRequest", + downloadLargeFileRequest: "downloadLargeFileRequest", + duplicateCollectionsRequest: "duplicateCollectionsRequest", + duplicateVariableRequest: "duplicateVariableRequest", + exportRequest: "exportRequest", + exportRunTestCSVRequest: "exportRunTestCSVRequest", + exportRunTestJsonRequest: "exportRunTestJsonRequest", + exportVariableRequest: "exportVariableRequest", + formDataFileRequest: "formDataFileRequest", + getAllCollectionNameRequest: "getAllCollectionNameRequest", + getAllCollectionsRequest: "getAllCollectionsRequest", + getAllCookiesRequest: "getAllCookiesRequest", + getAllHistoryRequest: "getAllHistoryRequest", + getAllVariableRequest: "getAllVariableRequest", + getAttachedColIdsRequest: "getAttachedColIdsRequest", + getCollectionsByIdRequest: "getCollectionsByIdRequest", + getCollectionsByIdWithPathRequest: "getCollectionsByIdWithPathRequest", + getColSettingsRequest: "getColSettingsRequest", + getCookiesByIdRequest: "getCookiesByIdRequest", + getErrorLogRequest: "getErrorLogRequest", + getHistoryItemRequest: "getHistoryItemRequest", + getOpenAndRunItemDataRequest: "getOpenAndRunItemDataRequest", + getParentSettingsRequest: "getParentSettingsRequest", + getRunItemDataRequest: "getRunItemDataRequest", + getVariableItemRequest: "getVariableItemRequest", + importCurlRequest: "importCurlRequest", + importRequest: "importRequest", + importVariableRequest: "importVariableRequest", + layoutConfigRequest: "layoutConfigRequest", + multipleApiRequest: "multipleApiRequest", + newCollectionRequest: "newCollectionRequest", + newRequest: "newRequest", + newVariableRequest: "newVariableRequest", + openAndRunItemRequest: "openAndRunItemRequest", + openColSettingsRequest: "openColSettingsRequest", + openExistingItemRequest: "openExistingItemRequest", + openHistoryItemRequest: "openHistoryItemRequest", + openManageCookiesRequest: "openManageCookiesRequest", + openRunRequest: "openRunRequest", + openSetToVariableUIRequest: "openSetToVariableUIRequest", + openVariableItemRequest: "openVariableItemRequest", + pasteItemRequest: "pasteItemRequest", + readFileRequest: "readFileRequest", + removeVariableFromColRequest: "removeVariableFromColRequest", + removeVariableRequest: "removeVariableRequest", + renameCollectionItemRequest: "renameCollectionItemRequest", + renameCollectionRequest: "renameCollectionRequest", + renameHistoryRequest: "renameHistoryRequest", + renameVariableRequest: "renameVariableRequest", + runAllRequest: "runAllRequest", + runAllUIOpenRequest: "runAllUIOpenRequest", + runCurlRequest: "runCurlRequest", + saveColSettingsRequest: "saveColSettingsRequest", + saveCookieRequest: "saveCookieRequest", + saveRequest: "saveRequest", + saveResponseRequest: "saveResponseRequest", + saveTestResponseRequest: "saveTestResponseRequest", + saveVariableRequest: "saveVariableRequest", + selectFileRequest: "selectFileRequest", + selectItemRequest: "selectItemRequest", + selectPathRequest:"selectPathRequest", + setToVariableRequest: "setToVariableRequest", + showMessageRequest:"showMessageRequest", + themeRequest: "themeRequest", + tokenRequest: "tokenRequest", + updateVariableRequest: "updateVariableRequest", + viewLogRequest: "viewLogRequest" }; export const responseTypes = { - activeVariableResponse: "activeVariableResponse", - addToCollectionsResponse: "addToCollectionsResponse", - apiResponse: "apiResponse", - appendToCollectionsResponse: "appendToCollectionsResponse", - appendToVariableResponse: "appendToVariableResponse", - attachVariableResponse: "attachVariableResponse", - cancelResponse: "cancelResponse", - clearResponse: "clearResponse", - configResponse: "configResponse", - convertCurlToJsonResponse: "convertCurlToJsonResponse", - copyItemResponse: "copyItemResponse", - copyToCollectionsResponse: "copyToCollectionsResponse", - createNewFolderResponse: "createNewFolderResponse", - createNewResponse: "createNewResponse", - curlErrorResponse: "curlErrorResponse", - deleteAllCookieResponse: "deleteAllCookieResponse", - deleteAllHistoryResponse: "deleteAllHistoryResponse", - deleteCollectionItemResponse: "deleteCollectionItemResponse", - deleteCollectionResponse: "deleteCollectionResponse", - deleteCookieByIdResponse: "deleteCookieByIdResponse", - deleteHistoryResponse: "deleteHistoryResponse", - deleteVariableResponse: "deleteVariableResponse", - duplicateCollectionsResponse: "duplicateCollectionsResponse", - duplicateVariableResponse: "duplicateVariableResponse", - exportVariableResponse: "exportVariableResponse", - formDataFileResponse: "formDataFileResponse", - getAllCollectionNameResponse: "getAllCollectionNameResponse", - getAllCollectionNamesResponse: "getAllCollectionNamesResponse", - getAllCollectionsResponse: "getAllCollectionsResponse", - getAllCookiesResponse: "getAllCookiesResponse", - getAllHistoryResponse: "getAllHistoryResponse", - getAllVariableResponse: "getAllVariableResponse", - getAttachedColIdsResponse: "getAttachedColIdsResponse", - getCollectionsByIdResponse: "getCollectionsByIdResponse", - getCollectionsByIdWithPathResponse: "getCollectionsByIdWithPathResponse", - getColSettingsResponse: "getColSettingsResponse", - getCookiesByIdResponse: "getCookiesByIdResponse", - getErrorLogResponse: "getErrorLogResponse", - getHistoryItemResponse: "getHistoryItemResponse", - getOpenAndRunItemDataResponse: "getOpenAndRunItemDataResponse", - getParentSettingsResponse: "getParentSettingsResponse", - getRunItemDataResponse: "getRunItemDataResponse", - getVariableItemResponse: "getVariableItemResponse", - importResponse: "importResponse", - importVariableResponse: "importVariableResponse", - layoutConfigResponse: "layoutConfigResponse", - multipleApiResponse: "multipleApiResponse", - newHistoryResponse: "newHistoryResponse", - openColSettingsResponse: "openColSettingsResponse", - openExistingItemResponse: "openExistingItemResponse", - openHistoryItemResponse: "openHistoryItemResponse", - pasteItemResponse: "pasteItemResponse", - readFileResponse: "readFileResponse", - removeVariableResponse: "removeVariableResponse", - removeVariableFromColResponse: "removeVariableFromColResponse", - renameCollectionItemResponse: "renameCollectionItemResponse", - renameCollectionResponse: "renameCollectionResponse", - renameHistoryResponse: "renameHistoryResponse", - renameVariableResponse: "renameVariableResponse", - runAllResponse: "runAllResponse", - runCurlResponse: "runCurlResponse", - saveColSettingsResponse: "saveColSettingsResponse", - saveCookieResponse: "saveCookieResponse", - saveResponse: "saveResponse", - saveVariableResponse: "saveVariableResponse", - selectFileResponse: "selectFileResponse", - setToVariableResponse: "setToVariableResponse", - tokenResponse: "tokenResponse", - themeResponse: "themeResponse", - updateVariableResponse: "updateVariableResponse", - updateCollectionHistoryItem:"updateCollectionHistoryItem" + activeVariableResponse: "activeVariableResponse", + addToCollectionsResponse: "addToCollectionsResponse", + apiResponse: "apiResponse", + appendToCollectionsResponse: "appendToCollectionsResponse", + appendToVariableResponse: "appendToVariableResponse", + attachVariableResponse: "attachVariableResponse", + bulkColExportResponse: "bulkColExportResponse", + cancelResponse: "cancelResponse", + clearResponse: "clearResponse", + configResponse: "configResponse", + convertCurlToJsonResponse: "convertCurlToJsonResponse", + copyItemResponse: "copyItemResponse", + copyToCollectionsResponse: "copyToCollectionsResponse", + createNewFolderResponse: "createNewFolderResponse", + createNewResponse: "createNewResponse", + curlErrorResponse: "curlErrorResponse", + deleteAllCookieResponse: "deleteAllCookieResponse", + deleteAllHistoryResponse: "deleteAllHistoryResponse", + deleteCollectionItemResponse: "deleteCollectionItemResponse", + deleteCollectionResponse: "deleteCollectionResponse", + deleteCookieByIdResponse: "deleteCookieByIdResponse", + deleteHistoryResponse: "deleteHistoryResponse", + deleteVariableResponse: "deleteVariableResponse", + duplicateCollectionsResponse: "duplicateCollectionsResponse", + duplicateVariableResponse: "duplicateVariableResponse", + exportVariableResponse: "exportVariableResponse", + formDataFileResponse: "formDataFileResponse", + getAllCollectionNameResponse: "getAllCollectionNameResponse", + getAllCollectionNamesResponse: "getAllCollectionNamesResponse", + getAllCollectionsResponse: "getAllCollectionsResponse", + getAllCookiesResponse: "getAllCookiesResponse", + getAllHistoryResponse: "getAllHistoryResponse", + getAllVariableResponse: "getAllVariableResponse", + getAttachedColIdsResponse: "getAttachedColIdsResponse", + getCollectionsByIdResponse: "getCollectionsByIdResponse", + getCollectionsByIdWithPathResponse: "getCollectionsByIdWithPathResponse", + getColSettingsResponse: "getColSettingsResponse", + getCookiesByIdResponse: "getCookiesByIdResponse", + getErrorLogResponse: "getErrorLogResponse", + getHistoryItemResponse: "getHistoryItemResponse", + getOpenAndRunItemDataResponse: "getOpenAndRunItemDataResponse", + getParentSettingsResponse: "getParentSettingsResponse", + getRunItemDataResponse: "getRunItemDataResponse", + getVariableItemResponse: "getVariableItemResponse", + importResponse: "importResponse", + importVariableResponse: "importVariableResponse", + layoutConfigResponse: "layoutConfigResponse", + multipleApiResponse: "multipleApiResponse", + newHistoryResponse: "newHistoryResponse", + openColSettingsResponse: "openColSettingsResponse", + openExistingItemResponse: "openExistingItemResponse", + openHistoryItemResponse: "openHistoryItemResponse", + pasteItemResponse: "pasteItemResponse", + readFileResponse: "readFileResponse", + removeVariableResponse: "removeVariableResponse", + removeVariableFromColResponse: "removeVariableFromColResponse", + renameCollectionItemResponse: "renameCollectionItemResponse", + renameCollectionResponse: "renameCollectionResponse", + renameHistoryResponse: "renameHistoryResponse", + renameVariableResponse: "renameVariableResponse", + runAllResponse: "runAllResponse", + runCurlResponse: "runCurlResponse", + saveColSettingsResponse: "saveColSettingsResponse", + saveCookieResponse: "saveCookieResponse", + saveResponse: "saveResponse", + saveVariableResponse: "saveVariableResponse", + selectFileResponse: "selectFileResponse", + selectPathResponse: "selectPathResponse", + setToVariableResponse: "setToVariableResponse", + tokenResponse: "tokenResponse", + themeResponse: "themeResponse", + updateVariableResponse: "updateVariableResponse", + updateCollectionHistoryItem:"updateCollectionHistoryItem" }; export const pubSubTypes = { - addCurrentVariable: "addCurrentVariable", - updateVariables: "updateVariables", - removeCurrentVariable: "removeCurrentVariable", - themeChanged: "themeChanged" + addCurrentVariable: "addCurrentVariable", + updateVariables: "updateVariables", + removeCurrentVariable: "removeCurrentVariable", + themeChanged: "themeChanged" }; export function getNonce() { - let text = ''; - const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - for (let i = 0; i < 32; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } - return text; + let text = ''; + const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < 32; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; } diff --git a/src/utils/crypto/fc-crypto.ts b/src/utils/crypto/fc-crypto.ts new file mode 100644 index 0000000..6b7ea10 --- /dev/null +++ b/src/utils/crypto/fc-crypto.ts @@ -0,0 +1,53 @@ +// This Dummy Package used for development purpose. +import { CryptoMode, ITableData } from "./types"; + +export class FCCipher { + + secret_key: string = ""; + + constructor(cryptoMode: CryptoMode) { + this.secret_key = cryptoMode === CryptoMode.Export ? "Export_Dummy" : "Transit_Dummy"; + } + + EncryptData(text: string): string { + try { + if (!text) { + return ""; + } + return text; + } + catch (err) { + console.log("error::EncryptData(): - Error Mesaage : " + err); + return ""; + } + } + + DecryptData(encryptedData: string): string { + try { + if (!encryptedData) { + return ""; + } + return encryptedData; + } + catch (err) { + console.log("error::DecryptData(): - Error Mesaage : " + err); + return ""; + } + } + + EncryptBulkData(data: ITableData[]): ITableData[] { + data.forEach((data) => { + data.value = this.EncryptData(data.value); + }); + + return data; + } + + DecryptBulkData(data: ITableData[]): ITableData[] { + data.forEach((data) => { + data.value = this.DecryptData(data.value); + }); + + return data; + } +} diff --git a/src/utils/crypto/index.ts b/src/utils/crypto/index.ts new file mode 100644 index 0000000..c21f873 --- /dev/null +++ b/src/utils/crypto/index.ts @@ -0,0 +1,6 @@ +// While development please uncomment the lines (3 & 4) and comment the lines (5 & 6) + +// export { FCCipher } from "./fc-crypto"; +// export { ITableData, CryptoMode } from "./types"; +export { FCCipher } from "@ganesan-chandran/fetch-client-crypto"; +export { ITableData, CryptoMode } from "@ganesan-chandran/fetch-client-crypto"; diff --git a/src/utils/crypto/types.ts b/src/utils/crypto/types.ts new file mode 100644 index 0000000..4d28772 --- /dev/null +++ b/src/utils/crypto/types.ts @@ -0,0 +1,12 @@ +export interface ITableData { + isFixed?: boolean; + isChecked?: boolean; + type?: string; + key: string; + value: string; +} + +export enum CryptoMode { + Transit = "Transit", + Export = "Export" +}; diff --git a/src/utils/curlToRequest.ts b/src/utils/curlToRequest.ts index efff6dc..c5a77f6 100644 --- a/src/utils/curlToRequest.ts +++ b/src/utils/curlToRequest.ts @@ -1,301 +1,301 @@ -import parser from "yargs-parser"; -import { v4 as uuidv4 } from 'uuid'; import { XMLValidator } from "fast-xml-parser"; -import { IRequestModel } from "../fetch-client-ui/components/RequestUI/redux/types"; -import { MIMETypes } from "./helper"; +import { v4 as uuidv4 } from 'uuid'; +import parser from "yargs-parser"; import { ITableData } from "../fetch-client-ui/components/Common/Table/types"; import { InitialAuth, InitialBody, InitialPreFetch, InitialSetVar, InitialTest } from "../fetch-client-ui/components/RequestUI/redux/reducer"; +import { IRequestModel } from "../fetch-client-ui/components/RequestUI/redux/types"; +import { MIMETypes } from "./helper"; import { writeLog } from "./logger/logger"; export const ConvertCurlToRequest = (curlRequest: string): IRequestModel | null => { - try { - if (!curlRequest.trim()) { - return null; - } - - curlRequest = curlRequest.trim(); - - if (!curlRequest.toLowerCase().startsWith("curl ")) { - return null; - } - - curlRequest = curlRequest.replace(/^\s+|\s+$/gm, ""); - curlRequest = curlRequest.replace(/(\r\n|\n|\r)/gm, " "); - - const argvs = parser(curlRequest); - - const request: IRequestModel = { - id: uuidv4(), - url: "", - name: "", - createdTime: "", - method: "get", - params: [], - auth: InitialAuth, - headers: [], - body: JSON.parse(JSON.stringify(InitialBody)), - tests: JSON.parse(JSON.stringify(InitialTest)), - setvar: JSON.parse(JSON.stringify(InitialSetVar)), - notes: "", - preFetch: JSON.parse(JSON.stringify(InitialPreFetch)) - }; - - const isJson = (str: string) => { - try { - JSON.parse(str); - } catch (e) { - return false; - } - return true; - }; - - const removeQuotes = (str: string) => str.trim().replace(/[""]+/g, "").replace(/['']+/g, ""); - - const stringIsUrl = (url: string) => { - return /(?:^|[ \t])((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)/.test(url); - }; - - const parseField = (str: string): string[] => { - return str.split(/: (.+)/); - }; - - const parseHeader = (header: any) => { - if (Array.isArray(header)) { - header.forEach((item) => { - addHeader(item); - }); - } else { - addHeader(header); - } - }; - - function addHeader(item: any) { - const field = parseField(item); - if (!checkAuthHeader(field)) { - request.headers.push({ - isChecked: true, - key: field[0], - value: field[1] - }); - } - } - - function checkAuthHeader(field: string[]): boolean { - if (field[0].toLowerCase() === "authorization" && field[1].toLowerCase().includes("bearer ")) { - request.auth.authType = "bearertoken"; - request.auth.password = field[1].replace("Bearer ", "").replace("bearer ", ""); - request.auth.tokenPrefix = "Bearer"; - return true; - } - - return false; - } - - const parseData = (data: any) => { - - const contentTypeHeader = request.headers.find(item => item.key.toLowerCase() === "content-type")?.value; - - if (contentTypeHeader?.includes("application/x-www-form-urlencoded")) { - request.body.urlencoded = parseDataUrlEncode(data); - request.body.bodyType = "formurlencoded"; - } else if (contentTypeHeader?.includes("application/json")) { - request.body.bodyType = "raw"; - if (isJson(data)) { - request.body.raw.data = JSON.parse(data); - request.body.raw.lang = "json"; - } - } else if (contentTypeHeader?.includes("application/xml") || contentTypeHeader?.includes("text/xml")) { - request.body.bodyType = "raw"; - if (XMLValidator.validate(data) === true) { - request.body.raw.data = data; - request.body.raw.lang = "xml"; - } - } else if (contentTypeHeader?.includes("application/html") || contentTypeHeader?.includes("text/html")) { - request.body.raw.data = data; - request.body.raw.lang = "html"; - request.body.bodyType = "raw"; - } else if (contentTypeHeader?.includes("text/plain")) { - request.body.raw.data = data; - request.body.raw.lang = "text"; - request.body.bodyType = "raw"; - } else if (contentTypeHeader && MIMETypes[contentTypeHeader]) { - request.body.binary = data; - request.body.bodyType = "binary"; - } else if (isJson(data)) { - request.headers.push({ - isChecked: true, - key: "Content-Type", - value: "application/json" - }); - request.body.raw.data = JSON.parse(data); - request.body.raw.lang = "json"; - } else if (XMLValidator.validate(data)) { - request.headers.push({ - isChecked: true, - key: "Content-Type", - value: "text/xml" - }); - request.body.raw.data = data; - request.body.raw.lang = "xml"; - } else { - request.body.raw.data = data; - request.body.raw.lang = "text"; - request.body.bodyType = "raw"; - } - }; - - const parseDataUrlEncode = (data: any): ITableData[] => { - let jsonUrlEncoded = ""; - - const contentTypeHeader = request.headers.find(item => item.key.toLowerCase() === "content-type")?.value; - - if (!contentTypeHeader) { - request.headers.push({ - isChecked: true, - key: "Content-Type", - value: "application/x-www-form-urlencoded" - }); - } - - if (Array.isArray(data)) { - data.forEach((item, index) => { - if (index === 0) { - jsonUrlEncoded = encodeURI(item); - } else { - jsonUrlEncoded = jsonUrlEncoded + "&" + encodeURI(item); - } - }); - return generateFormUrlEncode(jsonUrlEncoded); - } else { - return generateFormUrlEncode(data); - } - }; - - const generateFormUrlEncode = (data: string): ITableData[] => { - const searchParams = new URLSearchParams(data); - const params: ITableData[] = []; - for (const p of searchParams) { - if (p[0] && p[0].trim()) { - const tableData: ITableData = { - isChecked: true, - key: p[0].trim(), - value: p[1].trim() - }; - params.push(tableData); - } - } - - params.push({ isChecked: false, key: "", value: "" }); - return params; - }; - - const setRequestMethod = (): void => { - if (request.method === "get" || request.method === "options" || request.method === "head") { - request.method = "post"; - } - }; - - for (const argv in argvs) { - switch (argv) { - case "_": - { - const _ = argvs[argv]; - _.forEach((item: any) => { - item = removeQuotes(item); - if (stringIsUrl(item)) { - request.url = item; - } - }); - } - break; - - case "X": - case "request": - request.method = argvs[argv].toString().toLowerCase(); - break; - - case "H": - case "header": - parseHeader(argvs[argv]); - break; - - case "u": - case "user": { - const loginDetails = argvs[argv].split(":"); - request.auth.authType = "basic"; - request.auth.userName = loginDetails[0]; - request.auth.password = loginDetails[1]; - } - break; - - case "A": - case "user-agent": - request.headers.push({ - isChecked: true, - key: "user-agent", - value: argvs[argv] - }); - break; - - case "I": - case "head": - request.method = "head"; - break; - - case "b": - case "cookie": - request.headers.push({ - isChecked: true, - key: "Set-Cookie", - value: argvs[argv] - }); - break; - - case "d": - case "data": - case "data-raw": - case "data-ascii": - parseData(argvs[argv]); - setRequestMethod(); - break; - - case "data-urlencode": - request.body.urlencoded = parseDataUrlEncode(argvs[argv]); - request.body.bodyType = "formurlencoded"; - setRequestMethod(); - break; - - case "data-binary": - request.body.binary = argvs[argv]; - request.body.bodyType = "binary"; - setRequestMethod(); - break; - - case "compressed": { - const index = request.headers.findIndex(item => item.key.toLowerCase() === "accept-encoding"); - if (index === -1) { - request.headers.push({ - isChecked: true, - key: "Accept-Encoding", - value: argvs[argv] ? (typeof argvs[argv] === "boolean" ? "gzip, deflate" : argvs[argv]) : "gzip, deflate" - }); - } - } - break; - - default: - break; - } - } - - request.params.push({ isChecked: false, key: "", value: "" }); - request.headers.push({ isChecked: false, key: "", value: "" }); - - return request; - } - catch (err) { - writeLog("error::ConvertCurlToRequest(): " + err); - return null; - } + try { + if (!curlRequest.trim()) { + return null; + } + + curlRequest = curlRequest.trim(); + + if (!curlRequest.toLowerCase().startsWith("curl ")) { + return null; + } + + curlRequest = curlRequest.replace(/^\s+|\s+$/gm, ""); + curlRequest = curlRequest.replace(/(\r\n|\n|\r)/gm, " "); + + const argvs = parser(curlRequest); + + const request: IRequestModel = { + id: uuidv4(), + url: "", + name: "", + createdTime: "", + method: "get", + params: [], + auth: InitialAuth, + headers: [], + body: JSON.parse(JSON.stringify(InitialBody)), + tests: JSON.parse(JSON.stringify(InitialTest)), + setvar: JSON.parse(JSON.stringify(InitialSetVar)), + notes: "", + preFetch: JSON.parse(JSON.stringify(InitialPreFetch)) + }; + + const isJson = (str: string) => { + try { + JSON.parse(str); + } catch (e) { + return false; + } + return true; + }; + + const removeQuotes = (str: string) => str.trim().replace(/[""]+/g, "").replace(/['']+/g, ""); + + const stringIsUrl = (url: string) => { + return /(?:^|[ \t])((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)/.test(url); + }; + + const parseField = (str: string): string[] => { + return str.split(/: (.+)/); + }; + + const parseHeader = (header: any) => { + if (Array.isArray(header)) { + header.forEach((item) => { + addHeader(item); + }); + } else { + addHeader(header); + } + }; + + function addHeader(item: any) { + const field = parseField(item); + if (!checkAuthHeader(field)) { + request.headers.push({ + isChecked: true, + key: field[0], + value: field[1] + }); + } + } + + function checkAuthHeader(field: string[]): boolean { + if (field[0].toLowerCase() === "authorization" && field[1].toLowerCase().includes("bearer ")) { + request.auth.authType = "bearertoken"; + request.auth.password = field[1].replace("Bearer ", "").replace("bearer ", ""); + request.auth.tokenPrefix = "Bearer"; + return true; + } + + return false; + } + + const parseData = (data: any) => { + + const contentTypeHeader = request.headers.find(item => item.key.toLowerCase() === "content-type")?.value; + + if (contentTypeHeader?.includes("application/x-www-form-urlencoded")) { + request.body.urlencoded = parseDataUrlEncode(data); + request.body.bodyType = "formurlencoded"; + } else if (contentTypeHeader?.includes("application/json")) { + request.body.bodyType = "raw"; + if (isJson(data)) { + request.body.raw.data = JSON.parse(data); + request.body.raw.lang = "json"; + } + } else if (contentTypeHeader?.includes("application/xml") || contentTypeHeader?.includes("text/xml")) { + request.body.bodyType = "raw"; + if (XMLValidator.validate(data) === true) { + request.body.raw.data = data; + request.body.raw.lang = "xml"; + } + } else if (contentTypeHeader?.includes("application/html") || contentTypeHeader?.includes("text/html")) { + request.body.raw.data = data; + request.body.raw.lang = "html"; + request.body.bodyType = "raw"; + } else if (contentTypeHeader?.includes("text/plain")) { + request.body.raw.data = data; + request.body.raw.lang = "text"; + request.body.bodyType = "raw"; + } else if (contentTypeHeader && MIMETypes[contentTypeHeader]) { + request.body.binary = data; + request.body.bodyType = "binary"; + } else if (isJson(data)) { + request.headers.push({ + isChecked: true, + key: "Content-Type", + value: "application/json" + }); + request.body.raw.data = JSON.parse(data); + request.body.raw.lang = "json"; + } else if (XMLValidator.validate(data)) { + request.headers.push({ + isChecked: true, + key: "Content-Type", + value: "text/xml" + }); + request.body.raw.data = data; + request.body.raw.lang = "xml"; + } else { + request.body.raw.data = data; + request.body.raw.lang = "text"; + request.body.bodyType = "raw"; + } + }; + + const parseDataUrlEncode = (data: any): ITableData[] => { + let jsonUrlEncoded = ""; + + const contentTypeHeader = request.headers.find(item => item.key.toLowerCase() === "content-type")?.value; + + if (!contentTypeHeader) { + request.headers.push({ + isChecked: true, + key: "Content-Type", + value: "application/x-www-form-urlencoded" + }); + } + + if (Array.isArray(data)) { + data.forEach((item, index) => { + if (index === 0) { + jsonUrlEncoded = encodeURI(item); + } else { + jsonUrlEncoded = jsonUrlEncoded + "&" + encodeURI(item); + } + }); + return generateFormUrlEncode(jsonUrlEncoded); + } else { + return generateFormUrlEncode(data); + } + }; + + const generateFormUrlEncode = (data: string): ITableData[] => { + const searchParams = new URLSearchParams(data); + const params: ITableData[] = []; + for (const p of searchParams) { + if (p[0] && p[0].trim()) { + const tableData: ITableData = { + isChecked: true, + key: p[0].trim(), + value: p[1].trim() + }; + params.push(tableData); + } + } + + params.push({ isChecked: false, key: "", value: "" }); + return params; + }; + + const setRequestMethod = (): void => { + if (request.method === "get" || request.method === "options" || request.method === "head") { + request.method = "post"; + } + }; + + for (const argv in argvs) { + switch (argv) { + case "_": + { + const _ = argvs[argv]; + _.forEach((item: any) => { + item = removeQuotes(item); + if (stringIsUrl(item)) { + request.url = item; + } + }); + } + break; + + case "X": + case "request": + request.method = argvs[argv].toString().toLowerCase(); + break; + + case "H": + case "header": + parseHeader(argvs[argv]); + break; + + case "u": + case "user": { + const loginDetails = argvs[argv].split(":"); + request.auth.authType = "basic"; + request.auth.userName = loginDetails[0]; + request.auth.password = loginDetails[1]; + } + break; + + case "A": + case "user-agent": + request.headers.push({ + isChecked: true, + key: "user-agent", + value: argvs[argv] + }); + break; + + case "I": + case "head": + request.method = "head"; + break; + + case "b": + case "cookie": + request.headers.push({ + isChecked: true, + key: "Set-Cookie", + value: argvs[argv] + }); + break; + + case "d": + case "data": + case "data-raw": + case "data-ascii": + parseData(argvs[argv]); + setRequestMethod(); + break; + + case "data-urlencode": + request.body.urlencoded = parseDataUrlEncode(argvs[argv]); + request.body.bodyType = "formurlencoded"; + setRequestMethod(); + break; + + case "data-binary": + request.body.binary = argvs[argv]; + request.body.bodyType = "binary"; + setRequestMethod(); + break; + + case "compressed": { + const index = request.headers.findIndex(item => item.key.toLowerCase() === "accept-encoding"); + if (index === -1) { + request.headers.push({ + isChecked: true, + key: "Accept-Encoding", + value: argvs[argv] ? (typeof argvs[argv] === "boolean" ? "gzip, deflate" : argvs[argv]) : "gzip, deflate" + }); + } + } + break; + + default: + break; + } + } + + request.params.push({ isChecked: false, key: "", value: "" }); + request.headers.push({ isChecked: false, key: "", value: "" }); + + return request; + } + catch (err) { + writeLog("error::ConvertCurlToRequest(): " + err); + return null; + } }; diff --git a/src/utils/db/collectionDBUtil.ts b/src/utils/db/collectionDBUtil.ts index 88f7643..0a0d382 100644 --- a/src/utils/db/collectionDBUtil.ts +++ b/src/utils/db/collectionDBUtil.ts @@ -15,1071 +15,1073 @@ import { collectionDBPath, mainDBPath } from './dbPaths'; import { CopyExitingItems, DeleteExitingItems, GetColsRequests, RenameRequestItem } from './mainDBUtil'; function getDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(collectionDBPath(), { adapter: idbAdapter }); - db.autosaveDisable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(collectionDBPath(), { adapter: idbAdapter }); + db.autosaveDisable(); + return db; } function getRequestDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(mainDBPath(), { adapter: idbAdapter }); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(mainDBPath(), { adapter: idbAdapter }); + return db; } function findItem(source: any, id: string) { - let pos = source.data.findIndex((el: any) => el.id === id); + let pos = source.data.findIndex((el: any) => el.id === id); - if (pos !== -1) { - return source.data[pos]; - } + if (pos !== -1) { + return source.data[pos]; + } - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - const result = findItem(source.data[i], id); - if (result) { - return result; - } - } - } + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + const result = findItem(source.data[i], id); + if (result) { + return result; + } + } + } } function findParent(source: any, id: string) { - let pos = source.data.findIndex((el: any) => el.id === id); + let pos = source.data.findIndex((el: any) => el.id === id); - if (pos !== -1) { - return source; - } + if (pos !== -1) { + return source; + } - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - const result = findParent(source.data[i], id); + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + const result = findParent(source.data[i], id); - if (result) { - return result; - } - } - } + if (result) { + return result; + } + } + } } function findParentSettings(source: any, id: string, prevSettings: any = null) { - let pos = source.data.findIndex((el: any) => el.id === id); - let curSettings = source.settings; - - if (curSettings) { - if (curSettings.auth.authType === "inherit") { - curSettings = prevSettings; - } - } else { - curSettings = prevSettings; - } - - if (pos !== -1) { - if (source.data[pos].settings) { - if (source.data[pos].settings.auth.authType === "inherit") { - source.data[pos].settings.auth = curSettings.auth; - return source.data[pos].settings; - } else { - return source.data[pos].settings; - } - } else { - return curSettings; - } - } - - let folders = source.data.filter((item: any) => item.data !== undefined); - - for (let i = 0; i < folders.length; i++) { - const result: any = findParentSettings(folders[i], id, curSettings); - if (result) { - return result; - } - } + let pos = source.data.findIndex((el: any) => el.id === id); + let curSettings = source.settings; + + if (curSettings) { + if (curSettings.auth.authType === "inherit") { + curSettings = prevSettings; + } + } else { + curSettings = prevSettings; + } + + if (pos !== -1) { + if (source.data[pos].settings) { + if (source.data[pos].settings.auth.authType === "inherit") { + source.data[pos].settings.auth = curSettings.auth; + return source.data[pos].settings; + } else { + return source.data[pos].settings; + } + } else { + return curSettings; + } + } + + let folders = source.data.filter((item: any) => item.data !== undefined); + + for (let i = 0; i < folders.length; i++) { + const result: any = findParentSettings(folders[i], id, curSettings); + if (result) { + return result; + } + } } function duplicateFolderItems(sourceFolder: IFolder, destFolder: IFolder, oldIds: string[], ids: {}): { folder: IFolder, oIds: string[], nIds: {} } { - sourceFolder.data.forEach((item) => { - if (isFolder(item)) { - let folder: IFolder = { - id: uuidv4(), - name: item.name, - createdTime: formatDate(), - type: "folder", - data: [], - settings: (item as IFolder).settings ? (item as IFolder).settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - destFolder.data.push(folder); - duplicateFolderItems(item as IFolder, destFolder.data[destFolder.data.length - 1] as IFolder, oldIds, ids); - } else { - let newId = uuidv4(); - ids[item.id] = newId; - oldIds.push(item.id); - let his: IHistory = { - id: newId, - method: (item as IHistory).method, - name: item.name, - url: (item as IHistory).url, - createdTime: formatDate() - }; - destFolder.data.push(his); - } - }); - - return { folder: destFolder, oIds: oldIds, nIds: ids }; + sourceFolder.data.forEach((item) => { + if (isFolder(item)) { + let folder: IFolder = { + id: uuidv4(), + name: item.name, + createdTime: formatDate(), + type: "folder", + data: [], + settings: (item as IFolder).settings ? (item as IFolder).settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + destFolder.data.push(folder); + duplicateFolderItems(item as IFolder, destFolder.data[destFolder.data.length - 1] as IFolder, oldIds, ids); + } else { + let newId = uuidv4(); + ids[item.id] = newId; + oldIds.push(item.id); + let his: IHistory = { + id: newId, + method: (item as IHistory).method, + name: item.name, + url: (item as IHistory).url, + createdTime: formatDate() + }; + destFolder.data.push(his); + } + }); + + return { folder: destFolder, oIds: oldIds, nIds: ids }; } function getAllIds(source: any, ids: string[]) { - source.data.forEach(function (item) { - if (isFolder(item)) { - getAllIds(item, ids); - } else { - ids.push(item.id); - } - }); - - return ids; + source.data.forEach(function (item) { + if (isFolder(item)) { + getAllIds(item, ids); + } else { + ids.push(item.id); + } + }); + + return ids; } export function CreateNewCollection(name: string, sideBarView: vscode.WebviewView) { - try { - const colDB = getDB(); - colDB.loadDatabase({}, function () { - let item: ICollections = { - id: uuidv4(), - createdTime: formatDate(), - name: name, - data: [], - variableId: "", - settings: JSON.parse(JSON.stringify(InitialSettings)) - }; - const userCollections = colDB.getCollection('userCollections'); - userCollections.insert(item); - colDB.saveDatabase(); - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.appendToCollectionsResponse, collection: item }); - } - }); - } catch (err) { - writeLog("error::CreateNewCollection(): " + err); - } + try { + const colDB = getDB(); + colDB.loadDatabase({}, function () { + let item: ICollections = { + id: uuidv4(), + createdTime: formatDate(), + name: name, + data: [], + variableId: "", + settings: JSON.parse(JSON.stringify(InitialSettings)) + }; + const userCollections = colDB.getCollection('userCollections'); + userCollections.insert(item); + colDB.saveDatabase(); + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.appendToCollectionsResponse, collection: item }); + } + }); + } catch (err) { + writeLog("error::CreateNewCollection(): " + err); + } } export function AddToCollection(item: ICollections, hasFolder: boolean, isNewFolder: boolean, webview: vscode.Webview, sideBarView: vscode.WebviewView, request?: IRequestModel) { - try { - - const colDB = getDB(); - const reqDB = getRequestDB(); - const reqId = hasFolder ? (item.data[0] as IFolder).data[0].id : item.data[0].id; - const newId = uuidv4(); - - colDB.loadDatabase({}, function () { - const userCollections = colDB.getCollection('userCollections'); - - reqDB.loadDatabase({}, function () { - - let reqData: IRequestModel; - let results: any[]; - - //Add new item to main DB - const apiRequests = reqDB.getCollection('apiRequests'); - - if (request) { - reqData = request; - } else { - results = apiRequests.chain().find({ 'id': reqId }).data({ forceClones: true, removeMeta: true }); - if (results && results.length > 0) { - reqData = (results[0] as IRequestModel); - } - } - - if (reqData) { - reqData.id = newId; - apiRequests.insert(reqData); - reqDB.saveDatabase(); - - // Save item to collection DB - let colItem = userCollections.by("id", item.id); - - if (hasFolder) { - (item.data[0] as IFolder).data[0].id = newId; - } else { - item.data[0].id = newId; - } - - if (colItem === null || colItem === undefined) { - userCollections.insert(item); - } else { - if (item && item.data && item.data.length > 0) { - - if (hasFolder) { - if (isNewFolder) { - colItem.data.push(item.data[0]); - } else { - let folder = findItem(colItem, item.data[0].id); - folder.data.push((item.data[0] as IFolder).data[0]); - } - } else { - colItem.data.push(item.data[0]); - } - } - } - - colDB.saveDatabase(); - - if (webview) { - webview.postMessage({ - type: responseTypes.addToCollectionsResponse, - colId: item.id, - folderId: hasFolder ? item.data[0].id : "", - historyId: newId, - historyName: hasFolder ? (item.data[0] as IFolder).data[0].name : item.data[0].name, - varId: colItem ? colItem.variableId : "" - }); - } - - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.appendToCollectionsResponse, collection: colItem ? colItem : item }); - } - } - }); - }); - } catch (err) { - writeLog("error::AddToCollection(): " + err); - } + try { + + const colDB = getDB(); + const reqDB = getRequestDB(); + const reqId = hasFolder ? (item.data[0] as IFolder).data[0].id : item.data[0].id; + const newId = uuidv4(); + + colDB.loadDatabase({}, function () { + const userCollections = colDB.getCollection('userCollections'); + + reqDB.loadDatabase({}, function () { + + let reqData: IRequestModel; + let results: any[]; + + //Add new item to main DB + const apiRequests = reqDB.getCollection('apiRequests'); + + if (request) { + reqData = request; + } else { + results = apiRequests.chain().find({ 'id': reqId }).data({ forceClones: true, removeMeta: true }); + if (results && results.length > 0) { + reqData = (results[0] as IRequestModel); + } + } + + if (reqData) { + reqData.id = newId; + apiRequests.insert(reqData); + reqDB.saveDatabase(); + + // Save item to collection DB + let colItem = userCollections.by("id", item.id); + + if (hasFolder) { + (item.data[0] as IFolder).data[0].id = newId; + } else { + item.data[0].id = newId; + } + + if (colItem === null || colItem === undefined) { + userCollections.insert(item); + } else { + if (item && item.data && item.data.length > 0) { + + if (hasFolder) { + if (isNewFolder) { + colItem.data.push(item.data[0]); + } else { + let folder = findItem(colItem, item.data[0].id); + folder.data.push((item.data[0] as IFolder).data[0]); + } + } else { + colItem.data.push(item.data[0]); + } + } + } + + colDB.saveDatabase(); + + if (webview) { + webview.postMessage({ + type: responseTypes.addToCollectionsResponse, + colId: item.id, + folderId: hasFolder ? item.data[0].id : "", + historyId: newId, + historyName: hasFolder ? (item.data[0] as IFolder).data[0].name : item.data[0].name, + varId: colItem ? colItem.variableId : "" + }); + } + + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.appendToCollectionsResponse, collection: colItem ? colItem : item }); + } + } + }); + }); + } catch (err) { + writeLog("error::AddToCollection(): " + err); + } } export function DuplicateItem(coldId: string, folderId: string, historyId: string, folderType: boolean, sideBarView: vscode.WebviewView) { - try { - const colDB = getDB(); - let oldIds: string[] = []; - let ids = {}; - - colDB.loadDatabase({}, function () { - const collections = colDB.getCollection('userCollections').find({ 'id': coldId }); - - if (folderType) { - let parent = findParent(collections[0], folderId); - if (parent) { - let item = findItem(parent, folderId); - if (item) { - let destFolder: IFolder = { - id: uuidv4(), - name: item.name + " (Copy)", - createdTime: formatDate(), - type: "folder", - data: [], - settings: item.settings ? item.settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - - const { folder, oIds, nIds } = duplicateFolderItems(item, destFolder, [], {}); - oldIds = oIds; - ids = nIds; - parent.data.push(folder); - } - } - } else { - if (folderId) { - let folder = findItem(collections[0], folderId); - if (folder) { - let item = findItem(folder, historyId); - let newId = uuidv4(); - ids[item.id] = newId; - oldIds.push(item.id); - let his: IHistory = { - id: newId, - method: item.method, - name: item.name + " (Copy)", - url: item.url, - createdTime: formatDate() - }; - folder.data.push(his); - } - } - else if (historyId) { - let item = findItem(collections[0], historyId); - if (item) { - let newId = uuidv4(); - ids[item.id] = newId; - oldIds.push(item.id); - let his: IHistory = { - id: newId, - method: item.method, - name: item.name + " (Copy)", - url: item.url, - createdTime: formatDate() - }; - collections[0].data.push(his); - } - } else if (coldId) { - CopyToCollection(coldId, uuidv4(), collections[0].name + " (Copy)", null, sideBarView); - return; - } - } - colDB.saveDatabase(); - CopyExitingItems(oldIds, ids); - - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.copyToCollectionsResponse, data: collections[0] }); - } - }); - } catch (err) { - writeLog("error::DuplicateItem(): " + err); - } + try { + const colDB = getDB(); + let oldIds: string[] = []; + let ids = {}; + + colDB.loadDatabase({}, function () { + const collections = colDB.getCollection('userCollections').find({ 'id': coldId }); + + if (folderType) { + let parent = findParent(collections[0], folderId); + if (parent) { + let item = findItem(parent, folderId); + if (item) { + let destFolder: IFolder = { + id: uuidv4(), + name: item.name + " (Copy)", + createdTime: formatDate(), + type: "folder", + data: [], + settings: item.settings ? item.settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + + const { folder, oIds, nIds } = duplicateFolderItems(item, destFolder, [], {}); + oldIds = oIds; + ids = nIds; + parent.data.push(folder); + } + } + } else { + if (folderId) { + let folder = findItem(collections[0], folderId); + if (folder) { + let item = findItem(folder, historyId); + let newId = uuidv4(); + ids[item.id] = newId; + oldIds.push(item.id); + let his: IHistory = { + id: newId, + method: item.method, + name: item.name + " (Copy)", + url: item.url, + createdTime: formatDate() + }; + folder.data.push(his); + } + } + else if (historyId) { + let item = findItem(collections[0], historyId); + if (item) { + let newId = uuidv4(); + ids[item.id] = newId; + oldIds.push(item.id); + let his: IHistory = { + id: newId, + method: item.method, + name: item.name + " (Copy)", + url: item.url, + createdTime: formatDate() + }; + collections[0].data.push(his); + } + } else if (coldId) { + CopyToCollection(coldId, uuidv4(), collections[0].name + " (Copy)", null, sideBarView); + return; + } + } + colDB.saveDatabase(); + CopyExitingItems(oldIds, ids); + + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.copyToCollectionsResponse, data: collections[0] }); + } + }); + } catch (err) { + writeLog("error::DuplicateItem(): " + err); + } } export function NewRequestToCollection(item: IHistory, colId: string, folderId: string, sideBarView: vscode.WebviewView) { - try { - const colDB = getDB(); - - colDB.loadDatabase({}, function () { - let cols = colDB.getCollection('userCollections').by('id', colId); - if (cols) { - if (folderId) { - let folder = findItem(cols, folderId); - if (folder) { - folder.data.push(item); - } - } else { - cols.data.push(item); - } - } - - colDB.saveDatabase(); - - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.createNewResponse, item: item, id: colId, folderId: folderId, variableId: cols.variableId }); - } - - }); - } catch (err) { - writeLog("error::NewRequestToCollection(): " + err); - } + try { + const colDB = getDB(); + + colDB.loadDatabase({}, function () { + let cols = colDB.getCollection('userCollections').by('id', colId); + if (cols) { + if (folderId) { + let folder = findItem(cols, folderId); + if (folder) { + folder.data.push(item); + } + } else { + cols.data.push(item); + } + } + + colDB.saveDatabase(); + + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.createNewResponse, item: item, id: colId, folderId: folderId, variableId: cols.variableId }); + } + + }); + } catch (err) { + writeLog("error::NewRequestToCollection(): " + err); + } } export function CopyToCollection(sourceId: string, destID: string, destName: string, webview: vscode.Webview, sideBarView: vscode.WebviewView) { - try { - const colDB = getDB(); - - colDB.loadDatabase({}, function () { - let cols: any; - let ids = {}; - let oldIds: string[] = []; - - const userCollections = colDB.getCollection('userCollections'); - let sourceColItem = userCollections.chain().find({ 'id': sourceId }).data({ forceClones: true, removeMeta: true }); - let destColItem = userCollections.by("id", destID); - - if (destColItem === null || destColItem === undefined) { - let items: ICollections = { - id: destID, - name: destName, - createdTime: formatDate(), - variableId: "", - settings: sourceColItem[0].settings ? sourceColItem[0].settings : JSON.parse(JSON.stringify(InitialSettings)), - data: (sourceColItem[0] as ICollections).data.length > 0 ? (sourceColItem[0] as ICollections).data.map(item => { - if (isFolder(item)) { - let destFolder: IFolder = { - id: uuidv4(), - name: item.name, - createdTime: formatDate(), - type: "folder", - data: [], - settings: (item as IFolder).settings ? (item as IFolder).settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - const { folder, oIds, nIds } = duplicateFolderItems(item as IFolder, destFolder, [], {}); - oldIds = [...oldIds, ...oIds]; - ids = { ...ids, ...nIds }; - - return folder; - } else { - item = (item as IHistory); - let newId = uuidv4(); - oldIds.push(item.id); - ids[item.id] = newId; - let his: IHistory = { - id: newId, - method: item.method, - name: item.name, - url: item.url, - createdTime: formatDate() - }; - return his; - } - }) : [] - }; - - cols = items; - userCollections.insert(items); - - } else { - if ((sourceColItem[0] as ICollections).data.length > 0) { - let items = (sourceColItem[0] as ICollections).data.map(item => { - if (isFolder(item)) { - let destFolder: IFolder = { - id: uuidv4(), - name: item.name, - createdTime: formatDate(), - type: "folder", - data: [], - settings: (item as IFolder).settings ? (item as IFolder).settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - const { folder, oIds, nIds } = duplicateFolderItems(item as IFolder, destFolder, [], {}); - oldIds = [...oldIds, ...oIds]; - ids = { ...ids, ...nIds }; - return folder; - } else { - item = (item as IHistory); - let newId = uuidv4(); - oldIds.push(item.id); - ids[item.id] = newId; - let his: IHistory = { - id: newId, - method: item.method, - name: item.name, - url: item.url, - createdTime: formatDate() - }; - return his; - } - }); - - items.forEach(item => { - destColItem.data.push(item); - }); - - cols = destColItem; - } - } - - colDB.saveDatabase(); - CopyExitingItems(oldIds, ids); - - if (webview) { - webview.postMessage({ type: responseTypes.copyToCollectionsResponse }); - } - - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.copyToCollectionsResponse, data: cols }); - } - }); - - } catch (err) { - writeLog("error::CopyToCollection(): " + err); - } + try { + const colDB = getDB(); + + colDB.loadDatabase({}, function () { + let cols: any; + let ids = {}; + let oldIds: string[] = []; + + const userCollections = colDB.getCollection('userCollections'); + let sourceColItem = userCollections.chain().find({ 'id': sourceId }).data({ forceClones: true, removeMeta: true }); + let destColItem = userCollections.by("id", destID); + + if (destColItem === null || destColItem === undefined) { + let items: ICollections = { + id: destID, + name: destName, + createdTime: formatDate(), + variableId: "", + settings: sourceColItem[0].settings ? sourceColItem[0].settings : JSON.parse(JSON.stringify(InitialSettings)), + data: (sourceColItem[0] as ICollections).data.length > 0 ? (sourceColItem[0] as ICollections).data.map(item => { + if (isFolder(item)) { + let destFolder: IFolder = { + id: uuidv4(), + name: item.name, + createdTime: formatDate(), + type: "folder", + data: [], + settings: (item as IFolder).settings ? (item as IFolder).settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + const { folder, oIds, nIds } = duplicateFolderItems(item as IFolder, destFolder, [], {}); + oldIds = [...oldIds, ...oIds]; + ids = { ...ids, ...nIds }; + + return folder; + } else { + item = (item as IHistory); + let newId = uuidv4(); + oldIds.push(item.id); + ids[item.id] = newId; + let his: IHistory = { + id: newId, + method: item.method, + name: item.name, + url: item.url, + createdTime: formatDate() + }; + return his; + } + }) : [] + }; + + cols = items; + userCollections.insert(items); + + } else { + if ((sourceColItem[0] as ICollections).data.length > 0) { + let items = (sourceColItem[0] as ICollections).data.map(item => { + if (isFolder(item)) { + let destFolder: IFolder = { + id: uuidv4(), + name: item.name, + createdTime: formatDate(), + type: "folder", + data: [], + settings: (item as IFolder).settings ? (item as IFolder).settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + const { folder, oIds, nIds } = duplicateFolderItems(item as IFolder, destFolder, [], {}); + oldIds = [...oldIds, ...oIds]; + ids = { ...ids, ...nIds }; + return folder; + } else { + item = (item as IHistory); + let newId = uuidv4(); + oldIds.push(item.id); + ids[item.id] = newId; + let his: IHistory = { + id: newId, + method: item.method, + name: item.name, + url: item.url, + createdTime: formatDate() + }; + return his; + } + }); + + items.forEach(item => { + destColItem.data.push(item); + }); + + cols = destColItem; + } + } + + colDB.saveDatabase(); + CopyExitingItems(oldIds, ids); + + if (webview) { + webview.postMessage({ type: responseTypes.copyToCollectionsResponse }); + } + + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.copyToCollectionsResponse, data: cols }); + } + }); + + } catch (err) { + writeLog("error::CopyToCollection(): " + err); + } } export function GetAllCollectionName(webview: vscode.Webview, from: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userCollections = db.getCollection('userCollections').data; - - if (userCollections && userCollections.length > 0) { - let collections = []; - let folders = []; - userCollections.forEach(col => { - col.data.forEach(item => { - if (item.data) { - folders.push({ colId: col.id, value: item.id, name: item.name, disabled: false }); - } - }); - collections.push({ value: col.id, name: col.name, disabled: false }); - }); - - if (from === "addtocol") { - webview.postMessage({ type: responseTypes.getAllCollectionNameResponse, collectionNames: collections, folderNames: folders }); - } else { - webview.postMessage({ type: responseTypes.getAllCollectionNamesResponse, collectionNames: collections, folderNames: folders }); - } - } - }); - - } catch (err) { - writeLog("error::GetAllCollectionName(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userCollections = db.getCollection('userCollections').data; + + if (userCollections && userCollections.length > 0) { + let collections = []; + let folders = []; + userCollections.forEach(col => { + col.data.forEach(item => { + if (item.data) { + folders.push({ colId: col.id, value: item.id, name: item.name, disabled: false }); + } + }); + collections.push({ value: col.id, name: col.name, disabled: false }); + }); + + if (from === "addtocol") { + webview.postMessage({ type: responseTypes.getAllCollectionNameResponse, collectionNames: collections, folderNames: folders }); + } else { + webview.postMessage({ type: responseTypes.getAllCollectionNamesResponse, collectionNames: collections, folderNames: folders }); + } + } + }); + + } catch (err) { + writeLog("error::GetAllCollectionName(): " + err); + } } export function GetAllCollections(webview: vscode.Webview) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const userCollections = db.getCollection('userCollections').data; - webview.postMessage({ type: responseTypes.getAllCollectionsResponse, collections: userCollections }); - }); + db.loadDatabase({}, function () { + const userCollections = db.getCollection('userCollections').data; + webview.postMessage({ type: responseTypes.getAllCollectionsResponse, collections: userCollections }); + }); - } catch (err) { - writeLog("error::GetAllCollections(): " + err); - } + } catch (err) { + writeLog("error::GetAllCollections(): " + err); + } } export function RenameCollectionItem(webviewView: vscode.WebviewView, colId: string, historyId: string, folderId: string, folderType: boolean, name: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let cols = db.getCollection('userCollections').by('id', colId); - - if (cols) { - let item = findItem(cols, historyId ? historyId : folderId); - - if (item) { - item["name"] = name; - } - - db.saveDatabase(); - - if (!folderType) { - RenameRequestItem(historyId, name); - } - - webviewView.webview.postMessage( - { - type: responseTypes.renameCollectionItemResponse, - params: { colId: colId, historyId: historyId, folderId: folderId, isFolder: folderType, name: name } - } - ); - } - }); - } catch (err) { - writeLog("error::RenameCollectionItem(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let cols = db.getCollection('userCollections').by('id', colId); + + if (cols) { + let item = findItem(cols, historyId ? historyId : folderId); + + if (item) { + item["name"] = name; + } + + db.saveDatabase(); + + if (!folderType) { + RenameRequestItem(historyId, name); + } + + webviewView.webview.postMessage( + { + type: responseTypes.renameCollectionItemResponse, + params: { colId: colId, historyId: historyId, folderId: folderId, isFolder: folderType, name: name } + } + ); + } + }); + } catch (err) { + writeLog("error::RenameCollectionItem(): " + err); + } } export function DeleteCollectionItem(webviewView: vscode.WebviewView, colId: string, folderId: string, historyId: string, folderType: boolean) { - try { - - let ids: string[]; - - function deleteItem(source: any, id: string, folderType: boolean) { - let pos = source.data.findIndex((el: any) => el.id === id); - - if (pos !== -1) { - if (folderType) { - ids = getAllIds(source, []); - } else { - ids = [id]; - } - source.data.splice(pos, 1); - } - - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - deleteItem(source.data[i], id, folderType); - } - } - } - - const db = getDB(); - - db.loadDatabase({}, function () { - let cols = db.getCollection('userCollections').by('id', colId); - if (cols !== null) { - deleteItem(cols, folderType ? folderId : historyId, folderType); - db.saveDatabase(); - } - DeleteExitingItems(ids); - webviewView.webview.postMessage({ type: responseTypes.deleteCollectionItemResponse, params: { colId: colId, folderId: folderId, historyId: historyId, isFolder: folderType } }); - }); - - } catch (err) { - writeLog("error::DeleteCollectionItem(): " + err); - } + try { + + let ids: string[]; + + function deleteItem(source: any, id: string, folderType: boolean) { + let pos = source.data.findIndex((el: any) => el.id === id); + + if (pos !== -1) { + if (folderType) { + ids = getAllIds(source, []); + } else { + ids = [id]; + } + source.data.splice(pos, 1); + } + + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + deleteItem(source.data[i], id, folderType); + } + } + } + + const db = getDB(); + + db.loadDatabase({}, function () { + let cols = db.getCollection('userCollections').by('id', colId); + if (cols !== null) { + deleteItem(cols, folderType ? folderId : historyId, folderType); + db.saveDatabase(); + } + DeleteExitingItems(ids); + webviewView.webview.postMessage({ type: responseTypes.deleteCollectionItemResponse, params: { colId: colId, folderId: folderId, historyId: historyId, isFolder: folderType } }); + }); + + } catch (err) { + writeLog("error::DeleteCollectionItem(): " + err); + } } export function RenameCollection(webviewView: vscode.WebviewView, colId: string, name: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection('userCollections').findAndUpdate({ 'id': colId }, item => { item.name = name; }); - db.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.renameCollectionResponse, params: { id: colId, name: name } }); - }); - - } catch (err) { - writeLog("error::RenameCollection(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection('userCollections').findAndUpdate({ 'id': colId }, item => { item.name = name; }); + db.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.renameCollectionResponse, params: { id: colId, name: name } }); + }); + + } catch (err) { + writeLog("error::RenameCollection(): " + err); + } } export function DeleteCollection(webviewView: vscode.WebviewView, colId: string) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const userCollections = db.getCollection('userCollections'); - let results = userCollections.by('id', colId); - let ids = getAllIds(results, []); + db.loadDatabase({}, function () { + const userCollections = db.getCollection('userCollections'); + let results = userCollections.by('id', colId); + let ids = getAllIds(results, []); - userCollections.findAndRemove({ 'id': colId }); - db.saveDatabase(); + userCollections.findAndRemove({ 'id': colId }); + db.saveDatabase(); - DeleteExitingItems(ids); + DeleteExitingItems(ids); - webviewView.webview.postMessage({ type: responseTypes.deleteCollectionResponse, id: colId }); - }); + webviewView.webview.postMessage({ type: responseTypes.deleteCollectionResponse, id: colId }); + }); - } catch (err) { - writeLog("error::DeleteCollection(): " + err); - } + } catch (err) { + writeLog("error::DeleteCollection(): " + err); + } } export function DeleteAllCollectionItems(webviewView: vscode.WebviewView, colId: string, folderId: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userCollections = db.getCollection('userCollections'); - const results = userCollections.by('id', colId); - let ids = []; - if (folderId) { - let item = findItem(results, folderId); - if (item) { - ids = getAllIds(item, []); - item.data.length = 0; - } - } else { - ids = getAllIds(results, []); - results.data.length = 0; - } - - db.saveDatabase(); - DeleteExitingItems(ids); - webviewView.webview.postMessage({ type: responseTypes.clearResponse, id: colId, folderId: folderId }); - }); - - } catch (err) { - writeLog("error::DeleteAllCollectionItems(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userCollections = db.getCollection('userCollections'); + const results = userCollections.by('id', colId); + let ids = []; + if (folderId) { + let item = findItem(results, folderId); + if (item) { + ids = getAllIds(item, []); + item.data.length = 0; + } + } else { + ids = getAllIds(results, []); + results.data.length = 0; + } + + db.saveDatabase(); + DeleteExitingItems(ids); + webviewView.webview.postMessage({ type: responseTypes.clearResponse, id: colId, folderId: folderId }); + }); + + } catch (err) { + writeLog("error::DeleteAllCollectionItems(): " + err); + } } export function AttachVariable(colId: string, varId: string, webview: vscode.Webview, sideBarView: vscode.WebviewView) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - db.getCollection('userCollections').findAndUpdate({ 'id': colId }, item => { item.variableId = varId; }); - db.saveDatabase(); + db.loadDatabase({}, function () { + db.getCollection('userCollections').findAndUpdate({ 'id': colId }, item => { item.variableId = varId; }); + db.saveDatabase(); - if (webview) { - webview.postMessage({ type: responseTypes.attachVariableResponse }); - } + if (webview) { + webview.postMessage({ type: responseTypes.attachVariableResponse }); + } - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.attachVariableResponse, params: { id: colId, varId: varId } }); - } + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.attachVariableResponse, params: { id: colId, varId: varId } }); + } - if (pubSub.size > 0) { - pubSub.publish({ messageType: varId === "" ? pubSubTypes.removeCurrentVariable : pubSubTypes.addCurrentVariable, message: varId }); - } - }); + if (pubSub.size > 0) { + pubSub.publish({ messageType: varId === "" ? pubSubTypes.removeCurrentVariable : pubSubTypes.addCurrentVariable, message: varId }); + } + }); - } catch (err) { - writeLog("error::AttachVariable(): " + err); - } + } catch (err) { + writeLog("error::AttachVariable(): " + err); + } } export function RemoveVariableByVariableId(varId: string, sideBarView: vscode.WebviewView) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection('userCollections').findAndUpdate({ 'variableId': varId }, item => { item.variableId = ""; }); - db.saveDatabase(); - - if (sideBarView) { - const userCollections = db.getCollection('userCollections').data; - sideBarView.webview.postMessage({ type: responseTypes.getAllCollectionsResponse, collections: userCollections }); - } - }); - - } catch (err) { - writeLog("error::AttachVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection('userCollections').findAndUpdate({ 'variableId': varId }, item => { item.variableId = ""; }); + db.saveDatabase(); + + if (sideBarView) { + const userCollections = db.getCollection('userCollections').data; + sideBarView.webview.postMessage({ type: responseTypes.getAllCollectionsResponse, collections: userCollections }); + } + }); + + } catch (err) { + writeLog("error::AttachVariable(): " + err); + } } export function GetCollectionsByVariable(varId: string, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const cols = db.getCollection('userCollections').chain().find({ 'variableId': varId }).data(); - let colNames = []; - if (cols && cols.length > 0) { - colNames = cols.map((item) => { return item.name; }); - } - webview.postMessage({ type: responseTypes.getAttachedColIdsResponse, colNames: colNames }); - }); - - } catch (err) { - writeLog("error::GetCollectionsByVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const cols = db.getCollection('userCollections').chain().find({ 'variableId': varId }).data(); + let colNames = []; + if (cols && cols.length > 0) { + colNames = cols.map((item) => { return item.name; }); + } + webview.postMessage({ type: responseTypes.getAttachedColIdsResponse, colNames: colNames }); + }); + + } catch (err) { + writeLog("error::GetCollectionsByVariable(): " + err); + } } export function RemoveVariable(varId: string) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - db.getCollection('userCollections').findAndUpdate({ 'variableId': varId }, item => { item.variableId = ""; }); - db.saveDatabase(); - }); + db.loadDatabase({}, function () { + db.getCollection('userCollections').findAndUpdate({ 'variableId': varId }, item => { item.variableId = ""; }); + db.saveDatabase(); + }); - } catch (err) { - writeLog("error::RemoveVariable(): " + err); - } + } catch (err) { + writeLog("error::RemoveVariable(): " + err); + } } export function GetAllCollectionsById(colId: string, folderId: string, type: string, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let ids = []; - let paths: any; - let settings: ISettings; - - let colItem = db.getCollection('userCollections').by('id', colId); - if (type === "col") { - ({ paths, ids } = getPath(colItem, "", {}, [], "source")); - } else { - let item = findItem(colItem, folderId); - ({ paths, ids } = getPath(item, "", {}, [], "source")); - } - ids = ids.reverse(); - GetColsRequests(ids, paths, webview); - - if (colItem) { - if (folderId) { - settings = findParentSettings(colItem, folderId); - if (!settings) { - settings = JSON.parse(JSON.stringify(InitialSettings)) as ISettings; - } - } else { - settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; - } - - if (webview) { - webview.postMessage({ type: responseTypes.getParentSettingsResponse, settings: settings }); - } - } - }); - - } catch (err) { - writeLog("error::GetAllCollectionsById(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let ids = []; + let paths: any; + let settings: ISettings; + + let colItem = db.getCollection('userCollections').by('id', colId); + if (type === "col") { + ({ paths, ids } = getPath(colItem, "", {}, [], "source")); + } else { + let item = findItem(colItem, folderId); + ({ paths, ids } = getPath(item, "", {}, [], "source")); + } + ids = ids.reverse(); + GetColsRequests(ids, paths, webview); + + if (colItem) { + if (folderId) { + settings = findParentSettings(colItem, folderId); + if (!settings) { + settings = JSON.parse(JSON.stringify(InitialSettings)) as ISettings; + } + } else { + settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; + } + + if (webview) { + webview.postMessage({ type: responseTypes.getParentSettingsResponse, settings: settings }); + } + } + }); + + } catch (err) { + writeLog("error::GetAllCollectionsById(): " + err); + } } export function GetAllCollectionsByIdWithPath(colId: string, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let results = db.getCollection('userCollections').by('id', colId); - const { paths } = getPath(results, "", {}, [], "request"); - if (webview) { - webview.postMessage({ type: responseTypes.getCollectionsByIdWithPathResponse, colId: colId, paths: paths }); - } - }); - - } catch (err) { - writeLog("error::GetAllCollectionsByIdWithPath(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let results = db.getCollection('userCollections').by('id', colId); + const { paths } = getPath(results, "", {}, [], "request"); + if (webview) { + webview.postMessage({ type: responseTypes.getCollectionsByIdWithPathResponse, colId: colId, paths: paths }); + } + }); + + } catch (err) { + writeLog("error::GetAllCollectionsByIdWithPath(): " + err); + } } function getPath(source: any, path: string, paths: {}, ids: string[], type: string) { - let folders = source.data.filter(item => item.data !== undefined); - - if (folders.length === 0) { - source.data.forEach(item => { - paths[item.id] = path ? path + " > " + source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id) : source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id); - ids.unshift(item.id); - }); - - return { paths, ids }; - } else { - source.data.filter(i => i.data === undefined).forEach(item => { - paths[item.id] = path ? path + " > " + source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id) : source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id); - ids.unshift(item.id); - }); - } - - path = path ? path + " > " + source.name : source.name; - - for (let i = 0; i < folders.length; i++) { - const result = getPath(folders[i], path, paths, ids, type); - if (i === folders.length - 1) { - return result; - } - } + let folders = source.data.filter(item => item.data !== undefined); + + if (folders.length === 0) { + source.data.forEach(item => { + paths[item.id] = path ? path + " > " + source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id) : source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id); + ids.unshift(item.id); + }); + + return { paths, ids }; + } else { + source.data.filter(i => i.data === undefined).forEach(item => { + paths[item.id] = path ? path + " > " + source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id) : source.name + (type === "source" ? ";" + source.id : " > " + item.name + ";" + source.id); + ids.unshift(item.id); + }); + } + + path = path ? path + " > " + source.name : source.name; + + for (let i = 0; i < folders.length; i++) { + const result = getPath(folders[i], path, paths, ids, type); + if (i === folders.length - 1) { + return result; + } + } } export function GetVariableByColId(colId: string) { - try { - return new Promise((resolve, _reject) => { - const db = getDB(); - - db.loadDatabase({}, function (err: any) { - if (err) { - resolve(null); - } - const colItem = db.getCollection('userCollections').by("id", colId); - resolve(colItem ? colItem.variableId : ""); - }); - }); - } catch (err) { - writeLog("error::GetVariableByColId(): " + err); - } + try { + return new Promise((resolve, _reject) => { + const db = getDB(); + + db.loadDatabase({}, function (err: any) { + if (err) { + resolve(null); + } + const colItem = db.getCollection('userCollections').by("id", colId); + resolve(colItem ? colItem.variableId : ""); + }); + }); + } catch (err) { + writeLog("error::GetVariableByColId(): " + err); + throw err; + } } export function NewFolderToCollection(item: IFolder, colId: string, folderId: string, sideBarView: vscode.WebviewView) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const colItem = db.getCollection('userCollections').by("id", colId); - if (folderId) { - let folder = findItem(colItem, folderId); - if (folder) { - folder.data.push(item); - } - } else { - colItem.data.push(item); - } - db.saveDatabase(); - - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.createNewFolderResponse, folder: item, colId: colId, folderId: folderId }); - } - }); - } catch (err) { - writeLog("error::NewFolderToCollection(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const colItem = db.getCollection('userCollections').by("id", colId); + if (folderId) { + let folder = findItem(colItem, folderId); + if (folder) { + folder.data.push(item); + } + } else { + colItem.data.push(item); + } + db.saveDatabase(); + + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.createNewFolderResponse, folder: item, colId: colId, folderId: folderId }); + } + }); + } catch (err) { + writeLog("error::NewFolderToCollection(): " + err); + } } export function UpdateCollection(colId: string, item: IHistory) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const colItem = db.getCollection('userCollections').by("id", colId); - let req = findItem(colItem, item.id); - if (req) { - req.name = item.name; - req.method = item.method; - req.url = item.url; - } - db.saveDatabase(); - }); - } catch (err) { - writeLog("error::UpdateCollection(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const colItem = db.getCollection('userCollections').by("id", colId); + let req = findItem(colItem, item.id); + if (req) { + req.name = item.name; + req.method = item.method; + req.url = item.url; + } + db.saveDatabase(); + }); + } catch (err) { + writeLog("error::UpdateCollection(): " + err); + } } export function GetCollectionSettings(webview: vscode.Webview, colId: string, folderId: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let settings: any; - - const colItem = db.getCollection('userCollections').by("id", colId); - - if (colItem) { - if (folderId) { - let folderItem = findItem(colItem, folderId); - if (folderItem) { - settings = folderItem.settings ? folderItem.settings : JSON.parse(JSON.stringify(InitialSettings)); - } - } else { - settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings)); - } - - if (webview) { - webview.postMessage({ type: responseTypes.getColSettingsResponse, data: { settings: settings, type: folderId ? SettingsType.Folder : SettingsType.Collection, variableId: colItem.variableId } }); - } - } - }); - } - catch (err) { - writeLog("error::GetCollectionSettings(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let settings: any; + + const colItem = db.getCollection('userCollections').by("id", colId); + + if (colItem) { + if (folderId) { + let folderItem = findItem(colItem, folderId); + if (folderItem) { + settings = folderItem.settings ? folderItem.settings : JSON.parse(JSON.stringify(InitialSettings)); + } + } else { + settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings)); + } + + if (webview) { + webview.postMessage({ type: responseTypes.getColSettingsResponse, data: { settings: settings, type: folderId ? SettingsType.Folder : SettingsType.Collection, variableId: colItem.variableId } }); + } + } + }); + } + catch (err) { + writeLog("error::GetCollectionSettings(): " + err); + } } export function GetParentSettings(colId: string, folderId: string, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let settings: ISettings; - - const colItem = db.getCollection('userCollections').by("id", colId); - - if (colItem) { - if (folderId) { - settings = findParentSettings(colItem, folderId); - if (!settings) { - settings = JSON.parse(JSON.stringify(InitialSettings)) as ISettings; - } - } else { - settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; - } - - if (webview) { - webview.postMessage({ type: responseTypes.getParentSettingsResponse, settings: settings }); - } - } - }); - } - catch (err) { - writeLog("error::GetParentSettings(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let settings: ISettings; + + const colItem = db.getCollection('userCollections').by("id", colId); + + if (colItem) { + if (folderId) { + settings = findParentSettings(colItem, folderId); + if (!settings) { + settings = JSON.parse(JSON.stringify(InitialSettings)) as ISettings; + } + } else { + settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; + } + + if (webview) { + webview.postMessage({ type: responseTypes.getParentSettingsResponse, settings: settings }); + } + } + }); + } + catch (err) { + writeLog("error::GetParentSettings(): " + err); + } } export function GetParentSettingsSync(colId: string, folderId: string) { - try { - return new Promise((resolve, _reject) => { - const db = getDB(); - - db.loadDatabase({}, function (err: any) { - - if (err) { - resolve(null); - } - - - let settings: any; - const colItem = db.getCollection('userCollections').by("id", colId); - - if (colItem) { - if (folderId) { - settings = findParentSettings(colItem, folderId); - if (!settings) { - settings = JSON.parse(JSON.stringify(InitialSettings)); - } - } else { - settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; - } - } - - resolve(settings ? settings as ISettings : null); - }); - }); - } - catch (err) { - writeLog("error::GetParentSettingsSync(): " + err); - } + try { + return new Promise((resolve, _reject) => { + const db = getDB(); + + db.loadDatabase({}, function (err: any) { + + if (err) { + resolve(null); + } + + + let settings: any; + const colItem = db.getCollection('userCollections').by("id", colId); + + if (colItem) { + if (folderId) { + settings = findParentSettings(colItem, folderId); + if (!settings) { + settings = JSON.parse(JSON.stringify(InitialSettings)); + } + } else { + settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; + } + } + + resolve(settings ? settings as ISettings : null); + }); + }); + } + catch (err) { + writeLog("error::GetParentSettingsSync(): " + err); + throw err; + } } export function ExecuteRequest(reqData: any, fetchConfig: FetchConfig, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let settings: any; - - const colItem = db.getCollection('userCollections').by("id", reqData.data.colId); - - if (colItem) { - if (reqData.data.folderId) { - settings = findParentSettings(colItem, reqData.data.folderId); - if (!settings) { - settings = JSON.parse(JSON.stringify(InitialSettings)); - } - } else { - settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; - } - - apiFetch(reqData.data.reqData, reqData.data.variableData, settings, null, fetchConfig).then((data) => { - webview.postMessage(data); - }); - } - }); - } - catch (err) { - writeLog("error::ExecuteRequest(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let settings: any; + + const colItem = db.getCollection('userCollections').by("id", reqData.data.colId); + + if (colItem) { + if (reqData.data.folderId) { + settings = findParentSettings(colItem, reqData.data.folderId); + if (!settings) { + settings = JSON.parse(JSON.stringify(InitialSettings)); + } + } else { + settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; + } + + apiFetch(reqData.data.reqData, reqData.data.variableData, settings, null, fetchConfig).then((data) => { + webview.postMessage(data); + }); + } + }); + } + catch (err) { + writeLog("error::ExecuteRequest(): " + err); + } } export function ExecuteMultipleRequest(reqData: any, fetchConfig: FetchConfig, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let settings: any; - let requests: any[] = []; - - const colItem = db.getCollection('userCollections').by("id", reqData.data.colId); - - reqData.data.reqData.forEach(item => { - if (item.auth.authType === "inherit") { - - if (colItem) { - let id = item.data.itemPaths[item.id].split(";")[1]; - if (id === item.data.colId) { - id = ""; - } - - if (id) { - settings = findParentSettings(colItem, id); - if (!settings) { - settings = JSON.parse(JSON.stringify(InitialSettings)); - } - } else { - settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; - } - - requests.push(apiFetch(item, reqData.data.variableData, settings, null, fetchConfig)); - } - } else { - requests.push(apiFetch(item, reqData.data.variableData, null, null, fetchConfig)); - } - }); - - if (requests.length > 0) { - Promise.allSettled(requests).then((values) => { - webview.postMessage({ type: responseTypes.multipleApiResponse, output: values }); - }); - } - }); - } - catch (err) { - writeLog("error::ExecuteMultipleRequest(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let settings: any; + let requests: any[] = []; + + const colItem = db.getCollection('userCollections').by("id", reqData.data.colId); + + reqData.data.reqData.forEach(item => { + if (item.auth.authType === "inherit") { + + if (colItem) { + let id = item.data.itemPaths[item.id].split(";")[1]; + if (id === item.data.colId) { + id = ""; + } + + if (id) { + settings = findParentSettings(colItem, id); + if (!settings) { + settings = JSON.parse(JSON.stringify(InitialSettings)); + } + } else { + settings = colItem.settings ? colItem.settings : JSON.parse(JSON.stringify(InitialSettings));; + } + + requests.push(apiFetch(item, reqData.data.variableData, settings, null, fetchConfig)); + } + } else { + requests.push(apiFetch(item, reqData.data.variableData, null, null, fetchConfig)); + } + }); + + if (requests.length > 0) { + Promise.allSettled(requests).then((values) => { + webview.postMessage({ type: responseTypes.multipleApiResponse, output: values }); + }); + } + }); + } + catch (err) { + writeLog("error::ExecuteMultipleRequest(): " + err); + } } export function SaveCollectionSettings(webview: vscode.Webview, colId: string, folderId: string, settings: ISettings) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const colItem = db.getCollection('userCollections').by("id", colId); - - if (colItem) { - if (folderId) { - let folderItem = findItem(colItem, folderId); - if (folderItem) { - folderItem.settings = settings; - } - } else { - colItem.settings = settings; - } - - db.saveDatabase(); - } - - if (webview) { - webview.postMessage({ type: responseTypes.saveColSettingsResponse, colId: colId, folderId: folderId }); - } - }); - } - catch (err) { - writeLog("error::SaveCollectionSettings(): " + err); - } -} \ No newline at end of file + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const colItem = db.getCollection('userCollections').by("id", colId); + + if (colItem) { + if (folderId) { + let folderItem = findItem(colItem, folderId); + if (folderItem) { + folderItem.settings = settings; + } + } else { + colItem.settings = settings; + } + + db.saveDatabase(); + } + + if (webview) { + webview.postMessage({ type: responseTypes.saveColSettingsResponse, colId: colId, folderId: folderId }); + } + }); + } + catch (err) { + writeLog("error::SaveCollectionSettings(): " + err); + } +} diff --git a/src/utils/db/constants.ts b/src/utils/db/constants.ts index e23f4f8..6f19720 100644 --- a/src/utils/db/constants.ts +++ b/src/utils/db/constants.ts @@ -1,11 +1,11 @@ export enum ImportType { - FetchClient_1_0 = "FetchClient_1_0", - Postman_2_1 = "Postman_2_1", - ThunderClient_1_2 = "ThunderClient_1_2" + FetchClient_1_0 = "FetchClient_1_0", + Postman_2_1 = "Postman_2_1", + ThunderClient_1_2 = "ThunderClient_1_2" } export enum VariableImportType { - FetchClient_Variable_1_0 = "FetchClient_Variable_1_0", - Postman_Variable_2_1 = "Postman_Variable_2_1", - ThunderClient_Variable_1_2 = "ThunderClient_Variable_1_2" + FetchClient_Variable_1_0 = "FetchClient_Variable_1_0", + Postman_Variable_2_1 = "Postman_Variable_2_1", + ThunderClient_Variable_1_2 = "ThunderClient_Variable_1_2" } diff --git a/src/utils/db/cookieDBUtil.ts b/src/utils/db/cookieDBUtil.ts index b952e74..1cde301 100644 --- a/src/utils/db/cookieDBUtil.ts +++ b/src/utils/db/cookieDBUtil.ts @@ -4,103 +4,106 @@ import { ICookie } from '../../fetch-client-ui/components/Cookies/redux/types'; import { responseTypes } from '../configuration'; import { writeLog } from '../logger/logger'; import { cookieDBPath } from './dbPaths'; +import { ShowInformationDialog } from '../ui/helper'; function getDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(cookieDBPath(), { adapter: idbAdapter, autosave: true, autosaveInterval: 1000 }); - db.autosaveEnable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(cookieDBPath(), { adapter: idbAdapter, autosave: true, autosaveInterval: 1000 }); + db.autosaveEnable(); + return db; } export function SaveCookie(item: ICookie, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userCookies = db.getCollection('userCookies'); - let cookieItem = userCookies.find({ id: item.id }); - if (cookieItem === null || cookieItem.length === 0) { - userCookies.insert(item); - } else { - cookieItem[0].name = item.name; - cookieItem[0].id = item.id; - cookieItem[0].data = item.data; - } - - db.saveDatabase(); - - if (webview) { - webview.postMessage({ type: responseTypes.saveCookieResponse }); - } - }); - - } catch (err) { - writeLog("error::SaveCookie(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userCookies = db.getCollection('userCookies'); + let cookieItem = userCookies.find({ id: item.id }); + if (cookieItem === null || cookieItem?.length === 0) { + userCookies.insert(item); + } else { + cookieItem[0].name = item.name; + cookieItem[0].id = item.id; + cookieItem[0].data = item.data; + } + + db.saveDatabase(); + + if (webview) { + webview.postMessage({ type: responseTypes.saveCookieResponse }); + } + }); + + } catch (err) { + writeLog("error::SaveCookie(): " + err); + } } export function GetAllCookies(webview: vscode.Webview) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const userCookies = db.getCollection('userCookies').data; - webview.postMessage({ type: responseTypes.getAllCookiesResponse, cookies: userCookies }); - }); + db.loadDatabase({}, function () { + const userCookies = db.getCollection('userCookies').data; + webview.postMessage({ type: responseTypes.getAllCookiesResponse, cookies: userCookies }); + }); - } catch (err) { - writeLog("error::GetAllCookies(): " + err); - } + } catch (err) { + writeLog("error::GetAllCookies(): " + err); + } } export function GetCookieById(id: string, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userCookies = db.getCollection('userCookies').find({ 'id': id }); - db.saveDatabase(); - if (webview) { - webview.postMessage({ type: responseTypes.getCookiesByIdResponse, data: userCookies }); - } - }); - - } catch (err) { - writeLog("error::GetCookieById(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userCookies = db.getCollection('userCookies').find({ 'id': id }); + db.saveDatabase(); + if (webview) { + webview.postMessage({ type: responseTypes.getCookiesByIdResponse, data: userCookies }); + } + }); + + } catch (err) { + writeLog("error::GetCookieById(): " + err); + } } export function DeleteCookieById(id: string, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection('userCookies').findAndRemove({ 'id': id }); - db.saveDatabase(); - if (webview) { - webview.postMessage({ type: responseTypes.deleteCookieByIdResponse, id: id }); - } - }); - - } catch (err) { - writeLog("error::DeleteCookieById(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection('userCookies').findAndRemove({ 'id': id }); + db.saveDatabase(); + if (webview) { + webview.postMessage({ type: responseTypes.deleteCookieByIdResponse, id: id }); + ShowInformationDialog("Deleted successfully"); + } + }); + + } catch (err) { + writeLog("error::DeleteCookieById(): " + err); + } } export function DeleteAllCookies(webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userCookies = db.getCollection('userCookies'); - userCookies.removeDataOnly(); - db.saveDatabase(); - if (webview) { - webview.postMessage({ type: responseTypes.deleteAllCookieResponse }); - } - }); - - } catch (err) { - writeLog("error::DeleteAllCookies(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userCookies = db.getCollection('userCookies'); + userCookies.removeDataOnly(); + db.saveDatabase(); + if (webview) { + webview.postMessage({ type: responseTypes.deleteAllCookieResponse }); + ShowInformationDialog("Deleted successfully"); + } + }); + + } catch (err) { + writeLog("error::DeleteAllCookies(): " + err); + } } diff --git a/src/utils/db/dbPaths.ts b/src/utils/db/dbPaths.ts index 6c0fe92..c32fe94 100644 --- a/src/utils/db/dbPaths.ts +++ b/src/utils/db/dbPaths.ts @@ -2,16 +2,16 @@ import path from "path"; import { getExtDbPath } from "./getExtDbPath"; export const cookieDBPath = () => - path.resolve(getExtDbPath(), "fetchClientCookies.db"); + path.resolve(getExtDbPath(), "fetchClientCookies.db"); export const historyDBPath = () => - path.resolve(getExtDbPath(), "fetchClientHistory.db"); + path.resolve(getExtDbPath(), "fetchClientHistory.db"); export const collectionDBPath = () => - path.resolve(getExtDbPath(), "fetchClientCollection.db"); + path.resolve(getExtDbPath(), "fetchClientCollection.db"); export const mainDBPath = () => - path.resolve(getExtDbPath(), "fetchClient.db"); + path.resolve(getExtDbPath(), "fetchClient.db"); export const variableDBPath = () => - path.resolve(getExtDbPath(), "fetchClientVariable.db"); + path.resolve(getExtDbPath(), "fetchClientVariable.db"); diff --git a/src/utils/db/dbUtil.ts b/src/utils/db/dbUtil.ts index 17eeee9..4fc8dbe 100644 --- a/src/utils/db/dbUtil.ts +++ b/src/utils/db/dbUtil.ts @@ -3,171 +3,171 @@ import { v4 as uuidv4 } from "uuid"; import { formatDate } from "../helper"; import { writeLog } from "../logger/logger"; import { - collectionDBPath, - cookieDBPath, - historyDBPath, - mainDBPath, - variableDBPath, + collectionDBPath, + cookieDBPath, + historyDBPath, + mainDBPath, + variableDBPath, } from "./dbPaths"; export function CreateHistoryDB(): any { - let db: LokiConstructor; - - try { - const idbAdapter = new LokiFsAdapter(); - db = new loki(historyDBPath(), { - autoload: true, - autoloadCallback: dbInitialize, - autosave: true, - autosaveInterval: 1000, - serializationMethod: "normal", - adapter: idbAdapter, - }); - } catch (err: any) { - writeLog("error::CreateHistoryDB(): " + err); - } - - - function dbInitialize() { - try { - const userHistory = db.getCollection("userHistory"); - if (userHistory === null) { - db.addCollection("userHistory", { autoupdate: true, disableMeta: true, unique: ["id"], indices: "id" }); - } - - db.saveDatabase(); - } catch (err: any) { - writeLog("error::CreateHistoryDB()::dbInitialize(): " + err); - } - } + let db: LokiConstructor; + + try { + const idbAdapter = new LokiFsAdapter(); + db = new loki(historyDBPath(), { + autoload: true, + autoloadCallback: dbInitialize, + autosave: true, + autosaveInterval: 1000, + serializationMethod: "normal", + adapter: idbAdapter, + }); + } catch (err: any) { + writeLog("error::CreateHistoryDB(): " + err); + } + + + function dbInitialize() { + try { + const userHistory = db.getCollection("userHistory"); + if (userHistory === null) { + db.addCollection("userHistory", { autoupdate: true, disableMeta: true, unique: ["id"], indices: "id" }); + } + + db.saveDatabase(); + } catch (err: any) { + writeLog("error::CreateHistoryDB()::dbInitialize(): " + err); + } + } } export function CreateCollectionDB(): any { - let db: LokiConstructor; - - try { - const idbAdapter = new LokiFsAdapter(); - db = new loki(collectionDBPath(), { - autoload: true, - autoloadCallback: dbInitialize, - autosave: true, - autosaveInterval: 1000, - serializationMethod: "normal", - adapter: idbAdapter, - }); - } catch (err: any) { - writeLog("error::CreateCollectionDB(): " + err); - } - - - function dbInitialize() { - try { - let userCollections = db.getCollection("userCollections"); - if (userCollections === null) { - userCollections = db.addCollection("userCollections", { autoupdate: true, disableMeta: true, unique: ["id"], indices: ["id", "variableId"] }); - } - userCollections.insert({ id: uuidv4(), name: "Default", variableId: "", createdTime: formatDate(), data: [] }); - db.saveDatabase(); - } catch (err: any) { - writeLog("error::CreateCollectionDB()::dbInitialize(): " + err); - } - } + let db: LokiConstructor; + + try { + const idbAdapter = new LokiFsAdapter(); + db = new loki(collectionDBPath(), { + autoload: true, + autoloadCallback: dbInitialize, + autosave: true, + autosaveInterval: 1000, + serializationMethod: "normal", + adapter: idbAdapter, + }); + } catch (err: any) { + writeLog("error::CreateCollectionDB(): " + err); + } + + + function dbInitialize() { + try { + let userCollections = db.getCollection("userCollections"); + if (userCollections === null) { + userCollections = db.addCollection("userCollections", { autoupdate: true, disableMeta: true, unique: ["id"], indices: ["id", "variableId"] }); + } + userCollections.insert({ id: uuidv4(), name: "Default", variableId: "", createdTime: formatDate(), data: [] }); + db.saveDatabase(); + } catch (err: any) { + writeLog("error::CreateCollectionDB()::dbInitialize(): " + err); + } + } } export function CreateMainDB(): any { - let db: LokiConstructor; - - try { - const idbAdapter = new LokiFsAdapter(); - db = new loki(mainDBPath(), { - autoload: true, - autoloadCallback: dbInitialize, - autosave: true, - autosaveInterval: 1000, - serializationMethod: "normal", - adapter: idbAdapter, - }); - } - catch (err: any) { - writeLog("error::CreateMainDB(): " + err); - } - - - function dbInitialize() { - try { - const apiRequests = db.getCollection("apiRequests"); - if (apiRequests === null) { - db.addCollection("apiRequests", { autoupdate: true, disableMeta: true, unique: ["id"], indices: "id" }); - } - db.saveDatabase(); - } catch (err: any) { - writeLog("error::CreateMainDB::dbInitialize(): " + err); - } - } + let db: LokiConstructor; + + try { + const idbAdapter = new LokiFsAdapter(); + db = new loki(mainDBPath(), { + autoload: true, + autoloadCallback: dbInitialize, + autosave: true, + autosaveInterval: 1000, + serializationMethod: "normal", + adapter: idbAdapter, + }); + } + catch (err: any) { + writeLog("error::CreateMainDB(): " + err); + } + + + function dbInitialize() { + try { + const apiRequests = db.getCollection("apiRequests"); + if (apiRequests === null) { + db.addCollection("apiRequests", { autoupdate: true, disableMeta: true, unique: ["id"], indices: "id" }); + } + db.saveDatabase(); + } catch (err: any) { + writeLog("error::CreateMainDB::dbInitialize(): " + err); + } + } } export function CreateVariableDB(): any { - let db: LokiConstructor; - try { - const idbAdapter = new LokiFsAdapter(); - db = new loki(variableDBPath(), { - autoload: true, - autoloadCallback: dbInitialize, - autosave: true, - autosaveInterval: 1000, - serializationMethod: "normal", - adapter: idbAdapter, - }); - } catch (err: any) { - writeLog("error::CreateVariableDB(): " + err); - } - - function dbInitialize() { - try { - let userCollections = db.getCollection("userVariables"); - if (userCollections === null) { - userCollections = db.addCollection("userVariables", { autoupdate: true, disableMeta: true, unique: ["id"], indices: "id" }); - } - - userCollections.insert({ id: uuidv4(), name: "Global", isActive: true, createdTime: formatDate(), data: [] }); - - db.saveDatabase(); - } catch (err: any) { - writeLog("error::CreateVariableDB()::dbInitialize(): " + err); - } - } + let db: LokiConstructor; + try { + const idbAdapter = new LokiFsAdapter(); + db = new loki(variableDBPath(), { + autoload: true, + autoloadCallback: dbInitialize, + autosave: true, + autosaveInterval: 1000, + serializationMethod: "normal", + adapter: idbAdapter, + }); + } catch (err: any) { + writeLog("error::CreateVariableDB(): " + err); + } + + function dbInitialize() { + try { + let userCollections = db.getCollection("userVariables"); + if (userCollections === null) { + userCollections = db.addCollection("userVariables", { autoupdate: true, disableMeta: true, unique: ["id"], indices: "id" }); + } + + userCollections.insert({ id: uuidv4(), name: "Global", isActive: true, createdTime: formatDate(), data: [] }); + + db.saveDatabase(); + } catch (err: any) { + writeLog("error::CreateVariableDB()::dbInitialize(): " + err); + } + } } export function CreateCookieDB(): any { - let db: LokiConstructor; - try { - const idbAdapter = new LokiFsAdapter(); - db = new loki(cookieDBPath(), { - autoload: true, - autoloadCallback: dbInitialize, - autosave: true, - autosaveInterval: 1000, - serializationMethod: "normal", - adapter: idbAdapter, - }); - } catch (err: any) { - writeLog("error::CreateVariableDB(): " + err); - } - - - function dbInitialize() { - try { - let userCookies = db.getCollection("userCookies"); - if (userCookies === null) { - userCookies = db.addCollection("userCookies", { autoupdate: true, disableMeta: true, unique: ["id"], indices: ["id", "name"] }); - } - db.saveDatabase(); - } catch (err: any) { - writeLog("error::CreateCookieDB()::dbInitialize(): " + err); - } - } + let db: LokiConstructor; + try { + const idbAdapter = new LokiFsAdapter(); + db = new loki(cookieDBPath(), { + autoload: true, + autoloadCallback: dbInitialize, + autosave: true, + autosaveInterval: 1000, + serializationMethod: "normal", + adapter: idbAdapter, + }); + } catch (err: any) { + writeLog("error::CreateVariableDB(): " + err); + } + + + function dbInitialize() { + try { + let userCookies = db.getCollection("userCookies"); + if (userCookies === null) { + userCookies = db.addCollection("userCookies", { autoupdate: true, disableMeta: true, unique: ["id"], indices: ["id", "name"] }); + } + db.saveDatabase(); + } catch (err: any) { + writeLog("error::CreateCookieDB()::dbInitialize(): " + err); + } + } } diff --git a/src/utils/db/getExtDbPath.ts b/src/utils/db/getExtDbPath.ts index dc47da2..d5ec082 100644 --- a/src/utils/db/getExtDbPath.ts +++ b/src/utils/db/getExtDbPath.ts @@ -1,29 +1,29 @@ -import * as vscode from 'vscode'; import path from 'path'; +import * as vscode from 'vscode'; import { getSaveToWorkspaceConfiguration, getWorkspacePathConfiguration } from "../vscodeConfig"; let globalStorageUri = ""; export const setGlobalStorageUri = (pathDef: string) => { - globalStorageUri = pathDef; + globalStorageUri = pathDef; }; export const getGlobalStorageUri = () => globalStorageUri; export function getExtLocalDbPath(): string { - const existingPath = getWorkspacePathConfiguration(); - if (existingPath) { - return existingPath; - } - const workspacePath = vscode?.workspace?.workspaceFolders?.[0].uri.fsPath || ""; - return workspacePath ? path.resolve(workspacePath, "fetch-client") : ""; + const existingPath = getWorkspacePathConfiguration(); + if (existingPath) { + return existingPath; + } + const workspacePath = vscode?.workspace?.workspaceFolders?.[0].uri.fsPath || ""; + return workspacePath ? path.resolve(workspacePath, "fetch-client") : ""; } export function getExtDbPath(): string { - const pathState = getSaveToWorkspaceConfiguration(); - return pathState ? getExtLocalDbPath() : globalStorageUri; + const pathState = getSaveToWorkspaceConfiguration(); + return pathState ? getExtLocalDbPath() : globalStorageUri; } export function getExtDbBKPPath(): string { - return globalStorageUri + "-bkp"; + return globalStorageUri + "-bkp"; } diff --git a/src/utils/db/historyDBUtil.ts b/src/utils/db/historyDBUtil.ts index a065ba4..87f169b 100644 --- a/src/utils/db/historyDBUtil.ts +++ b/src/utils/db/historyDBUtil.ts @@ -9,145 +9,145 @@ import { DeleteExitingItem, DeleteExitingItems, RenameRequestItem } from './main function getDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(historyDBPath(), { adapter: idbAdapter, autosave: true, autosaveInterval: 1000 }); - db.autosaveEnable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(historyDBPath(), { adapter: idbAdapter, autosave: true, autosaveInterval: 1000 }); + db.autosaveEnable(); + return db; } export function SaveHistory(item: IHistory, webviewView: vscode.WebviewView) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userHistory = db.getCollection("userHistory"); - userHistory.insert(item); - db.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.newHistoryResponse, history: item }); - }); - - } catch (err) { - writeLog("error::SaveHistory(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userHistory = db.getCollection("userHistory"); + userHistory.insert(item); + db.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.newHistoryResponse, history: item }); + }); + + } catch (err) { + writeLog("error::SaveHistory(): " + err); + } } export function UpdateHistory(item: IHistory) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userHistory = db.getCollection("userHistory"); - var req = userHistory.findOne({ 'id': item.id }); - if (req) { - req.name = item.name; - req.method = item.method; - req.url = item.url; - req.createdTime = item.createdTime; - userHistory.update(req); - db.saveDatabase(); - } - }); - - } catch (err) { - writeLog("error::UpdateHistory(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userHistory = db.getCollection("userHistory"); + var req = userHistory.findOne({ 'id': item.id }); + if (req) { + req.name = item.name; + req.method = item.method; + req.url = item.url; + req.createdTime = item.createdTime; + userHistory.update(req); + db.saveDatabase(); + } + }); + + } catch (err) { + writeLog("error::UpdateHistory(): " + err); + } } export function GetHistoryById(id: string, webview: vscode.Webview) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const userHistory = db.getCollection("userHistory").find({ 'id': id }); - webview.postMessage({ type: responseTypes.getHistoryItemResponse, history: userHistory }); - }); + db.loadDatabase({}, function () { + const userHistory = db.getCollection("userHistory").find({ 'id': id }); + webview.postMessage({ type: responseTypes.getHistoryItemResponse, history: userHistory }); + }); - } catch (err) { - writeLog("error::GetHistoryById(): " + err); - } + } catch (err) { + writeLog("error::GetHistoryById(): " + err); + } } export function GetAllHistory(webviewView: vscode.WebviewView) { - try { - const db = getDB(); - - let limit = getHistoryLimitConfiguration(); - - db.loadDatabase({}, function () { - let userHistory: any; - let len = db.getCollection("userHistory").find().length; - switch (limit) { - case "All": - userHistory = db.getCollection("userHistory").data.reverse(); - break; - default: - let intLimit = parseInt(limit); - if (len > intLimit) { - userHistory = db.getCollection("userHistory").chain().offset(len - intLimit).limit(intLimit).data().reverse(); - } else { - userHistory = db.getCollection("userHistory").chain().limit(intLimit).data().reverse(); - } - break; - } - webviewView.webview.postMessage({ type: responseTypes.getAllHistoryResponse, history: userHistory }); - }); - - } catch (err) { - writeLog("error::GetAllHistory(): " + err); - } + try { + const db = getDB(); + + let limit = getHistoryLimitConfiguration(); + + db.loadDatabase({}, function () { + let userHistory: any; + let len = db.getCollection("userHistory").find().length; + switch (limit) { + case "All": + userHistory = db.getCollection("userHistory").data.reverse(); + break; + default: + let intLimit = parseInt(limit); + if (len > intLimit) { + userHistory = db.getCollection("userHistory").chain().offset(len - intLimit).limit(intLimit).data().reverse(); + } else { + userHistory = db.getCollection("userHistory").chain().limit(intLimit).data().reverse(); + } + break; + } + webviewView.webview.postMessage({ type: responseTypes.getAllHistoryResponse, history: userHistory }); + }); + + } catch (err) { + writeLog("error::GetAllHistory(): " + err); + } } export function DeleteAllHistory(webviewView: vscode.WebviewView) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const userHistory = db.getCollection("userHistory"); - let results = userHistory.chain().data({ forceClones: true, removeMeta: true }); + db.loadDatabase({}, function () { + const userHistory = db.getCollection("userHistory"); + let results = userHistory.chain().data({ forceClones: true, removeMeta: true }); - const ids = results.map(item => item.id); + const ids = results.map(item => item.id); - userHistory.removeDataOnly(); - db.saveDatabase(); + userHistory.removeDataOnly(); + db.saveDatabase(); - DeleteExitingItems(ids); + DeleteExitingItems(ids); - webviewView.webview.postMessage({ type: responseTypes.deleteAllHistoryResponse }); - }); + webviewView.webview.postMessage({ type: responseTypes.deleteAllHistoryResponse }); + }); - } catch (err) { - writeLog("error::DeleteAllHistory(): " + err); - } + } catch (err) { + writeLog("error::DeleteAllHistory(): " + err); + } } export function DeleteHistory(webviewView: vscode.WebviewView, id: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection("userHistory").findAndRemove({ 'id': id }); - db.saveDatabase(); - DeleteExitingItem(id); - webviewView.webview.postMessage({ type: responseTypes.deleteHistoryResponse, id: id }); - }); - - } catch (err) { - writeLog("error::DeleteHistory(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection("userHistory").findAndRemove({ 'id': id }); + db.saveDatabase(); + DeleteExitingItem(id); + webviewView.webview.postMessage({ type: responseTypes.deleteHistoryResponse, id: id }); + }); + + } catch (err) { + writeLog("error::DeleteHistory(): " + err); + } } export function RenameHistory(webviewView: vscode.WebviewView, id: string, name: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection("userHistory").findAndUpdate({ 'id': id }, item => { item.name = name; }); - db.saveDatabase(); - RenameRequestItem(id, name); - webviewView.webview.postMessage({ type: responseTypes.renameHistoryResponse, params: { id: id, name: name } }); - }); - - } catch (err) { - writeLog("error::RenameHistory(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection("userHistory").findAndUpdate({ 'id': id }, item => { item.name = name; }); + db.saveDatabase(); + RenameRequestItem(id, name); + webviewView.webview.postMessage({ type: responseTypes.renameHistoryResponse, params: { id: id, name: name } }); + }); + + } catch (err) { + writeLog("error::RenameHistory(): " + err); + } } diff --git a/src/utils/db/mainDBUtil.ts b/src/utils/db/mainDBUtil.ts index 67ce018..fa5de66 100644 --- a/src/utils/db/mainDBUtil.ts +++ b/src/utils/db/mainDBUtil.ts @@ -3,7 +3,7 @@ import loki, { LokiFsAdapter } from "lokijs"; import * as vscode from "vscode"; import { IRequestModel } from '../../fetch-client-ui/components/RequestUI/redux/types'; import { InitialSettings } from '../../fetch-client-ui/components/SideBar/redux/reducer'; -import { ICollections, IFolder, IHistory } from '../../fetch-client-ui/components/SideBar/redux/types'; +import { ICollections, IFolder } from '../../fetch-client-ui/components/SideBar/redux/types'; import { isFolder } from '../../fetch-client-ui/components/SideBar/util'; import { isJson } from '../../fetch-client-ui/components/TestUI/TestPanel/helper'; import { responseTypes } from '../configuration'; @@ -11,461 +11,516 @@ import { formatDate } from '../helper'; import { fetchClientImporter } from '../importers/fetchClient/fetchClientImporter_1_0'; import { postmanImporter } from '../importers/postman/postmanImporter_2_1'; import { POSTMAN_SCHEMA_V2_1, PostmanSchema_2_1 } from '../importers/postman/postman_2_1.types'; +import { thunderClientImporter } from "../importers/thunderClient/thunderClientImporter_1_2"; +import { ThunderClient_Schema_1_2 } from "../importers/thunderClient/thunderClient_1_2_types"; import { writeLog } from '../logger/logger'; import { FetchClientDataProxy } from '../validators/fetchClientCollectionValidator'; import { ImportType } from "./constants"; import { collectionDBPath, mainDBPath, variableDBPath } from "./dbPaths"; -import { thunderClientImporter } from "../importers/thunderClient/thunderClientImporter_1_2"; -import { ThunderClient_Schema_1_2 } from "../importers/thunderClient/thunderClient_1_2_types"; function getDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(mainDBPath(), { adapter: idbAdapter }); - db.autosaveDisable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(mainDBPath(), { adapter: idbAdapter }); + db.autosaveDisable(); + return db; } function getCollectionDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(collectionDBPath(), { adapter: idbAdapter }); - db.autosaveDisable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(collectionDBPath(), { adapter: idbAdapter }); + db.autosaveDisable(); + return db; } function getVariableDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(variableDBPath(), { adapter: idbAdapter }); - db.autosaveDisable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(variableDBPath(), { adapter: idbAdapter }); + db.autosaveDisable(); + return db; } export function SaveRequest(reqData: IRequestModel) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests"); - apiRequests.insert(reqData); - db.saveDatabase(); - }); - - } catch (err) { - writeLog("error::SaveRequest(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests"); + apiRequests.insert(reqData); + db.saveDatabase(); + }); + + } catch (err) { + writeLog("error::SaveRequest(): " + err); + } } export function UpdateRequest(reqData: IRequestModel) { - try { - const db = getDB(); - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests"); - var req = apiRequests.findOne({ 'id': reqData.id }); - req.url = reqData.url; - req.name = reqData.name; - req.method = reqData.method; - req.params = reqData.params; - req.auth = reqData.auth; - req.headers = reqData.headers; - req.body = reqData.body; - req.tests = reqData.tests; - req.setvar = reqData.setvar; - req.notes = reqData.notes; - req.preFetch = reqData.preFetch; - apiRequests.update(req); - db.saveDatabase(); - }); - - } catch (err) { - writeLog("error::UpdateRequest(): " + err); - throw err; - } + try { + const db = getDB(); + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests"); + var req = apiRequests.findOne({ 'id': reqData.id }); + req.url = reqData.url; + req.name = reqData.name; + req.method = reqData.method; + req.params = reqData.params; + req.auth = reqData.auth; + req.headers = reqData.headers; + req.body = reqData.body; + req.tests = reqData.tests; + req.setvar = reqData.setvar; + req.notes = reqData.notes; + req.preFetch = reqData.preFetch; + apiRequests.update(req); + db.saveDatabase(); + }); + + } catch (err) { + writeLog("error::UpdateRequest(): " + err); + throw err; + } } export function GetRequestItem(reqId: string) { - try { - return new Promise((resolve, _reject) => { - const db = getDB(); - db.loadDatabase({}, function (err: any) { - if (err) { - resolve(null); - } - const results = db.getCollection("apiRequests").chain().find({ 'id': reqId }).data(); - resolve(results && results.length > 0 ? results[0] as IRequestModel : null); - }); - }); - } catch (err) { - writeLog("error::GetRequestItem(): " + err); - } + try { + return new Promise((resolve, _reject) => { + const db = getDB(); + db.loadDatabase({}, function (err: any) { + if (err) { + resolve(null); + } + const results = db.getCollection("apiRequests").chain().find({ 'id': reqId }).data(); + resolve(results && results.length > 0 ? results[0] as IRequestModel : null); + }); + }); + } catch (err) { + writeLog("error::GetRequestItem(): " + err); + throw err; + } } export function GetExitingItem(webview: vscode.Webview, id: string, callback: any = null, type: string = null) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const results = db.getCollection("apiRequests").chain().find({ 'id': id }).data(); - if (webview) { - webview.postMessage({ type: type === "OpenAndRun" ? responseTypes.getOpenAndRunItemDataResponse : responseTypes.openExistingItemResponse, item: results }); - } - - if (callback) { - callback(results); - } - }); - - } catch (err) { - writeLog("error::GetExitingItem(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const results = db.getCollection("apiRequests").chain().find({ 'id': id }).data(); + if (webview) { + webview.postMessage({ type: type === "OpenAndRun" ? responseTypes.getOpenAndRunItemDataResponse : responseTypes.openExistingItemResponse, item: results }); + } + + if (callback) { + callback(results); + } + }); + + } catch (err) { + writeLog("error::GetExitingItem(): " + err); + } } export function CopyExitingItems(oldIds: string[], ids: any) { - try { + try { - if (oldIds.length === 0) { - return; - } + if (oldIds.length === 0) { + return; + } - const db = getDB(); + const db = getDB(); - db.loadDatabase({}, function () { - let apiRequests = db.getCollection("apiRequests"); - const results = apiRequests.chain().find({ 'id': { '$in': oldIds } }).data({ forceClones: true, removeMeta: true }); + db.loadDatabase({}, function () { + let apiRequests = db.getCollection("apiRequests"); + const results = apiRequests.chain().find({ 'id': { '$in': oldIds } }).data({ forceClones: true, removeMeta: true }); - if (results && results.length > 0) { - results.forEach(item => { - item.id = ids[item.id]; - item.name = item.name + " (Copy)"; - }); + if (results && results.length > 0) { + results.forEach(item => { + item.id = ids[item.id]; + item.name = item.name + " (Copy)"; + }); - apiRequests.insert(results); - db.saveDatabase(); - } - }); + apiRequests.insert(results); + db.saveDatabase(); + } + }); - } catch (err) { - writeLog("error::CopyExitingItems(): " + err); - } + } catch (err) { + writeLog("error::CopyExitingItems(): " + err); + } } export function DeleteExitingItem(id: string) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - db.getCollection("apiRequests").findAndRemove({ 'id': id }); - db.saveDatabase(); - }); + db.loadDatabase({}, function () { + db.getCollection("apiRequests").findAndRemove({ 'id': id }); + db.saveDatabase(); + }); - } catch (err) { - writeLog("error::DeleteExitingItem(): " + err); - } + } catch (err) { + writeLog("error::DeleteExitingItem(): " + err); + } } export function DeleteExitingItems(ids: string[]) { - try { + try { - if (ids.length === 0) { - return; - } + if (ids.length === 0) { + return; + } - const db = getDB(); + const db = getDB(); - db.loadDatabase({}, function () { - db.getCollection("apiRequests").findAndRemove({ 'id': { '$in': ids } }); - db.saveDatabase(); - }); + db.loadDatabase({}, function () { + db.getCollection("apiRequests").findAndRemove({ 'id': { '$in': ids } }); + db.saveDatabase(); + }); - } catch (err) { - writeLog("error::DeleteExitingItems(): " + err); - } + } catch (err) { + writeLog("error::DeleteExitingItems(): " + err); + } } function findItem(source: any, Id: string) { - let pos = source.data.findIndex((el: any) => el.id === Id); + let pos = source.data.findIndex((el: any) => el.id === Id); - if (pos !== -1) { - return source.data[pos]; - } + if (pos !== -1) { + return source.data[pos]; + } - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - return findItem(source.data[i], Id); - } - } + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + return findItem(source.data[i], Id); + } + } - return ""; + return ""; } function ExportItemFromFolder(source: any, apiRequests: any, exportData: any[], isSub: boolean, level: number): any { - let totalResults = []; + let totalResults = []; - source.data.filter(item => item.data !== undefined).forEach((item) => { - let currentResults = ExportItemFromFolder(item, apiRequests, [exportData], true, level + 1); - totalResults.push(currentResults); - }); + source.data.filter(item => item.data !== undefined).forEach((item) => { + let currentResults = ExportItemFromFolder(item, apiRequests, [exportData], true, level + 1); + totalResults.push(currentResults); + }); - const ids = source.data.filter(item => item.data === undefined).map(itm => itm.id); - let results = apiRequests.chain().find({ 'id': { '$in': ids } }).data({ forceClones: true, removeMeta: true }); + const ids = source.data.filter(item => item.data === undefined).map(itm => itm.id); + let results = apiRequests.chain().find({ 'id': { '$in': ids } }).data({ forceClones: true, removeMeta: true }); - if (isSub) { - source.data = totalResults.length > 0 ? [...totalResults, ...results] : results; - } else { - exportData = [...totalResults, ...results]; - return exportData; - } + if (isSub) { + source.data = totalResults.length > 0 ? [...totalResults, ...results] : results; + } else { + exportData = [...totalResults, ...results]; + return exportData; + } - return source; + return source; +} + +export function BulkExport(path: string, selectedCols: string[], webview: vscode.Webview) { + try { + const colDB = getCollectionDB(); + + colDB.loadDatabase({}, function () { + + selectedCols?.forEach(async (item: string) => { + + const cols = colDB.getCollection('userCollections').chain().find({ "id": item }).data({ forceClones: true, removeMeta: true }); + + const apiRequests = await GetAPIRequestSync(); + + let exportData = ExportCollection(cols, apiRequests, "", ""); + + let fullPath = path + "\\" + "fetch-client-collection_" + exportData.name.replace(/[/\\?%*:|"<>]/g, '-') + ".json"; + + fs.writeFile(fullPath, JSON.stringify(exportData), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + path + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::BulkExport()::FileWrite()" + error.message); + } + }); + }); + + webview?.postMessage({ type: responseTypes.bulkColExportResponse }); + }); + + } catch (err) { + writeLog("error::BulkExport(): " + err); + } +} + +function GetAPIRequestSync() { + return new Promise>((resolve, _reject) => { + const db = getDB(); + + db.loadDatabase({}, function (err: any) { + if (err) { + resolve(null); + } + const apiRequests = db.getCollection("apiRequests"); + resolve(apiRequests ? apiRequests : null); + }); + }); } export function Export(path: string, colId: string, hisId: string, folderId: string) { - try { - const db = getDB(); - const colDB = getCollectionDB(); - - colDB.loadDatabase({}, function () { - const cols = colDB.getCollection('userCollections').chain().find({ "id": colId }).data({ forceClones: true, removeMeta: true }); - - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests"); - let exportData = { - app: "Fetch Client", - id: cols[0].id, - name: cols[0].name.toUpperCase().trim() === "DEFAULT" ? "Default Export" : cols[0].name, - version: "1.0", - type: "collections", - createdTime: cols[0].createdTime, - exportedDate: formatDate(), - data: [], - settings: cols[0].settings ? cols[0].settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - - if (hisId) { - if (folderId) { - let item = findItem(cols[0], folderId); - let results = apiRequests.chain().find({ 'id': { '$in': [hisId] } }).data({ forceClones: true, removeMeta: true }); - (item as IFolder).data = results; - exportData.data.push(item); - } else { - let results = apiRequests.chain().find({ 'id': { '$in': [hisId] } }).data({ forceClones: true, removeMeta: true }); - exportData.data.push(results[0]); - } - } else { - if (folderId) { - let folder = findItem(cols[0], folderId); - let results = ExportItemFromFolder(folder, apiRequests, [], false, 0); - if (results) { - (folder as IFolder).data = results; - exportData.data.push(folder); - } - } else { - let results = ExportItemFromFolder(cols[0], apiRequests, [], false, 0); - if (results) { - exportData.data = results; - } - } - } - - fs.writeFile(path, JSON.stringify(exportData), (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + path + "'. Error Message : " + error.message, { modal: true }); - writeLog("error::ExportItem()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + path + "'.", { modal: true }); - } - }); - }); - }); - - } catch (err) { - writeLog("error::Export(): " + err); - } + try { + const db = getDB(); + const colDB = getCollectionDB(); + + colDB.loadDatabase({}, function () { + const cols = colDB.getCollection('userCollections').chain().find({ "id": colId }).data({ forceClones: true, removeMeta: true }); + + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests"); + + let exportData = ExportCollection(cols, apiRequests, hisId, folderId); + + fs.writeFile(path, JSON.stringify(exportData), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + path + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::Export()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + path + "'.", { modal: true }); + } + }); + }); + }); + + } catch (err) { + writeLog("error::Export(): " + err); + } +} + +function ExportCollection(cols: any[], apiRequests: Collection, hisId: string, folderId: string): any { + let exportData = { + app: "Fetch Client", + id: cols[0].id, + name: cols[0].name.toUpperCase().trim() === "DEFAULT" ? "Default Export" : cols[0].name, + version: "1.0", + type: "collections", + createdTime: cols[0].createdTime, + exportedDate: formatDate(), + data: [], + settings: cols[0].settings ? cols[0].settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + + if (hisId) { + if (folderId) { + let item = findItem(cols[0], folderId); + let results = apiRequests.chain().find({ 'id': { '$in': [hisId] } }).data({ forceClones: true, removeMeta: true }); + (item as IFolder).data = results; + exportData.data.push(item); + } else { + let results = apiRequests.chain().find({ 'id': { '$in': [hisId] } }).data({ forceClones: true, removeMeta: true }); + exportData.data.push(results[0]); + } + } else { + if (folderId) { + let folder = findItem(cols[0], folderId); + let results = ExportItemFromFolder(folder, apiRequests, [], false, 0); + if (results) { + (folder as IFolder).data = results; + exportData.data.push(folder); + } + } else { + let results = ExportItemFromFolder(cols[0], apiRequests, [], false, 0); + if (results) { + exportData.data = results; + } + } + } + + return exportData; } export function RenameRequestItem(id: string, name: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let req = db.getCollection("apiRequests").find({ 'id': id }); - if (req && req.length > 0) { - req[0].name = name; - db.saveDatabase(); - } - }); - - } catch (err) { - writeLog("error::RenameRequestItem(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let req = db.getCollection("apiRequests").find({ 'id': id }); + if (req && req.length > 0) { + req[0].name = name; + db.saveDatabase(); + } + }); + + } catch (err) { + writeLog("error::RenameRequestItem(): " + err); + } } function ValidateData(data: string): ImportType | null { - try { - if (!data || data.length === 0 || !isJson(data)) { - vscode.window.showErrorMessage("Could not import the collection - Empty Data.", { modal: true }); - writeLog("error::Import::ValidateData() " + "Error Message : Could not import the collection - Empty Data."); - return null; - } - - try { - FetchClientDataProxy.Parse(data); - return ImportType.FetchClient_1_0; - } catch (err) { - let postmanData = JSON.parse(data) as PostmanSchema_2_1; - if (postmanData.info?._postman_id && postmanData.info?.schema === POSTMAN_SCHEMA_V2_1) { - return ImportType.Postman_2_1; - } - - let thunderClientData = JSON.parse(data) as ThunderClient_Schema_1_2; - if (thunderClientData.clientName = "Thunder Client") { - if (thunderClientData.version !== "1.2") { - vscode.window.showErrorMessage("Could not import the variable - Invalid version.", { modal: true }); - return null; - } - return ImportType.ThunderClient_1_2; - } - - return null; - } - } - catch (err) { - vscode.window.showErrorMessage("Could not import the collection - Invalid Data.", { modal: true }); - writeLog("error::Import::ValidateData() " + "Error Message : Could not import the collection - " + err); - return null; - } + try { + if (!data || data.length === 0 || !isJson(data)) { + vscode.window.showErrorMessage("Could not import the collection - Empty Data.", { modal: true }); + writeLog("error::Import::ValidateData() " + "Error Message : Could not import the collection - Empty Data."); + return null; + } + + try { + FetchClientDataProxy.Parse(data); + return ImportType.FetchClient_1_0; + } catch (err) { + writeLog("error::Import::ValidateData() " + err); + let postmanData = JSON.parse(data) as PostmanSchema_2_1; + if (postmanData.info?._postman_id && postmanData.info?.schema === POSTMAN_SCHEMA_V2_1) { + return ImportType.Postman_2_1; + } + + let thunderClientData = JSON.parse(data) as ThunderClient_Schema_1_2; + if (thunderClientData.clientName = "Thunder Client") { + if (thunderClientData.version !== "1.2") { + vscode.window.showErrorMessage("Could not import the collection - Invalid thunder client version.", { modal: true }); + return null; + } + return ImportType.ThunderClient_1_2; + } + + return null; + } + } + catch (err) { + vscode.window.showErrorMessage("Could not import the collection - Invalid Data.", { modal: true }); + writeLog("error::Import::ValidateData() " + "Error Message : Could not import the collection - " + err); + return null; + } } function insertCollections(colDB: loki, webviewView: vscode.WebviewView, fcCollection: ICollections) { - colDB.loadDatabase({}, function () { - const userCollections = colDB.getCollection('userCollections'); - userCollections.insert(fcCollection); - colDB.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.importResponse, data: fcCollection }); - }); + colDB.loadDatabase({}, function () { + const userCollections = colDB.getCollection('userCollections'); + userCollections.insert(fcCollection); + colDB.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.importResponse, data: fcCollection }); + }); } export function Import(webviewView: vscode.WebviewView, path: string) { - try { - const data = fs.readFileSync(path, "utf8"); - var type = ValidateData(data); - switch (type) { - case ImportType.FetchClient_1_0: - ImportFC(webviewView, data); - break; - case ImportType.Postman_2_1: - ImportPostman(webviewView, data); - break; - case ImportType.ThunderClient_1_2: - ImportThunderClient(webviewView, data); - break; - default: - vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); - } - - } catch (err) { - vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); - writeLog("error::Import(): - Error Message : " + err); - } + try { + const data = fs.readFileSync(path, "utf8"); + var type = ValidateData(data); + switch (type) { + case ImportType.FetchClient_1_0: + ImportFC(webviewView, data); + break; + case ImportType.Postman_2_1: + ImportPostman(webviewView, data); + break; + case ImportType.ThunderClient_1_2: + ImportThunderClient(webviewView, data); + break; + default: + vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); + } + + } catch (err) { + vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); + writeLog("error::Import(): - Error Message : " + err); + } } function ImportPostman(webviewView: vscode.WebviewView, data: string) { - try { - const convertedData = postmanImporter(data); - if (!convertedData || !convertedData.fcCollection || !convertedData.fcRequests) { - return; - } - - const db = getDB(); - const colDB = getCollectionDB(); - const varDB = getVariableDB(); - - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests"); - apiRequests.insert(convertedData.fcRequests); - db.saveDatabase(); - - if (convertedData.fcVariable) { - varDB.loadDatabase({}, function () { - const userVariables = varDB.getCollection('userVariables'); - userVariables.insert(convertedData.fcVariable); - varDB.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.importVariableResponse, vars: convertedData.fcVariable }); - insertCollections(colDB, webviewView, convertedData.fcCollection); - }); - } else { - insertCollections(colDB, webviewView, convertedData.fcCollection); - } - }); - } catch (err) { - vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); - writeLog("error::ImportPostman(): - Error Message : " + err); - } + try { + const convertedData = postmanImporter(data); + if (!convertedData || !convertedData.fcCollection || !convertedData.fcRequests) { + return; + } + + const db = getDB(); + const colDB = getCollectionDB(); + const varDB = getVariableDB(); + + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests"); + apiRequests.insert(convertedData.fcRequests); + db.saveDatabase(); + + if (convertedData.fcVariable) { + varDB.loadDatabase({}, function () { + const userVariables = varDB.getCollection('userVariables'); + userVariables.insert(convertedData.fcVariable); + varDB.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.importVariableResponse, vars: convertedData.fcVariable }); + insertCollections(colDB, webviewView, convertedData.fcCollection); + }); + } else { + insertCollections(colDB, webviewView, convertedData.fcCollection); + } + }); + } catch (err) { + vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); + writeLog("error::ImportPostman(): - Error Message : " + err); + } } function ImportThunderClient(webviewView: vscode.WebviewView, data: string) { - try { - const convertedData = thunderClientImporter(data); - if (!convertedData || !convertedData.fcCollection || !convertedData.fcRequests) { - return; - } - - const db = getDB(); - const colDB = getCollectionDB(); - - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests"); - apiRequests.insert(convertedData.fcRequests); - db.saveDatabase(); - - insertCollections(colDB, webviewView, convertedData.fcCollection); - }); - } catch (err) { - vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); - writeLog("error::ImportThunderClient(): - Error Message : " + err); - } + try { + const convertedData = thunderClientImporter(data); + if (!convertedData || !convertedData.fcCollection || !convertedData.fcRequests) { + return; + } + + const db = getDB(); + const colDB = getCollectionDB(); + + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests"); + apiRequests.insert(convertedData.fcRequests); + db.saveDatabase(); + + insertCollections(colDB, webviewView, convertedData.fcCollection); + }); + } catch (err) { + vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); + writeLog("error::ImportThunderClient(): - Error Message : " + err); + } } function ImportFC(webviewView: vscode.WebviewView, data: string) { - try { - const parsedData = JSON.parse(data); - - const convertedData = fetchClientImporter(parsedData); - if (!convertedData || !convertedData.fcCollection || !convertedData.fcRequests) { - return; - } - - const db = getDB(); - const colDB = getCollectionDB(); - - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests"); - apiRequests.insert(convertedData.fcRequests); - db.saveDatabase(); - - colDB.loadDatabase({}, function () { - const userCollections = colDB.getCollection("userCollections"); - userCollections.insert(convertedData.fcCollection); - colDB.saveDatabase(); - - webviewView.webview.postMessage({ type: responseTypes.importResponse, data: convertedData.fcCollection }); - }); - }); - - } catch (err) { - vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); - writeLog("error::ImportFC(): - Error Message : " + err); - } + try { + const parsedData = JSON.parse(data); + + const convertedData = fetchClientImporter(parsedData); + if (!convertedData || !convertedData.fcCollection || !convertedData.fcRequests) { + return; + } + + const db = getDB(); + const colDB = getCollectionDB(); + + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests"); + apiRequests.insert(convertedData.fcRequests); + db.saveDatabase(); + + colDB.loadDatabase({}, function () { + const userCollections = colDB.getCollection("userCollections"); + userCollections.insert(convertedData.fcCollection); + colDB.saveDatabase(); + + webviewView.webview.postMessage({ type: responseTypes.importResponse, data: convertedData.fcCollection }); + }); + }); + + } catch (err) { + vscode.window.showErrorMessage("Could not import the collection - Invalid data.", { modal: true }); + writeLog("error::ImportFC(): - Error Message : " + err); + } } export function GetColsRequests(ids: string[], paths: any, webview: vscode.Webview) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const apiRequests = db.getCollection("apiRequests").find({ 'id': { '$in': ids } }); - webview.postMessage({ type: responseTypes.getCollectionsByIdResponse, collections: apiRequests, paths: paths }); - }); + db.loadDatabase({}, function () { + const apiRequests = db.getCollection("apiRequests").find({ 'id': { '$in': ids } }); + webview.postMessage({ type: responseTypes.getCollectionsByIdResponse, collections: apiRequests, paths: paths }); + }); - } catch (err) { - writeLog("error::GetColsRequests(): " + err); - } + } catch (err) { + writeLog("error::GetColsRequests(): " + err); + } } diff --git a/src/utils/db/transferDBConfig.ts b/src/utils/db/transferDBConfig.ts index 9d44d57..5f18dbd 100644 --- a/src/utils/db/transferDBConfig.ts +++ b/src/utils/db/transferDBConfig.ts @@ -1,11 +1,11 @@ import fs from "fs"; +import path from "path"; +import { getSaveToWorkspaceConfiguration, updateWorkspacePathConfiguration } from "../vscodeConfig"; import { - getExtDbBKPPath, - getExtLocalDbPath, - getGlobalStorageUri + getExtDbBKPPath, + getExtLocalDbPath, + getGlobalStorageUri } from "./getExtDbPath"; -import { getSaveToWorkspaceConfiguration, updateSaveToWorkspaceConfiguration, updateWorkspacePathConfiguration } from "../vscodeConfig"; -import path from "path"; /** * In case we use the config option keepInLocalPath, @@ -13,47 +13,47 @@ import path from "path"; * And the db files should be moved to the global path if the option is disabled. */ export const transferDbConfig = () => { - const customPath = getExtLocalDbPath(); - const pathState = getSaveToWorkspaceConfiguration(); - const actualPath = getGlobalStorageUri(); - const files = ['fetchClientCookies.db', 'fetchClientHistory.db', 'fetchClientCollection.db', 'fetchClient.db', 'fetchClientVariable.db', 'fetch-client.log']; - const dbFile = path.resolve(customPath, "fetchClientCollection.db"); + const customPath = getExtLocalDbPath(); + const pathState = getSaveToWorkspaceConfiguration(); + const actualPath = getGlobalStorageUri(); + const files = ['fetchClientCookies.db', 'fetchClientHistory.db', 'fetchClientCollection.db', 'fetchClient.db', 'fetchClientVariable.db', 'fetch-client.log']; + const dbFile = path.resolve(customPath, "fetchClientCollection.db"); - if (actualPath && customPath && actualPath !== customPath) { - if (pathState) { - // First time taking bakeup of the data in actual global path - let bkpPath = getExtDbBKPPath(); - if (!fs.existsSync(bkpPath)) { - fs.cpSync(actualPath, bkpPath, { recursive: true }); - } + if (actualPath && customPath && actualPath !== customPath) { + if (pathState) { + // First time taking bakeup of the data in actual global path + let bkpPath = getExtDbBKPPath(); + if (!fs.existsSync(bkpPath)) { + fs.cpSync(actualPath, bkpPath, { recursive: true }); + } - // Check if files are already available in the workspace path - if (fs.existsSync(dbFile)) { - let customBKPPath = path.resolve(customPath, "BKP"); - if (!fs.existsSync(customBKPPath)) { - fs.mkdirSync(customBKPPath, { recursive: true }); - } + // Check if files are already available in the workspace path + if (fs.existsSync(dbFile)) { + let customBKPPath = path.resolve(customPath, "BKP"); + if (!fs.existsSync(customBKPPath)) { + fs.mkdirSync(customBKPPath, { recursive: true }); + } - // Copy all files to backup path in custom folder - files.forEach(file => { - fs.cpSync(path.resolve(customPath, file), path.resolve(customBKPPath, file), { recursive: true, force: true }); - }); - } + // Copy all files to backup path in custom folder + files.forEach(file => { + fs.cpSync(path.resolve(customPath, file), path.resolve(customBKPPath, file), { recursive: true, force: true }); + }); + } - // Copy all files to custom folder - files.forEach(file => { - fs.cpSync(path.resolve(actualPath, file), path.resolve(customPath, file), { recursive: true, force: true }); - fs.unlinkSync(path.resolve(actualPath, file)); - }); - updateWorkspacePathConfiguration(customPath); - } else { + // Copy all files to custom folder + files.forEach(file => { + fs.cpSync(path.resolve(actualPath, file), path.resolve(customPath, file), { recursive: true, force: true }); + fs.unlinkSync(path.resolve(actualPath, file)); + }); + updateWorkspacePathConfiguration(customPath); + } else { - // Copy all files to actual global path - files.forEach(file => { - fs.cpSync(path.resolve(customPath, file), path.resolve(actualPath, file), { recursive: true, force: true }); - fs.unlinkSync(path.resolve(customPath, file)); - }); - updateWorkspacePathConfiguration(""); - } - } + // Copy all files to actual global path + files.forEach(file => { + fs.cpSync(path.resolve(customPath, file), path.resolve(actualPath, file), { recursive: true, force: true }); + fs.unlinkSync(path.resolve(customPath, file)); + }); + updateWorkspacePathConfiguration(""); + } + } }; diff --git a/src/utils/db/varDBUtil.ts b/src/utils/db/varDBUtil.ts index b3a9db8..6cf7e5d 100644 --- a/src/utils/db/varDBUtil.ts +++ b/src/utils/db/varDBUtil.ts @@ -8,421 +8,574 @@ import { IVariable } from "../../fetch-client-ui/components/SideBar/redux/types" import { pubSubTypes, responseTypes } from '../configuration'; import { formatDate } from '../helper'; import { PostmanVariableSchema_2_1 } from '../importers/postman/postman_2_1.variable_types'; +import { ThunderClientVariableSchema_1_2 } from "../importers/thunderClient/thunderClient_1_2.variable_types"; import { writeLog } from '../logger/logger'; import { FetchClientVariableProxy } from '../validators/fetchClientVariableValidator'; import { RemoveVariable } from './collectionDBUtil'; import { VariableImportType } from './constants'; import { variableDBPath } from './dbPaths'; -import { ThunderClientVariableSchema_1_2 } from "../importers/thunderClient/thunderClient_1_2.variable_types"; +import { getExportVariableEncryptionConfiguration, getVariableEncryptionConfiguration } from "../vscodeConfig"; +import { FCCipher } from "../crypto/index"; +import { CryptoMode } from "../crypto/index"; function getDB(): loki { - const idbAdapter = new LokiFsAdapter(); - const db = new loki(variableDBPath(), { adapter: idbAdapter }); - db.autosaveDisable(); - return db; + const idbAdapter = new LokiFsAdapter(); + const db = new loki(variableDBPath(), { adapter: idbAdapter }); + db.autosaveDisable(); + return db; } export function SaveVariable(item: IVariable, webview: vscode.Webview, sideBarView: vscode.WebviewView) { - try { - const db = getDB(); + try { + const db = getDB(); - db.loadDatabase({}, function () { - const userVariables = db.getCollection("userVariables"); - userVariables.insert(item); - db.saveDatabase(); + db.loadDatabase({}, function () { + const userVariables = db.getCollection("userVariables"); + userVariables.insert(item); + db.saveDatabase(); - if (webview) { - webview.postMessage({ type: responseTypes.saveVariableResponse }); - } + if (webview) { + webview.postMessage({ type: responseTypes.saveVariableResponse }); + } - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.appendToVariableResponse, collection: item }); - } + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.appendToVariableResponse, collection: item }); + } - if (pubSub.size > 0) { - pubSub.publish({ messageType: pubSubTypes.updateVariables }); - } + if (pubSub.size > 0) { + pubSub.publish({ messageType: pubSubTypes.updateVariables }); + } - }); + }); - } catch (err) { - writeLog("error::SaveVariable(): " + err); - } + } catch (err) { + writeLog("error::SaveVariable(): " + err); + } } export function DuplicateVariable(id: string, webview: vscode.Webview, sideBarView: vscode.WebviewView) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const sourceData = db.getCollection("userVariables").chain().find({ 'id': id }).data({ forceClones: true, removeMeta: true }); - if (sourceData && sourceData.length > 0) { - let distData: IVariable = { - id: uuidv4(), - name: sourceData[0].name.toUpperCase().trim() === "GLOBAL" ? "Global - Copy" : sourceData[0].name + " - Copy", - createdTime: formatDate(), - isActive: true, - data: sourceData[0].data - }; - db.getCollection("userVariables").insert(distData); - db.saveDatabase(); - - if (webview) { - webview.postMessage({ type: responseTypes.saveVariableResponse }); - } - - if (sideBarView) { - sideBarView.webview.postMessage({ type: responseTypes.appendToVariableResponse, collection: distData }); - } - } - }); - - } catch (err) { - writeLog("error::DuplicateVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const sourceData = db.getCollection("userVariables").chain().find({ 'id': id }).data({ forceClones: true, removeMeta: true }); + if (sourceData && sourceData.length > 0) { + let distData: IVariable = { + id: uuidv4(), + name: sourceData[0].name.toUpperCase().trim() === "GLOBAL" ? "Global - Copy" : sourceData[0].name + " - Copy", + createdTime: formatDate(), + isActive: true, + data: sourceData[0].data + }; + db.getCollection("userVariables").insert(distData); + db.saveDatabase(); + + if (webview) { + webview.postMessage({ type: responseTypes.saveVariableResponse }); + } + + if (sideBarView) { + sideBarView.webview.postMessage({ type: responseTypes.appendToVariableResponse, collection: distData }); + } + } + }); + + } catch (err) { + writeLog("error::DuplicateVariable(): " + err); + } } export function UpdateVariable(item: IVariable, webview: vscode.Webview) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection("userVariables").findAndUpdate({ 'id': item.id }, itm => { itm.data = item.data; }); - db.saveDatabase(function (err) { - if (!err) { - if (webview) { - webview.postMessage({ type: responseTypes.updateVariableResponse }); - } - - if (pubSub.size > 0) { - pubSub.publish({ messageType: pubSubTypes.updateVariables }); - } - } - }); - }); - - } catch (err) { - writeLog("error::SaveVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + + if (getVariableEncryptionConfiguration()) { + item.data = new FCCipher(CryptoMode.Transit).EncryptBulkData(item.data); + } + + db.getCollection("userVariables").findAndUpdate({ 'id': item.id }, itm => { itm.data = item.data; }); + db.saveDatabase(function (err) { + if (!err) { + if (webview) { + webview.postMessage({ type: responseTypes.updateVariableResponse }); + } + + if (pubSub.size > 0) { + pubSub.publish({ messageType: pubSubTypes.updateVariables }); + } + } + }); + }); + + } catch (err) { + writeLog("error::SaveVariable(): " + err); + } } export function UpdateVariableSync(item: IVariable) { - try { - return new Promise(async (resolve, _reject) => { - const db = getDB(); - db.loadDatabase({}, function () { - db.getCollection("userVariables").findAndUpdate({ 'id': item.id }, itm => { itm.data = item.data; }); - db.saveDatabase(function (err) { - if (!err) { - let vars = db.getCollection("userVariables").find({ 'id': item.id }); - resolve(vars && vars.length > 0 ? vars[0] as IVariable : null); - } - }); - }); - }); - } catch (err) { - writeLog("error::UpdateVariableSync(): " + err); - } + try { + return new Promise(async (resolve, _reject) => { + const db = getDB(); + db.loadDatabase({}, function () { + + if (getVariableEncryptionConfiguration()) { + item.data = new FCCipher(CryptoMode.Transit).EncryptBulkData(item.data); + } + + db.getCollection("userVariables").findAndUpdate({ 'id': item.id }, itm => { itm.data = item.data; }); + db.saveDatabase(function (err) { + if (!err) { + let vars = db.getCollection("userVariables").find({ 'id': item.id }); + resolve(vars && vars.length > 0 ? vars[0] as IVariable : null); + } + }); + }); + }); + } catch (err) { + writeLog("error::UpdateVariableSync(): " + err); + throw err; + } } export function GetAllVariable(webview: vscode.Webview) { - try { - const db = getDB(); + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userVariables = db.getCollection("userVariables").data; + + if (getVariableEncryptionConfiguration()) { + userVariables.forEach((item: IVariable) => { + item.data = new FCCipher(CryptoMode.Transit).DecryptBulkData(item.data); + }); + } + + webview?.postMessage({ type: responseTypes.getAllVariableResponse, variable: userVariables }); + }); + + } catch (err) { + writeLog("error::GetAllVariable(): " + err); + } +} - db.loadDatabase({}, function () { - const userVariables = db.getCollection("userVariables").data; - webview.postMessage({ type: responseTypes.getAllVariableResponse, variable: userVariables }); - }); +export function UpdateToEncryptedVariables() { + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userVariables = db.getCollection("userVariables").data as IVariable[]; + userVariables.forEach((item: IVariable) => { + item.data = new FCCipher(CryptoMode.Transit).EncryptBulkData(item.data); + db.getCollection("userVariables").findAndUpdate({ 'id': item.id }, itm => { itm.data = item.data; }); + }); + db.saveDatabase(); + }); + + } catch (err) { + writeLog("error::UpdateToEncryptedVariables(): " + err); + } +} - } catch (err) { - writeLog("error::GetAllVariable(): " + err); - } +export function UpdateToDecryptedVariables() { + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userVariables = db.getCollection("userVariables").data as IVariable[]; + userVariables?.forEach((item: IVariable) => { + item.data = new FCCipher(CryptoMode.Transit).DecryptBulkData(item.data); + db.getCollection("userVariables").findAndUpdate({ 'id': item.id }, itm => { itm.data = item.data; }); + }); + db.saveDatabase(); + }); + + } catch (err) { + writeLog("error::UpdateToDecryptedVariables(): " + err); + } } export function GetVariableById(id: string, isGlobal: boolean, webview: vscode.Webview) { - try { - const db = getDB(); + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let userVariables = db.getCollection("userVariables").find(isGlobal ? { 'name': 'Global' } : { 'id': id }); - db.loadDatabase({}, function () { - let userVariables = db.getCollection("userVariables").find(isGlobal ? { 'name': 'Global' } : { 'id': id }); - webview.postMessage({ type: responseTypes.getVariableItemResponse, data: userVariables }); - }); + if (getVariableEncryptionConfiguration()) { + userVariables?.forEach((item: IVariable) => { + item.data = new FCCipher(CryptoMode.Transit).DecryptBulkData(item.data); + }); + } - } catch (err) { - writeLog("error::GetVariableById(): " + err); - } + webview.postMessage({ type: responseTypes.getVariableItemResponse, data: userVariables }); + }); + + } catch (err) { + writeLog("error::GetVariableById(): " + err); + } } export function GetVariableByIdSync(id: string) { - try { - return new Promise(async (resolve, _reject) => { - const db = getDB(); - db.loadDatabase({}, function () { - let userVariables = db.getCollection("userVariables").find({ 'id': id }); - resolve(userVariables && userVariables.length > 0 ? userVariables[0] as IVariable : null); - }); - }); - - } catch (err) { - writeLog("error::GetVariableByIdSync(): " + err); - } + try { + return new Promise(async (resolve, _reject) => { + const db = getDB(); + db.loadDatabase({}, function () { + let userVariables = db.getCollection("userVariables").find({ 'id': id }); + if (getVariableEncryptionConfiguration()) { + userVariables?.forEach((item: IVariable) => { + item.data = new FCCipher(CryptoMode.Transit).DecryptBulkData(item.data); + }); + } + resolve(userVariables && userVariables.length > 0 ? userVariables[0] as IVariable : null); + }); + }); + + } catch (err) { + writeLog("error::GetVariableByIdSync(): " + err); + throw err; + } } export function DeleteVariable(webviewView: vscode.WebviewView, id: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection("userVariables").findAndRemove({ 'id': id }); - db.saveDatabase(); - RemoveVariable(id); - webviewView.webview.postMessage({ type: responseTypes.deleteVariableResponse, id: id }); - if (pubSub.size > 0) { - pubSub.publish({ messageType: pubSubTypes.updateVariables }); - } - }); - - } catch (err) { - writeLog("error::DeleteVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection("userVariables").findAndRemove({ 'id': id }); + db.saveDatabase(); + RemoveVariable(id); + webviewView.webview.postMessage({ type: responseTypes.deleteVariableResponse, id: id }); + if (pubSub.size > 0) { + pubSub.publish({ messageType: pubSubTypes.updateVariables }); + } + }); + + } catch (err) { + writeLog("error::DeleteVariable(): " + err); + } } export function RenameVariable(webviewView: vscode.WebviewView, id: string, name: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection("userVariables").findAndUpdate({ 'id': id }, item => { item.name = name; }); - db.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.renameVariableResponse, params: { id: id, name: name } }); - if (pubSub.size > 0) { - pubSub.publish({ messageType: pubSubTypes.updateVariables }); - } - }); - - } catch (err) { - writeLog("error::RenameVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection("userVariables").findAndUpdate({ 'id': id }, item => { item.name = name; }); + db.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.renameVariableResponse, params: { id: id, name: name } }); + if (pubSub.size > 0) { + pubSub.publish({ messageType: pubSubTypes.updateVariables }); + } + }); + + } catch (err) { + writeLog("error::RenameVariable(): " + err); + } } export function ChangeVariableStatus(id: string, status: boolean, webviewView: vscode.WebviewView) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - db.getCollection("userVariables").findAndUpdate({ 'id': id }, item => { item.isActive = status; }); - db.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.activeVariableResponse, params: { id: id, status: status } }); - }); - - } catch (err) { - writeLog("error::ChangeVariableStatus(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + db.getCollection("userVariables").findAndUpdate({ 'id': id }, item => { item.isActive = status; }); + db.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.activeVariableResponse, params: { id: id, status: status } }); + }); + + } catch (err) { + writeLog("error::ChangeVariableStatus(): " + err); + } +} + +export function BulkExportVariables(path: string, selectedVars: string[], webview: vscode.Webview) { + try { + const db = getDB(); + + db.loadDatabase({}, function () { + + selectedVars?.forEach(async (item: string) => { + + let vars = db.getCollection("userVariables").find({ 'id': item }); + + if (vars?.length > 0) { + + let exportData = FormatExportedVariables(vars); + + let fullPath = path + "\\" + "fetch-client-variable_" + exportData.name.replace(/[/\\?%*:|"<>]/g, '-') + ".json"; + + fs.writeFile(fullPath, JSON.stringify(exportData), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + path + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::BulkExport()::FileWrite()" + error.message); + } + }); + } + }); + + webview?.postMessage({ type: responseTypes.bulkColExportResponse }); + }); + + } catch (err) { + writeLog("error::BulkExport(): " + err); + } } export function ExportVariable(path: string, id: string) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - let vars = db.getCollection("userVariables").find({ 'id': id }); - if (vars && vars.length > 0) { - let exportData = { - app: "Fetch Client", - id: vars[0].id, - name: vars[0].name.toUpperCase().trim() === "GLOBAL" ? "Global Export" : vars[0].name, - version: "1.0", - type: "variables", - createdTime: vars[0].createdTime, - exportedDate: formatDate(), - isActive: true, - data: vars[0].data - }; - - fs.writeFile(path, JSON.stringify(exportData), (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + path + "'. Error Message : " + error.message, { modal: true }); - writeLog("error::ExportVariable()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + path + "'.", { modal: true }); - } - }); - } - }); - - } catch (err) { - writeLog("error::ExportVariable(): " + err); - } + try { + const db = getDB(); + + db.loadDatabase({}, function () { + let vars = db.getCollection("userVariables").find({ 'id': id }); + if (vars && vars.length > 0) { + let exportData = FormatExportedVariables(vars); + fs.writeFile(path, JSON.stringify(exportData), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + path + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::ExportVariable()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + path + "'.", { modal: true }); + } + }); + } + }); + + } catch (err) { + writeLog("error::ExportVariable(): " + err); + } +} + +function FormatExportedVariables(vars: any[]) { + let exportData = { + app: "Fetch Client", + id: vars[0].id, + name: vars[0].name.toUpperCase().trim() === "GLOBAL" ? "Global Export" : vars[0].name, + version: "1.0", + type: "variables", + createdTime: vars[0].createdTime, + exportedDate: formatDate(), + isActive: true, + secretVariables: false, + data: vars[0].data, + }; + + let fcCryptoDecrypt = new FCCipher(CryptoMode.Transit); + let fcCryptoEncrypt = new FCCipher(CryptoMode.Export); + + if (getVariableEncryptionConfiguration()) { + exportData.data.forEach((item: ITableData) => { + item.value = fcCryptoDecrypt.DecryptData(item.value); + }); + } + + if (getExportVariableEncryptionConfiguration()) { + exportData.data.forEach((item: ITableData) => { + item.value = fcCryptoEncrypt.EncryptData(item.value); + }); + exportData.secretVariables = true; + } + + return exportData; } function ValidateData(data: string): VariableImportType | null { - try { - if (!data || data.length === 0) { - vscode.window.showErrorMessage("Could not import the variable - Empty Data.", { modal: true }); - writeLog("error::ImportVariable::ValidateData() " + "Error Message : Could not import the variable - Empty Data."); - return null; - } - - try { - FetchClientVariableProxy.Parse(data); - return VariableImportType.FetchClient_Variable_1_0; - } catch (err) { - let postmanData = JSON.parse(data) as PostmanVariableSchema_2_1; - if (postmanData?._postman_variable_scope && postmanData?._postman_exported_using) { - return VariableImportType.Postman_Variable_2_1; - } - - let thunderClientData = JSON.parse(data) as ThunderClientVariableSchema_1_2; - if (thunderClientData?.clientName === "Thunder Client" && thunderClientData?.ref) { - if (thunderClientData?.version !== "1.2") { - vscode.window.showErrorMessage("Could not import the variable - Invalid version.", { modal: true }); - return null; - } - return VariableImportType.ThunderClient_Variable_1_2; - } - - return null; - } - } - catch (err) { - vscode.window.showErrorMessage("Could not import the variable - Invalid Data.", { modal: true }); - writeLog("error::ImportVariable::ValidateData() " + "Error Message : Could not import the variable - " + err); - return null; - } + try { + if (!data || data.length === 0) { + vscode.window.showErrorMessage("Could not import the variable - Empty Data.", { modal: true }); + writeLog("error::ImportVariable::ValidateData() " + "Error Message : Could not import the variable - Empty Data."); + return null; + } + + try { + FetchClientVariableProxy.Parse(data); + return VariableImportType.FetchClient_Variable_1_0; + } catch (err) { + let postmanData = JSON.parse(data) as PostmanVariableSchema_2_1; + if (postmanData?._postman_variable_scope && postmanData?._postman_exported_using) { + return VariableImportType.Postman_Variable_2_1; + } + + let thunderClientData = JSON.parse(data) as ThunderClientVariableSchema_1_2; + if (thunderClientData?.clientName === "Thunder Client" && thunderClientData?.ref) { + if (thunderClientData?.version !== "1.2") { + vscode.window.showErrorMessage("Could not import the variable - Invalid version.", { modal: true }); + return null; + } + return VariableImportType.ThunderClient_Variable_1_2; + } + + return null; + } + } + catch (err) { + vscode.window.showErrorMessage("Could not import the variable - Invalid Data.", { modal: true }); + writeLog("error::ImportVariable::ValidateData() " + "Error Message : Could not import the variable - " + err); + return null; + } } export function ImportVariableFromJsonFile(webviewView: vscode.WebviewView, path: string) { - try { - const data = fs.readFileSync(path, "utf8"); - var type = ValidateData(data); - switch (type) { - case VariableImportType.FetchClient_Variable_1_0: - ImportFetchClientVariable(webviewView, data); - break; - case VariableImportType.Postman_Variable_2_1: - ImportPostmanVariable(webviewView, data); - break; - case VariableImportType.ThunderClient_Variable_1_2: - ImportThunderClientVariable(webviewView, data); - break; - default: - vscode.window.showErrorMessage("Could not import the collection - Invalid type.", { modal: true }); - } - } catch (err) { - vscode.window.showErrorMessage("Could not import the variable - Invalid data.", { modal: true }); - writeLog("error::ImportVariableFromJsonFile(): - Error Mesaage : " + err); - } + try { + const data = fs.readFileSync(path, "utf8"); + var type = ValidateData(data); + switch (type) { + case VariableImportType.FetchClient_Variable_1_0: + ImportFetchClientVariable(webviewView, data); + break; + case VariableImportType.Postman_Variable_2_1: + ImportPostmanVariable(webviewView, data); + break; + case VariableImportType.ThunderClient_Variable_1_2: + ImportThunderClientVariable(webviewView, data); + break; + default: + vscode.window.showErrorMessage("Could not import the collection - Invalid type.", { modal: true }); + } + } catch (err) { + vscode.window.showErrorMessage("Could not import the variable - Invalid data.", { modal: true }); + writeLog("error::ImportVariableFromJsonFile(): - Error Mesaage : " + err); + } } function ImportFetchClientVariable(webviewView: vscode.WebviewView, data: string) { - const parsedData = JSON.parse(data); - let reqData = parsedData as IVariable; - reqData.id = uuidv4(); - reqData.createdTime = formatDate(); - ImportVariable(webviewView, reqData); + const parsedData = JSON.parse(data); + let secretVariables = parsedData.secretVariables; + let encryptVariableConfiguration = getVariableEncryptionConfiguration(); + let reqData: IVariable = { + id: uuidv4(), + createdTime: formatDate(), + name: parsedData.name, + isActive: parsedData.isActive, + data: parsedData.data + }; + + let fcCryptoDecrypt = new FCCipher(CryptoMode.Export); + let fcCryptoEncrypt = new FCCipher(CryptoMode.Transit); + + reqData.data.forEach((item) => { + if (secretVariables) { + item.value = fcCryptoDecrypt.DecryptData(item.value); + } + if (encryptVariableConfiguration) { + item.value = fcCryptoEncrypt.EncryptData(item.value); + } + }); + + ImportVariable(webviewView, reqData); } function ImportPostmanVariable(webviewView: vscode.WebviewView, data: string) { - const parsedData = JSON.parse(data) as PostmanVariableSchema_2_1; - let varData: ITableData[] = []; - - if (!parsedData?._postman_exported_using?.includes("Postman/") || !parsedData?._postman_variable_scope?.includes("environment")) { - writeLog("error::ImportPostmanVariable(): - Error Mesaage : Could not import the variable - Invalid data."); - throw new Error("Could not import the variable - Invalid data."); - } - - for (let i = 0; i < parsedData.values?.length; i++) { - if (parsedData.values[i].key) { - varData.push({ - isChecked: parsedData.values[i].enabled, - key: parsedData.values[i].key, - value: parsedData.values[i].value - }); - } - } - - let convertedData: IVariable = { - id: uuidv4(), - createdTime: formatDate(), - name: parsedData.name, - isActive: true, - data: varData - }; - - ImportVariable(webviewView, convertedData); + const parsedData = JSON.parse(data) as PostmanVariableSchema_2_1; + let varData: ITableData[] = []; + + if (!parsedData?._postman_exported_using?.includes("Postman/") || !parsedData?._postman_variable_scope?.includes("environment")) { + writeLog("error::ImportPostmanVariable(): - Error Mesaage : Could not import the variable - Invalid data."); + throw new Error("Could not import the variable - Invalid data."); + } + + let encryptVariableConfiguration = getVariableEncryptionConfiguration(); + let fcCrypto = new FCCipher(CryptoMode.Transit); + + for (let i = 0; i < parsedData.values?.length; i++) { + if (parsedData.values[i].key) { + varData.push({ + isChecked: parsedData.values[i].enabled, + key: parsedData.values[i].key, + value: encryptVariableConfiguration ? fcCrypto.EncryptData(parsedData.values[i].value) : parsedData.values[i].value + }); + } + } + + let convertedData: IVariable = { + id: uuidv4(), + createdTime: formatDate(), + name: parsedData.name, + isActive: true, + data: varData + }; + + ImportVariable(webviewView, convertedData); } function ImportThunderClientVariable(webviewView: vscode.WebviewView, data: string) { - const parsedData = JSON.parse(data) as ThunderClientVariableSchema_1_2; - - let varData: ITableData[] = []; - - for (let i = 0; i < parsedData.variables?.length; i++) { - if (parsedData.variables[i].name) { - varData.push({ - isChecked: true, - key: parsedData.variables[i].name, - value: parsedData.variables[i].value - }); - } - } - - let convertedData: IVariable = { - id: uuidv4(), - createdTime: formatDate(), - name: parsedData.environmentName, - isActive: true, - data: varData - }; - - ImportVariable(webviewView, convertedData); + const parsedData = JSON.parse(data) as ThunderClientVariableSchema_1_2; + + let varData: ITableData[] = []; + + let encryptVariableConfiguration = getVariableEncryptionConfiguration(); + let fcCrypto = new FCCipher(CryptoMode.Transit); + + for (let i = 0; i < parsedData.variables?.length; i++) { + if (parsedData.variables[i].name) { + varData.push({ + isChecked: true, + key: parsedData.variables[i].name, + value: encryptVariableConfiguration ? fcCrypto.EncryptData(parsedData.variables[i].value) : parsedData.variables[i].value + }); + } + } + + let convertedData: IVariable = { + id: uuidv4(), + createdTime: formatDate(), + name: parsedData.environmentName, + isActive: true, + data: varData + }; + + ImportVariable(webviewView, convertedData); } export function ImportVariableFromEnvFile(webviewView: vscode.WebviewView, path: string) { - try { - const data = fs.readFileSync(path, "utf8").toString().split("\n"); - let fileName = path.split('\\').pop().split('/').pop().split('.')[0]?.trim(); - - let reqData: IVariable = { - id: uuidv4(), - name: fileName ? fileName : ".env", - createdTime: formatDate(), - isActive: true, - data: [] - }; - - for (let l in data) { - let line = data[l].trim(); - if (line.indexOf("=") > -1) { - reqData.data.push({ - isChecked: true, - key: line.substring(0, line.indexOf("=")).trim(), - value: line.substring(line.indexOf("=") + 1).trim() - }); - } - } - - ImportVariable(webviewView, reqData); - - } catch (err) { - vscode.window.showErrorMessage("Could not import the variable - Invalid data.", { modal: true }); - writeLog("error::ImportVariableFromEnvFile(): - Error Mesaage : " + err); - } + try { + const data = fs.readFileSync(path, "utf8").toString().split("\n"); + let fileName = path.split('\\').pop().split('/').pop().split('.')[0]?.trim(); + + let reqData: IVariable = { + id: uuidv4(), + name: fileName ? fileName : ".env", + createdTime: formatDate(), + isActive: true, + data: [] + }; + + let encryptVariableConfiguration = getVariableEncryptionConfiguration(); + let fcCrypto = new FCCipher(CryptoMode.Transit); + + for (let l in data) { + let line = data[l].trim(); + if (line.indexOf("=") > -1) { + reqData.data.push({ + isChecked: true, + key: line.substring(0, line.indexOf("=")).trim(), + value: encryptVariableConfiguration ? fcCrypto.EncryptData(line.substring(line.indexOf("=") + 1).trim()) : line.substring(line.indexOf("=") + 1).trim() + }); + } + } + + ImportVariable(webviewView, reqData); + + } catch (err) { + vscode.window.showErrorMessage("Could not import the variable - Invalid data.", { modal: true }); + writeLog("error::ImportVariableFromEnvFile(): - Error Mesaage : " + err); + } } export function ImportVariable(webviewView: vscode.WebviewView, reqData: IVariable) { - try { - const db = getDB(); - - db.loadDatabase({}, function () { - const userVariables = db.getCollection("userVariables"); - userVariables.insert(reqData); - db.saveDatabase(); - webviewView.webview.postMessage({ type: responseTypes.importVariableResponse, vars: reqData }); - }); - - } catch (err) { - vscode.window.showErrorMessage("Could not import the variable - Invalid data.", { modal: true }); - writeLog("error::ImportVariable(): - Error Mesaage : " + err); - } -} \ No newline at end of file + try { + const db = getDB(); + + db.loadDatabase({}, function () { + const userVariables = db.getCollection("userVariables"); + userVariables.insert(reqData); + db.saveDatabase(); + webviewView.webview.postMessage({ type: responseTypes.importVariableResponse, vars: reqData }); + }); + + } catch (err) { + vscode.window.showErrorMessage("Could not import the variable - Invalid data.", { modal: true }); + writeLog("error::ImportVariable(): - Error Mesaage : " + err); + } +} diff --git a/src/utils/fetchUtil.ts b/src/utils/fetchUtil.ts index 273d4f5..ed864b2 100644 --- a/src/utils/fetchUtil.ts +++ b/src/utils/fetchUtil.ts @@ -1,354 +1,354 @@ -import { getErrorResponse, getFileType, getRandomNumber, isFileType, replaceAuthSettingsInRequest, replaceHeaderSettingsInRequest, replaceValueWithVariable } from "./helper"; -import { getProtocolConfiguration, getSSLConfiguration } from "./vscodeConfig"; +import { Request as awsRequest, sign } from 'aws4'; +import axios, { CancelTokenSource } from "axios"; +import FormData from 'form-data'; +import fs from "fs"; +import * as https from "https"; +import { ITableData } from "../fetch-client-ui/components/Common/Table/types"; import { IReqSettings, IRequestModel } from "../fetch-client-ui/components/RequestUI/redux/types"; import { ISettings } from "../fetch-client-ui/components/SideBar/redux/types"; -import { ITableData } from "../fetch-client-ui/components/Common/Table/types"; -import { logDetails } from "./logger/requestLog"; import { responseTypes } from "./configuration"; -import { sign, Request as awsRequest } from 'aws4'; +import { getErrorResponse, getFileType, getRandomNumber, isFileType, replaceAuthSettingsInRequest, replaceHeaderSettingsInRequest, replaceValueWithVariable } from "./helper"; import { writeLog } from "./logger/logger"; -import * as https from "https"; -import axios, { CancelTokenSource } from "axios"; -import FormData from 'form-data'; -import fs from "fs"; +import { logDetails } from "./logger/requestLog"; +import { getProtocolConfiguration, getSSLConfiguration } from "./vscodeConfig"; export interface FetchConfig { - timeOut: number, - headersCase: boolean, - runMainRequest?: boolean, - source?: CancelTokenSource + timeOut: number, + headersCase: boolean, + runMainRequest?: boolean, + source?: CancelTokenSource } export const updateAuthSettings = (requestData: IRequestModel, settings?: ISettings): IRequestModel => { - if (settings && requestData.auth.authType === "inherit") { - let copyData = JSON.parse(JSON.stringify(requestData)); - return replaceAuthSettingsInRequest(copyData, settings); - } - return requestData; + if (settings && requestData.auth.authType === "inherit") { + let copyData = JSON.parse(JSON.stringify(requestData)); + return replaceAuthSettingsInRequest(copyData, settings); + } + return requestData; }; export const updateHeaderSettings = (requestData: IRequestModel, settings?: ISettings): IRequestModel => { - if (settings?.headers && settings?.headers?.length > 0) { - let copyData = JSON.parse(JSON.stringify(requestData)); - return replaceHeaderSettingsInRequest(copyData, settings); - } - return requestData; + if (settings?.headers && settings?.headers?.length > 0) { + let copyData = JSON.parse(JSON.stringify(requestData)); + return replaceHeaderSettingsInRequest(copyData, settings); + } + return requestData; }; export const updateVariables = (requestData: IRequestModel, variableData?: ITableData[]): IRequestModel => { - let varData = {}; - if (variableData?.length > 0) { - variableData.forEach(item => { - varData[item.key] = item.value; - }); - } - let copy = JSON.parse(JSON.stringify(requestData)); - return replaceValueWithVariable(copy, varData); + let varData = {}; + if (variableData?.length > 0) { + variableData.forEach(item => { + varData[item.key] = item.value; + }); + } + let copy = JSON.parse(JSON.stringify(requestData)); + return replaceValueWithVariable(copy, varData); }; export const apiFetch = async ( - requestData: IRequestModel, - variableData: ITableData[], - settings: ISettings, - reqSettings: IReqSettings, - fetchConfig: FetchConfig, - resType: string = responseTypes.apiResponse + requestData: IRequestModel, + variableData: ITableData[], + settings: ISettings, + reqSettings: IReqSettings, + fetchConfig: FetchConfig, + resType: string = responseTypes.apiResponse ) => { - const reqHeaders = {}; - let startTime: number, fetchDuration: number; - let reqData: any = ""; - let apiResponse: any; - - let request = updateAuthSettings(requestData, settings); - request = updateVariables(request, variableData); - - if (!reqSettings || reqSettings?.skipParentHeaders === false) { - request = updateHeaderSettings(request, settings); - } - - try { - if (request.auth.authType === "bearertoken") { - reqHeaders[fetchConfig.headersCase ? "Authorization" : "authorization"] = `${request.auth.tokenPrefix} ${request.auth.password}`; - } - - if (request.auth.authType === "oauth2") { - reqHeaders[fetchConfig.headersCase ? "Authorization" : "authorization"] = `${request.auth.tokenPrefix} ${request.auth.password}`; - } - - request.headers.forEach(({ isChecked, key, value }) => { - if (isChecked && key) { - reqHeaders[fetchConfig.headersCase ? key : key.toLocaleLowerCase()] = value; - } - }); - - if (request.body.bodyType === "formdata") { - const bodyFormData = new FormData(); - request.body.formdata.forEach(({ isChecked, key, value, type }) => { - if (isChecked && key) { - if (type === "File") { - if (!fs.existsSync(value)) { - throw new Error("Error : ENOENT: No such file or directory - " + value); - } - bodyFormData.append(key, fs.createReadStream(value)); - } else { - bodyFormData.append(key, value); - } - } - }); - reqData = bodyFormData; - } else if (request.body.bodyType === "formurlencoded") { - const bodyUrlEncoded = new URLSearchParams(); - request.body.urlencoded.forEach(({ isChecked, key, value }) => { - if (isChecked && key) { - bodyUrlEncoded.append(key, value); - } - }); - reqData = bodyUrlEncoded; - } else if (request.body.bodyType === "raw") { - reqData = request.body.raw.data; - } else if (request.body.bodyType === "binary") { - if (!request.body.binary.data) { - throw new Error("Error : ENOENT: No such file or directory - " + request.body.binary.fileName); - } - reqData = request.body.binary.data; - } else if (request.body.bodyType === "graphql") { - reqData = JSON.stringify({ - query: request.body.graphql.query, - variables: request.body.graphql.variables, - }); - } - - if (request.body.bodyType === "formdata") { - let header = reqData.getHeaders(); - reqHeaders[fetchConfig.headersCase ? "Content-Type" : "content-type"] = header["content-type"] ? header["content-type"] : getContentType(request.body.bodyType, ""); - } else { - if (request.body.bodyType !== "none" && !reqHeaders["Content-Type"] && !reqHeaders["content-type"]) { - reqHeaders[fetchConfig.headersCase ? "Content-Type" : "content-type"] = getContentType(request.body.bodyType, request.body.bodyType === "raw" ? request.body.raw.lang : ""); - } - } - - https.globalAgent.options.rejectUnauthorized = getSSLConfiguration(); - - axios.interceptors.request.use((config) => { - startTime = new Date().getTime(); - return config; - }); - - axios.interceptors.response.use((config) => { - fetchDuration = new Date().getTime() - startTime; - return config; - }); - - axios.defaults.withCredentials = true; - - let requestconfig: any; - let url = validateURL(request.url) ? request.url : getProtocolConfiguration() + "://" + request.url; - request.url = url; - - if (request.auth.authType === "aws") { - const baseRequest: awsRequest = { - host: getHost(url), - method: request.method.toUpperCase(), - path: getPath(url), - headers: reqHeaders - }; - - if (request.auth.aws.service) { - baseRequest.service = request.auth.aws.service; - } - - if (request.auth.aws.region) { - baseRequest.region = request.auth.aws.region; - } - - if (reqData) { - if (request.body.bodyType === "formdata") { - baseRequest.body = reqData.getBuffer(); - } else if (request.body.bodyType === "formurlencoded") { - baseRequest.body = JSON.stringify(reqData.toString()); - } else { - baseRequest.body = JSON.stringify(reqData); - } - } - - const signedRequest = sign(baseRequest, - { - secretAccessKey: request.auth.aws.secretAccessKey, - accessKeyId: request.auth.aws.accessKey, - sessionToken: request.auth.aws.sessionToken - }); - - if (signedRequest.headers) { - delete signedRequest.headers.Host; - delete signedRequest.headers['Content-Length']; - } - - requestconfig = { - ...signedRequest, - url: url, - data: reqData, - validateStatus: () => true, - transformResponse: [function (data) { return data; }], - timeout: fetchConfig.timeOut, - responseType: 'arraybuffer', - maxContentLength: Infinity, - maxBodyLength: Infinity, - }; - - } else { - requestconfig = { - url: url, - method: request.method, - headers: reqHeaders, - auth: request.auth.authType === "basic" ? { username: request.auth.userName, password: request.auth.password } : undefined, - data: reqData, - validateStatus: () => true, - transformResponse: [function (data) { return data; }], - timeout: fetchConfig.timeOut, - responseType: 'arraybuffer', - maxContentLength: Infinity, - maxBodyLength: Infinity, - }; - } - - if (fetchConfig.source) { - requestconfig.cancelToken = fetchConfig.source.token; - } - - const resp = await axios(requestconfig); - const respHeaders: ITableData[] = []; - const resCookies: ITableData[] = []; - let responseData: any; - let cookieData: any; - Object.entries(resp.headers).forEach(([key, value]) => { - if (key.trim().toLowerCase() === "set-cookie") { - cookieData = value; - } - respHeaders.push({ - isFixed: true, - key: key, - value: value.toString() - }); - }); - - let isFile = isFileType(respHeaders); - - if (!isFile) { - responseData = new Uint8Array(resp.data).reduce(function (data, byte) { - return data + String.fromCharCode(byte); - }, ''); - } - - if (cookieData) { - if (typeof cookieData === 'string') { - if (cookieData.includes(";")) { - Object.entries(cookieData.split(";")).forEach(([_key, value]) => { - let data = value.toString().trim(); - resCookies.push({ - isFixed: true, - isChecked: true, - key: data.substring(0, data.indexOf("=")), - value: data.substring(data.indexOf("=") + 1, data.length) - }); - }); - } - } else { - Object.entries(cookieData).forEach(([_key, value]) => { - let data = value.toString().trim(); - resCookies.push({ - isFixed: true, - isChecked: true, - key: data.substring(0, data.indexOf("=")), - value: data.substring(data.indexOf("=") + 1, data.length) - }); - }); - } - } - - setTimeout(() => { - logDetails(request, reqHeaders, reqData, resp.status, respHeaders, isFile ? "View Response is not supported for 'file' type in the log window." : responseData, fetchDuration); - }, 500); - - return apiResponse = { - type: resType, - response: { - responseData: isFile ? resp.data : responseData, - status: resp.status, - statusText: resp.statusText, - size: resp.data.byteLength, - duration: fetchDuration, - isError: false, - responseType: { - isBinaryFile: isFile, - format: getFileType(respHeaders) - } - }, - headers: respHeaders, - cookies: resCookies && resCookies.length > 0 ? resCookies : [], - }; - } - catch (err) { - writeLog("error::apiFetch(): " + err); - - apiResponse = getErrorResponse(); - - setTimeout(() => { - logDetails(request, reqHeaders, reqData, apiResponse.response.status, apiResponse.headers, err.message, fetchDuration); - }, 1000); - - if (axios.isCancel(err)) { - apiResponse.response.responseData = err.message; - } else { - apiResponse.response.responseData = err.message; - } - - return apiResponse; - } + const reqHeaders = {}; + let startTime: number, fetchDuration: number; + let reqData: any = ""; + let apiResponse: any; + + let request = updateAuthSettings(requestData, settings); + request = updateVariables(request, variableData); + + if (!reqSettings || reqSettings?.skipParentHeaders === false) { + request = updateHeaderSettings(request, settings); + } + + try { + if (request.auth.authType === "bearertoken") { + reqHeaders[fetchConfig.headersCase ? "Authorization" : "authorization"] = `${request.auth.tokenPrefix} ${request.auth.password}`; + } + + if (request.auth.authType === "oauth2") { + reqHeaders[fetchConfig.headersCase ? "Authorization" : "authorization"] = `${request.auth.tokenPrefix} ${request.auth.password}`; + } + + request.headers.forEach(({ isChecked, key, value }) => { + if (isChecked && key) { + reqHeaders[fetchConfig.headersCase ? key : key.toLocaleLowerCase()] = value; + } + }); + + if (request.body.bodyType === "formdata") { + const bodyFormData = new FormData(); + request.body.formdata.forEach(({ isChecked, key, value, type }) => { + if (isChecked && key) { + if (type === "File") { + if (!fs.existsSync(value)) { + throw new Error("Error : ENOENT: No such file or directory - " + value); + } + bodyFormData.append(key, fs.createReadStream(value)); + } else { + bodyFormData.append(key, value); + } + } + }); + reqData = bodyFormData; + } else if (request.body.bodyType === "formurlencoded") { + const bodyUrlEncoded = new URLSearchParams(); + request.body.urlencoded.forEach(({ isChecked, key, value }) => { + if (isChecked && key) { + bodyUrlEncoded.append(key, value); + } + }); + reqData = bodyUrlEncoded; + } else if (request.body.bodyType === "raw") { + reqData = request.body.raw.data; + } else if (request.body.bodyType === "binary") { + if (!request.body.binary.data) { + throw new Error("Error : ENOENT: No such file or directory - " + request.body.binary.fileName); + } + reqData = request.body.binary.data; + } else if (request.body.bodyType === "graphql") { + reqData = JSON.stringify({ + query: request.body.graphql.query, + variables: request.body.graphql.variables, + }); + } + + if (request.body.bodyType === "formdata") { + let header = reqData.getHeaders(); + reqHeaders[fetchConfig.headersCase ? "Content-Type" : "content-type"] = header["content-type"] ? header["content-type"] : getContentType(request.body.bodyType, ""); + } else { + if (request.body.bodyType !== "none" && !reqHeaders["Content-Type"] && !reqHeaders["content-type"]) { + reqHeaders[fetchConfig.headersCase ? "Content-Type" : "content-type"] = getContentType(request.body.bodyType, request.body.bodyType === "raw" ? request.body.raw.lang : ""); + } + } + + https.globalAgent.options.rejectUnauthorized = getSSLConfiguration(); + + axios.interceptors.request.use((config) => { + startTime = new Date().getTime(); + return config; + }); + + axios.interceptors.response.use((config) => { + fetchDuration = new Date().getTime() - startTime; + return config; + }); + + axios.defaults.withCredentials = true; + + let requestconfig: any; + let url = validateURL(request.url) ? request.url : getProtocolConfiguration() + "://" + request.url; + request.url = url; + + if (request.auth.authType === "aws") { + const baseRequest: awsRequest = { + host: getHost(url), + method: request.method.toUpperCase(), + path: getPath(url), + headers: reqHeaders + }; + + if (request.auth.aws.service) { + baseRequest.service = request.auth.aws.service; + } + + if (request.auth.aws.region) { + baseRequest.region = request.auth.aws.region; + } + + if (reqData) { + if (request.body.bodyType === "formdata") { + baseRequest.body = reqData.getBuffer(); + } else if (request.body.bodyType === "formurlencoded") { + baseRequest.body = JSON.stringify(reqData.toString()); + } else { + baseRequest.body = JSON.stringify(reqData); + } + } + + const signedRequest = sign(baseRequest, + { + secretAccessKey: request.auth.aws.secretAccessKey, + accessKeyId: request.auth.aws.accessKey, + sessionToken: request.auth.aws.sessionToken + }); + + if (signedRequest.headers) { + delete signedRequest.headers.Host; + delete signedRequest.headers['Content-Length']; + } + + requestconfig = { + ...signedRequest, + url: url, + data: reqData, + validateStatus: () => true, + transformResponse: [function (data) { return data; }], + timeout: fetchConfig.timeOut, + responseType: 'arraybuffer', + maxContentLength: Infinity, + maxBodyLength: Infinity, + }; + + } else { + requestconfig = { + url: url, + method: request.method, + headers: reqHeaders, + auth: request.auth.authType === "basic" ? { username: request.auth.userName, password: request.auth.password } : undefined, + data: reqData, + validateStatus: () => true, + transformResponse: [function (data) { return data; }], + timeout: fetchConfig.timeOut, + responseType: 'arraybuffer', + maxContentLength: Infinity, + maxBodyLength: Infinity, + }; + } + + if (fetchConfig.source) { + requestconfig.cancelToken = fetchConfig.source.token; + } + + const resp = await axios(requestconfig); + const respHeaders: ITableData[] = []; + const resCookies: ITableData[] = []; + let responseData: any; + let cookieData: any; + Object.entries(resp.headers).forEach(([key, value]) => { + if (key.trim().toLowerCase() === "set-cookie") { + cookieData = value; + } + respHeaders.push({ + isFixed: true, + key: key, + value: value.toString() + }); + }); + + let isFile = isFileType(respHeaders); + + if (!isFile) { + responseData = new Uint8Array(resp.data).reduce(function (data, byte) { + return data + String.fromCharCode(byte); + }, ''); + } + + if (cookieData) { + if (typeof cookieData === 'string') { + if (cookieData.includes(";")) { + Object.entries(cookieData.split(";")).forEach(([_key, value]) => { + let data = value.toString().trim(); + resCookies.push({ + isFixed: true, + isChecked: true, + key: data.substring(0, data.indexOf("=")), + value: data.substring(data.indexOf("=") + 1, data.length) + }); + }); + } + } else { + Object.entries(cookieData).forEach(([_key, value]) => { + let data = value.toString().trim(); + resCookies.push({ + isFixed: true, + isChecked: true, + key: data.substring(0, data.indexOf("=")), + value: data.substring(data.indexOf("=") + 1, data.length) + }); + }); + } + } + + setTimeout(() => { + logDetails(request, reqHeaders, reqData, resp.status, respHeaders, isFile ? "View Response is not supported for 'file' type in the log window." : responseData, fetchDuration); + }, 500); + + return apiResponse = { + type: resType, + response: { + responseData: isFile ? resp.data : responseData, + status: resp.status, + statusText: resp.statusText, + size: resp.data.byteLength, + duration: fetchDuration, + isError: false, + responseType: { + isBinaryFile: isFile, + format: getFileType(respHeaders) + } + }, + headers: respHeaders, + cookies: resCookies && resCookies.length > 0 ? resCookies : [], + }; + } + catch (err) { + writeLog("error::apiFetch(): " + err); + + apiResponse = getErrorResponse(); + + setTimeout(() => { + logDetails(request, reqHeaders, reqData, apiResponse.response.status, apiResponse.headers, err.message, fetchDuration); + }, 1000); + + if (axios.isCancel(err)) { + apiResponse.response.responseData = err.message; + } else { + apiResponse.response.responseData = err.message; + } + + return apiResponse; + } }; function getRawContentType(rawType: string): string { - let contentTypes = { - json: "application/json", - html: "text/html", - xml: "text/xml", - text: "text/plain" - }; - return contentTypes[rawType]; + let contentTypes = { + json: "application/json", + html: "text/html", + xml: "text/xml", + text: "text/plain" + }; + return contentTypes[rawType]; } function getContentType(type: string, rawLang: string) { - switch (type) { - case "formdata": - return "multipart/form-data; boundary=" + generateBoundryValue(); - case "formurlencoded": - return "application/x-www-form-urlencoded"; - case "raw": - return getRawContentType(rawLang); - case "graphql": - return "application/json"; - default: //binary - return "application/octet-stream"; - } + switch (type) { + case "formdata": + return "multipart/form-data; boundary=" + generateBoundryValue(); + case "formurlencoded": + return "application/x-www-form-urlencoded"; + case "raw": + return getRawContentType(rawLang); + case "graphql": + return "application/json"; + default: //binary + return "application/octet-stream"; + } } function generateBoundryValue() { - return "--------------------------" + getRandomNumber(25); + return "--------------------------" + getRandomNumber(25); } function validateURL(url: string): boolean { - if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0) { - return true; - } + if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0) { + return true; + } - return false; + return false; } function getHost(urlString: string) { - const url = new URL(urlString); - return url.host; + const url = new URL(urlString); + return url.host; } function getPath(urlString: string) { - const url = new URL(urlString); - return url.pathname; + const url = new URL(urlString); + return url.pathname; } diff --git a/src/utils/helper.ts b/src/utils/helper.ts index fb04769..b696fcd 100644 --- a/src/utils/helper.ts +++ b/src/utils/helper.ts @@ -5,315 +5,315 @@ import { ISettings } from "../fetch-client-ui/components/SideBar/redux/types"; import { responseTypes } from "./configuration"; export const MIMETypes = { - "audio/aac": "aac", - "application/x-abiword": "abw", - "application/x-freearc": "arc", - "image/avif": "avif", - "video/x-msvideo": "avi", - "application/vnd.amazon.ebook": "azw", - "application/octet-stream": "bin", - "image/bmp": "bmp", - "application/x-bzip": "bz", - "application/x-bzip2": "bz2", - "application/x-cdf": "cda", - "application/x-csh": "csh", - "text/css": "css", - "text/csv": "csv", - "application/msword": "doc", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx", - "application/vnd.ms-fontobject": "eot", - "application/epub+zip": "epub", - "application/gzip": "gz", - "image/gif": "gif", - "text/html": "html", - "image/vnd.microsoft.icon": "ico", - "text/calendar": "ics", - "application/java-archive": "jar", - "image/jpeg": "jpg", - "text/javascript": "javascript", - "application/json": "json", - "application/ld+json": "json", - "application/vnd.api+json": "json", - "audio/midi": "mid", - "audio/x-midi": "midi", - "audio/mpeg": "mp3", - "video/mp4": "mp4", - "video/mpeg": "mpeg", - "application/vnd.apple.installer+xml": "mpkg", - "application/vnd.oasis.opendocument.presentation": "odp", - "application/vnd.oasis.opendocument.spreadsheet": "ods", - "application/vnd.oasis.opendocument.text": "odt", - "audio/ogg": "oga", - "video/ogg": "ogv", - "application/ogg": "ogx", - "audio/opus": "opus", - "font/otf": "otf", - "image/png": "png", - "application/pdf": "pdf", - "application/x-httpd-php": "php", - "application/vnd.ms-powerpoint": "ppt", - "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx", - "application/vnd.rar": "rar", - "application/rtf": "rtf", - "application/x-sh": "sh", - "image/svg+xml": "svg", - "application/x-shockwave-flash": "swf", - "application/x-tar": "tar", - "image/tiff": "tif tiff", - "video/mp2t": "ts", - "font/ttf": "ttf", - "text/plain": "plaintext", - "application/vnd.visio": "vsd", - "audio/wav": "wav", - "audio/webm": "weba", - "video/webm": "webm", - "image/webp": "webp", - "font/woff": "woff", - "font/woff2": "woff2", - "application/xhtml+xml": "xhtml", - "application/vnd.ms-excel": "xls", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx", - "application/xml ": "xml", - "application/vnd.mozilla.xul+xml": "xul", - "application/zip": "zip", - "video/3gpp": "3gp", - "audio/3gpp": "3gp", - "video/3gpp2": "3g2", - "audio/3gpp2": "3g2", - "application/x-7z-compressed": "7z", + "audio/aac": "aac", + "application/x-abiword": "abw", + "application/x-freearc": "arc", + "image/avif": "avif", + "video/x-msvideo": "avi", + "application/vnd.amazon.ebook": "azw", + "application/octet-stream": "bin", + "image/bmp": "bmp", + "application/x-bzip": "bz", + "application/x-bzip2": "bz2", + "application/x-cdf": "cda", + "application/x-csh": "csh", + "text/css": "css", + "text/csv": "csv", + "application/msword": "doc", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx", + "application/vnd.ms-fontobject": "eot", + "application/epub+zip": "epub", + "application/gzip": "gz", + "image/gif": "gif", + "text/html": "html", + "image/vnd.microsoft.icon": "ico", + "text/calendar": "ics", + "application/java-archive": "jar", + "image/jpeg": "jpg", + "text/javascript": "javascript", + "application/json": "json", + "application/ld+json": "json", + "application/vnd.api+json": "json", + "audio/midi": "mid", + "audio/x-midi": "midi", + "audio/mpeg": "mp3", + "video/mp4": "mp4", + "video/mpeg": "mpeg", + "application/vnd.apple.installer+xml": "mpkg", + "application/vnd.oasis.opendocument.presentation": "odp", + "application/vnd.oasis.opendocument.spreadsheet": "ods", + "application/vnd.oasis.opendocument.text": "odt", + "audio/ogg": "oga", + "video/ogg": "ogv", + "application/ogg": "ogx", + "audio/opus": "opus", + "font/otf": "otf", + "image/png": "png", + "application/pdf": "pdf", + "application/x-httpd-php": "php", + "application/vnd.ms-powerpoint": "ppt", + "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx", + "application/vnd.rar": "rar", + "application/rtf": "rtf", + "application/x-sh": "sh", + "image/svg+xml": "svg", + "application/x-shockwave-flash": "swf", + "application/x-tar": "tar", + "image/tiff": "tif tiff", + "video/mp2t": "ts", + "font/ttf": "ttf", + "text/plain": "plaintext", + "application/vnd.visio": "vsd", + "audio/wav": "wav", + "audio/webm": "weba", + "video/webm": "webm", + "image/webp": "webp", + "font/woff": "woff", + "font/woff2": "woff2", + "application/xhtml+xml": "xhtml", + "application/vnd.ms-excel": "xls", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx", + "application/xml ": "xml", + "application/vnd.mozilla.xul+xml": "xul", + "application/zip": "zip", + "video/3gpp": "3gp", + "audio/3gpp": "3gp", + "video/3gpp2": "3g2", + "audio/3gpp2": "3g2", + "application/x-7z-compressed": "7z", }; export function isFileType(headers: ITableData[]): boolean { - let item = headers.filter(t => t.key.toLowerCase() === "content-type"); + let item = headers.filter(t => t.key.toLowerCase() === "content-type"); - if (item.length > 0) { - return checkType(item[0].value); - } + if (item.length > 0) { + return checkType(item[0].value); + } - return false; + return false; } function checkType(value: string): boolean { - if (value.toLowerCase().includes("application/json")) { - return false; - } - if (value.toLowerCase().includes("application/ld+json")) { - return false; - } - if (value.toLowerCase().includes("application/vnd.api+json")) { - return false; - } - if (value.toLowerCase().includes("application/xml")) { - return false; - } - if (value.toLowerCase().includes("text/javascript")) { - return false; - } - if (value.toLowerCase().includes("text/html")) { - return false; - } - if (value.toLowerCase().includes("text/css")) { - return false; - } - if (value.toLowerCase().includes("text/plain")) { - return false; - } - if (value.toLowerCase().includes("application/javascript")) { - return false; - } - - return true; + if (value.toLowerCase().includes("application/json")) { + return false; + } + if (value.toLowerCase().includes("application/ld+json")) { + return false; + } + if (value.toLowerCase().includes("application/vnd.api+json")) { + return false; + } + if (value.toLowerCase().includes("application/xml")) { + return false; + } + if (value.toLowerCase().includes("text/javascript")) { + return false; + } + if (value.toLowerCase().includes("text/html")) { + return false; + } + if (value.toLowerCase().includes("text/css")) { + return false; + } + if (value.toLowerCase().includes("text/plain")) { + return false; + } + if (value.toLowerCase().includes("application/javascript")) { + return false; + } + + return true; } export function getFileType(headers: ITableData[]) { - let type: string; - let item = headers.filter(t => t.key.toLowerCase() === "content-type"); - if (item.length > 0) { - if (item[0].value.includes(";")) { - type = MIMETypes[item[0].value.toLowerCase().split(";")[0].trim()]; - } else { - type = MIMETypes[item[0].value.toLowerCase().trim()]; - } - } - - return type ? type : ""; + let type: string; + let item = headers.filter(t => t.key.toLowerCase() === "content-type"); + if (item.length > 0) { + if (item[0].value.includes(";")) { + type = MIMETypes[item[0].value.toLowerCase().split(";")[0].trim()]; + } else { + type = MIMETypes[item[0].value.toLowerCase().trim()]; + } + } + + return type ? type : ""; } export function formatDate(value?: string) { - let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - let t = value ? new Date(value) : new Date(); - let date = ("0" + t.getDate()).slice(-2); - let timeFormat = ("0" + t.getHours()).slice(-2) + ":" + ("0" + t.getMinutes()).slice(-2) + ":" + ("0" + t.getSeconds()).slice(-2); + let t = value ? new Date(value) : new Date(); + let date = ("0" + t.getDate()).slice(-2); + let timeFormat = ("0" + t.getHours()).slice(-2) + ":" + ("0" + t.getMinutes()).slice(-2) + ":" + ("0" + t.getSeconds()).slice(-2); - return date + "-" + months[t.getMonth()] + "-" + t.getFullYear() + " " + timeFormat; + return date + "-" + months[t.getMonth()] + "-" + t.getFullYear() + " " + timeFormat; } export function formatDateWithMs(value?: string) { - let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - let t = value ? new Date(value) : new Date(); - let date = ("0" + t.getDate()).slice(-2); - let timeFormat = ("0" + t.getHours()).slice(-2) + ":" + ("0" + t.getMinutes()).slice(-2) + ":" + ("0" + t.getSeconds()).slice(-2) + ":" + ("0" + t.getMilliseconds()).slice(-4); + let t = value ? new Date(value) : new Date(); + let date = ("0" + t.getDate()).slice(-2); + let timeFormat = ("0" + t.getHours()).slice(-2) + ":" + ("0" + t.getMinutes()).slice(-2) + ":" + ("0" + t.getSeconds()).slice(-2) + ":" + ("0" + t.getMilliseconds()).slice(-4); - return date + "-" + months[t.getMonth()] + "-" + t.getFullYear() + " " + timeFormat; + return date + "-" + months[t.getMonth()] + "-" + t.getFullYear() + " " + timeFormat; } export function replaceValueWithVariable(request: IRequestModel, varData: any): IRequestModel { - request.url = replaceDataWithVariable(request.url, varData); - if (request.params.filter(item => item.isChecked).length > 0) { - request.params = replaceTableDataWithVariable(request.params, varData); - } - - if (request.headers.filter(item => item.isChecked).length > 0) { - request.headers = replaceTableDataWithVariable(request.headers, varData); - } - - request.auth.userName = replaceDataWithVariable(request.auth.userName, varData); - request.auth.password = replaceDataWithVariable(request.auth.password, varData); - request.auth.tokenPrefix = replaceDataWithVariable(request.auth.tokenPrefix, varData); - - if (request.auth.aws) { - request.auth.aws.accessKey = replaceDataWithVariable(request.auth.aws.accessKey, varData); - request.auth.aws.secretAccessKey = replaceDataWithVariable(request.auth.aws.secretAccessKey, varData); - request.auth.aws.service = replaceDataWithVariable(request.auth.aws.service, varData); - request.auth.aws.region = replaceDataWithVariable(request.auth.aws.region, varData); - request.auth.aws.sessionToken = replaceDataWithVariable(request.auth.aws.sessionToken, varData); - } - - if (request.body.bodyType === "formurlencoded" && request.body.urlencoded.filter(item => item.isChecked).length > 0) { - request.body.urlencoded = replaceTableDataWithVariable(request.body.urlencoded, varData); - } - - if (request.body.bodyType === "formdata" && request.body.formdata.filter(item => item.isChecked).length > 0) { - request.body.formdata = replaceTableDataWithVariable(request.body.formdata, varData); - } - - if (request.body.bodyType === "raw") { - request.body.raw.data = replaceDataWithVariable(request.body.raw.data, varData); - } - - if (request.body.bodyType === "graphql") { - request.body.graphql.query = replaceDataWithVariable(request.body.graphql.query, varData); - request.body.graphql.variables = replaceDataWithVariable(request.body.graphql.variables, varData); - } - - return request; + request.url = replaceDataWithVariable(request.url, varData); + if (request.params.filter(item => item.isChecked).length > 0) { + request.params = replaceTableDataWithVariable(request.params, varData); + } + + if (request.headers.filter(item => item.isChecked).length > 0) { + request.headers = replaceTableDataWithVariable(request.headers, varData); + } + + request.auth.userName = replaceDataWithVariable(request.auth.userName, varData); + request.auth.password = replaceDataWithVariable(request.auth.password, varData); + request.auth.tokenPrefix = replaceDataWithVariable(request.auth.tokenPrefix, varData); + + if (request.auth.aws) { + request.auth.aws.accessKey = replaceDataWithVariable(request.auth.aws.accessKey, varData); + request.auth.aws.secretAccessKey = replaceDataWithVariable(request.auth.aws.secretAccessKey, varData); + request.auth.aws.service = replaceDataWithVariable(request.auth.aws.service, varData); + request.auth.aws.region = replaceDataWithVariable(request.auth.aws.region, varData); + request.auth.aws.sessionToken = replaceDataWithVariable(request.auth.aws.sessionToken, varData); + } + + if (request.body.bodyType === "formurlencoded" && request.body.urlencoded.filter(item => item.isChecked).length > 0) { + request.body.urlencoded = replaceTableDataWithVariable(request.body.urlencoded, varData); + } + + if (request.body.bodyType === "formdata" && request.body.formdata.filter(item => item.isChecked).length > 0) { + request.body.formdata = replaceTableDataWithVariable(request.body.formdata, varData); + } + + if (request.body.bodyType === "raw") { + request.body.raw.data = replaceDataWithVariable(request.body.raw.data, varData); + } + + if (request.body.bodyType === "graphql") { + request.body.graphql.query = replaceDataWithVariable(request.body.graphql.query, varData); + request.body.graphql.variables = replaceDataWithVariable(request.body.graphql.variables, varData); + } + + return request; } export function replaceAuthSettingsInRequest(request: IRequestModel, settings: ISettings): IRequestModel { - if (settings.auth) { - request.auth.authType = settings.auth.authType; - request.auth.userName = settings.auth.userName; - request.auth.password = settings.auth.password; - request.auth.tokenPrefix = settings.auth.tokenPrefix; - if (request.auth.aws) { - request.auth.aws.accessKey = settings.auth.aws.accessKey; - request.auth.aws.secretAccessKey = settings.auth.aws.secretAccessKey; - request.auth.aws.service = settings.auth.aws.service; - request.auth.aws.region = settings.auth.aws.region; - request.auth.aws.sessionToken = settings.auth.aws.sessionToken; - } - } - - return request; + if (settings.auth) { + request.auth.authType = settings.auth.authType; + request.auth.userName = settings.auth.userName; + request.auth.password = settings.auth.password; + request.auth.tokenPrefix = settings.auth.tokenPrefix; + if (request.auth.aws) { + request.auth.aws.accessKey = settings.auth.aws.accessKey; + request.auth.aws.secretAccessKey = settings.auth.aws.secretAccessKey; + request.auth.aws.service = settings.auth.aws.service; + request.auth.aws.region = settings.auth.aws.region; + request.auth.aws.sessionToken = settings.auth.aws.sessionToken; + } + } + + return request; } export function replaceHeaderSettingsInRequest(request: IRequestModel, settings: ISettings): IRequestModel { - if (settings.headers) { - settings.headers.forEach((header) => { - if (header.isChecked && header.key) { - let index = request.headers.findIndex(item => (item.key.toLowerCase() === header.key.toLowerCase()) && item.isChecked); - if (index === -1) { - request.headers.push(header); - } - } - }); - } - - return request; + if (settings.headers) { + settings.headers.forEach((header) => { + if (header.isChecked && header.key) { + let index = request.headers.findIndex(item => (item.key.toLowerCase() === header.key.toLowerCase()) && item.isChecked); + if (index === -1) { + request.headers.push(header); + } + } + }); + } + + return request; } function replaceTableDataWithVariable(data: ITableData[], varData: any) { - const re = new RegExp("({{([^}}]+)}})"); - data.forEach(item => { - if (re.test(item.key)) { - let ptn = item.key.match(/({{([^}}]+)}})/gm); - ptn?.forEach(p => { - item.key = updateVariable(p, item.key, varData); - }); - } - - if (re.test(item.value)) { - let ptn = item.value.match(/({{([^}}]+)}})/gm); - ptn?.forEach(p => { - item.value = updateVariable(p, item.value, varData); - }); - } - }); - - return data; + const re = new RegExp("({{([^}}]+)}})"); + data.forEach(item => { + if (re.test(item.key)) { + let ptn = item.key.match(/({{([^}}]+)}})/gm); + ptn?.forEach(p => { + item.key = updateVariable(p, item.key, varData); + }); + } + + if (re.test(item.value)) { + let ptn = item.value.match(/({{([^}}]+)}})/gm); + ptn?.forEach(p => { + item.value = updateVariable(p, item.value, varData); + }); + } + }); + + return data; } export function replaceDataWithVariable(data: string, varData: any) { - if (checkVariableMatch(data)) { - let ptn = data.match(/({{([^}}]+)}})/gm); - ptn?.forEach(item => { - data = updateVariable(item, data, varData); - }); - } - - return data; + if (checkVariableMatch(data)) { + let ptn = data.match(/({{([^}}]+)}})/gm); + ptn?.forEach(item => { + data = updateVariable(item, data, varData); + }); + } + + return data; } function updateVariable(item: string, data: string, varData: any) { - if (item.includes("{{#") && item.includes("}}")) { - let variable = checkSysVariable(item); - if (variable) { - let value = getSysVariableWithValue(variable); - data = data.replace(item, value?.toString()); - } - } else { - if (varData && Object.keys(varData).length > 0) { - let replacedValue = varData[item.replace("{{", "").replace("}}", "")]; - if (replacedValue && checkVariableMatch(replacedValue)) { - data = data.replace(item, replaceDataWithVariable(replacedValue, varData)); - } else { - data = data.replace(item, varData[item.replace("{{", "").replace("}}", "")]); - } - } - } - - return data; + if (item.includes("{{#") && item.includes("}}")) { + let variable = checkSysVariable(item); + if (variable) { + let value = getSysVariableWithValue(variable); + data = data.replace(item, value?.toString()); + } + } else { + if (varData && Object.keys(varData).length > 0) { + let replacedValue = varData[item.replace("{{", "").replace("}}", "")]; + if (replacedValue && checkVariableMatch(replacedValue)) { + data = data.replace(item, replaceDataWithVariable(replacedValue, varData)); + } else { + data = data.replace(item, varData[item.replace("{{", "").replace("}}", "")]); + } + } + } + + return data; } function checkVariableMatch(data: string): boolean { - const re = new RegExp("({{([^}}]+)}})"); - return re.test(data); + const re = new RegExp("({{([^}}]+)}})"); + return re.test(data); } export function getRandomNumber(digit: number) { - return Math.random().toFixed(digit).split('.')[1]; + return Math.random().toFixed(digit).split('.')[1]; } export function getErrorResponse() { - return { - type: responseTypes.apiResponse, - response: { - responseData: "", - status: 0, - statusText: "", - size: "0", - duration: 0, - isError: true, - responseType: { - isBinaryFile: false, - format: "" - } - }, - headers: [], - cookies: [] - }; -} \ No newline at end of file + return { + type: responseTypes.apiResponse, + response: { + responseData: "", + status: 0, + statusText: "", + size: "0", + duration: 0, + isError: true, + responseType: { + isBinaryFile: false, + format: "" + } + }, + headers: [], + cookies: [] + }; +} diff --git a/src/utils/importers/fetchClient/fetchClientImporter_1_0.ts b/src/utils/importers/fetchClient/fetchClientImporter_1_0.ts index b8df233..891497a 100644 --- a/src/utils/importers/fetchClient/fetchClientImporter_1_0.ts +++ b/src/utils/importers/fetchClient/fetchClientImporter_1_0.ts @@ -7,88 +7,88 @@ import { formatDate } from "../../helper"; import { writeLog } from "../../logger/logger"; export const fetchClientImporter = (parsedData: any): { fcCollection: ICollections, fcRequests: IRequestModel[] } | null => { - try { - let reqData = []; + try { + let reqData = []; - let colData: ICollections = { - id: uuidv4(), - name: parsedData.name, - createdTime: formatDate(), - variableId: "", - data: [], - settings: parsedData.settings ? parsedData.settings : JSON.parse(JSON.stringify(InitialSettings)) - }; + let colData: ICollections = { + id: uuidv4(), + name: parsedData.name, + createdTime: formatDate(), + variableId: "", + data: [], + settings: parsedData.settings ? parsedData.settings : JSON.parse(JSON.stringify(InitialSettings)) + }; - let importedData = parsedData.data; + let importedData = parsedData.data; - importedData.forEach(item => { - item.id = uuidv4(); - item.createdTime = formatDate(); - if (isFolder(item)) { - let importData: any; - let folder: IFolder = { - id: uuidv4(), - name: item.name, - createdTime: formatDate(), - type: "folder", - data: [], - settings: item.settings ? item.settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - ({ importData, reqData } = ImportFolder(item, folder, reqData)); - colData.data.push(importData); - } else { - item.id = uuidv4(); - item.createdTime = formatDate(); - reqData.push(item); - let his: IHistory = { - id: item.id, - method: item.method, - name: item.name, - url: item.url, - createdTime: formatDate() - }; - colData.data.push(his); - } - }); + importedData.forEach(item => { + item.id = uuidv4(); + item.createdTime = formatDate(); + if (isFolder(item)) { + let importData: any; + let folder: IFolder = { + id: uuidv4(), + name: item.name, + createdTime: formatDate(), + type: "folder", + data: [], + settings: item.settings ? item.settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + ({ importData, reqData } = ImportFolder(item, folder, reqData)); + colData.data.push(importData); + } else { + item.id = uuidv4(); + item.createdTime = formatDate(); + reqData.push(item); + let his: IHistory = { + id: item.id, + method: item.method, + name: item.name, + url: item.url, + createdTime: formatDate() + }; + colData.data.push(his); + } + }); - return { - fcCollection: colData, - fcRequests: reqData - }; + return { + fcCollection: colData, + fcRequests: reqData + }; - } catch (err) { - writeLog("error::fetchClientImporter(): - Error Message : " + err); - return null; - } + } catch (err) { + writeLog("error::fetchClientImporter(): - Error Message : " + err); + return null; + } }; function ImportFolder(source: any, importData: any, reqData: any): any { - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - let folder: IFolder = { - id: uuidv4(), - name: source.data[i].name, - createdTime: formatDate(), - type: "folder", - data: [], - settings: source.data[i].settings ? source.data[i].settings : JSON.parse(JSON.stringify(InitialSettings)) - }; - let result = ImportFolder(source.data[i], folder, reqData); - importData.data.push(result.importData); - } else { - source.data[i].id = uuidv4(); - source.data[i].createdTime = formatDate(); - let his: IHistory = { - id: source.data[i].id, - method: source.data[i].method, - name: source.data[i].name, - url: source.data[i].url, - createdTime: source.data[i].createdTime - }; - reqData.push(source.data[i]); - importData.data.push(his); - } - } + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + let folder: IFolder = { + id: uuidv4(), + name: source.data[i].name, + createdTime: formatDate(), + type: "folder", + data: [], + settings: source.data[i].settings ? source.data[i].settings : JSON.parse(JSON.stringify(InitialSettings)) + }; + let result = ImportFolder(source.data[i], folder, reqData); + importData.data.push(result.importData); + } else { + source.data[i].id = uuidv4(); + source.data[i].createdTime = formatDate(); + let his: IHistory = { + id: source.data[i].id, + method: source.data[i].method, + name: source.data[i].name, + url: source.data[i].url, + createdTime: source.data[i].createdTime + }; + reqData.push(source.data[i]); + importData.data.push(his); + } + } - return { importData, reqData }; + return { importData, reqData }; } diff --git a/src/utils/importers/postman/postmanImporter_2_1.ts b/src/utils/importers/postman/postmanImporter_2_1.ts index fab4489..fe5b1ee 100644 --- a/src/utils/importers/postman/postmanImporter_2_1.ts +++ b/src/utils/importers/postman/postmanImporter_2_1.ts @@ -11,459 +11,461 @@ import { writeLog } from "../../logger/logger"; import { Auth, Body, Header, Items, POSTMAN_SCHEMA_V2_1, PostmanSchema_2_1, RequestObject, URLObject, Variable } from "./postman_2_1.types"; export class PostmanImport { - private collection: PostmanSchema_2_1; - - constructor(collection: PostmanSchema_2_1) { - this.collection = collection; - } - - importVariable = (variables: Variable[], name: string): IVariable => { - if (variables?.length === 0) { - return null; - } - - let varData: ITableData[] = []; - for (let i = 0; i < variables.length; i++) { - const key = variables[i].key; - if (key === undefined) { - continue; - } - varData.push({ - isChecked: variables[i].disabled === true ? false : true, - key: key, - value: variables[i].value - }); - } - return { - id: uuidv4(), - name: name, - createdTime: formatDate(), - isActive: true, - data: varData - }; - }; - - getUrl = (url?: URLObject | string) => { - if (!url) { - return ""; - } - - if (typeof url === "object" && url.raw) { - return url.raw; - } - - if (typeof url === "string") { - return url; - } - return ""; - }; - - getParams = (url?: URLObject | string): ITableData[] => { - let fcParams: ITableData[] = []; - - if (url && typeof url === "object" && url.query) { - url.query.forEach(item => { - fcParams.push({ - key: item.key, - value: item.value, - isChecked: item.disabled === true ? false : true - }); - }); - } - return [...fcParams, { - isChecked: false, - key: "", - value: "" - }]; - }; - - getHeders = (headers: Header[] | string): ITableData[] => { - let fcHeaders: ITableData[] = []; - if (headers && typeof headers !== "string") { - (headers as Header[]).forEach(item => { - fcHeaders.push({ - key: item.key, - value: item.value, - isChecked: item.disabled === true ? false : true - }); - }); - } - - return [...fcHeaders, { - isChecked: false, - key: "", - value: "" - }]; - }; - - getAuthDetails = (auth?: Auth | null): IAuth => { - - let fcAuth: IAuth = JSON.parse(JSON.stringify(InitialAuth)); - - if (!auth) { - fcAuth.authType = "inherit"; - return fcAuth; - } - - switch (auth.type) { - case "awsv4": - if (!auth.awsv4) { - return fcAuth; - } - - fcAuth.aws.accessKey = this.findValueByKey(auth.awsv4, "accessKey"); - fcAuth.aws.secretAccessKey = this.findValueByKey(auth.awsv4, "secretKey"); - fcAuth.aws.service = this.findValueByKey(auth.awsv4, "service"); - fcAuth.aws.sessionToken = this.findValueByKey(auth.awsv4, "sessionToken"); - fcAuth.aws.region = this.findValueByKey(auth.awsv4, "region"); - fcAuth.authType = "aws"; - - return fcAuth; - - - case "basic": - if (!auth.basic) { - return fcAuth; - } - - fcAuth.userName = this.findValueByKey(auth.basic, "username"); - fcAuth.password = this.findValueByKey(auth.basic, "password"); - fcAuth.authType = "basic"; - - return fcAuth; - - case "apikey": - if (!auth.apikey) { - return fcAuth; - } - - fcAuth.userName = this.findValueByKey(auth.apikey, "key"); - fcAuth.password = this.findValueByKey(auth.apikey, "value"); - let addToSection = this.findValueByKey(auth.apikey, "in"); - fcAuth.addTo = addToSection === "query" ? "queryparams" : "header"; - fcAuth.authType = "apikey"; - - return fcAuth; - - case "bearer": - if (!auth.bearer) { - return fcAuth; - } - - fcAuth.password = this.findValueByKey(auth.bearer, "token"); - fcAuth.tokenPrefix = "Bearer"; - fcAuth.authType = "bearertoken"; - - return fcAuth; - - case "oauth2": - if (!auth.oauth2) { - return fcAuth; - } - - let grantType = this.findValueByKey(auth.oauth2, "grant_type"); - - if (grantType !== "client_credentials" && grantType !== "password_credentials") { - return fcAuth; - } - - let clientAuth = this.findValueByKey(auth.oauth2, "client_authentication"); - fcAuth.oauth.clientAuth = clientAuth === "body" ? ClientAuth.Body : ClientAuth.Header; - fcAuth.oauth.clientId = this.findValueByKey(auth.oauth2, "clientId"); - fcAuth.oauth.clientSecret = this.findValueByKey(auth.oauth2, "clientSecret"); - fcAuth.oauth.grantType = grantType === "client_credentials" ? GrantType.Client_Crd : GrantType.PWD_Crd; - fcAuth.oauth.password = this.findValueByKey(auth.oauth2, "password"); - fcAuth.oauth.username = this.findValueByKey(auth.oauth2, "username"); - fcAuth.oauth.scope = this.findValueByKey(auth.oauth2, "scope"); - fcAuth.oauth.tokenUrl = this.findValueByKey(auth.oauth2, "accessTokenUrl"); - - let resource = this.findObjectByKey(auth.oauth2, "resource"); - let key = resource ? Object.keys(resource)[0] : ""; - fcAuth.oauth.advancedOpt.resource = resource && key ? resource[key] : ""; - let audience = this.findObjectByKey(auth.oauth2, "audience"); - key = audience ? Object.keys(audience)[0] : ""; - fcAuth.oauth.advancedOpt.audience = audience && key ? audience[key] : ""; - - fcAuth.authType = "oauth2"; - - return fcAuth; - - default: - return fcAuth; - } - }; - - getSrc = (src: any[] | null | string): string => { - if (!src) { - return ""; - } - - if (typeof src === "string") { - return src.length > 1 ? src.substring(1) : src; - } - - if (typeof src === "object") { - return src.length > 0 ? src[0].length > 1 ? src[0].substring(1) : src[0] : ""; - } - }; - - getBody = (body: Body): IBodyData => { - - let fcBody = JSON.parse(JSON.stringify(InitialBody)); - - if (!body) { - return fcBody; - } - - switch (body.mode) { - case 'formdata': - fcBody.bodyType = "formdata"; - fcBody.formdata.shift(); - body.formdata?.forEach(item => { - fcBody.formdata.push({ - isChecked: item.disabled === true ? false : true, - key: item.key, - value: item.type === "file" ? this.getSrc(item.src) : item.value, - type: item.type === "file" ? "File" : "Text" - }); - }); - - fcBody.formdata.push({ - isChecked: false, - key: "", - value: "", - type: "Text" - }); - - return fcBody; - - case 'urlencoded': - fcBody.bodyType = "formurlencoded"; - fcBody.urlencoded.shift(); - body.urlencoded?.forEach(item => { - fcBody.urlencoded.push({ - isChecked: item.disabled === true ? false : true, - key: item.key, - value: item.value - }); - }); - - fcBody.urlencoded.push({ - isChecked: false, - key: "", - value: "" - }); - - return fcBody; - - case 'graphql': - fcBody.bodyType = "graphql"; - fcBody.graphql.query = JSON.stringify(body.graphql.query); - fcBody.graphql.variables = JSON.stringify(body.graphql.variables); - return fcBody; - - case 'raw': - fcBody.bodyType = "raw"; - fcBody.raw.data = body.raw; - fcBody.raw.lang = this.getRawBodyType(body.raw.replace(/(?:\\[rn]|[\r\n]+)+/g, "")); - return fcBody; - - case 'file': - fcBody.bodyType = "binary"; - fcBody.binary.data = body.file.content; - fcBody.binary.fileName = body.file.src.substring(1); - fcBody.binary.contentTypeOption = "manual"; - return fcBody; - - default: - return fcBody; - } - }; - - getRawBodyType = (data: string): string => { - if (isJson(data) === "true") { - return "json"; - } - if (XMLValidator.validate(data) === true) { - return "xml"; - } - if (this.isHTML(data)) { - return "html"; - } - return "text"; - }; - - isHTML = (str: string) => !(str || '') - // replace html tag with content - .replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, '') - // remove remaining self closing tags - .replace(/(<([^>]+)>)/ig, '') - // remove extra space at start and end - .trim(); - - findValueByKey = (array?: T[], key?: string,) => { - if (!array) { - return ""; - } - - const obj = array.find(o => o.key === key); - - if (obj && typeof obj.value === "string") { - return obj.value || ""; - } - - return ""; - }; - - findObjectByKey = (array?: T[], key?: string,) => { - if (!array) { - return ""; - } - - const obj = array.find(o => o.key === key); - - if (obj && typeof obj.value === "object") { - return obj.value || undefined; - } - - return {}; - }; - - getHistoryItem = (i: Items, req: IRequestModel[]): IHistory => { - let history: IHistory = { - id: uuidv4(), - name: i.name, - method: (i.request as RequestObject).method, - url: this.getUrl((i.request as RequestObject).url), - createdTime: formatDate() - }; - - let reqObject = i.request as RequestObject; - - if (reqObject) { - let request: IRequestModel = { - id: history.id, - url: history.url, - name: history.name, - createdTime: history.createdTime, - method: history.method as MethodType, - params: this.getParams(reqObject.url), - auth: this.getAuthDetails(reqObject.auth), - headers: this.getHeders(reqObject.header), - body: this.getBody(reqObject.body), - tests: JSON.parse(JSON.stringify(InitialTest)), - setvar: JSON.parse(JSON.stringify(InitialSetVar)), - notes: "", - preFetch: JSON.parse(JSON.stringify(InitialPreFetch)) - }; - - req.push(request); - } - - return history; - }; - - getFolderItem = (items: Items[], requests: IRequestModel[]) => { - return items.map((i: Items) => { - if (Object.prototype.hasOwnProperty.call(i, "request")) { - return this.getHistoryItem(i, requests); - - } else { - let folder: IFolder = { - id: uuidv4(), - name: i.name, - type: "folder", - createdTime: formatDate(), - data: i.item.reduce((accumulator: (IHistory | IFolder)[], item: Items) => { - if (Object.prototype.hasOwnProperty.call(item, "request")) { - return [...accumulator, this.getHistoryItem(item, requests)]; - } - - const requestGroup = this.importFolderItem(item, requests); - return [...accumulator, requestGroup]; - }, []), - settings: JSON.parse(JSON.stringify(InitialSettings)) - }; - return folder; - } - }); - }; - - importFolderItem = (item: Items, requests: IRequestModel[]): IFolder => { - return { - id: uuidv4(), - name: item.name, - type: "folder", - createdTime: formatDate(), - data: this.getFolderItem(item.item, requests), - settings: this.importSettings(item.auth) - }; - }; - - importSettings = (auth: Auth | undefined | null): ISettings => { - let settings: ISettings = { - auth: this.getAuthDetails(auth), - preFetch: { - requests: [] - }, - headers: [{ - key: "User-Agent", - value: "Fetch Client", - isChecked: true, - }, { - key: "", - value: "", - isChecked: false, - }] - }; - - return settings; - }; - - importCollection = (): { fcCollection: ICollections, fcRequests: IRequestModel[], fcVariable: IVariable } => { - const variable = this.importVariable(this.collection.variable || [], this.collection.info.name); - - let requests: IRequestModel[] = []; - - let collection: ICollections = { - id: uuidv4(), - name: this.collection.info.name, - createdTime: formatDate(), - variableId: variable ? variable.id : "", - data: [], - settings: this.importSettings(this.collection.auth) - }; - - let data = this.collection.item.reduce((accumulator: (IHistory | IFolder)[], item: Items) => { - if (Object.prototype.hasOwnProperty.call(item, "request")) { - return [...accumulator, this.getHistoryItem(item, requests)]; - } - - const requestGroup = this.importFolderItem(item, requests); - return [...accumulator, requestGroup]; - }, []); - - collection.data = data; - - return { - fcCollection: collection, - fcRequests: requests, - fcVariable: variable - }; - }; + private collection: PostmanSchema_2_1; + + constructor(collection: PostmanSchema_2_1) { + this.collection = collection; + } + + importVariable = (variables: Variable[], name: string): IVariable => { + if (variables?.length === 0) { + return null; + } + + let varData: ITableData[] = []; + for (let i = 0; i < variables.length; i++) { + const key = variables[i].key; + if (key === undefined) { + continue; + } + varData.push({ + isChecked: variables[i].disabled === true ? false : true, + key: key, + value: variables[i].value + }); + } + return { + id: uuidv4(), + name: name, + createdTime: formatDate(), + isActive: true, + data: varData + }; + }; + + getUrl = (url?: URLObject | string) => { + if (!url) { + return ""; + } + + if (typeof url === "object" && url.raw) { + return url.raw; + } + + if (typeof url === "string") { + return url; + } + return ""; + }; + + getParams = (url?: URLObject | string): ITableData[] => { + let fcParams: ITableData[] = []; + + if (url && typeof url === "object" && url.query) { + url.query.forEach(item => { + fcParams.push({ + key: item.key, + value: item.value, + isChecked: item.disabled === true ? false : true + }); + }); + } + return [...fcParams, { + isChecked: false, + key: "", + value: "" + }]; + }; + + getHeders = (headers: Header[] | string): ITableData[] => { + let fcHeaders: ITableData[] = []; + if (headers && typeof headers !== "string") { + (headers as Header[]).forEach(item => { + fcHeaders.push({ + key: item.key, + value: item.value, + isChecked: item.disabled === true ? false : true + }); + }); + } + + return [...fcHeaders, { + isChecked: false, + key: "", + value: "" + }]; + }; + + getAuthDetails = (auth?: Auth | null): IAuth => { + + let fcAuth: IAuth = JSON.parse(JSON.stringify(InitialAuth)); + + if (!auth) { + fcAuth.authType = "inherit"; + return fcAuth; + } + + switch (auth.type) { + case "awsv4": + if (!auth.awsv4) { + return fcAuth; + } + + fcAuth.aws.accessKey = this.findValueByKey(auth.awsv4, "accessKey"); + fcAuth.aws.secretAccessKey = this.findValueByKey(auth.awsv4, "secretKey"); + fcAuth.aws.service = this.findValueByKey(auth.awsv4, "service"); + fcAuth.aws.sessionToken = this.findValueByKey(auth.awsv4, "sessionToken"); + fcAuth.aws.region = this.findValueByKey(auth.awsv4, "region"); + fcAuth.authType = "aws"; + + return fcAuth; + + + case "basic": + if (!auth.basic) { + return fcAuth; + } + + fcAuth.userName = this.findValueByKey(auth.basic, "username"); + fcAuth.password = this.findValueByKey(auth.basic, "password"); + fcAuth.authType = "basic"; + + return fcAuth; + + case "apikey": + if (!auth.apikey) { + return fcAuth; + } + + fcAuth.userName = this.findValueByKey(auth.apikey, "key"); + fcAuth.password = this.findValueByKey(auth.apikey, "value"); + let addToSection = this.findValueByKey(auth.apikey, "in"); + fcAuth.addTo = addToSection === "query" ? "queryparams" : "header"; + fcAuth.authType = "apikey"; + + return fcAuth; + + case "bearer": + if (!auth.bearer) { + return fcAuth; + } + + fcAuth.password = this.findValueByKey(auth.bearer, "token"); + fcAuth.tokenPrefix = "Bearer"; + fcAuth.authType = "bearertoken"; + + return fcAuth; + + case "oauth2": + if (!auth.oauth2) { + return fcAuth; + } + + let grantType = this.findValueByKey(auth.oauth2, "grant_type"); + + if (grantType !== "client_credentials" && grantType !== "password_credentials") { + return fcAuth; + } + + let clientAuth = this.findValueByKey(auth.oauth2, "client_authentication"); + fcAuth.oauth.clientAuth = clientAuth === "body" ? ClientAuth.Body : ClientAuth.Header; + fcAuth.oauth.clientId = this.findValueByKey(auth.oauth2, "clientId"); + fcAuth.oauth.clientSecret = this.findValueByKey(auth.oauth2, "clientSecret"); + fcAuth.oauth.grantType = grantType === "client_credentials" ? GrantType.Client_Crd : GrantType.PWD_Crd; + fcAuth.oauth.password = this.findValueByKey(auth.oauth2, "password"); + fcAuth.oauth.username = this.findValueByKey(auth.oauth2, "username"); + fcAuth.oauth.scope = this.findValueByKey(auth.oauth2, "scope"); + fcAuth.oauth.tokenUrl = this.findValueByKey(auth.oauth2, "accessTokenUrl"); + + let resource = this.findObjectByKey(auth.oauth2, "resource"); + let key = resource ? Object.keys(resource)[0] : ""; + fcAuth.oauth.advancedOpt.resource = resource && key ? resource[key] : ""; + let audience = this.findObjectByKey(auth.oauth2, "audience"); + key = audience ? Object.keys(audience)[0] : ""; + fcAuth.oauth.advancedOpt.audience = audience && key ? audience[key] : ""; + + fcAuth.authType = "oauth2"; + + return fcAuth; + + default: + return fcAuth; + } + }; + + getSrc = (src: any[] | null | string): string => { + if (!src) { + return ""; + } + + if (typeof src === "string") { + return src.length > 1 ? src.substring(1) : src; + } + + if (typeof src === "object") { + return src.length > 0 ? src[0].length > 1 ? src[0].substring(1) : src[0] : ""; + } + + return ""; + }; + + getBody = (body: Body): IBodyData => { + + let fcBody = JSON.parse(JSON.stringify(InitialBody)); + + if (!body) { + return fcBody; + } + + switch (body.mode) { + case 'formdata': + fcBody.bodyType = "formdata"; + fcBody.formdata.shift(); + body.formdata?.forEach(item => { + fcBody.formdata.push({ + isChecked: item.disabled === true ? false : true, + key: item.key, + value: item.type === "file" ? this.getSrc(item.src) : item.value, + type: item.type === "file" ? "File" : "Text" + }); + }); + + fcBody.formdata.push({ + isChecked: false, + key: "", + value: "", + type: "Text" + }); + + return fcBody; + + case 'urlencoded': + fcBody.bodyType = "formurlencoded"; + fcBody.urlencoded.shift(); + body.urlencoded?.forEach(item => { + fcBody.urlencoded.push({ + isChecked: item.disabled === true ? false : true, + key: item.key, + value: item.value + }); + }); + + fcBody.urlencoded.push({ + isChecked: false, + key: "", + value: "" + }); + + return fcBody; + + case 'graphql': + fcBody.bodyType = "graphql"; + fcBody.graphql.query = JSON.stringify(body.graphql.query); + fcBody.graphql.variables = JSON.stringify(body.graphql.variables); + return fcBody; + + case 'raw': + fcBody.bodyType = "raw"; + fcBody.raw.data = body.raw; + fcBody.raw.lang = this.getRawBodyType(body.raw.replace(/(?:\\[rn]|[\r\n]+)+/g, "")); + return fcBody; + + case 'file': + fcBody.bodyType = "binary"; + fcBody.binary.data = body.file.content; + fcBody.binary.fileName = body.file.src.substring(1); + fcBody.binary.contentTypeOption = "manual"; + return fcBody; + + default: + return fcBody; + } + }; + + getRawBodyType = (data: string): string => { + if (isJson(data) === "true") { + return "json"; + } + if (XMLValidator.validate(data) === true) { + return "xml"; + } + if (this.isHTML(data)) { + return "html"; + } + return "text"; + }; + + isHTML = (str: string) => !(str || '') + // replace html tag with content + .replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, '') + // remove remaining self closing tags + .replace(/(<([^>]+)>)/ig, '') + // remove extra space at start and end + .trim(); + + findValueByKey = (array?: T[], key?: string,) => { + if (!array) { + return ""; + } + + const obj = array.find(o => o.key === key); + + if (obj && typeof obj.value === "string") { + return obj.value || ""; + } + + return ""; + }; + + findObjectByKey = (array?: T[], key?: string,) => { + if (!array) { + return ""; + } + + const obj = array.find(o => o.key === key); + + if (obj && typeof obj.value === "object") { + return obj.value || undefined; + } + + return {}; + }; + + getHistoryItem = (i: Items, req: IRequestModel[]): IHistory => { + let history: IHistory = { + id: uuidv4(), + name: i.name, + method: (i.request as RequestObject).method, + url: this.getUrl((i.request as RequestObject).url), + createdTime: formatDate() + }; + + let reqObject = i.request as RequestObject; + + if (reqObject) { + let request: IRequestModel = { + id: history.id, + url: history.url, + name: history.name, + createdTime: history.createdTime, + method: history.method as MethodType, + params: this.getParams(reqObject.url), + auth: this.getAuthDetails(reqObject.auth), + headers: this.getHeders(reqObject.header), + body: this.getBody(reqObject.body), + tests: JSON.parse(JSON.stringify(InitialTest)), + setvar: JSON.parse(JSON.stringify(InitialSetVar)), + notes: "", + preFetch: JSON.parse(JSON.stringify(InitialPreFetch)) + }; + + req.push(request); + } + + return history; + }; + + getFolderItem = (items: Items[], requests: IRequestModel[]) => { + return items.map((i: Items) => { + if (Object.prototype.hasOwnProperty.call(i, "request")) { + return this.getHistoryItem(i, requests); + + } else { + let folder: IFolder = { + id: uuidv4(), + name: i.name, + type: "folder", + createdTime: formatDate(), + data: i.item.reduce((accumulator: (IHistory | IFolder)[], item: Items) => { + if (Object.prototype.hasOwnProperty.call(item, "request")) { + return [...accumulator, this.getHistoryItem(item, requests)]; + } + + const requestGroup = this.importFolderItem(item, requests); + return [...accumulator, requestGroup]; + }, []), + settings: JSON.parse(JSON.stringify(InitialSettings)) + }; + return folder; + } + }); + }; + + importFolderItem = (item: Items, requests: IRequestModel[]): IFolder => { + return { + id: uuidv4(), + name: item.name, + type: "folder", + createdTime: formatDate(), + data: this.getFolderItem(item.item, requests), + settings: this.importSettings(item.auth) + }; + }; + + importSettings = (auth: Auth | undefined | null): ISettings => { + let settings: ISettings = { + auth: this.getAuthDetails(auth), + preFetch: { + requests: [] + }, + headers: [{ + key: "User-Agent", + value: "Fetch Client", + isChecked: true, + }, { + key: "", + value: "", + isChecked: false, + }] + }; + + return settings; + }; + + importCollection = (): { fcCollection: ICollections, fcRequests: IRequestModel[], fcVariable: IVariable } => { + const variable = this.importVariable(this.collection.variable || [], this.collection.info.name); + + let requests: IRequestModel[] = []; + + let collection: ICollections = { + id: uuidv4(), + name: this.collection.info.name, + createdTime: formatDate(), + variableId: variable ? variable.id : "", + data: [], + settings: this.importSettings(this.collection.auth) + }; + + let data = this.collection.item.reduce((accumulator: (IHistory | IFolder)[], item: Items) => { + if (Object.prototype.hasOwnProperty.call(item, "request")) { + return [...accumulator, this.getHistoryItem(item, requests)]; + } + + const requestGroup = this.importFolderItem(item, requests); + return [...accumulator, requestGroup]; + }, []); + + collection.data = data; + + return { + fcCollection: collection, + fcRequests: requests, + fcVariable: variable + }; + }; }; export const postmanImporter = (rawData: string): { fcCollection: ICollections, fcRequests: IRequestModel[], fcVariable: IVariable } | null => { - try { - const collection = JSON.parse(rawData) as PostmanSchema_2_1; - if (collection.info.schema === POSTMAN_SCHEMA_V2_1) { - return new PostmanImport(collection).importCollection(); - } - } catch (err) { - writeLog("error::postmanImporter(): - Error Message : " + err); - return null; - } - - return null; -}; \ No newline at end of file + try { + const collection = JSON.parse(rawData) as PostmanSchema_2_1; + if (collection.info.schema === POSTMAN_SCHEMA_V2_1) { + return new PostmanImport(collection).importCollection(); + } + } catch (err) { + writeLog("error::postmanImporter(): - Error Message : " + err); + return null; + } + + return null; +}; diff --git a/src/utils/importers/postman/postman_2_1.types.ts b/src/utils/importers/postman/postman_2_1.types.ts index 5ef40b2..0ae9f96 100644 --- a/src/utils/importers/postman/postman_2_1.types.ts +++ b/src/utils/importers/postman/postman_2_1.types.ts @@ -7,71 +7,71 @@ export const POSTMAN_SCHEMA_V2_1 = "https://schema.getpostman.com/json/collectio **/ export interface PostmanSchema_2_1 { - auth?: null | Auth; - event?: Event[]; - info: Information; - /** - * Items are the basic unit for a Postman collection. You can think of them as corresponding - * to a single API endpoint. Each Item has one request and may have multiple API responses - * associated with it. - */ - item: Items[]; - protocolProfileBehavior?: { [key: string]: any }; - variable?: Variable[]; + auth?: null | Auth; + event?: Event[]; + info: Information; + /** + * Items are the basic unit for a Postman collection. You can think of them as corresponding + * to a single API endpoint. Each Item has one request and may have multiple API responses + * associated with it. + */ + item: Items[]; + protocolProfileBehavior?: { [key: string]: any }; + variable?: Variable[]; } /** * Represents authentication helpers provided by Postman */ export interface Auth { - /** - * The attributes for API Key Authentication. - */ - apikey?: ApikeyElement[]; - /** - * The attributes for [AWS - * Auth](http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html). - */ - awsv4?: ApikeyElement[]; - /** - * The attributes for [Basic - * Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication). - */ - basic?: ApikeyElement[]; - /** - * The helper attributes for [Bearer Token - * Authentication](https://tools.ietf.org/html/rfc6750) - */ - bearer?: ApikeyElement[]; - /** - * The attributes for [Digest - * Authentication](https://en.wikipedia.org/wiki/Digest_access_authentication). - */ - digest?: ApikeyElement[]; - /** - * The attributes for [Akamai EdgeGrid - * Authentication](https://developer.akamai.com/legacy/introduction/Client_Auth.html). - */ - edgegrid?: ApikeyElement[]; - /** - * The attributes for [Hawk Authentication](https://github.com/hueniverse/hawk) - */ - hawk?: ApikeyElement[]; - noauth?: any; - /** - * The attributes for [NTLM - * Authentication](https://msdn.microsoft.com/en-us/library/cc237488.aspx) - */ - ntlm?: ApikeyElement[]; - /** - * The attributes for [OAuth2](https://oauth.net/1/) - */ - oauth1?: ApikeyElement[]; - /** - * Helper attributes for [OAuth2](https://oauth.net/2/) - */ - oauth2?: ApikeyElement[]; - type: AuthType; + /** + * The attributes for API Key Authentication. + */ + apikey?: ApikeyElement[]; + /** + * The attributes for [AWS + * Auth](http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html). + */ + awsv4?: ApikeyElement[]; + /** + * The attributes for [Basic + * Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication). + */ + basic?: ApikeyElement[]; + /** + * The helper attributes for [Bearer Token + * Authentication](https://tools.ietf.org/html/rfc6750) + */ + bearer?: ApikeyElement[]; + /** + * The attributes for [Digest + * Authentication](https://en.wikipedia.org/wiki/Digest_access_authentication). + */ + digest?: ApikeyElement[]; + /** + * The attributes for [Akamai EdgeGrid + * Authentication](https://developer.akamai.com/legacy/introduction/Client_Auth.html). + */ + edgegrid?: ApikeyElement[]; + /** + * The attributes for [Hawk Authentication](https://github.com/hueniverse/hawk) + */ + hawk?: ApikeyElement[]; + noauth?: any; + /** + * The attributes for [NTLM + * Authentication](https://msdn.microsoft.com/en-us/library/cc237488.aspx) + */ + ntlm?: ApikeyElement[]; + /** + * The attributes for [OAuth2](https://oauth.net/1/) + */ + oauth1?: ApikeyElement[]; + /** + * Helper attributes for [OAuth2](https://oauth.net/2/) + */ + oauth2?: ApikeyElement[]; + type: AuthType; } /** @@ -79,23 +79,23 @@ export interface Auth { * `username` and `password` are set as auth attributes for Basic Authentication method. */ export interface ApikeyElement { - key: string; - type?: string; - value?: any; + key: string; + type?: string; + value?: any; } export enum AuthType { - Apikey = "apikey", - Awsv4 = "awsv4", - Basic = "basic", - Bearer = "bearer", - Digest = "digest", - Edgegrid = "edgegrid", - Hawk = "hawk", - NTLM = "ntlm", - Noauth = "noauth", - Oauth1 = "oauth1", - Oauth2 = "oauth2", + Apikey = "apikey", + Awsv4 = "awsv4", + Basic = "basic", + Bearer = "bearer", + Digest = "digest", + Edgegrid = "edgegrid", + Hawk = "hawk", + NTLM = "ntlm", + Noauth = "noauth", + Oauth1 = "oauth1", + Oauth2 = "oauth2", } /** @@ -105,19 +105,19 @@ export enum AuthType { * Defines a script associated with an associated event name */ export interface Event { - /** - * Indicates whether the event is disabled. If absent, the event is assumed to be enabled. - */ - disabled?: boolean; - /** - * A unique identifier for the enclosing event. - */ - id?: string; - /** - * Can be set to `test` or `prerequest` for test scripts or pre-request scripts respectively. - */ - listen: string; - script?: Script; + /** + * Indicates whether the event is disabled. If absent, the event is assumed to be enabled. + */ + disabled?: boolean; + /** + * A unique identifier for the enclosing event. + */ + id?: string; + /** + * Can be set to `test` or `prerequest` for test scripts or pre-request scripts respectively. + */ + listen: string; + script?: Script; } /** @@ -125,90 +125,90 @@ export interface Event { * operations on a particular response. */ export interface Script { - exec?: string[] | string; - /** - * A unique, user defined identifier that can be used to refer to this script from requests. - */ - id?: string; - /** - * Script name - */ - name?: string; - src?: URLObject | string; - /** - * Type of the script. E.g: 'text/javascript' - */ - type?: string; + exec?: string[] | string; + /** + * A unique, user defined identifier that can be used to refer to this script from requests. + */ + id?: string; + /** + * Script name + */ + name?: string; + src?: URLObject | string; + /** + * Type of the script. E.g: 'text/javascript' + */ + type?: string; } export interface URLObject { - /** - * Contains the URL fragment (if any). Usually this is not transmitted over the network, but - * it could be useful to store this in some cases. - */ - hash?: string; - /** - * The host for the URL, E.g: api.yourdomain.com. Can be stored as a string or as an array - * of strings. - */ - host?: string[] | string; - path?: Array | string; - /** - * The port number present in this URL. An empty value implies 80/443 depending on whether - * the protocol field contains http/https. - */ - port?: string; - /** - * The protocol associated with the request, E.g: 'http' - */ - protocol?: string; - /** - * An array of QueryParams, which is basically the query string part of the URL, parsed into - * separate variables - */ - query?: QueryParam[]; - /** - * The string representation of the request URL, including the protocol, host, path, hash, - * query parameter(s) and path variable(s). - */ - raw?: string; - /** - * Postman supports path variables with the syntax `/path/:variableName/to/somewhere`. These - * variables are stored in this field. - */ - variable?: Variable[]; + /** + * Contains the URL fragment (if any). Usually this is not transmitted over the network, but + * it could be useful to store this in some cases. + */ + hash?: string; + /** + * The host for the URL, E.g: api.yourdomain.com. Can be stored as a string or as an array + * of strings. + */ + host?: string[] | string; + path?: Array | string; + /** + * The port number present in this URL. An empty value implies 80/443 depending on whether + * the protocol field contains http/https. + */ + port?: string; + /** + * The protocol associated with the request, E.g: 'http' + */ + protocol?: string; + /** + * An array of QueryParams, which is basically the query string part of the URL, parsed into + * separate variables + */ + query?: QueryParam[]; + /** + * The string representation of the request URL, including the protocol, host, path, hash, + * query parameter(s) and path variable(s). + */ + raw?: string; + /** + * Postman supports path variables with the syntax `/path/:variableName/to/somewhere`. These + * variables are stored in this field. + */ + variable?: Variable[]; } export interface PathObject { - type?: string; - value?: string; + type?: string; + value?: string; } export interface QueryParam { - description?: null | Description | string; - /** - * If set to true, the current query parameter will not be sent with the request. - */ - disabled?: boolean; - key?: null | string; - value?: null | string; + description?: null | Description | string; + /** + * If set to true, the current query parameter will not be sent with the request. + */ + disabled?: boolean; + key?: null | string; + value?: null | string; } export interface Description { - /** - * The content of the description goes here, as a raw string. - */ - content?: string; - /** - * Holds the mime type of the raw description content. E.g: 'text/markdown' or 'text/html'. - * The type is used to correctly render the description when generating documentation, or in - * the Postman app. - */ - type?: string; - /** - * Description can have versions associated with it, which should be put in this property. - */ - version?: any; + /** + * The content of the description goes here, as a raw string. + */ + content?: string; + /** + * Holds the mime type of the raw description content. E.g: 'text/markdown' or 'text/html'. + * The type is used to correctly render the description when generating documentation, or in + * the Postman app. + */ + type?: string; + /** + * Description can have versions associated with it, which should be put in this property. + */ + version?: any; } /** @@ -221,94 +221,94 @@ export interface Description { * request. */ export interface Variable { - description?: null | Description | string; - disabled?: boolean; - /** - * A variable ID is a unique user-defined value that identifies the variable within a - * collection. In traditional terms, this would be a variable name. - */ - id?: string; - /** - * A variable key is a human friendly value that identifies the variable within a - * collection. In traditional terms, this would be a variable name. - */ - key?: string; - /** - * Variable name - */ - name?: string; - /** - * When set to true, indicates that this variable has been set by Postman - */ - system?: boolean; - /** - * A variable may have multiple types. This field specifies the type of the variable. - */ - type?: VariableType; - /** - * The value that a variable holds in this collection. Ultimately, the variables will be - * replaced by this value, when say running a set of requests from a collection - */ - value?: any; + description?: null | Description | string; + disabled?: boolean; + /** + * A variable ID is a unique user-defined value that identifies the variable within a + * collection. In traditional terms, this would be a variable name. + */ + id?: string; + /** + * A variable key is a human friendly value that identifies the variable within a + * collection. In traditional terms, this would be a variable name. + */ + key?: string; + /** + * Variable name + */ + name?: string; + /** + * When set to true, indicates that this variable has been set by Postman + */ + system?: boolean; + /** + * A variable may have multiple types. This field specifies the type of the variable. + */ + type?: VariableType; + /** + * The value that a variable holds in this collection. Ultimately, the variables will be + * replaced by this value, when say running a set of requests from a collection + */ + value?: any; } /** * A variable may have multiple types. This field specifies the type of the variable. */ export enum VariableType { - Any = "any", - Boolean = "boolean", - Number = "number", - String = "string", + Any = "any", + Boolean = "boolean", + Number = "number", + String = "string", } /** * Detailed description of the info block */ export interface Information { - /** - * Every collection is identified by the unique value of this field. The value of this field - * is usually easiest to generate using a UID generator function. If you already have a - * collection, it is recommended that you maintain the same id since changing the id usually - * implies that is a different collection than it was originally. - * *Note: This field exists for compatibility reasons with Collection Format V1.* - */ - _postman_id?: string; - description?: null | Description | string; - /** - * A collection's friendly name is defined by this field. You would want to set this field - * to a value that would allow you to easily identify this collection among a bunch of other - * collections, as such outlining its usage or content. - */ - name: string; - /** - * This should ideally hold a link to the Postman schema that is used to validate this - * collection. E.g: https://schema.getpostman.com/collection/v1 - */ - schema: string; - version?: CollectionVersionObject | string; + /** + * Every collection is identified by the unique value of this field. The value of this field + * is usually easiest to generate using a UID generator function. If you already have a + * collection, it is recommended that you maintain the same id since changing the id usually + * implies that is a different collection than it was originally. + * *Note: This field exists for compatibility reasons with Collection Format V1.* + */ + _postman_id?: string; + description?: null | Description | string; + /** + * A collection's friendly name is defined by this field. You would want to set this field + * to a value that would allow you to easily identify this collection among a bunch of other + * collections, as such outlining its usage or content. + */ + name: string; + /** + * This should ideally hold a link to the Postman schema that is used to validate this + * collection. E.g: https://schema.getpostman.com/collection/v1 + */ + schema: string; + version?: CollectionVersionObject | string; } export interface CollectionVersionObject { - /** - * A human friendly identifier to make sense of the version numbers. E.g: 'beta-3' - */ - identifier?: string; - /** - * Increment this number if you make changes to the collection that changes its behaviour. - * E.g: Removing or adding new test scripts. (partly or completely). - */ - major: number; - meta?: any; - /** - * You should increment this number if you make changes that will not break anything that - * uses the collection. E.g: removing a folder. - */ - minor: number; - /** - * Ideally, minor changes to a collection should result in the increment of this number. - */ - patch: number; + /** + * A human friendly identifier to make sense of the version numbers. E.g: 'beta-3' + */ + identifier?: string; + /** + * Increment this number if you make changes to the collection that changes its behaviour. + * E.g: Removing or adding new test scripts. (partly or completely). + */ + major: number; + meta?: any; + /** + * You should increment this number if you make changes that will not break anything that + * uses the collection. E.g: removing a folder. + */ + minor: number; + /** + * Ideally, minor changes to a collection should result in the increment of this number. + */ + patch: number; } /** @@ -320,153 +320,153 @@ export interface CollectionVersionObject { * 'Folders'. A folder just is an ordered set of requests. */ export interface Items { - description?: null | Description | string; - event?: Event[]; - /** - * A unique ID that is used to identify collections internally - */ - id?: string; - /** - * A human readable identifier for the current item. - * - * A folder's friendly name is defined by this field. You would want to set this field to a - * value that would allow you to easily identify this folder. - */ - name?: string; - protocolProfileBehavior?: { [key: string]: any }; - request?: RequestObject | string; - response?: Array; - variable?: Variable[]; - auth?: null | Auth; - /** - * Items are entities which contain an actual HTTP request, and sample responses attached to - * it. Folders may contain many items. - */ - item?: Items[]; + description?: null | Description | string; + event?: Event[]; + /** + * A unique ID that is used to identify collections internally + */ + id?: string; + /** + * A human readable identifier for the current item. + * + * A folder's friendly name is defined by this field. You would want to set this field to a + * value that would allow you to easily identify this folder. + */ + name?: string; + protocolProfileBehavior?: { [key: string]: any }; + request?: RequestObject | string; + response?: Array; + variable?: Variable[]; + auth?: null | Auth; + /** + * Items are entities which contain an actual HTTP request, and sample responses attached to + * it. Folders may contain many items. + */ + item?: Items[]; } export interface RequestObject { - auth?: null | Auth; - body?: null | Body; - certificate?: Certificate; - description?: null | Description | string; - header?: Header[] | string; - method?: string; - proxy?: ProxyConfig; - url?: URLObject | string; + auth?: null | Auth; + body?: null | Body; + certificate?: Certificate; + description?: null | Description | string; + header?: Header[] | string; + method?: string; + proxy?: ProxyConfig; + url?: URLObject | string; } /** * This field contains the data usually contained in the request body. */ export interface Body { - /** - * When set to true, prevents request body from being sent. - */ - disabled?: boolean; - file?: File; - formdata?: FormParameter[]; - graphql?: { [key: string]: any }; - /** - * Postman stores the type of data associated with this request in this field. - */ - mode?: Mode; - /** - * Additional configurations and options set for various body modes. - */ - options?: { [key: string]: any }; - raw?: string; - urlencoded?: URLEncodedParameter[]; + /** + * When set to true, prevents request body from being sent. + */ + disabled?: boolean; + file?: File; + formdata?: FormParameter[]; + graphql?: { [key: string]: any }; + /** + * Postman stores the type of data associated with this request in this field. + */ + mode?: Mode; + /** + * Additional configurations and options set for various body modes. + */ + options?: { [key: string]: any }; + raw?: string; + urlencoded?: URLEncodedParameter[]; } export interface File { - content?: string; - src?: null | string; + content?: string; + src?: null | string; } export interface FormParameter { - /** - * Override Content-Type header of this form data entity. - */ - contentType?: string; - description?: null | Description | string; - /** - * When set to true, prevents this form data entity from being sent. - */ - disabled?: boolean; - key: string; - type?: FormParameterType; - value?: string; - src?: any[] | null | string; + /** + * Override Content-Type header of this form data entity. + */ + contentType?: string; + description?: null | Description | string; + /** + * When set to true, prevents this form data entity from being sent. + */ + disabled?: boolean; + key: string; + type?: FormParameterType; + value?: string; + src?: any[] | null | string; } export enum FormParameterType { - File = "file", - Text = "text", + File = "file", + Text = "text", } /** * Postman stores the type of data associated with this request in this field. */ export enum Mode { - File = "file", - Formdata = "formdata", - Graphql = "graphql", - Raw = "raw", - Urlencoded = "urlencoded", + File = "file", + Formdata = "formdata", + Graphql = "graphql", + Raw = "raw", + Urlencoded = "urlencoded", } export interface URLEncodedParameter { - description?: null | Description | string; - disabled?: boolean; - key: string; - value?: string; + description?: null | Description | string; + disabled?: boolean; + key: string; + value?: string; } /** * A representation of an ssl certificate */ export interface Certificate { - /** - * An object containing path to file certificate, on the file system - */ - cert?: CERT; - /** - * An object containing path to file containing private key, on the file system - */ - key?: Key; - /** - * A list of Url match pattern strings, to identify Urls this certificate can be used for. - */ - matches?: string[]; - /** - * A name for the certificate for user reference - */ - name?: string; - /** - * The passphrase for the certificate - */ - passphrase?: string; + /** + * An object containing path to file certificate, on the file system + */ + cert?: CERT; + /** + * An object containing path to file containing private key, on the file system + */ + key?: Key; + /** + * A list of Url match pattern strings, to identify Urls this certificate can be used for. + */ + matches?: string[]; + /** + * A name for the certificate for user reference + */ + name?: string; + /** + * The passphrase for the certificate + */ + passphrase?: string; } /** * An object containing path to file certificate, on the file system */ export interface CERT { - /** - * The path to file containing key for certificate, on the file system - */ - src?: any; + /** + * The path to file containing key for certificate, on the file system + */ + src?: any; } /** * An object containing path to file containing private key, on the file system */ export interface Key { - /** - * The path to file containing key for certificate, on the file system - */ - src?: any; + /** + * The path to file containing key for certificate, on the file system + */ + src?: any; } /** @@ -475,19 +475,19 @@ export interface Key { * Represents a single HTTP Header */ export interface Header { - description?: null | Description | string; - /** - * If set to true, the current header will not be sent with requests. - */ - disabled?: boolean; - /** - * This holds the LHS of the HTTP Header, e.g ``Content-Type`` or ``X-Custom-Header`` - */ - key: string; - /** - * The value (or the RHS) of the Header is stored in this field. - */ - value: string; + description?: null | Description | string; + /** + * If set to true, the current header will not be sent with requests. + */ + disabled?: boolean; + /** + * This holds the LHS of the HTTP Header, e.g ``Content-Type`` or ``X-Custom-Header`` + */ + key: string; + /** + * The value (or the RHS) of the Header is stored in this field. + */ + value: string; } /** @@ -495,58 +495,58 @@ export interface Header { * match */ export interface ProxyConfig { - /** - * When set to true, ignores this proxy configuration entity - */ - disabled?: boolean; - /** - * The proxy server host - */ - host?: string; - /** - * The Url match for which the proxy config is defined - */ - match?: string; - /** - * The proxy server port - */ - port?: number; - /** - * The tunneling details for the proxy config - */ - tunnel?: boolean; + /** + * When set to true, ignores this proxy configuration entity + */ + disabled?: boolean; + /** + * The proxy server host + */ + host?: string; + /** + * The Url match for which the proxy config is defined + */ + match?: string; + /** + * The proxy server port + */ + port?: number; + /** + * The tunneling details for the proxy config + */ + tunnel?: boolean; } export interface ResponseObject { - /** - * The raw text of the response. - */ - body?: null | string; - /** - * The numerical response code, example: 200, 201, 404, etc. - */ - code?: number; - cookie?: Cookie[]; - header?: Array
| null | string; - /** - * A unique, user defined identifier that can be used to refer to this response from - * requests. - */ - id?: string; - originalRequest?: RequestObject | string; - /** - * The time taken by the request to complete. If a number, the unit is milliseconds. If the - * response is manually created, this can be set to `null`. - */ - responseTime?: number | null | string; - /** - * The response status, e.g: '200 OK' - */ - status?: string; - /** - * Set of timing information related to request and response in milliseconds - */ - timings?: { [key: string]: any } | null; + /** + * The raw text of the response. + */ + body?: null | string; + /** + * The numerical response code, example: 200, 201, 404, etc. + */ + code?: number; + cookie?: Cookie[]; + header?: Array
| null | string; + /** + * A unique, user defined identifier that can be used to refer to this response from + * requests. + */ + id?: string; + originalRequest?: RequestObject | string; + /** + * The time taken by the request to complete. If a number, the unit is milliseconds. If the + * response is manually created, this can be set to `null`. + */ + responseTime?: number | null | string; + /** + * The response status, e.g: '200 OK' + */ + status?: string; + /** + * Set of timing information related to request and response in milliseconds + */ + timings?: { [key: string]: any } | null; } /** @@ -554,49 +554,49 @@ export interface ResponseObject { * format](https://developer.chrome.com/extensions/cookies) */ export interface Cookie { - /** - * The domain for which this cookie is valid. - */ - domain: string; - /** - * When the cookie expires. - */ - expires?: number | string; - /** - * Custom attributes for a cookie go here, such as the [Priority - * Field](https://code.google.com/p/chromium/issues/detail?id=232693) - */ - extensions?: any[]; - /** - * True if the cookie is a host-only cookie. (i.e. a request's URL domain must exactly match - * the domain of the cookie). - */ - hostOnly?: boolean; - /** - * Indicates if this cookie is HTTP Only. (if True, the cookie is inaccessible to - * client-side scripts) - */ - httpOnly?: boolean; - maxAge?: string; - /** - * This is the name of the Cookie. - */ - name?: string; - /** - * The path associated with the Cookie. - */ - path: string; - /** - * Indicates if the 'secure' flag is set on the Cookie, meaning that it is transmitted over - * secure connections only. (typically HTTPS) - */ - secure?: boolean; - /** - * True if the cookie is a session cookie. - */ - session?: boolean; - /** - * The value of the Cookie. - */ - value?: string; + /** + * The domain for which this cookie is valid. + */ + domain: string; + /** + * When the cookie expires. + */ + expires?: number | string; + /** + * Custom attributes for a cookie go here, such as the [Priority + * Field](https://code.google.com/p/chromium/issues/detail?id=232693) + */ + extensions?: any[]; + /** + * True if the cookie is a host-only cookie. (i.e. a request's URL domain must exactly match + * the domain of the cookie). + */ + hostOnly?: boolean; + /** + * Indicates if this cookie is HTTP Only. (if True, the cookie is inaccessible to + * client-side scripts) + */ + httpOnly?: boolean; + maxAge?: string; + /** + * This is the name of the Cookie. + */ + name?: string; + /** + * The path associated with the Cookie. + */ + path: string; + /** + * Indicates if the 'secure' flag is set on the Cookie, meaning that it is transmitted over + * secure connections only. (typically HTTPS) + */ + secure?: boolean; + /** + * True if the cookie is a session cookie. + */ + session?: boolean; + /** + * The value of the Cookie. + */ + value?: string; } diff --git a/src/utils/importers/postman/postman_2_1.variable_types.ts b/src/utils/importers/postman/postman_2_1.variable_types.ts index b6d28a0..f104cbd 100644 --- a/src/utils/importers/postman/postman_2_1.variable_types.ts +++ b/src/utils/importers/postman/postman_2_1.variable_types.ts @@ -1,14 +1,14 @@ export interface PostmanVariableSchema_2_1 { - id: string - name: string - values: IValue[] - _postman_variable_scope: string - _postman_exported_at: string - _postman_exported_using: string + id: string + name: string + values: IValue[] + _postman_variable_scope: string + _postman_exported_at: string + _postman_exported_using: string } export interface IValue { - key: string - value: string - enabled: boolean + key: string + value: string + enabled: boolean } diff --git a/src/utils/importers/thunderClient/thunderClientImporter_1_2.ts b/src/utils/importers/thunderClient/thunderClientImporter_1_2.ts index 9ac0553..bb0361d 100644 --- a/src/utils/importers/thunderClient/thunderClientImporter_1_2.ts +++ b/src/utils/importers/thunderClient/thunderClientImporter_1_2.ts @@ -3,412 +3,400 @@ import { v4 as uuidv4 } from "uuid"; import { ITableData } from "../../../fetch-client-ui/components/Common/Table/types"; import { InitialAuth, InitialBody, InitialPreFetch, InitialRequestHeaders, InitialSetVar, InitialTest } from "../../../fetch-client-ui/components/RequestUI/redux/reducer"; import { ClientAuth, GrantType, IAuth, IBodyData, IRequestModel, MethodType } from "../../../fetch-client-ui/components/RequestUI/redux/types"; +import { InitialSettings } from "../../../fetch-client-ui/components/SideBar/redux/reducer"; import { ICollections, IFolder, IHistory, ISettings } from "../../../fetch-client-ui/components/SideBar/redux/types"; import { isFolder } from "../../../fetch-client-ui/components/SideBar/util"; import { isJson } from "../../../fetch-client-ui/components/TestUI/TestPanel/helper"; import { formatDate } from "../../helper"; import { writeLog } from "../../logger/logger"; import { Auth, BodyEntity, FoldersEntity, HeadersEntityOrFormEntity, ParamsEntity, RequestsEntity, Settings, ThunderClient_Schema_1_2 } from "./thunderClient_1_2_types"; -import { InitialSettings } from "../../../fetch-client-ui/components/SideBar/redux/reducer"; export class ThunderClientImport { - private collection: ThunderClient_Schema_1_2; - - constructor(collection: ThunderClient_Schema_1_2) { - this.collection = collection; - } - - getParams = (params: ParamsEntity[]): ITableData[] => { - let fcParams: ITableData[] = []; - - if (params?.length > 0) { - params.forEach(item => { - fcParams.push({ - key: item.name, - value: item.value, - isChecked: !item.isDisabled - }); - }); - } - return [...fcParams, { - isChecked: false, - key: "", - value: "" - }]; - }; - - getHeaders = (headers?: HeadersEntityOrFormEntity[]): ITableData[] => { - let fcHeaders: ITableData[] = []; - - if (headers?.length > 0) { - headers.forEach(header => { - if (header.name) { - fcHeaders.push({ - isChecked: !header.isDisabled, - key: header.name, - value: header.value - }); - } - }); - - fcHeaders.push({ - key: "", - value: "", - isChecked: false, - }); - } else { - fcHeaders = JSON.parse(JSON.stringify(InitialRequestHeaders)); - } - - return fcHeaders; - }; - - getAuthDetails = (auth?: Auth): IAuth => { - - let fcAuth: IAuth = JSON.parse(JSON.stringify(InitialAuth)); - - if (!auth) { - fcAuth.authType = "inherit"; - return fcAuth; - } - - switch (auth.type) { - case "aws": - if (!auth.aws) { - return fcAuth; - } - - fcAuth.aws.accessKey = auth.aws.accessKeyId ?? ""; - fcAuth.aws.secretAccessKey = auth.aws.secretKey ?? ""; - fcAuth.aws.service = auth.aws.service ?? ""; - fcAuth.aws.sessionToken = auth.aws.sessionToken ?? ""; - fcAuth.aws.region = auth.aws.region ?? ""; - fcAuth.authType = "aws"; - - return fcAuth; - - - case "basic": - if (!auth.basic) { - return fcAuth; - } - - fcAuth.userName = auth.basic.username ?? ""; - fcAuth.password = auth.basic.password ?? ""; - fcAuth.authType = "basic"; - - return fcAuth; - - case "bearer": - if (!auth.bearer) { - return fcAuth; - } - - fcAuth.password = auth.bearer ?? ""; - fcAuth.tokenPrefix = auth.bearerPrefix ?? ""; - fcAuth.authType = "bearertoken"; - - return fcAuth; - - case "oauth2": - if (!auth.oauth2) { - return fcAuth; - } - - let grantType = auth.oauth2.grantType ?? ""; - - if (grantType !== "client_credentials" && grantType !== "password") { - return fcAuth; - } - - let clientAuth = auth.oauth2.clientAuth; - fcAuth.oauth.clientAuth = clientAuth === "in-header" ? ClientAuth.Header : ClientAuth.Body; - fcAuth.oauth.clientId = auth.oauth2.clientId ?? ""; - fcAuth.oauth.clientSecret = auth.oauth2.clientSecret ?? ""; - fcAuth.oauth.grantType = grantType === "client_credentials" ? GrantType.Client_Crd : GrantType.PWD_Crd; - fcAuth.oauth.password = auth.oauth2.password ?? ""; - fcAuth.oauth.username = auth.oauth2.username ?? ""; - fcAuth.oauth.scope = auth.oauth2.scope ?? ""; - fcAuth.oauth.tokenUrl = auth.oauth2.tokenUrl ?? ""; - - fcAuth.oauth.advancedOpt.resource = auth.oauth2.resource ?? ""; - fcAuth.oauth.advancedOpt.audience = auth.oauth2.audience ?? ""; - - fcAuth.authType = "oauth2"; - - return fcAuth; - - default: - return fcAuth; - } - }; - - getSrc = (src: any[] | null | string): string => { - if (!src) { - return ""; - } - - if (typeof src === "string") { - return src.length > 1 ? src.substring(1) : src; - } - - if (typeof src === "object") { - return src.length > 0 ? src[0].length > 1 ? src[0].substring(1) : src[0] : ""; - } - }; - - getBody = (body: BodyEntity): IBodyData => { - - let fcBody: IBodyData = JSON.parse(JSON.stringify(InitialBody)); - - if (!body) { - return fcBody; - } - - switch (body.type) { - case 'formdata': - fcBody.bodyType = "formdata"; - fcBody.formdata.shift(); - body.form?.forEach(item => { - fcBody.formdata.push({ - isChecked: item.isDisabled === true ? false : true, - key: item.name, - value: item.value, - type: "Text" - }); - }); - - body.files?.forEach(item => { - fcBody.formdata.push({ - isChecked: item.isDisabled === true ? false : true, - key: item.name, - value: item.value, - type: "File" - }); - }); - - fcBody.formdata.push({ - isChecked: false, - key: "", - value: "", - type: "Text" - }); - - return fcBody; - - case 'formencoded': - fcBody.bodyType = "formurlencoded"; - fcBody.urlencoded.shift(); - body.form?.forEach(item => { - fcBody.urlencoded.push({ - isChecked: item.isDisabled === true ? false : true, - key: item.name, - value: item.value - }); - }); - - fcBody.urlencoded.push({ - isChecked: false, - key: "", - value: "" - }); - - return fcBody; - - case 'graphql': - fcBody.bodyType = "graphql"; - fcBody.graphql.query = JSON.stringify(body.graphql.query); - fcBody.graphql.variables = JSON.stringify(body.graphql.variables); - return fcBody; - - case 'json': - case 'xml': - case 'text': - fcBody.bodyType = "raw"; - fcBody.raw.data = body.raw; - fcBody.raw.lang = this.getRawBodyType(body.raw.replace(/(?:\\[rn]|[\r\n]+)+/g, "")); - return fcBody; - - case 'binary': - fcBody.bodyType = "binary"; - fcBody.binary.fileName = body.binary; - fcBody.binary.contentTypeOption = "manual"; - return fcBody; - - default: - return fcBody; - } - }; - - getRawBodyType = (data: string): string => { - if (isJson(data) === "true") { - return "json"; - } - if (XMLValidator.validate(data) === true) { - return "xml"; - } - if (this.isHTML(data)) { - return "html"; - } - return "text"; - }; - - isHTML = (str: string) => !(str || '') - // replace html tag with content - .replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, '') - // remove remaining self closing tags - .replace(/(<([^>]+)>)/ig, '') - // remove extra space at start and end - .trim(); - - findValueByKey = (array?: T[], key?: string,) => { - if (!array) { - return ""; - } - - const obj = array.find(o => o.key === key); - - if (obj && typeof obj.value === "string") { - return obj.value || ""; - } - - return ""; - }; - - findObjectByKey = (array?: T[], key?: string,) => { - if (!array) { - return ""; - } - - const obj = array.find(o => o.key === key); - - if (obj && typeof obj.value === "object") { - return obj.value || undefined; - } - - return {}; - }; - - getRequestItem = (req: RequestsEntity): IRequestModel => { - let request: IRequestModel = { - id: uuidv4(), - url: req.url, - name: req.name, - createdTime: formatDate(), - method: req.method.toLocaleLowerCase() as MethodType, - params: this.getParams(req.params), - auth: this.getAuthDetails(req.auth), - headers: this.getHeaders(req.headers), - body: this.getBody(req.body), - tests: JSON.parse(JSON.stringify(InitialTest)), - setvar: JSON.parse(JSON.stringify(InitialSetVar)), - notes: "", - preFetch: JSON.parse(JSON.stringify(InitialPreFetch)) - }; - return request; - }; - - importFolderItem = (item: FoldersEntity): IFolder => { - return { - id: uuidv4(), - name: item.name, - type: "folder", - createdTime: formatDate(), - data: [], - settings: item.settings ? this.importSettings(item.settings) : JSON.parse(JSON.stringify(InitialSettings)) - }; - }; - - importSettings = (parentsettings: Settings): ISettings => { - let settings: ISettings = { - auth: this.getAuthDetails(parentsettings.auth), - preFetch: { requests: [] }, - headers: this.getHeaders(parentsettings.headers) - }; - - return settings; - }; - - getParentItem = (source: ICollections | IFolder, searchId: string): IFolder => { - let pos = source.data.findIndex((el: any) => el.id === searchId); - - if (pos !== -1) { - return (source.data[pos] as IFolder); - } - - for (let i = 0; i < source.data.length; i++) { - if (isFolder(source.data[i])) { - return this.getParentItem(source.data[i] as IFolder, searchId); - } - } - }; - - importCollection = (): { fcCollection: ICollections, fcRequests: IRequestModel[] } => { - let requests: IRequestModel[] = []; - let ids: { [id: string]: string } = {}; - - let collection: ICollections = { - id: uuidv4(), - name: this.collection.collectionName, - createdTime: formatDate(), - variableId: "", - data: [], - settings: this.collection.settings ? this.importSettings(this.collection.settings) : JSON.parse(JSON.stringify(InitialSettings)) - }; - - this.collection.folders?.forEach((folderItem: FoldersEntity) => { - let fcFolder = this.importFolderItem(folderItem); - ids[folderItem._id] = fcFolder.id; - if (folderItem.containerId) { - let parentFolder = this.getParentItem(collection, ids[folderItem.containerId]); - parentFolder.data.push(fcFolder); - } - else { - collection.data.push(fcFolder); - } - }); - - this.collection.requests?.forEach((request: RequestsEntity) => { - let req = this.getRequestItem(request); - - let history: IHistory = { - id: req.id, - name: req.name, - method: req.method, - url: req.url, - createdTime: formatDate() - }; - - requests.push(req); - - if (request.containerId) { - let folder = this.getParentItem(collection, ids[request.containerId]); - folder.data.push(history); - } - else { - collection.data.push(history); - } - }); - - return { - fcCollection: collection, - fcRequests: requests - }; - }; + private collection: ThunderClient_Schema_1_2; + + constructor(collection: ThunderClient_Schema_1_2) { + this.collection = collection; + } + + getParams = (params: ParamsEntity[]): ITableData[] => { + let fcParams: ITableData[] = []; + + if (params?.length > 0) { + params.forEach(item => { + fcParams.push({ + key: item.name ?? "", + value: item.value ?? "", + isChecked: !item.isDisabled + }); + }); + } + return [...fcParams, { + isChecked: false, + key: "", + value: "" + }]; + }; + + getHeaders = (headers?: HeadersEntityOrFormEntity[]): ITableData[] => { + let fcHeaders: ITableData[] = []; + + if (headers?.length > 0) { + headers.forEach(header => { + if (header.name) { + fcHeaders.push({ + isChecked: !header.isDisabled, + key: header.name, + value: header.value + }); + } + }); + + fcHeaders.push({ + key: "", + value: "", + isChecked: false, + }); + } else { + fcHeaders = JSON.parse(JSON.stringify(InitialRequestHeaders)); + } + + return fcHeaders; + }; + + getAuthDetails = (auth?: Auth): IAuth => { + + let fcAuth: IAuth = JSON.parse(JSON.stringify(InitialAuth)); + + if (!auth) { + fcAuth.authType = "inherit"; + return fcAuth; + } + + switch (auth.type) { + case "aws": + if (!auth.aws) { + return fcAuth; + } + + fcAuth.aws.accessKey = auth.aws.accessKeyId ?? ""; + fcAuth.aws.secretAccessKey = auth.aws.secretKey ?? ""; + fcAuth.aws.service = auth.aws.service ?? ""; + fcAuth.aws.sessionToken = auth.aws.sessionToken ?? ""; + fcAuth.aws.region = auth.aws.region ?? ""; + fcAuth.authType = "aws"; + + return fcAuth; + + + case "basic": + if (!auth.basic) { + return fcAuth; + } + + fcAuth.userName = auth.basic.username ?? ""; + fcAuth.password = auth.basic.password ?? ""; + fcAuth.authType = "basic"; + + return fcAuth; + + case "bearer": + if (!auth.bearer) { + return fcAuth; + } + + fcAuth.password = auth.bearer ?? ""; + fcAuth.tokenPrefix = auth.bearerPrefix ?? "Bearer"; + fcAuth.authType = "bearertoken"; + + return fcAuth; + + case "oauth2": + if (!auth.oauth2) { + return fcAuth; + } + + let grantType = auth.oauth2.grantType ?? ""; + + if (grantType !== "client_credentials" && grantType !== "password") { + return fcAuth; + } + + let clientAuth = auth.oauth2.clientAuth; + fcAuth.oauth.clientAuth = clientAuth === "in-header" ? ClientAuth.Header : ClientAuth.Body; + fcAuth.oauth.clientId = auth.oauth2.clientId ?? ""; + fcAuth.oauth.clientSecret = auth.oauth2.clientSecret ?? ""; + fcAuth.oauth.grantType = grantType === "client_credentials" ? GrantType.Client_Crd : GrantType.PWD_Crd; + fcAuth.oauth.password = auth.oauth2.password ?? ""; + fcAuth.oauth.username = auth.oauth2.username ?? ""; + fcAuth.oauth.scope = auth.oauth2.scope ?? ""; + fcAuth.oauth.tokenUrl = auth.oauth2.tokenUrl ?? ""; + + fcAuth.oauth.advancedOpt.resource = auth.oauth2.resource ?? ""; + fcAuth.oauth.advancedOpt.audience = auth.oauth2.audience ?? ""; + + fcAuth.authType = "oauth2"; + + return fcAuth; + + default: + return fcAuth; + } + }; + + getBody = (body: BodyEntity): IBodyData => { + + let fcBody: IBodyData = JSON.parse(JSON.stringify(InitialBody)); + + if (!body) { + return fcBody; + } + + switch (body.type) { + case 'formdata': + fcBody.bodyType = "formdata"; + fcBody.formdata.shift(); + body.form?.forEach(item => { + fcBody.formdata.push({ + isChecked: item.isDisabled === true ? false : true, + key: item.name ?? "", + value: item.value ?? "", + type: "Text" + }); + }); + + body.files?.forEach(item => { + fcBody.formdata.push({ + isChecked: item.isDisabled === true ? false : true, + key: item.name ?? "", + value: item.value ?? "", + type: "File" + }); + }); + + fcBody.formdata.push({ + isChecked: false, + key: "", + value: "", + type: "Text" + }); + + return fcBody; + + case 'formencoded': + fcBody.bodyType = "formurlencoded"; + fcBody.urlencoded.shift(); + body.form?.forEach(item => { + fcBody.urlencoded.push({ + isChecked: item.isDisabled === true ? false : true, + key: item.name ?? "", + value: item.value ?? "" + }); + }); + + fcBody.urlencoded.push({ + isChecked: false, + key: "", + value: "" + }); + + return fcBody; + + case 'graphql': + fcBody.bodyType = "graphql"; + fcBody.graphql.query = JSON.stringify(body.graphql.query); + fcBody.graphql.variables = JSON.stringify(body.graphql.variables); + return fcBody; + + case 'json': + case 'xml': + case 'text': + fcBody.bodyType = "raw"; + fcBody.raw.data = body.raw; + fcBody.raw.lang = this.getRawBodyType(body.raw.replace(/(?:\\[rn]|[\r\n]+)+/g, "")); + return fcBody; + + case 'binary': + fcBody.bodyType = "binary"; + fcBody.binary.fileName = body.binary; + fcBody.binary.contentTypeOption = "manual"; + return fcBody; + + default: + return fcBody; + } + }; + + getRawBodyType = (data: string): string => { + if (isJson(data) === "true") { + return "json"; + } + if (XMLValidator.validate(data) === true) { + return "xml"; + } + if (this.isHTML(data)) { + return "html"; + } + return "text"; + }; + + isHTML = (str: string) => !(str || '') + // replace html tag with content + .replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, '') + // remove remaining self closing tags + .replace(/(<([^>]+)>)/ig, '') + // remove extra space at start and end + .trim(); + + findValueByKey = (array?: T[], key?: string,) => { + if (!array) { + return ""; + } + + const obj = array.find(o => o.key === key); + + if (obj && typeof obj.value === "string") { + return obj.value || ""; + } + + return ""; + }; + + findObjectByKey = (array?: T[], key?: string,) => { + if (!array) { + return ""; + } + + const obj = array.find(o => o.key === key); + + if (obj && typeof obj.value === "object") { + return obj.value || undefined; + } + + return {}; + }; + + getRequestItem = (req: RequestsEntity): IRequestModel => { + let request: IRequestModel = { + id: uuidv4(), + url: req.url, + name: req.name, + createdTime: formatDate(), + method: req.method.toLocaleLowerCase() as MethodType, + params: this.getParams(req.params), + auth: this.getAuthDetails(req.auth), + headers: this.getHeaders(req.headers), + body: this.getBody(req.body), + tests: JSON.parse(JSON.stringify(InitialTest)), + setvar: JSON.parse(JSON.stringify(InitialSetVar)), + notes: "", + preFetch: JSON.parse(JSON.stringify(InitialPreFetch)) + }; + return request; + }; + + importFolderItem = (item: FoldersEntity): IFolder => { + return { + id: uuidv4(), + name: item.name, + type: "folder", + createdTime: formatDate(), + data: [], + settings: item.settings ? this.importSettings(item.settings) : JSON.parse(JSON.stringify(InitialSettings)) + }; + }; + + importSettings = (parentsettings: Settings): ISettings => { + let settings: ISettings = { + auth: this.getAuthDetails(parentsettings.auth), + preFetch: { requests: [] }, + headers: this.getHeaders(parentsettings.headers) + }; + + return settings; + }; + + getParentItem = (source: ICollections | IFolder, searchId: string): IFolder => { + let pos = source.data.findIndex((el: any) => el.id === searchId); + + if (pos !== -1) { + return (source.data[pos] as IFolder); + } + + for (let i = 0; i < source.data.length; i++) { + if (isFolder(source.data[i])) { + return this.getParentItem(source.data[i] as IFolder, searchId); + } + } + + return null; + }; + + importCollection = (): { fcCollection: ICollections, fcRequests: IRequestModel[] } => { + let requests: IRequestModel[] = []; + let ids: { [id: string]: string } = {}; + + let collection: ICollections = { + id: uuidv4(), + name: this.collection.collectionName, + createdTime: formatDate(), + variableId: "", + data: [], + settings: this.collection.settings ? this.importSettings(this.collection.settings) : JSON.parse(JSON.stringify(InitialSettings)) + }; + + this.collection.folders?.forEach((folderItem: FoldersEntity) => { + let fcFolder = this.importFolderItem(folderItem); + ids[folderItem._id] = fcFolder.id; + if (folderItem.containerId) { + let parentFolder = this.getParentItem(collection, ids[folderItem.containerId]); + parentFolder.data.push(fcFolder); + } + else { + collection.data.push(fcFolder); + } + }); + + this.collection.requests?.forEach((request: RequestsEntity) => { + let req = this.getRequestItem(request); + + let history: IHistory = { + id: req.id, + name: req.name, + method: req.method, + url: req.url, + createdTime: formatDate() + }; + + requests.push(req); + + if (request.containerId) { + let folder = this.getParentItem(collection, ids[request.containerId]); + folder.data.push(history); + } + else { + collection.data.push(history); + } + }); + + return { + fcCollection: collection, + fcRequests: requests + }; + }; }; export const thunderClientImporter = (rawData: string): { fcCollection: ICollections, fcRequests: IRequestModel[] } | null => { - try { - const collection = JSON.parse(rawData) as ThunderClient_Schema_1_2; - if (collection.clientName === "Thunder Client") { - return new ThunderClientImport(collection).importCollection(); - } - } catch (err) { - writeLog("error::thunderClientImporter(): - Error Message : " + err); - return null; - } - - return null; -}; \ No newline at end of file + try { + const collection = JSON.parse(rawData) as ThunderClient_Schema_1_2; + if (collection.clientName === "Thunder Client") { + return new ThunderClientImport(collection).importCollection(); + } + } catch (err) { + writeLog("error::thunderClientImporter(): - Error Message : " + err); + return null; + } + + return null; +}; diff --git a/src/utils/importers/thunderClient/thunderClient_1_2.variable_types.ts b/src/utils/importers/thunderClient/thunderClient_1_2.variable_types.ts index f12673a..e5f8461 100644 --- a/src/utils/importers/thunderClient/thunderClient_1_2.variable_types.ts +++ b/src/utils/importers/thunderClient/thunderClient_1_2.variable_types.ts @@ -1,13 +1,13 @@ export interface ThunderClientVariableSchema_1_2 { - clientName: string; - environmentName: string; - environmentId: string; - dateExported: string; - version: string; - variables?: (VariablesEntity)[]; - ref: string; + clientName: string; + environmentName: string; + environmentId: string; + dateExported: string; + version: string; + variables?: (VariablesEntity)[]; + ref: string; } export interface VariablesEntity { - name: string; - value: string; + name: string; + value: string; } diff --git a/src/utils/importers/thunderClient/thunderClient_1_2_types.ts b/src/utils/importers/thunderClient/thunderClient_1_2_types.ts index e09db4d..23ce913 100644 --- a/src/utils/importers/thunderClient/thunderClient_1_2_types.ts +++ b/src/utils/importers/thunderClient/thunderClient_1_2_types.ts @@ -1,104 +1,104 @@ export interface ThunderClient_Schema_1_2 { - clientName: string; - collectionName: string; - collectionId: string; - dateExported: string; - version: string; - folders?: (FoldersEntity)[] | null; - requests?: (RequestsEntity)[] | null; - settings: Settings; - ref: string; + clientName: string; + collectionName: string; + collectionId: string; + dateExported: string; + version: string; + folders?: (FoldersEntity)[] | null; + requests?: (RequestsEntity)[] | null; + settings: Settings; + ref: string; } export interface FoldersEntity { - _id: string; - name: string; - containerId: string; - created: string; - sortNum: number; - settings: Settings; + _id: string; + name: string; + containerId: string; + created: string; + sortNum: number; + settings: Settings; } export interface RequestsEntity { - _id: string; - colId: string; - containerId: string; - name: string; - url: string; - method: string; - sortNum: number; - created: string; - modified: string; - headers?: HeadersEntityOrFormEntity[]; - params?: ParamsEntity[]; - body?: BodyEntity; - auth?: Auth; + _id: string; + colId: string; + containerId: string; + name: string; + url: string; + method: string; + sortNum: number; + created: string; + modified: string; + headers?: HeadersEntityOrFormEntity[]; + params?: ParamsEntity[]; + body?: BodyEntity; + auth?: Auth; } export interface ParamsEntity { - name: string; - value: string; - isPath: boolean; - isDisabled?: boolean; + name: string; + value: string; + isPath: boolean; + isDisabled?: boolean; } export interface BodyEntity { - type: string; - raw: string; - form?: HeadersEntityOrFormEntity[]; - graphql?: Graphql; - binary?: string; - files?: HeadersEntityOrFormEntity[]; + type: string; + raw: string; + form?: HeadersEntityOrFormEntity[]; + graphql?: Graphql; + binary?: string; + files?: HeadersEntityOrFormEntity[]; } export interface HeadersEntityOrFormEntity { - name: string; - value: string; - isDisabled?: boolean; + name: string; + value: string; + isDisabled?: boolean; } export interface Graphql { - query: string; - variables: string; + query: string; + variables: string; } export interface Settings { - auth: Auth; - headers?: HeadersEntityOrFormEntity[]; + auth: Auth; + headers?: HeadersEntityOrFormEntity[]; } export interface Auth { - type: string; - bearer?: string; - bearerPrefix?: string; - oauth2?: Oauth2; - aws?: Aws; - basic?: Basic; + type: string; + bearer?: string; + bearerPrefix?: string; + oauth2?: Oauth2; + aws?: Aws; + basic?: Basic; } export interface Oauth2 { - grantType: string; - tokenUrl: string; - clientId: string; - clientSecret: string; - clientAuth: string; - scope: string; - username: string; - password: string; - tokenPrefix: string; - audience: string; - resource: string; + grantType: string; + tokenUrl: string; + clientId: string; + clientSecret: string; + clientAuth: string; + scope: string; + username: string; + password: string; + tokenPrefix: string; + audience: string; + resource: string; } export interface Aws { - accessKeyId: string; - secretKey: string; - region: string; - service: string; - sessionToken: string; + accessKeyId: string; + secretKey: string; + region: string; + service: string; + sessionToken: string; } export interface Basic { - username: string; - password: string; -} \ No newline at end of file + username: string; + password: string; +} diff --git a/src/utils/logger/constants.ts b/src/utils/logger/constants.ts index 212b78c..c6dd1df 100644 --- a/src/utils/logger/constants.ts +++ b/src/utils/logger/constants.ts @@ -1 +1 @@ -export const logPath = 'fetch-client.log'; \ No newline at end of file +export const logPath = 'fetch-client.log'; diff --git a/src/utils/logger/logger.ts b/src/utils/logger/logger.ts index f321eae..7ca98be 100644 --- a/src/utils/logger/logger.ts +++ b/src/utils/logger/logger.ts @@ -1,25 +1,25 @@ import fs from "fs"; +import path from "path"; import { getExtDbPath } from "../db/getExtDbPath"; import { formatDate } from "../helper"; import { logPath } from "./constants"; -import path from "path"; export function createLogFile() { - fs.writeFileSync(path.resolve(getExtDbPath(), logPath), ""); + fs.writeFileSync(path.resolve(getExtDbPath(), logPath), ""); } export function writeLog(err: any) { - clearLog(); - const data = "\n" + formatDate() + " " + err + "\n"; - fs.appendFileSync(path.resolve(getExtDbPath(), logPath), data); + clearLog(); + const data = "\n" + formatDate() + " " + err + "\n"; + fs.appendFileSync(path.resolve(getExtDbPath(), logPath), data); } function clearLog() { - const logFilePath = path.resolve(getExtDbPath(), logPath); - const stats = fs.statSync(logFilePath); - const fileSizeInBytes = stats.size; - const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024); - if (fileSizeInMegabytes > 1) { - fs.writeFileSync(logFilePath, ""); - } + const logFilePath = path.resolve(getExtDbPath(), logPath); + const stats = fs.statSync(logFilePath); + const fileSizeInBytes = stats.size; + const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024); + if (fileSizeInMegabytes > 1) { + fs.writeFileSync(logFilePath, ""); + } } diff --git a/src/utils/logger/requestLog.ts b/src/utils/logger/requestLog.ts index a388495..5a99b3f 100644 --- a/src/utils/logger/requestLog.ts +++ b/src/utils/logger/requestLog.ts @@ -7,63 +7,63 @@ import { getLogOption } from "../vscodeConfig"; import { writeLog } from "./logger"; export function logDetails(request: IRequestModel, reqHeaders: {}, requestBody: any, responseStatus: number, responseHeaders: ITableData[], responseData: any, duration: number) { - logRequestDeatils(request, reqHeaders, requestBody); - logResponseDeatils(responseStatus, responseHeaders, responseData, duration); + logRequestDeatils(request, reqHeaders, requestBody); + logResponseDeatils(responseStatus, responseHeaders, responseData, duration); } function logRequestDeatils(request: IRequestModel, reqHeaders: {}, requestBody: any) { - try { - let reqLog = `\n\n-----------------------------------------------------------------------------`; - reqLog = reqLog + `\n▶ ${request.method.toUpperCase()} ${request.url}\n`; - reqLog = reqLog + `-----------------------------------------------------------------------------\n`; - reqLog = reqLog + `𝘙𝘦𝘲𝘶𝘦𝘴𝘵 𝘋𝘦𝘵𝘢𝘪𝘭𝘴: \n Url: ${request.url}\n Method: ${request.method.toUpperCase()}\n`; - reqLog = reqLog + ` Time: ${formatDateWithMs()}\n`; - if (request.headers.filter(i => i.isChecked)?.length > 0) { - reqLog = reqLog + ` Request Headers:`; - for (var prop in reqHeaders) { - reqLog = reqLog + `\n ${prop}: "${reqHeaders[prop]}"`; - } - } + try { + let reqLog = `\n\n-----------------------------------------------------------------------------`; + reqLog = reqLog + `\n▶ ${request.method.toUpperCase()} ${request.url}\n`; + reqLog = reqLog + `-----------------------------------------------------------------------------\n`; + reqLog = reqLog + `𝘙𝘦𝘲𝘶𝘦𝘴𝘵 𝘋𝘦𝘵𝘢𝘪𝘭𝘴: \n Url: ${request.url}\n Method: ${request.method.toUpperCase()}\n`; + reqLog = reqLog + ` Time: ${formatDateWithMs()}\n`; + if (request.headers.filter(i => i.isChecked)?.length > 0) { + reqLog = reqLog + ` Request Headers:`; + for (var prop in reqHeaders) { + reqLog = reqLog + `\n ${prop}: "${reqHeaders[prop]}"`; + } + } - if (requestBody) { - reqLog = reqLog + `\n Request Body:\n`; - if (request.body.bodyType === "binary") { - reqLog = reqLog + ` src: ${request.body.binary.fileName}\n`; - } else if (request.body.bodyType === "formurlencoded") { - reqLog = reqLog + ` ${decodeURIComponent(requestBody.toString().replace(/\+/g, ' '))}`; - } else if (request.body.bodyType === "formdata") { - reqLog = reqLog + ` ${requestBody.getBuffer()}`; - } else { - reqLog = reqLog + ` ${requestBody}`; - } - } + if (requestBody) { + reqLog = reqLog + `\n Request Body:\n`; + if (request.body.bodyType === "binary") { + reqLog = reqLog + ` src: ${request.body.binary.fileName}\n`; + } else if (request.body.bodyType === "formurlencoded") { + reqLog = reqLog + ` ${decodeURIComponent(requestBody.toString().replace(/\+/g, ' '))}`; + } else if (request.body.bodyType === "formdata") { + reqLog = reqLog + ` ${requestBody.getBuffer()}`; + } else { + reqLog = reqLog + ` ${requestBody}`; + } + } - vsCodeLogger.log("INFO", reqLog); + vsCodeLogger.log("INFO", reqLog); - } catch (err) { - writeLog("error::logRequestDeatils(): " + err); - } + } catch (err) { + writeLog("error::logRequestDeatils(): " + err); + } } function logResponseDeatils(status: number, headers: ITableData[], responseData: any, duration: number) { - try { - let resLog = `\n𝘙𝘦𝘴𝘱𝘰𝘯𝘴𝘦 𝘋𝘦𝘵𝘢𝘪𝘭𝘴: \n Status: ${status} ${status <= 399 ? "✅" : "❌"}\n`; - resLog = resLog + ` Time: ${GetResponseTime(duration)}\n\n`; + try { + let resLog = `\n𝘙𝘦𝘴𝘱𝘰𝘯𝘴𝘦 𝘋𝘦𝘵𝘢𝘪𝘭𝘴: \n Status: ${status} ${status <= 399 ? "✅" : "❌"}\n`; + resLog = resLog + ` Time: ${GetResponseTime(duration)}\n\n`; - if (getLogOption()) { - if (headers.length > 0) { - resLog = resLog + ` Response Headers:\n`; - headers.forEach(({ key, value }) => { - resLog = resLog + ` ${key}: "${value}"\n`; - }); - } + if (getLogOption()) { + if (headers.length > 0) { + resLog = resLog + ` Response Headers:\n`; + headers.forEach(({ key, value }) => { + resLog = resLog + ` ${key}: "${value}"\n`; + }); + } - resLog = resLog + ` Response Body:\n`; - resLog = resLog + ` ${responseData}`; - } + resLog = resLog + ` Response Body:\n`; + resLog = resLog + ` ${responseData}`; + } - vsCodeLogger.log("INFO", resLog); - } catch (err) { - writeLog("error::logResponseDeatils(): " + err); - } -} \ No newline at end of file + vsCodeLogger.log("INFO", resLog); + } catch (err) { + writeLog("error::logResponseDeatils(): " + err); + } +} diff --git a/src/utils/logger/vsCodeLogger.ts b/src/utils/logger/vsCodeLogger.ts index b2354f5..dcb468c 100644 --- a/src/utils/logger/vsCodeLogger.ts +++ b/src/utils/logger/vsCodeLogger.ts @@ -2,70 +2,70 @@ import * as vscode from 'vscode'; export class VSCodeLogger { - private _logChannel: vscode.OutputChannel; - private _isOpen = false; + private _logChannel: vscode.OutputChannel; + private _isOpen = false; - constructor() { - this._logChannel = vscode.window.createOutputChannel("Fetch Client"); - } + constructor() { + this._logChannel = vscode.window.createOutputChannel("Fetch Client"); + } - public showLog() { - this._isOpen ? this._logChannel?.hide() : this._logChannel?.show(); - this._isOpen = !this._isOpen; - } + public showLog() { + this._isOpen ? this._logChannel?.hide() : this._logChannel?.show(); + this._isOpen = !this._isOpen; + } - public log(category: string, ...o: any) { - switch (category.toLowerCase()) { - case 'info': - o.map((args: any) => { - this._logChannel.appendLine('' + this.mapObject(args)); - }); - return; + public log(category: string, ...o: any) { + switch (category.toLowerCase()) { + case 'info': + o.map((args: any) => { + this._logChannel.appendLine('' + this.mapObject(args)); + }); + return; - case 'warn': - o.map((args: any) => { - this._logChannel.appendLine('' + this.mapObject(args)); - }); - return; + case 'warn': + o.map((args: any) => { + this._logChannel.appendLine('' + this.mapObject(args)); + }); + return; - case 'error': - let err: string = ''; - o.map((args: any) => { - err += this.mapObject(args); - }); - this._logChannel.appendLine(err); - vscode.window.showErrorMessage(err, { modal: true }); - return; + case 'error': + let err: string = ''; + o.map((args: any) => { + err += this.mapObject(args); + }); + this._logChannel.appendLine(err); + vscode.window.showErrorMessage(err, { modal: true }); + return; - default: - this._logChannel.appendLine(this.mapObject(category)); - o.map((args: any) => { - this._logChannel.appendLine('' + this.mapObject(args)); - }); - return; - } - } + default: + this._logChannel.appendLine(this.mapObject(category)); + o.map((args: any) => { + this._logChannel.appendLine('' + this.mapObject(args)); + }); + return; + } + } - private mapObject(obj: any) { - switch (typeof obj) { - case 'undefined': - return 'undefined'; + private mapObject(obj: any) { + switch (typeof obj) { + case 'undefined': + return 'undefined'; - case 'string': - return obj; + case 'string': + return obj; - case 'number': - return obj.toString; + case 'number': + return obj.toString; - case 'object': - let ret: string = ''; - for (const [key, value] of Object.entries(obj)) { - ret += (`${key}: ${value}\n`); - } - return ret; + case 'object': + let ret: string = ''; + for (const [key, value] of Object.entries(obj)) { + ret += (`${key}: ${value}\n`); + } + return ret; - default: - return obj; - } - } + default: + return obj; + } + } }; diff --git a/src/utils/ui/addToCollectionUIProvider.tsx b/src/utils/ui/addToCollectionUIProvider.tsx index 298d6e6..598a55b 100644 --- a/src/utils/ui/addToCollectionUIProvider.tsx +++ b/src/utils/ui/addToCollectionUIProvider.tsx @@ -1,133 +1,135 @@ -import * as vscode from 'vscode'; +import axios from 'axios'; import fs from "fs"; +import * as vscode from 'vscode'; import { getStorageManager, OpenExistingItem, sideBarProvider } from '../../extension'; import { getNonce, requestTypes, responseTypes } from '../configuration'; -import { AddToCollection, AttachVariable, CopyToCollection, ExecuteMultipleRequest, ExecuteRequest, GetAllCollectionName, GetAllCollectionsById, GetAllCollectionsByIdWithPath, GetCollectionSettings, GetParentSettings, SaveCollectionSettings } from '../db/collectionDBUtil'; +import { AddToCollection, AttachVariable, CopyToCollection, ExecuteMultipleRequest, GetAllCollectionName, GetAllCollectionsById, GetAllCollectionsByIdWithPath, GetCollectionSettings, GetParentSettings, SaveCollectionSettings } from '../db/collectionDBUtil'; import { GetHistoryById } from '../db/historyDBUtil'; import { GetAllVariable, GetVariableById, UpdateVariable } from '../db/varDBUtil'; import { apiFetch, FetchConfig } from '../fetchUtil'; -import { getHeadersConfiguration, getTimeOutConfiguration } from '../vscodeConfig'; import { writeLog } from '../logger/logger'; -import axios from 'axios'; -import { ExecuteAPIRequest } from './helper'; +import { getHeadersConfiguration, getTimeOutConfiguration } from '../vscodeConfig'; +import { ExecuteAPIRequest, ShowInformationDialog } from './helper'; export const AddToColUI = (extensionUri: any) => { - const disposable = vscode.commands.registerCommand('fetch-client.addToCol', (colId: string, folderId: string, name: string, type: string, varId?: string) => { - const colPanel = vscode.window.createWebviewPanel( - "fetch-client", - name ? name : "Fetch Client - Collection", - vscode.ViewColumn.One, - { enableScripts: true, retainContextWhenHidden: true } - ); + const disposable = vscode.commands.registerCommand('fetch-client.addToCol', (colId: string, folderId: string, name: string, type: string, varId?: string) => { + const colPanel = vscode.window.createWebviewPanel( + "fetch-client", + name ? name : "Fetch Client - Collection", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); - const scriptUri = colPanel.webview.asWebviewUri( - vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") - ); + const scriptUri = colPanel.webview.asWebviewUri( + vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") + ); - const styleUri = colPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); + const styleUri = colPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); - const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); - colPanel.iconPath = iconUri; + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + colPanel.iconPath = iconUri; - const nonce = getNonce(); - const title = `${type}@:@${colId}@:@${folderId}@:@${name}@:@${varId}`; + const nonce = getNonce(); + const title = `${type}@:@${colId}@:@${folderId}@:@${name}@:@${varId}`; - colPanel.webview.html = ` - - - - - - ${title} - - - -
- - - `; + colPanel.webview.html = ` + + + + + + ${title} + + + +
+ + + `; - let fetchConfig: FetchConfig = { - timeOut: getTimeOutConfiguration(), - headersCase: getHeadersConfiguration(), - source: null - }; + let fetchConfig: FetchConfig = { + timeOut: getTimeOutConfiguration(), + headersCase: getHeadersConfiguration(), + source: null + }; - colPanel.webview.onDidReceiveMessage(async (message: any) => { - if (message.type === requestTypes.getAllCollectionNameRequest) { - GetAllCollectionName(colPanel.webview, message.data); - } else if (message.type === requestTypes.getHistoryItemRequest) { - GetHistoryById(message.data, colPanel.webview); - } else if (message.type === requestTypes.addToCollectionsRequest) { - AddToCollection(message.data.col, message.data.hasFolder, message.data.isNewFolder, colPanel.webview, sideBarProvider.view); - } else if (message.type === requestTypes.copyToCollectionsRequest) { - CopyToCollection(message.data.sourceId, message.data.distId, message.data.name, colPanel.webview, sideBarProvider.view); - } else if (message.type === requestTypes.getAllVariableRequest) { - GetAllVariable(colPanel.webview); - } else if (message.type === requestTypes.attachVariableRequest) { - AttachVariable(message.data.colId, message.data.varId, colPanel.webview, sideBarProvider.view); - } else if (message.type === requestTypes.getCollectionsByIdRequest) { - GetAllCollectionsById(message.data.colId, message.data.folderId, message.data.type, colPanel.webview); - } else if (message.type === requestTypes.apiRequest) { - const CancelToken = axios.CancelToken; - fetchConfig.source = CancelToken.source(); - await ExecuteAPIRequest(message, fetchConfig, colPanel.webview); - } else if (message.type === requestTypes.multipleApiRequest) { - ExecuteMultipleRequest(message, fetchConfig, colPanel.webview); - } else if (message.type === requestTypes.getAllVariableRequest) { - GetAllVariable(colPanel.webview); - } else if (message.type === requestTypes.openRunRequest) { - getStorageManager().setValue("run-request", message.data.reqData); - getStorageManager().setValue("run-response", message.data.resData); - OpenExistingItem(message.data.reqData.id, message.data.reqData.name, message.data.colId, message.data.folderId, message.data.varId, "runopen"); - } else if (message.type === requestTypes.exportRunTestJsonRequest) { - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-collection-report-" + message.name + ".json"), filters: { 'Json Files': ['json'] } }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - fs.writeFile(value, JSON.stringify(message.data), (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); - writeLog("error::ExportVariable()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); - } - }); - } - }); - } else if (message.type === requestTypes.exportRunTestCSVRequest) { - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-collection-report-" + message.name + ".csv"), filters: { 'CSV': ['csv'] } }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - fs.writeFile(value, message.data.toString(), (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); - writeLog("error::ExportVariable()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); - } - }); - } - }); - } else if (message.type === requestTypes.saveColSettingsRequest) { - SaveCollectionSettings(colPanel.webview, message.data.colId, message.data.folderId, message.data.settings); - } else if (message.type === requestTypes.getColSettingsRequest) { - GetCollectionSettings(colPanel.webview, message.data.colId, message.data.folderId); - } else if (message.type === requestTypes.updateVariableRequest) { - UpdateVariable(message.data, null); - } else if (message.type === requestTypes.getVariableItemRequest) { - GetVariableById(message.data.id, message.data.isGlobal, colPanel.webview); - } else if (message.type === requestTypes.tokenRequest) { - apiFetch(message.data.reqData, message.data.variableData, message.data.settings, null, fetchConfig, responseTypes.tokenResponse).then((data) => { - colPanel.webview.postMessage(data); - }); - } else if (message.type === requestTypes.getCollectionsByIdWithPathRequest) { - GetAllCollectionsByIdWithPath(message.data, colPanel.webview); - } else if (message.type === requestTypes.getParentSettingsRequest) { - GetParentSettings(message.data.colId, message.data.folderId, colPanel.webview); - } - }); - }); + colPanel.webview.onDidReceiveMessage(async (message: any) => { + if (message.type === requestTypes.getAllCollectionNameRequest) { + GetAllCollectionName(colPanel.webview, message.data); + } else if (message.type === requestTypes.getHistoryItemRequest) { + GetHistoryById(message.data, colPanel.webview); + } else if (message.type === requestTypes.addToCollectionsRequest) { + AddToCollection(message.data.col, message.data.hasFolder, message.data.isNewFolder, colPanel.webview, sideBarProvider.view); + } else if (message.type === requestTypes.copyToCollectionsRequest) { + CopyToCollection(message.data.sourceId, message.data.distId, message.data.name, colPanel.webview, sideBarProvider.view); + } else if (message.type === requestTypes.getAllVariableRequest) { + GetAllVariable(colPanel.webview); + } else if (message.type === requestTypes.attachVariableRequest) { + AttachVariable(message.data.colId, message.data.varId, colPanel.webview, sideBarProvider.view); + } else if (message.type === requestTypes.getCollectionsByIdRequest) { + GetAllCollectionsById(message.data.colId, message.data.folderId, message.data.type, colPanel.webview); + } else if (message.type === requestTypes.apiRequest) { + const CancelToken = axios.CancelToken; + fetchConfig.source = CancelToken.source(); + await ExecuteAPIRequest(message, fetchConfig, colPanel.webview); + } else if (message.type === requestTypes.multipleApiRequest) { + ExecuteMultipleRequest(message, fetchConfig, colPanel.webview); + } else if (message.type === requestTypes.getAllVariableRequest) { + GetAllVariable(colPanel.webview); + } else if (message.type === requestTypes.openRunRequest) { + getStorageManager().setValue("run-request", message.data.reqData); + getStorageManager().setValue("run-response", message.data.resData); + OpenExistingItem(message.data.reqData.id, message.data.reqData.name, message.data.colId, message.data.folderId, message.data.varId, "runopen"); + } else if (message.type === requestTypes.exportRunTestJsonRequest) { + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-collection-report-" + message.name?.replace(/[/\\?%*:|"<>]/g, '-') + ".json"), filters: { 'Json Files': ['json'] } }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + fs.writeFile(value, JSON.stringify(message.data), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::ExportVariable()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); + } + }); + } + }); + } else if (message.type === requestTypes.exportRunTestCSVRequest) { + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-collection-report-" + message.name?.replace(/[/\\?%*:|"<>]/g, '-') + ".csv"), filters: { 'CSV': ['csv'] } }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + fs.writeFile(value, message.data.toString(), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::ExportVariable()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); + } + }); + } + }); + } else if (message.type === requestTypes.saveColSettingsRequest) { + SaveCollectionSettings(colPanel.webview, message.data.colId, message.data.folderId, message.data.settings); + } else if (message.type === requestTypes.getColSettingsRequest) { + GetCollectionSettings(colPanel.webview, message.data.colId, message.data.folderId); + } else if (message.type === requestTypes.updateVariableRequest) { + UpdateVariable(message.data, null); + } else if (message.type === requestTypes.getVariableItemRequest) { + GetVariableById(message.data.id, message.data.isGlobal, colPanel.webview); + } else if (message.type === requestTypes.tokenRequest) { + apiFetch(message.data.reqData, message.data.variableData, message.data.settings, null, fetchConfig, responseTypes.tokenResponse).then((data) => { + colPanel.webview.postMessage(data); + }); + } else if (message.type === requestTypes.getCollectionsByIdWithPathRequest) { + GetAllCollectionsByIdWithPath(message.data, colPanel.webview); + } else if (message.type === requestTypes.getParentSettingsRequest) { + GetParentSettings(message.data.colId, message.data.folderId, colPanel.webview); + } else if (message.type === requestTypes.showMessageRequest) { + ShowInformationDialog(message.data); + } + }); + }); - return disposable; + return disposable; -}; \ No newline at end of file +}; diff --git a/src/utils/ui/bulkExportUIProvider.tsx b/src/utils/ui/bulkExportUIProvider.tsx new file mode 100644 index 0000000..f0564e6 --- /dev/null +++ b/src/utils/ui/bulkExportUIProvider.tsx @@ -0,0 +1,66 @@ +import * as vscode from 'vscode'; +import { getNonce, requestTypes, responseTypes } from '../configuration'; +import { GetAllCollectionName } from '../db/collectionDBUtil'; +import { BulkExport } from '../db/mainDBUtil'; +import { BulkExportVariables, GetAllVariable } from '../db/varDBUtil'; + +export const BulkExportProviderUI = (extensionUri: any) => { + const disposable = vscode.commands.registerCommand('fetch-client.bulkExport', (type: string) => { + const bulkExportPanel = vscode.window.createWebviewPanel( + "fetch-client", + "Fetch Client - Bulk Export", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); + + const scriptUri = bulkExportPanel.webview.asWebviewUri( + vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") + ); + + const styleUri = bulkExportPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); + + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + bulkExportPanel.iconPath = iconUri; + + const nonce = getNonce(); + const title = `bulkexport@:@${type}`; + + bulkExportPanel.webview.html = ` + + + + + + ${title} + + + +
+ + + `; + + bulkExportPanel.webview.onDidReceiveMessage((message: any) => { + if (message.type === requestTypes.getAllCollectionNameRequest) { + GetAllCollectionName(bulkExportPanel.webview, message.data); + } else if (message.type === requestTypes.selectPathRequest) { + vscode.window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, openLabel: 'Select', }).then(fileUri => { + if (fileUri && fileUri[0]) { + bulkExportPanel.webview.postMessage({ type: responseTypes.selectPathResponse, path: fileUri[0].fsPath }); + } + }); + } else if (message.type === requestTypes.bulkColExportRequest) { + if(message.data.type === "col"){ + BulkExport(message.data.path, message.data?.cols, bulkExportPanel.webview); + } else { + BulkExportVariables(message.data.path, message.data?.cols, bulkExportPanel.webview); + } + } else if (message.type === requestTypes.getAllVariableRequest) { + GetAllVariable(bulkExportPanel.webview); + } + }); + }); + + return disposable; + +}; diff --git a/src/utils/ui/cookieUIProvider.tsx b/src/utils/ui/cookieUIProvider.tsx index e3be2dc..96372d7 100644 --- a/src/utils/ui/cookieUIProvider.tsx +++ b/src/utils/ui/cookieUIProvider.tsx @@ -1,67 +1,70 @@ import * as vscode from 'vscode'; import { getNonce, requestTypes } from '../configuration'; -import { DeleteAllCookies, DeleteCookieById, GetAllCookies, SaveCookie } from '../db/cookieDBUtil'; +import { DeleteAllCookies, DeleteCookieById, GetAllCookies } from '../db/cookieDBUtil'; +import { ShowInformationDialog } from './helper'; export const CookieUI = (extensionUri: any) => { - const disposable = vscode.commands.registerCommand('fetch-client.manageCookies', (id?: string) => { - const cookiePanel = vscode.window.createWebviewPanel( - "fetch-client", - "Fetch Client - Manage Cookies", - vscode.ViewColumn.One, - { enableScripts: true, retainContextWhenHidden: true } - ); + const disposable = vscode.commands.registerCommand('fetch-client.manageCookies', (id?: string) => { + const cookiePanel = vscode.window.createWebviewPanel( + "fetch-client", + "Fetch Client - Manage Cookies", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); - const scriptUri = cookiePanel.webview.asWebviewUri( - vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") - ); + const scriptUri = cookiePanel.webview.asWebviewUri( + vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") + ); - const styleUri = cookiePanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); + const styleUri = cookiePanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); - const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); - cookiePanel.iconPath = iconUri; + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + cookiePanel.iconPath = iconUri; - const nonce = getNonce(); - const title = `managecookies@:@${id}`; + const nonce = getNonce(); + const title = `managecookies@:@${id}`; - cookiePanel.webview.html = ` - - - - - - ${title} - - - -
- - - `; + cookiePanel.webview.html = ` + + + + + + ${title} + + + +
+ + + `; - cookiePanel.webview.onDidReceiveMessage((reqData: any) => { - if (reqData.type === requestTypes.getAllCookiesRequest) { - GetAllCookies(cookiePanel.webview); - } else if (reqData.type === requestTypes.deleteCookieByIdRequest) { - showConfirmationBox("Do you want to delete this cookie?").then((data: any) => { - if (data === "Yes") { - DeleteCookieById(reqData.data, cookiePanel.webview); - } - }); - } else if (reqData.type === requestTypes.deleteAllCookieRequest) { - showConfirmationBox("Do you want to delete all cookies?").then((data: any) => { - if (data === "Yes") { - DeleteAllCookies(cookiePanel.webview); - } - }); - } - }); - }); + cookiePanel.webview.onDidReceiveMessage((reqData: any) => { + if (reqData.type === requestTypes.getAllCookiesRequest) { + GetAllCookies(cookiePanel.webview); + } else if (reqData.type === requestTypes.deleteCookieByIdRequest) { + showConfirmationBox("Do you want to delete this cookie?").then((data: any) => { + if (data === "Yes") { + DeleteCookieById(reqData.data, cookiePanel.webview); + } + }); + } else if (reqData.type === requestTypes.deleteAllCookieRequest) { + showConfirmationBox("Do you want to delete all cookies?").then((data: any) => { + if (data === "Yes") { + DeleteAllCookies(cookiePanel.webview); + } + }); + } else if (reqData.type === requestTypes.showMessageRequest) { + ShowInformationDialog(reqData.data); + } + }); + }); - return disposable; + return disposable; }; async function showConfirmationBox(text: string) { - const res = await vscode.window.showWarningMessage(text, { modal: true }, "Yes", "No"); - return res; -} \ No newline at end of file + const res = await vscode.window.showWarningMessage(text, { modal: true }, "Yes", "No"); + return res; +} diff --git a/src/utils/ui/curlUIProvider.tsx b/src/utils/ui/curlUIProvider.tsx index e0d383d..3b24407 100644 --- a/src/utils/ui/curlUIProvider.tsx +++ b/src/utils/ui/curlUIProvider.tsx @@ -8,84 +8,84 @@ import { getErrorResponse } from '../helper'; import { getHeadersConfiguration, getTimeOutConfiguration } from '../vscodeConfig'; export const CurlProviderUI = (extensionUri: any) => { - const disposable = vscode.commands.registerCommand('fetch-client.curlRequest', () => { - const curlPanel = vscode.window.createWebviewPanel( - "fetch-client", - "Fetch Client - Curl Request", - vscode.ViewColumn.One, - { enableScripts: true, retainContextWhenHidden: true } - ); + const disposable = vscode.commands.registerCommand('fetch-client.curlRequest', () => { + const curlPanel = vscode.window.createWebviewPanel( + "fetch-client", + "Fetch Client - Curl Request", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); - const scriptUri = curlPanel.webview.asWebviewUri( - vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") - ); + const scriptUri = curlPanel.webview.asWebviewUri( + vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") + ); - const styleUri = curlPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); + const styleUri = curlPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); - const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); - curlPanel.iconPath = iconUri; + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + curlPanel.iconPath = iconUri; - const nonce = getNonce(); - const title = `curlreq`; + const nonce = getNonce(); + const title = `curlreq`; - curlPanel.webview.html = ` - - - - - - ${title} - - - -
- - - `; + curlPanel.webview.html = ` + + + + + + ${title} + + + +
+ + + `; - let fetchConfig: FetchConfig = { - timeOut: getTimeOutConfiguration(), - headersCase: getHeadersConfiguration(), - source: null - }; - - curlPanel.webview.onDidReceiveMessage((reqData: any) => { - if (reqData.type === requestTypes.runCurlRequest) { - let req = ConvertCurlToRequest(reqData.data); - if (!req || !req.url) { - let apiResponse = getErrorResponse(); - apiResponse.response.responseData = "Invalid Curl Command"; - curlPanel.webview.postMessage({ type: responseTypes.runCurlResponse, request: null, response: apiResponse }); - return; - } - apiFetch(req, null, null, null, fetchConfig).then((data) => { - curlPanel.webview.postMessage({ type: responseTypes.runCurlResponse, request: req, response: data }); - }); - } else if (reqData.type === requestTypes.convertCurlToJsonRequest) { - let req = ConvertCurlToRequest(reqData.data.curl); - if (!req || !req.url) { - curlPanel.webview.postMessage({ type: responseTypes.curlErrorResponse, error: "Invalid Curl Command" }); - return; - } - req.name = req.url; - if (reqData.data.hasFolder) { - reqData.data.col.data[0].data[0].method = req.method; - reqData.data.col.data[0].data[0].name = req.name; - reqData.data.col.data[0].data[0].url = req.url; - } else { - reqData.data.col.data[0].method = req.method; - reqData.data.col.data[0].name = req.name; - reqData.data.col.data[0].url = req.url; - } - AddToCollection(reqData.data.col, reqData.data.hasFolder, reqData.data.isNewFolder, curlPanel.webview, sideBarProvider.view, req); - } else if (reqData.type === requestTypes.getAllCollectionNameRequest) { - GetAllCollectionName(curlPanel.webview, reqData.data); - } else if (reqData.type === requestTypes.openHistoryItemRequest) { - OpenExistingItem(reqData.data.id, reqData.data.name, reqData.data.colId, reqData.data.folderId, reqData.data.varId); - } - }); - }); + let fetchConfig: FetchConfig = { + timeOut: getTimeOutConfiguration(), + headersCase: getHeadersConfiguration(), + source: null + }; - return disposable; + curlPanel.webview.onDidReceiveMessage((reqData: any) => { + if (reqData.type === requestTypes.runCurlRequest) { + let req = ConvertCurlToRequest(reqData.data); + if (!req || !req.url) { + let apiResponse = getErrorResponse(); + apiResponse.response.responseData = "Invalid Curl Command"; + curlPanel.webview.postMessage({ type: responseTypes.runCurlResponse, request: null, response: apiResponse }); + return; + } + apiFetch(req, null, null, null, fetchConfig).then((data) => { + curlPanel.webview.postMessage({ type: responseTypes.runCurlResponse, request: req, response: data }); + }); + } else if (reqData.type === requestTypes.convertCurlToJsonRequest) { + let req = ConvertCurlToRequest(reqData.data.curl); + if (!req || !req.url) { + curlPanel.webview.postMessage({ type: responseTypes.curlErrorResponse, error: "Invalid Curl Command" }); + return; + } + req.name = req.url; + if (reqData.data.hasFolder) { + reqData.data.col.data[0].data[0].method = req.method; + reqData.data.col.data[0].data[0].name = req.name; + reqData.data.col.data[0].data[0].url = req.url; + } else { + reqData.data.col.data[0].method = req.method; + reqData.data.col.data[0].name = req.name; + reqData.data.col.data[0].url = req.url; + } + AddToCollection(reqData.data.col, reqData.data.hasFolder, reqData.data.isNewFolder, curlPanel.webview, sideBarProvider.view, req); + } else if (reqData.type === requestTypes.getAllCollectionNameRequest) { + GetAllCollectionName(curlPanel.webview, reqData.data); + } else if (reqData.type === requestTypes.openHistoryItemRequest) { + OpenExistingItem(reqData.data.id, reqData.data.name, reqData.data.colId, reqData.data.folderId, reqData.data.varId); + } + }); + }); + + return disposable; }; diff --git a/src/utils/ui/errorLogUIProvider.tsx b/src/utils/ui/errorLogUIProvider.tsx index 35e8423..0f051e1 100644 --- a/src/utils/ui/errorLogUIProvider.tsx +++ b/src/utils/ui/errorLogUIProvider.tsx @@ -1,61 +1,61 @@ -import * as vscode from 'vscode'; import fs from "fs"; import path from 'path'; +import * as vscode from 'vscode'; import { getNonce, requestTypes, responseTypes } from '../configuration'; -import { logPath } from '../logger/constants'; import { getExtDbPath } from '../db/getExtDbPath'; +import { logPath } from '../logger/constants'; export const ErrorLogUI = (extensionUri: any) => { - const disposable = vscode.commands.registerCommand('fetch-client.openErrorLog', () => { - const errorLogPanel = vscode.window.createWebviewPanel( - "fetch-client", - "Fetch Client - Error Log", - vscode.ViewColumn.One, - { enableScripts: true, retainContextWhenHidden: true } - ); - - const scriptUri = errorLogPanel.webview.asWebviewUri( - vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") - ); - - const styleUri = errorLogPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); - - const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); - errorLogPanel.iconPath = iconUri; - - const nonce = getNonce(); - const title = "errorlog"; - - errorLogPanel.webview.html = ` - - - - - - ${title} - - - -
- - - `; - - errorLogPanel.webview.onDidReceiveMessage((reqData: any) => { - if (reqData.type === requestTypes.getErrorLogRequest) { - let data = ""; - try { - if (fs.existsSync(path.resolve(getExtDbPath(), logPath))) { - data = fs.readFileSync(path.resolve(getExtDbPath(), logPath), "utf8"); - } - } catch { - data = ""; - } - errorLogPanel.webview.postMessage({ type: responseTypes.getErrorLogResponse, fileData: data }); - } - }); - }); - - return disposable; - -}; \ No newline at end of file + const disposable = vscode.commands.registerCommand('fetch-client.openErrorLog', () => { + const errorLogPanel = vscode.window.createWebviewPanel( + "fetch-client", + "Fetch Client - Error Log", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); + + const scriptUri = errorLogPanel.webview.asWebviewUri( + vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") + ); + + const styleUri = errorLogPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); + + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + errorLogPanel.iconPath = iconUri; + + const nonce = getNonce(); + const title = "errorlog"; + + errorLogPanel.webview.html = ` + + + + + + ${title} + + + +
+ + + `; + + errorLogPanel.webview.onDidReceiveMessage((reqData: any) => { + if (reqData.type === requestTypes.getErrorLogRequest) { + let data = ""; + try { + if (fs.existsSync(path.resolve(getExtDbPath(), logPath))) { + data = fs.readFileSync(path.resolve(getExtDbPath(), logPath), "utf8"); + } + } catch { + data = ""; + } + errorLogPanel.webview.postMessage({ type: responseTypes.getErrorLogResponse, fileData: data }); + } + }); + }); + + return disposable; + +}; diff --git a/src/utils/ui/helper.ts b/src/utils/ui/helper.ts index db1456e..6922500 100644 --- a/src/utils/ui/helper.ts +++ b/src/utils/ui/helper.ts @@ -1,98 +1,103 @@ +import * as vscode from "vscode"; import { Webview } from "vscode"; import { sideBarProvider, vsCodeLogger } from "../../extension"; import { IPreFetch, IReqSettings, IRequestModel } from "../../fetch-client-ui/components/RequestUI/redux/types"; import { IHistory, ISettings, IVariable } from "../../fetch-client-ui/components/SideBar/redux/types"; -import { apiFetch, FetchConfig } from "../fetchUtil"; -import { formatDate, getErrorResponse } from "../helper"; -import { PreFetchRunner } from "../PreFetchRunner"; -import { SaveRequest, UpdateRequest } from "../db/mainDBUtil"; import { SaveHistory, UpdateHistory } from "../db/historyDBUtil"; +import { SaveRequest, UpdateRequest } from "../db/mainDBUtil"; import { GetVariableByIdSync } from "../db/varDBUtil"; +import { apiFetch, FetchConfig } from "../fetchUtil"; +import { formatDate, getErrorResponse } from "../helper"; import { writeLog } from "../logger/logger"; +import { PreFetchRunner } from "../PreFetchRunner"; export async function ExecuteAPIRequest(message: any, fetchConfig: FetchConfig, webview: Webview) { - try { - let request = message.data.reqData as IRequestModel; - let settings = message.data.settings as ISettings; - let reqSettings = message.data.reqSettings as IReqSettings; - let isVariableUpdated: boolean = false; - let updatedVariable: IVariable = message.data.variableData; + try { + let request = message.data.reqData as IRequestModel; + let settings = message.data.settings as ISettings; + let reqSettings = message.data.reqSettings as IReqSettings; + let isVariableUpdated: boolean = false; + let updatedVariable: IVariable = message.data.variableData; - // Run PreRequests in the parent - if ((!reqSettings || reqSettings?.skipParentPreFetch === false) && settings?.preFetch?.requests?.length > 0) { - let continueRequest = await runPreRequest(message, settings.preFetch, true, fetchConfig, webview); - if (!continueRequest) { - return; - } - isVariableUpdated = true; - } + // Run PreRequests in the parent + if ((!reqSettings || reqSettings?.skipParentPreFetch === false) && settings?.preFetch?.requests?.length > 0) { + let continueRequest = await runPreRequest(message, settings.preFetch, true, fetchConfig, webview); + if (!continueRequest) { + return; + } + isVariableUpdated = true; + } - // Run PreRequests in the request item - if (request.preFetch?.requests?.length > 0 && request.preFetch?.requests[0].reqId) { - let continueRequest = await runPreRequest(message, request.preFetch, false, fetchConfig, webview); - if (!continueRequest) { - return; - } - isVariableUpdated = true; - } + // Run PreRequests in the request item + if (request.preFetch?.requests?.length > 0 && request.preFetch?.requests[0].reqId) { + let continueRequest = await runPreRequest(message, request.preFetch, false, fetchConfig, webview); + if (!continueRequest) { + return; + } + isVariableUpdated = true; + } - if (isVariableUpdated && message.data.variableData?.data?.length > 0) { - updatedVariable = await GetVariableByIdSync(message.data.variableData?.id); - } + if (isVariableUpdated && message.data.variableData?.data?.length > 0) { + updatedVariable = await GetVariableByIdSync(message.data.variableData?.id); + } - _executeAPIRequest(message, updatedVariable, fetchConfig, webview); - } catch (err) { - writeLog("error::helper::ExecuteAPIRequest()" + err); - throw err; - } + _executeAPIRequest(message, updatedVariable, fetchConfig, webview); + } catch (err) { + writeLog("error::helper::ExecuteAPIRequest()" + err); + throw err; + } } async function runPreRequest(message: any, preFetch: IPreFetch, isParentPreRequest: boolean, fetchConfig: FetchConfig, webview: Webview): Promise { - let request = message.data.reqData as IRequestModel; - let preFetchCollectionRunner = new PreFetchRunner(fetchConfig, request.id); - await preFetchCollectionRunner.RunPreRequests(preFetch, 0, 0, request.name, isParentPreRequest); - if (preFetchCollectionRunner.message) { - if (fetchConfig.runMainRequest === true) { - setTimeout(() => { - vsCodeLogger.log("INFO", "\n\n" + preFetchCollectionRunner.message + "\n"); - }, 500); - return true; - } else { - fetchConfig.source = null; - let errorResponse = getErrorResponse(); - errorResponse.response.responseData = preFetchCollectionRunner.message; - webview.postMessage(errorResponse); - return false; - } - } + let request = message.data.reqData as IRequestModel; + let preFetchCollectionRunner = new PreFetchRunner(fetchConfig, request.id); + await preFetchCollectionRunner.RunPreRequests(preFetch, 0, 0, request.name, isParentPreRequest); + if (preFetchCollectionRunner.message) { + if (fetchConfig.runMainRequest === true) { + setTimeout(() => { + vsCodeLogger.log("INFO", "\n\n" + preFetchCollectionRunner.message + "\n"); + }, 500); + return true; + } else { + fetchConfig.source = null; + let errorResponse = getErrorResponse(); + errorResponse.response.responseData = preFetchCollectionRunner.message; + webview.postMessage(errorResponse); + return false; + } + } - return true; + return true; } function _executeAPIRequest(message: any, variable: IVariable, fetchConfig: FetchConfig, webview: Webview) { - apiFetch(message.data.reqData, variable?.data, message.data.settings, message.data.reqSettings, fetchConfig).then((data) => { - fetchConfig.source = null; - webview.postMessage(data); + apiFetch(message.data.reqData, variable?.data, message.data.settings, message.data.reqSettings, fetchConfig).then((data) => { + fetchConfig.source = null; + webview.postMessage(data); - let item: IHistory = { - id: message.data.reqData.id, - method: message.data.reqData.method, - name: message.data.reqData.name ? message.data.reqData.name : message.data.reqData.url, - url: message.data.reqData.url, - createdTime: message.data.reqData.createdTime ? message.data.reqData.createdTime : formatDate() - }; + let item: IHistory = { + id: message.data.reqData.id, + method: message.data.reqData.method, + name: message.data.reqData.name ? message.data.reqData.name : message.data.reqData.url, + url: message.data.reqData.url, + createdTime: message.data.reqData.createdTime ? message.data.reqData.createdTime : formatDate() + }; - let reqData = message.data.reqData as IRequestModel; - if (reqData.body.bodyType === "binary") { - reqData.body.binary.data = ""; - } + let reqData = message.data.reqData as IRequestModel; + if (reqData.body.bodyType === "binary") { + reqData.body.binary.data = ""; + } - if (message.data.isNew) { - SaveRequest(reqData); - SaveHistory(item, sideBarProvider.view); - } else { - UpdateRequest(reqData); - UpdateHistory(item); - } - }); -} \ No newline at end of file + if (message.data.isNew) { + SaveRequest(reqData); + SaveHistory(item, sideBarProvider.view); + } else { + UpdateRequest(reqData); + UpdateHistory(item); + } + }); +} + +export function ShowInformationDialog(info: string) { + vscode.window.showInformationMessage(info, { modal: true }); +} diff --git a/src/utils/ui/mainUIProvider.tsx b/src/utils/ui/mainUIProvider.tsx index 0458ab2..843dfc7 100644 --- a/src/utils/ui/mainUIProvider.tsx +++ b/src/utils/ui/mainUIProvider.tsx @@ -1,9 +1,9 @@ import axios from "axios"; import fs from "fs"; import * as vscode from "vscode"; -import { getStorageManager, OpenCookieUI, OpenVariableUI, pubSub, sideBarProvider, vsCodeLogger } from "../../extension"; +import { getStorageManager, OpenCookieUI, OpenVariableUI, pubSub, sideBarProvider } from "../../extension"; import { IRequestModel } from "../../fetch-client-ui/components/RequestUI/redux/types"; -import { IHistory, ISettings } from "../../fetch-client-ui/components/SideBar/redux/types"; +import { IHistory } from "../../fetch-client-ui/components/SideBar/redux/types"; import { IPubSubMessage, Subscription } from "../PubSub"; import { getNonce, pubSubTypes, requestTypes, responseTypes } from "../configuration"; import { GetAllCollectionName, GetAllCollectionsByIdWithPath, GetParentSettings, UpdateCollection } from "../db/collectionDBUtil"; @@ -12,320 +12,320 @@ import { SaveHistory, UpdateHistory } from "../db/historyDBUtil"; import { GetExitingItem, SaveRequest, UpdateRequest } from "../db/mainDBUtil"; import { GetAllVariable, GetVariableById, UpdateVariable } from "../db/varDBUtil"; import { apiFetch, FetchConfig } from "../fetchUtil"; -import { formatDate, getErrorResponse } from "../helper"; +import { formatDate } from "../helper"; import { writeLog } from "../logger/logger"; import { getConfiguration, getHeadersConfiguration, getLayoutConfiguration, getRequestTabOption, getRunMainRequestOption, getTimeOutConfiguration, getVSCodeTheme } from "../vscodeConfig"; import { ExecuteAPIRequest } from "./helper"; export class WebAppPanel { - public static currentPanel: WebAppPanel | undefined; - private readonly _panel: vscode.WebviewPanel; - private readonly _extensionUri: vscode.Uri; - private _disposables: vscode.Disposable[] = []; - - private _scriptionId: Subscription; - - public static createOrShow(extensionUri: vscode.Uri, id?: string, name?: string, colId?: string, varId?: string, type?: string, folderId?: string, newTab?: boolean) { - const column = vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.viewColumn : undefined; - - let tabOption = getRequestTabOption(); - - if (!tabOption && !newTab && WebAppPanel.currentPanel) { - WebAppPanel.currentPanel._update(id, colId, varId, type, folderId); - WebAppPanel.currentPanel._panel.reveal(column); - WebAppPanel.currentPanel._panel.title = name ? name : "New Request"; - return; - } - - const panel = vscode.window.createWebviewPanel( - "fetch-client", - name ? name : "New Request", - vscode.ViewColumn.One, - { enableScripts: true, retainContextWhenHidden: true } - ); - - const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); - panel.iconPath = iconUri; - - WebAppPanel.currentPanel = new WebAppPanel(panel, extensionUri, id, colId, varId, type, folderId); - } - - public static kill() { - WebAppPanel.currentPanel?.dispose(); - WebAppPanel.currentPanel = undefined; - } - - public static getCurrentWebView() { - if (WebAppPanel.currentPanel) { return WebAppPanel.currentPanel._panel.webview; } - - return null; - } - - private constructor( - panel: vscode.WebviewPanel, - extensionUri: vscode.Uri, - id?: string, - colId?: string, - varId?: string, - type?: string, - folderId?: string - ) { - this._panel = panel; - this._extensionUri = extensionUri; - - this._update(id, colId, varId, type, folderId); - - this._pushMessages = this._pushMessages.bind(this); - - this._scriptionId = pubSub.subscribe(this._pushMessages); - - this._panel.onDidDispose(() => { - this._scriptionId.unsubscribe(); - this.dispose(id, colId, folderId); - }, null, this._disposables); - - this._panel.onDidChangeViewState(function (event) { - if (event.webviewPanel.active) { - sideBarProvider.view.webview.postMessage({ type: requestTypes.selectItemRequest, colId: colId, folId: folderId, id: id }); - } - }, null, this._disposables); - - let fetchConfig: FetchConfig = { - timeOut: getTimeOutConfiguration(), - headersCase: getHeadersConfiguration(), - runMainRequest: getRunMainRequestOption() - }; - - - // Handle messages from the webview - this._panel.webview.onDidReceiveMessage( - async message => { - try { - if (message.type === requestTypes.apiRequest) { - const CancelToken = axios.CancelToken; - fetchConfig.source = CancelToken.source(); - - await ExecuteAPIRequest(message, fetchConfig, this._panel.webview); - - let item: IHistory = { - id: message.data.reqData.id, - method: message.data.reqData.method, - name: message.data.reqData.name ? message.data.reqData.name : message.data.reqData.url, - url: message.data.reqData.url, - createdTime: message.data.reqData.createdTime ? message.data.reqData.createdTime : formatDate() - }; - - if (message.data.colId) { - UpdateCollection(message.data.colId, item); - } - - sideBarProvider.view.webview.postMessage({ type: responseTypes.updateCollectionHistoryItem, colId: message.data.colId, item: item }); - - } else if (message.type === requestTypes.cancelRequest) { - if (fetchConfig.source) { - fetchConfig.source.cancel("The request has been cancelled by the user."); - } - } else if (message.type === requestTypes.layoutConfigRequest) { - this._panel.webview.postMessage(getLayoutConfiguration()); - } else if (message.type === requestTypes.configRequest) { - this._panel.webview.postMessage(getConfiguration()); - } else if (message.type === requestTypes.openExistingItemRequest) { - GetExitingItem(this._panel.webview, message.data); - } else if (message.type === requestTypes.getOpenAndRunItemDataRequest) { - GetExitingItem(this._panel.webview, message.data, null, "OpenAndRun"); - } else if (message.type === requestTypes.saveResponseRequest) { - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-response." + message.fileType) }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - fs.writeFile(value, message.data, (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); - writeLog("error::saveResponseRequest()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); - } - }); - } - }); - } else if (message.type === requestTypes.saveTestResponseRequest) { - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-tests.json") }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - fs.writeFile(value, message.data, (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); - writeLog("error::saveTestResponseRequest()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); - } - }); - } - }); - } else if (message.type === requestTypes.downloadFileTypeRequest) { - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-file." + message.fileType) }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - fs.writeFile(value, new Uint8Array(message.resData.data), (error) => { - if (error) { - vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message), { modal: true }; - writeLog("error::downloadFileTypeRequest()::FileWrite()" + error.message); - } else { - vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); - } - }); - } - }); - } else if (message.type === requestTypes.selectFileRequest) { - vscode.window.showOpenDialog().then((uri: vscode.Uri[] | undefined) => { - if (uri && uri.length > 0) { - const value = uri[0].fsPath; - const data = fs.readFileSync(value, "utf8"); - this._panel.webview.postMessage({ type: responseTypes.selectFileResponse, path: value, fileData: data }); - } - }); - } else if (message.type === requestTypes.readFileRequest) { - if (!fs.existsSync(message.path)) { - this._panel.webview.postMessage({ type: responseTypes.readFileResponse, fileData: "" }); - } else { - const data = fs.readFileSync(message.path, "utf8"); - this._panel.webview.postMessage({ type: responseTypes.readFileResponse, fileData: data }); - } - } else if (message.type === requestTypes.getVariableItemRequest) { - GetVariableById(message.data.id, message.data.isGlobal, this._panel.webview); - } else if (message.type === requestTypes.getAllVariableRequest) { - GetAllVariable(this._panel.webview); - } else if (message.type === requestTypes.getRunItemDataRequest) { - this._panel.webview.postMessage({ type: responseTypes.getRunItemDataResponse, reqData: getStorageManager().getValue("run-request"), resData: getStorageManager().getValue("run-response") }); - getStorageManager().setValue("run-request", ""); - getStorageManager().setValue("run-response", ""); - } else if (message.type === requestTypes.saveRequest) { - let item: IHistory = { - id: message.data.reqData.id, - method: message.data.reqData.method, - name: message.data.reqData.name ? message.data.reqData.name : message.data.reqData.url, - url: message.data.reqData.url, - createdTime: message.data.reqData.createdTime ? message.data.reqData.createdTime : formatDate() - }; - - let reqData = message.data.reqData as IRequestModel; - if (reqData.body.bodyType === "binary") { - reqData.body.binary.data = ""; - } - if (message.data.isNew) { - SaveRequest(reqData); - SaveHistory(item, sideBarProvider.view); - } else { - UpdateRequest(reqData); - UpdateHistory(item); - if (message.data.colId) { - UpdateCollection(message.data.colId, item); - } - } - this._panel.webview.postMessage({ type: responseTypes.saveResponse }); - sideBarProvider.view.webview.postMessage({ type: responseTypes.updateCollectionHistoryItem, colId: message.data.colId, item: item }); - } - else if (message.type === requestTypes.openVariableItemRequest) { - OpenVariableUI(message.data); - } else if (message.type === requestTypes.updateVariableRequest) { - UpdateVariable(message.data, null); - } else if (message.type === requestTypes.saveCookieRequest) { - SaveCookie(message.data, null); - } else if (message.type === requestTypes.getAllCookiesRequest) { - GetAllCookies(this._panel.webview); - } else if (message.type === requestTypes.openManageCookiesRequest) { - OpenCookieUI(message.data); - } else if (message.type === requestTypes.getParentSettingsRequest) { - GetParentSettings(message.data.colId, message.data.folderId, this._panel.webview); - } else if (message.type === requestTypes.formDataFileRequest) { - vscode.window.showOpenDialog().then((uri: vscode.Uri[] | undefined) => { - if (uri && uri.length > 0) { - const value = uri[0].fsPath; - this._panel.webview.postMessage({ type: responseTypes.formDataFileResponse, path: value, index: message.index }); - } - }); - } else if (message.type === requestTypes.tokenRequest) { - apiFetch(message.data.reqData, message.data.variableData, message.data.settings, null, fetchConfig, responseTypes.tokenResponse).then((data) => { - this._panel.webview.postMessage(data); - }); - } else if (message.type === requestTypes.themeRequest) { - this._panel.webview.postMessage(getVSCodeTheme()); - } else if (message.type === requestTypes.getCollectionsByIdWithPathRequest) { - GetAllCollectionsByIdWithPath(message.data, this._panel.webview); - } else if (message.type === requestTypes.getAllCollectionNameRequest) { - GetAllCollectionName(this._panel.webview, message.data); - } - } - catch (error) { - writeLog("error::mainUIProvider::onDidReceiveMessage()" + error); - } - }, - null, - this._disposables - ); - } - - public dispose(id?: string, colId?: string, folderId?: string) { - - sideBarProvider.view.webview.postMessage({ type: requestTypes.closeItemRequest, id: id, colId: colId, folderId: folderId }); - - WebAppPanel.currentPanel = undefined; - - // Clean up our resources - this._panel.dispose(); - - while (this._disposables.length) { - const x = this._disposables.pop(); - if (x) { - x.dispose(); - } - } - } - - private async _update(id?: string, colId?: string, varId?: string, type?: string, folderId?: string) { - const webview = this._panel.webview; - this._panel.webview.html = this._getHtmlForWebview(webview, id, colId, varId, type, folderId); - } - - private _pushMessages(message: IPubSubMessage) { - if (message.messageType === pubSubTypes.updateVariables) { - this._panel.webview.postMessage({ type: message.messageType }); - } else if (message.messageType === pubSubTypes.removeCurrentVariable) { - this._panel.webview.postMessage({ type: message.messageType }); - } else if (message.messageType === pubSubTypes.addCurrentVariable) { - this._panel.webview.postMessage({ type: message.messageType, data: { varId: message.message } }); - } else if (message.messageType === pubSubTypes.themeChanged) { - this._panel.webview.postMessage({ type: message.messageType }); - } - } - - private _getHtmlForWebview(webview: vscode.Webview, id?: string, colId?: string, varId?: string, type?: string, folderId?: string) { - - const scriptUri = webview.asWebviewUri( - vscode.Uri.joinPath(this._extensionUri, "dist/fetch-client-ui.js") - ); - - const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "/dist/main.css")); - - const nonce = getNonce(); - - return ` - - - - - - - ${id}@:@${colId}@:@${varId}@:@${type}@:@${folderId} - - - -
- - - - `; - } + public static currentPanel: WebAppPanel | undefined; + private readonly _panel: vscode.WebviewPanel; + private readonly _extensionUri: vscode.Uri; + private _disposables: vscode.Disposable[] = []; + + private _scriptionId: Subscription; + + public static createOrShow(extensionUri: vscode.Uri, id?: string, name?: string, colId?: string, varId?: string, type?: string, folderId?: string, newTab?: boolean) { + const column = vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.viewColumn : undefined; + + let tabOption = getRequestTabOption(); + + if (!tabOption && !newTab && WebAppPanel.currentPanel) { + WebAppPanel.currentPanel._update(id, colId, varId, type, folderId); + WebAppPanel.currentPanel._panel.reveal(column); + WebAppPanel.currentPanel._panel.title = name ? name : "New Request"; + return; + } + + const panel = vscode.window.createWebviewPanel( + "fetch-client", + name ? name : "New Request", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); + + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + panel.iconPath = iconUri; + + WebAppPanel.currentPanel = new WebAppPanel(panel, extensionUri, id, colId, varId, type, folderId); + } + + public static kill() { + WebAppPanel.currentPanel?.dispose(); + WebAppPanel.currentPanel = undefined; + } + + public static getCurrentWebView() { + if (WebAppPanel.currentPanel) { return WebAppPanel.currentPanel._panel.webview; } + + return null; + } + + private constructor( + panel: vscode.WebviewPanel, + extensionUri: vscode.Uri, + id?: string, + colId?: string, + varId?: string, + type?: string, + folderId?: string + ) { + this._panel = panel; + this._extensionUri = extensionUri; + + this._update(id, colId, varId, type, folderId); + + this._pushMessages = this._pushMessages.bind(this); + + this._scriptionId = pubSub.subscribe(this._pushMessages); + + this._panel.onDidDispose(() => { + this._scriptionId.unsubscribe(); + this.dispose(id, colId, folderId); + }, null, this._disposables); + + this._panel.onDidChangeViewState(function (event) { + if (event.webviewPanel.active) { + sideBarProvider.view.webview.postMessage({ type: requestTypes.selectItemRequest, colId: colId, folId: folderId, id: id }); + } + }, null, this._disposables); + + let fetchConfig: FetchConfig = { + timeOut: getTimeOutConfiguration(), + headersCase: getHeadersConfiguration(), + runMainRequest: getRunMainRequestOption() + }; + + + // Handle messages from the webview + this._panel.webview.onDidReceiveMessage( + async message => { + try { + if (message.type === requestTypes.apiRequest) { + const CancelToken = axios.CancelToken; + fetchConfig.source = CancelToken.source(); + + await ExecuteAPIRequest(message, fetchConfig, this._panel.webview); + + let item: IHistory = { + id: message.data.reqData.id, + method: message.data.reqData.method, + name: message.data.reqData.name ? message.data.reqData.name : message.data.reqData.url, + url: message.data.reqData.url, + createdTime: message.data.reqData.createdTime ? message.data.reqData.createdTime : formatDate() + }; + + if (message.data.colId) { + UpdateCollection(message.data.colId, item); + } + + sideBarProvider.view.webview.postMessage({ type: responseTypes.updateCollectionHistoryItem, colId: message.data.colId, item: item }); + + } else if (message.type === requestTypes.cancelRequest) { + if (fetchConfig.source) { + fetchConfig.source.cancel("The request has been cancelled by the user."); + } + } else if (message.type === requestTypes.layoutConfigRequest) { + this._panel.webview.postMessage(getLayoutConfiguration()); + } else if (message.type === requestTypes.configRequest) { + this._panel.webview.postMessage(getConfiguration()); + } else if (message.type === requestTypes.openExistingItemRequest) { + GetExitingItem(this._panel.webview, message.data); + } else if (message.type === requestTypes.getOpenAndRunItemDataRequest) { + GetExitingItem(this._panel.webview, message.data, null, "OpenAndRun"); + } else if (message.type === requestTypes.saveResponseRequest) { + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-response." + message.fileType) }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + fs.writeFile(value, message.data, (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::saveResponseRequest()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); + } + }); + } + }); + } else if (message.type === requestTypes.saveTestResponseRequest) { + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-tests.json") }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + fs.writeFile(value, message.data, (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message, { modal: true }); + writeLog("error::saveTestResponseRequest()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); + } + }); + } + }); + } else if (message.type === requestTypes.downloadFileTypeRequest) { + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-file." + message.fileType) }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + fs.writeFile(value, new Uint8Array(message.resData.data), (error) => { + if (error) { + vscode.window.showErrorMessage("Could not save to '" + value + "'. Error Message : " + error.message), { modal: true }; + writeLog("error::downloadFileTypeRequest()::FileWrite()" + error.message); + } else { + vscode.window.showInformationMessage("Successfully saved to '" + value + "'.", { modal: true }); + } + }); + } + }); + } else if (message.type === requestTypes.selectFileRequest) { + vscode.window.showOpenDialog().then((uri: vscode.Uri[] | undefined) => { + if (uri && uri.length > 0) { + const value = uri[0].fsPath; + const data = fs.readFileSync(value, "utf8"); + this._panel.webview.postMessage({ type: responseTypes.selectFileResponse, path: value, fileData: data }); + } + }); + } else if (message.type === requestTypes.readFileRequest) { + if (!fs.existsSync(message.path)) { + this._panel.webview.postMessage({ type: responseTypes.readFileResponse, fileData: "" }); + } else { + const data = fs.readFileSync(message.path, "utf8"); + this._panel.webview.postMessage({ type: responseTypes.readFileResponse, fileData: data }); + } + } else if (message.type === requestTypes.getVariableItemRequest) { + GetVariableById(message.data.id, message.data.isGlobal, this._panel.webview); + } else if (message.type === requestTypes.getAllVariableRequest) { + GetAllVariable(this._panel.webview); + } else if (message.type === requestTypes.getRunItemDataRequest) { + this._panel.webview.postMessage({ type: responseTypes.getRunItemDataResponse, reqData: getStorageManager().getValue("run-request"), resData: getStorageManager().getValue("run-response") }); + getStorageManager().setValue("run-request", ""); + getStorageManager().setValue("run-response", ""); + } else if (message.type === requestTypes.saveRequest) { + let item: IHistory = { + id: message.data.reqData.id, + method: message.data.reqData.method, + name: message.data.reqData.name ? message.data.reqData.name : message.data.reqData.url, + url: message.data.reqData.url, + createdTime: message.data.reqData.createdTime ? message.data.reqData.createdTime : formatDate() + }; + + let reqData = message.data.reqData as IRequestModel; + if (reqData.body.bodyType === "binary") { + reqData.body.binary.data = ""; + } + if (message.data.isNew) { + SaveRequest(reqData); + SaveHistory(item, sideBarProvider.view); + } else { + UpdateRequest(reqData); + UpdateHistory(item); + if (message.data.colId) { + UpdateCollection(message.data.colId, item); + } + } + this._panel.webview.postMessage({ type: responseTypes.saveResponse }); + sideBarProvider.view.webview.postMessage({ type: responseTypes.updateCollectionHistoryItem, colId: message.data.colId, item: item }); + } + else if (message.type === requestTypes.openVariableItemRequest) { + OpenVariableUI(message.data); + } else if (message.type === requestTypes.updateVariableRequest) { + UpdateVariable(message.data, null); + } else if (message.type === requestTypes.saveCookieRequest) { + SaveCookie(message.data, null); + } else if (message.type === requestTypes.getAllCookiesRequest) { + GetAllCookies(this._panel.webview); + } else if (message.type === requestTypes.openManageCookiesRequest) { + OpenCookieUI(message.data); + } else if (message.type === requestTypes.getParentSettingsRequest) { + GetParentSettings(message.data.colId, message.data.folderId, this._panel.webview); + } else if (message.type === requestTypes.formDataFileRequest) { + vscode.window.showOpenDialog().then((uri: vscode.Uri[] | undefined) => { + if (uri && uri.length > 0) { + const value = uri[0].fsPath; + this._panel.webview.postMessage({ type: responseTypes.formDataFileResponse, path: value, index: message.index }); + } + }); + } else if (message.type === requestTypes.tokenRequest) { + apiFetch(message.data.reqData, message.data.variableData, message.data.settings, null, fetchConfig, responseTypes.tokenResponse).then((data) => { + this._panel.webview.postMessage(data); + }); + } else if (message.type === requestTypes.themeRequest) { + this._panel.webview.postMessage(getVSCodeTheme()); + } else if (message.type === requestTypes.getCollectionsByIdWithPathRequest) { + GetAllCollectionsByIdWithPath(message.data, this._panel.webview); + } else if (message.type === requestTypes.getAllCollectionNameRequest) { + GetAllCollectionName(this._panel.webview, message.data); + } + } + catch (error) { + writeLog("error::mainUIProvider::onDidReceiveMessage()" + error); + } + }, + null, + this._disposables + ); + } + + public dispose(id?: string, colId?: string, folderId?: string) { + + sideBarProvider.view.webview.postMessage({ type: requestTypes.closeItemRequest, id: id, colId: colId, folderId: folderId }); + + WebAppPanel.currentPanel = undefined; + + // Clean up our resources + this._panel.dispose(); + + while (this._disposables.length) { + const x = this._disposables.pop(); + if (x) { + x.dispose(); + } + } + } + + private async _update(id?: string, colId?: string, varId?: string, type?: string, folderId?: string) { + const webview = this._panel.webview; + this._panel.webview.html = this._getHtmlForWebview(webview, id, colId, varId, type, folderId); + } + + private _pushMessages(message: IPubSubMessage) { + if (message.messageType === pubSubTypes.updateVariables) { + this._panel.webview.postMessage({ type: message.messageType }); + } else if (message.messageType === pubSubTypes.removeCurrentVariable) { + this._panel.webview.postMessage({ type: message.messageType }); + } else if (message.messageType === pubSubTypes.addCurrentVariable) { + this._panel.webview.postMessage({ type: message.messageType, data: { varId: message.message } }); + } else if (message.messageType === pubSubTypes.themeChanged) { + this._panel.webview.postMessage({ type: message.messageType }); + } + } + + private _getHtmlForWebview(webview: vscode.Webview, id?: string, colId?: string, varId?: string, type?: string, folderId?: string) { + + const scriptUri = webview.asWebviewUri( + vscode.Uri.joinPath(this._extensionUri, "dist/fetch-client-ui.js") + ); + + const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "/dist/main.css")); + + const nonce = getNonce(); + + return ` + + + + + + + ${id}@:@${colId}@:@${varId}@:@${type}@:@${folderId} + + + +
+ + + + `; + } } diff --git a/src/utils/ui/sideBarUIProvider.tsx b/src/utils/ui/sideBarUIProvider.tsx index c93d340..0a1e888 100644 --- a/src/utils/ui/sideBarUIProvider.tsx +++ b/src/utils/ui/sideBarUIProvider.tsx @@ -1,24 +1,24 @@ import * as vscode from 'vscode'; import { - getStorageManager, OpenAddToColUI, OpenAttachVariableUI, OpenColSettings, OpenCopyToColUI, - OpenCurlUI, OpenExistingItem, OpenRunAllUI, OpenVariableUI, pubSub, vsCodeLogger + getStorageManager, OpenAddToColUI, OpenAttachVariableUI, OpenBulkExportUI, OpenColSettings, OpenCopyToColUI, + OpenCurlUI, OpenExistingItem, OpenRunAllUI, OpenVariableUI, pubSub, vsCodeLogger } from '../../extension'; import { ICollections, IFolder, IHistory } from '../../fetch-client-ui/components/SideBar/redux/types'; import { getNonce, pubSubTypes, requestTypes, responseTypes } from '../../utils/configuration'; import { - AddToCollection, AttachVariable, CreateNewCollection, - DeleteAllCollectionItems, DeleteCollection, DeleteCollectionItem, - DuplicateItem, GetAllCollections, NewFolderToCollection, NewRequestToCollection, - RemoveVariableByVariableId, RenameCollection, RenameCollectionItem + AddToCollection, AttachVariable, CreateNewCollection, + DeleteAllCollectionItems, DeleteCollection, DeleteCollectionItem, + DuplicateItem, GetAllCollections, NewFolderToCollection, NewRequestToCollection, + RemoveVariableByVariableId, RenameCollection, RenameCollectionItem } from '../../utils/db/collectionDBUtil'; import { DeleteAllHistory, DeleteHistory, GetAllHistory, RenameHistory } from '../../utils/db/historyDBUtil'; import { Export, Import, SaveRequest } from '../db/mainDBUtil'; import { - ChangeVariableStatus, DeleteVariable, DuplicateVariable, ExportVariable, - GetAllVariable, - ImportVariableFromEnvFile, - ImportVariableFromJsonFile, - RenameVariable + ChangeVariableStatus, DeleteVariable, DuplicateVariable, ExportVariable, + GetAllVariable, + ImportVariableFromEnvFile, + ImportVariableFromJsonFile, + RenameVariable } from '../db/varDBUtil'; import { formatDate } from '../helper'; import { IPubSubMessage, Subscription } from '../PubSub'; @@ -26,313 +26,325 @@ import { getVSCodeTheme } from '../vscodeConfig'; export class SideBarProvider implements vscode.WebviewViewProvider { - public static readonly viewType = 'fetch-client.sideBar'; + public static readonly viewType = 'fetch-client.sideBar'; - public view?: vscode.WebviewView; + public view?: vscode.WebviewView; - private _scriptionId: Subscription; + private _scriptionId: Subscription; - constructor( - private readonly _extensionUri: vscode.Uri, - ) { - this._pushMessages = this._pushMessages.bind(this); - this._scriptionId = pubSub.subscribe(this._pushMessages); - } + constructor( + private readonly _extensionUri: vscode.Uri, + ) { + this._pushMessages = this._pushMessages.bind(this); + this._scriptionId = pubSub.subscribe(this._pushMessages); + } - public resolveWebviewView(webviewView: vscode.WebviewView, _context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken,) { - this.view = webviewView; + public resolveWebviewView(webviewView: vscode.WebviewView, _context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken,) { + this.view = webviewView; - webviewView.webview.options = { - enableScripts: true, - localResourceRoots: [this._extensionUri], - }; + webviewView.webview.options = { + enableScripts: true, + localResourceRoots: [this._extensionUri], + }; - webviewView.webview.html = this.getHtmlForWebview(webviewView.webview); + webviewView.webview.html = this.getHtmlForWebview(webviewView.webview); - webviewView.onDidDispose(() => { - this._scriptionId.unsubscribe(); - }); + webviewView.onDidDispose(() => { + this._scriptionId.unsubscribe(); + }); - webviewView.webview.onDidReceiveMessage(reqData => { - switch (reqData.type) { - case requestTypes.getAllHistoryRequest: - GetAllHistory(webviewView); - break; - case requestTypes.deleteAllHistoryRequest: - this.showConfirmationBox("Do you want to clear all history?").then((data: any) => { - if (data === "Yes") { - DeleteAllHistory(webviewView); - } - }); - break; - case requestTypes.deleteHistoryRequest: - this.showConfirmationBox(`Do you want to delete the '${reqData.name}' history item?`).then((data: any) => { - if (data === "Yes") { - DeleteHistory(webviewView, reqData.data); - } - }); - break; - case requestTypes.renameHistoryRequest: - this.showInputBox().then((data: any) => { - if (data) { - RenameHistory(webviewView, reqData.data, data); - } - }); - break; - case requestTypes.openHistoryItemRequest: - OpenExistingItem(reqData.data.id, reqData.data.name, reqData.data.colId, reqData.data.folderId, reqData.data.varId, undefined, reqData.data.isNewTab); - break; - case requestTypes.openAndRunItemRequest: - OpenExistingItem(reqData.data.id, reqData.data.name, reqData.data.colId, reqData.data.folderId, reqData.data.varId, "OpenAndRun", reqData.data.isNewTab); - break; - case requestTypes.addToCollectionsRequest: - OpenAddToColUI(reqData.data); - break; - case requestTypes.getAllCollectionsRequest: - GetAllCollections(webviewView.webview); - break; - case requestTypes.renameCollectionItemRequest: - this.showInputBox().then((name: any) => { - if (name) { - RenameCollectionItem(webviewView, reqData.data.colId, reqData.data.historyId, reqData.data.folderId, reqData.data.isFolder, name); - } - }); - break; - case requestTypes.deleteCollectionItemRequest: - this.showConfirmationBox(`Do you want to delete the '${reqData.data.name}' ${reqData.data.isFolder ? "folder?" : "item?"}`).then((data: any) => { - if (data === "Yes") { - DeleteCollectionItem(webviewView, reqData.data.colId, reqData.data.folderId, reqData.data.historyId, reqData.data.isFolder); - } - }); - break; - case requestTypes.renameCollectionRequest: - this.showInputBox().then((name: any) => { - if (name) { - RenameCollection(webviewView, reqData.data, name); - } - }); - break; - case requestTypes.deleteCollectionRequest: - this.showConfirmationBox(`Do you want to delete the '${reqData.name}' collection?`).then((data: any) => { - if (data === "Yes") { - DeleteCollection(webviewView, reqData.data); - } - }); - break; - case requestTypes.newRequest: - OpenExistingItem(); - break; - case requestTypes.duplicateCollectionsRequest: - DuplicateItem(reqData.data.coldId, reqData.data.folderId, reqData.data.historyId, reqData.data.isFolder, webviewView); - break; - case requestTypes.exportRequest: - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-" + reqData.data.name + ".json") }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - Export(value, reqData.data.colId, reqData.data.hisId, reqData.data.folderId); - } - }); - break; - case requestTypes.clearRequest: - this.showConfirmationBox(`Do you want to clear all items in '${reqData.data.name}' ?`).then((data: any) => { - if (data === "Yes") { - DeleteAllCollectionItems(webviewView, reqData.data.colId, reqData.data.folderId); - } - }); - break; - case requestTypes.importRequest: - vscode.window.showOpenDialog({ filters: { 'Json Files': ['json'] } }).then((uri: vscode.Uri[] | undefined) => { - if (uri && uri.length > 0) { - const value = uri[0].fsPath; - Import(webviewView, value); - } - }); - break; - case requestTypes.copyToCollectionsRequest: - OpenCopyToColUI(reqData.data.id, reqData.data.name); - break; - case requestTypes.getAllVariableRequest: - GetAllVariable(webviewView.webview); - break; - case requestTypes.renameVariableRequest: - this.showInputBox().then((name: any) => { - if (name) { - RenameVariable(webviewView, reqData.data, name); - } - }); - break; - case requestTypes.deleteVariableRequest: - this.showConfirmationBox(`Do you want to delete the '${reqData.name}' variable?`).then((data: any) => { - if (data === "Yes") { - DeleteVariable(webviewView, reqData.data); - } - }); - break; - case requestTypes.newVariableRequest: - OpenVariableUI(); - break; - case requestTypes.openVariableItemRequest: - OpenVariableUI(reqData.data); - break; - case requestTypes.attachVariableRequest: - OpenAttachVariableUI(reqData.data.id, reqData.data.name); - break; - case requestTypes.removeVariableRequest: - this.showConfirmationBox(`Do you want to remove the variable from '${reqData.data.name}' collection?`).then((data: any) => { - if (data === "Yes") { - AttachVariable(reqData.data.id, "", null, webviewView); - } - }); - break; - case requestTypes.activeVariableRequest: - ChangeVariableStatus(reqData.data.id, reqData.data.status, webviewView); - break; - case requestTypes.exportVariableRequest: - vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-" + reqData.vars.name + ".json") }).then((uri: vscode.Uri | undefined) => { - if (uri) { - const value = uri.fsPath; - ExportVariable(value, reqData.vars.id); - } - }); - break; - case requestTypes.importVariableRequest: - vscode.window.showOpenDialog({ filters: { 'Files': ['json', 'env'] } }).then((uri: vscode.Uri[] | undefined) => { - if (uri && uri.length > 0) { - const value = uri[0].fsPath; - let ext = value.split('.').pop(); - if (ext.toLowerCase() === "json") { - ImportVariableFromJsonFile(webviewView, value); - } else { - ImportVariableFromEnvFile(webviewView, value); - } - } - }); - break; - case requestTypes.duplicateVariableRequest: - DuplicateVariable(reqData.id, null, webviewView); - break; - case requestTypes.runAllUIOpenRequest: - OpenRunAllUI(reqData.data.colId, reqData.data.folderId, reqData.data.name, reqData.data.varId); - break; - case requestTypes.createNewRequest: - this.showInputBox().then((data: any) => { - if (data) { - reqData.data.request.name = data; - SaveRequest(reqData.data.request); - let item: IHistory = { - id: reqData.data.request.id, - method: reqData.data.request.method, - name: data, - url: reqData.data.request.url, - createdTime: reqData.data.request.createdTime ? reqData.data.request.createdTime : formatDate() - }; - NewRequestToCollection(item, reqData.data.colId, reqData.data.folderId, webviewView); - } - }); - break; - case requestTypes.createNewFolderRequest: - this.showInputBox().then((data: any) => { - if (data) { - let folder = reqData.data.folder as IFolder; - folder.name = data; - NewFolderToCollection(folder, reqData.data.colId, reqData.data.folderId, webviewView); - } - }); - break; - case requestTypes.newCollectionRequest: - this.showInputBox().then((name: any) => { - if (name) { - CreateNewCollection(name, webviewView); - } - }); - break; - case requestTypes.openColSettingsRequest: - OpenColSettings(reqData.data.colId, reqData.data.folderId, reqData.data.name, reqData.data.type, reqData.data.varId); - break; - case requestTypes.copyItemRequest: - getStorageManager().setValue("item-copy-data", reqData.data.history); - webviewView.webview.postMessage({ type: responseTypes.copyItemResponse }); - break; - case requestTypes.pasteItemRequest: - let history = getStorageManager().getValue("item-copy-data"); - if (history) { - getStorageManager().setValue("item-copy-data", ""); - let col: ICollections = reqData.data.col; - if (reqData.data.isFolder) { - (col.data[0] as IFolder).data.push(history as IHistory); - } else { - col.data.push(history as IHistory); - } - AddToCollection(col, reqData.data.isFolder, false, null, webviewView); - webviewView.webview.postMessage({ type: responseTypes.pasteItemResponse }); - } - break; - case requestTypes.importCurlRequest: - OpenCurlUI(); - break; - case requestTypes.removeVariableFromColRequest: - if (reqData.data.varId) { - RemoveVariableByVariableId(reqData.data.varId, webviewView); - } - break; - case requestTypes.viewLogRequest: - if (vsCodeLogger) { - vsCodeLogger.showLog(); - } - break; - case requestTypes.themeRequest: - webviewView.webview.postMessage(getVSCodeTheme()); - break; - } - }); - } + webviewView.webview.onDidReceiveMessage(reqData => { + switch (reqData.type) { + case requestTypes.getAllHistoryRequest: + GetAllHistory(webviewView); + break; + case requestTypes.deleteAllHistoryRequest: + this.showConfirmationBox("Do you want to clear all history?").then((data: any) => { + if (data === "Yes") { + DeleteAllHistory(webviewView); + } + }); + break; + case requestTypes.deleteHistoryRequest: + this.showConfirmationBox(`Do you want to delete the '${reqData.name}' history item?`).then((data: any) => { + if (data === "Yes") { + DeleteHistory(webviewView, reqData.data); + } + }); + break; + case requestTypes.renameHistoryRequest: + this.showInputBox().then((data: any) => { + if (data) { + RenameHistory(webviewView, reqData.data, data); + } + }); + break; + case requestTypes.openHistoryItemRequest: + OpenExistingItem(reqData.data.id, reqData.data.name, reqData.data.colId, reqData.data.folderId, reqData.data.varId, undefined, reqData.data.isNewTab); + break; + case requestTypes.openAndRunItemRequest: + OpenExistingItem(reqData.data.id, reqData.data.name, reqData.data.colId, reqData.data.folderId, reqData.data.varId, "OpenAndRun", reqData.data.isNewTab); + break; + case requestTypes.addToCollectionsRequest: + OpenAddToColUI(reqData.data); + break; + case requestTypes.getAllCollectionsRequest: + GetAllCollections(webviewView.webview); + break; + case requestTypes.renameCollectionItemRequest: + this.showInputBox().then((name: any) => { + if (name) { + RenameCollectionItem(webviewView, reqData.data.colId, reqData.data.historyId, reqData.data.folderId, reqData.data.isFolder, name); + } + }); + break; + case requestTypes.deleteCollectionItemRequest: + this.showConfirmationBox(`Do you want to delete the '${reqData.data.name}' ${reqData.data.isFolder ? "folder?" : "item?"}`).then((data: any) => { + if (data === "Yes") { + DeleteCollectionItem(webviewView, reqData.data.colId, reqData.data.folderId, reqData.data.historyId, reqData.data.isFolder); + } + }); + break; + case requestTypes.renameCollectionRequest: + this.showInputBox().then((name: any) => { + if (name) { + RenameCollection(webviewView, reqData.data, name); + } + }); + break; + case requestTypes.deleteCollectionRequest: + this.showConfirmationBox(`Do you want to delete the '${reqData.name}' collection?`).then((data: any) => { + if (data === "Yes") { + DeleteCollection(webviewView, reqData.data); + } + }); + break; + case requestTypes.newRequest: + OpenExistingItem(); + break; + case requestTypes.duplicateCollectionsRequest: + DuplicateItem(reqData.data.coldId, reqData.data.folderId, reqData.data.historyId, reqData.data.isFolder, webviewView); + break; + case requestTypes.exportRequest: + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-collection_" + reqData.data.name?.replace(/[/\\?%*:|"<>]/g, '-') + ".json") }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + Export(value, reqData.data.colId, reqData.data.hisId, reqData.data.folderId); + } + }); + break; + case requestTypes.clearRequest: + this.showConfirmationBox(`Do you want to clear all items in '${reqData.data.name}' ?`).then((data: any) => { + if (data === "Yes") { + DeleteAllCollectionItems(webviewView, reqData.data.colId, reqData.data.folderId); + } + }); + break; + case requestTypes.importRequest: + vscode.window.showOpenDialog({ filters: { 'Json Files': ['json'] }, canSelectMany: true }).then((uri: vscode.Uri[] | undefined) => { + if (uri && uri.length > 0) { + uri.forEach((item, index) => { + const value = item.fsPath; + setTimeout(function () { Import(webviewView, value); }, 250 * index); + }); + } + }); + break; + case requestTypes.copyToCollectionsRequest: + OpenCopyToColUI(reqData.data.id, reqData.data.name); + break; + case requestTypes.getAllVariableRequest: + GetAllVariable(webviewView.webview); + break; + case requestTypes.renameVariableRequest: + this.showInputBox().then((name: any) => { + if (name) { + RenameVariable(webviewView, reqData.data, name); + } + }); + break; + case requestTypes.deleteVariableRequest: + this.showConfirmationBox(`Do you want to delete the '${reqData.name}' variable?`).then((data: any) => { + if (data === "Yes") { + DeleteVariable(webviewView, reqData.data); + } + }); + break; + case requestTypes.newVariableRequest: + OpenVariableUI(); + break; + case requestTypes.openVariableItemRequest: + OpenVariableUI(reqData.data); + break; + case requestTypes.attachVariableRequest: + OpenAttachVariableUI(reqData.data.id, reqData.data.name); + break; + case requestTypes.removeVariableRequest: + this.showConfirmationBox(`Do you want to remove the variable from '${reqData.data.name}' collection?`).then((data: any) => { + if (data === "Yes") { + AttachVariable(reqData.data.id, "", null, webviewView); + } + }); + break; + case requestTypes.activeVariableRequest: + ChangeVariableStatus(reqData.data.id, reqData.data.status, webviewView); + break; + case requestTypes.exportVariableRequest: + vscode.window.showSaveDialog({ defaultUri: vscode.Uri.file("fetch-client-variable_" + reqData.vars.name?.replace(/[/\\?%*:|"<>]/g, '-') + ".json") }).then((uri: vscode.Uri | undefined) => { + if (uri) { + const value = uri.fsPath; + ExportVariable(value, reqData.vars.id); + } + }); + break; + case requestTypes.importVariableRequest: + vscode.window.showOpenDialog({ filters: { 'Files': ['json', 'env'] }, canSelectMany: true }).then((uri: vscode.Uri[] | undefined) => { + if (uri && uri.length > 0) { + uri.forEach((item, index) => { + const value = item.fsPath; + let ext = value.split('.').pop(); + if (ext.toLowerCase() === "json") { + setTimeout(function () { ImportVariableFromJsonFile(webviewView, value); }, 250 * index); + } else { + setTimeout(function () { ImportVariableFromEnvFile(webviewView, value); }, 250 * index); + } + }); + } + }); + break; + case requestTypes.duplicateVariableRequest: + DuplicateVariable(reqData.id, null, webviewView); + break; + case requestTypes.runAllUIOpenRequest: + OpenRunAllUI(reqData.data.colId, reqData.data.folderId, reqData.data.name, reqData.data.varId); + break; + case requestTypes.createNewRequest: + this.showInputBox().then((data: any) => { + if (data) { + reqData.data.request.name = data; + SaveRequest(reqData.data.request); + let item: IHistory = { + id: reqData.data.request.id, + method: reqData.data.request.method, + name: data, + url: reqData.data.request.url, + createdTime: reqData.data.request.createdTime ? reqData.data.request.createdTime : formatDate() + }; + NewRequestToCollection(item, reqData.data.colId, reqData.data.folderId, webviewView); + } + }); + break; + case requestTypes.createNewFolderRequest: + this.showInputBox().then((data: any) => { + if (data) { + let folder = reqData.data.folder as IFolder; + folder.name = data; + NewFolderToCollection(folder, reqData.data.colId, reqData.data.folderId, webviewView); + } + }); + break; + case requestTypes.newCollectionRequest: + this.showInputBox().then((name: string) => { + if (name) { + if (name.toLocaleLowerCase() === "default") { + vscode.window.showInformationMessage("Collection name should not be 'default'", { modal: true }); + } + else { + CreateNewCollection(name, webviewView); + } + } + }); + break; + case requestTypes.openColSettingsRequest: + OpenColSettings(reqData.data.colId, reqData.data.folderId, reqData.data.name, reqData.data.type, reqData.data.varId); + break; + case requestTypes.copyItemRequest: + getStorageManager().setValue("item-copy-data", reqData.data.history); + webviewView.webview.postMessage({ type: responseTypes.copyItemResponse }); + break; + case requestTypes.pasteItemRequest: + let history = getStorageManager().getValue("item-copy-data"); + if (history) { + getStorageManager().setValue("item-copy-data", ""); + let col: ICollections = reqData.data.col; + if (reqData.data.isFolder) { + (col.data[0] as IFolder).data.push(history as IHistory); + } else { + col.data.push(history as IHistory); + } + AddToCollection(col, reqData.data.isFolder, false, null, webviewView); + webviewView.webview.postMessage({ type: responseTypes.pasteItemResponse }); + } + break; + case requestTypes.importCurlRequest: + OpenCurlUI(); + break; + case requestTypes.removeVariableFromColRequest: + if (reqData.data.varId) { + RemoveVariableByVariableId(reqData.data.varId, webviewView); + } + break; + case requestTypes.viewLogRequest: + if (vsCodeLogger) { + vsCodeLogger.showLog(); + } + break; + case requestTypes.themeRequest: + webviewView.webview.postMessage(getVSCodeTheme()); + break; + case requestTypes.bulkExportRequest: + OpenBulkExportUI(reqData.data.type); + break; + } + }); + } - private _pushMessages(message: IPubSubMessage) { - if (message.messageType === pubSubTypes.themeChanged) { - this.view.webview.postMessage({ type: message.messageType }); - } - } + private _pushMessages(message: IPubSubMessage) { + if (message.messageType === pubSubTypes.themeChanged) { + this.view.webview.postMessage({ type: message.messageType }); + } + } - private async showInputBox() { - const res = await vscode.window.showInputBox({ - value: "", prompt: "Enter new name", placeHolder: "Enter new name", ignoreFocusOut: false, - validateInput: text => { - return text !== "" && text.length <= 50 ? null : "Enter the valid name (length should be <=50)"; - } - }); + private async showInputBox() { + const res = await vscode.window.showInputBox({ + value: "", prompt: "Enter new name", placeHolder: "Enter new name", ignoreFocusOut: false, + validateInput: text => { + return text !== "" && text.length <= 50 ? null : "Enter the valid name (length should be <=50)"; + } + }); - return res; - } + return res; + } - private async showConfirmationBox(text: string) { - const res = await vscode.window.showWarningMessage(text, { modal: true }, "Yes", "No"); - return res; - } + private async showConfirmationBox(text: string) { + const res = await vscode.window.showWarningMessage(text, { modal: true }, "Yes", "No"); + return res; + } - private getHtmlForWebview(webview: vscode.Webview) { + private getHtmlForWebview(webview: vscode.Webview) { - const nonce = getNonce(); + const nonce = getNonce(); - const scriptUri = webview.asWebviewUri( - vscode.Uri.joinPath(this._extensionUri, "dist/fetch-client-ui.js") - ); + const scriptUri = webview.asWebviewUri( + vscode.Uri.joinPath(this._extensionUri, "dist/fetch-client-ui.js") + ); - const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "/dist/main.css")); + const styleUri = webview.asWebviewUri(vscode.Uri.joinPath(this._extensionUri, "/dist/main.css")); - return ` - - - - - - sideBar - - - -
- - - `;; - } + return ` + + + + + + sideBar + + + +
+ + + `;; + } } diff --git a/src/utils/ui/variableUIProvider.tsx b/src/utils/ui/variableUIProvider.tsx index 46f3a09..9ec3e14 100644 --- a/src/utils/ui/variableUIProvider.tsx +++ b/src/utils/ui/variableUIProvider.tsx @@ -3,58 +3,57 @@ import { sideBarProvider } from '../../extension'; import { getNonce, requestTypes } from '../configuration'; import { GetCollectionsByVariable } from '../db/collectionDBUtil'; import { GetAllVariable, GetVariableById, SaveVariable, UpdateVariable } from '../db/varDBUtil'; -import { WebAppPanel } from './mainUIProvider'; export const VariableUI = (extensionUri: any) => { - const disposable = vscode.commands.registerCommand('fetch-client.newVar', (id?: string) => { - const varPanel = vscode.window.createWebviewPanel( - "fetch-client", - "Fetch Client - Variable", - vscode.ViewColumn.One, - { enableScripts: true, retainContextWhenHidden: true } - ); - - const scriptUri = varPanel.webview.asWebviewUri( - vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") - ); - - const styleUri = varPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); - - const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); - varPanel.iconPath = iconUri; - - const nonce = getNonce(); - const title = `newvar@:@${id}`; - - varPanel.webview.html = ` - - - - - - ${title} - - - -
- - - `; - - varPanel.webview.onDidReceiveMessage((reqData: any) => { - if (reqData.type === requestTypes.getVariableItemRequest) { - GetVariableById(reqData.data.id, reqData.data.isGlobal, varPanel.webview); - GetCollectionsByVariable(reqData.data.id, varPanel.webview); - } else if (reqData.type === requestTypes.updateVariableRequest) { - UpdateVariable(reqData.data, varPanel.webview); - } else if (reqData.type === requestTypes.saveVariableRequest) { - SaveVariable(reqData.data, varPanel.webview, sideBarProvider.view); - } else if (reqData.type === requestTypes.getAllVariableRequest) { - GetAllVariable(varPanel.webview); - } - }); - }); - - return disposable; - -}; \ No newline at end of file + const disposable = vscode.commands.registerCommand('fetch-client.newVar', (id?: string) => { + const varPanel = vscode.window.createWebviewPanel( + "fetch-client", + "Fetch Client - Variable", + vscode.ViewColumn.One, + { enableScripts: true, retainContextWhenHidden: true } + ); + + const scriptUri = varPanel.webview.asWebviewUri( + vscode.Uri.joinPath(extensionUri, "dist/fetch-client-ui.js") + ); + + const styleUri = varPanel.webview.asWebviewUri(vscode.Uri.joinPath(extensionUri, "/dist/main.css")); + + const iconUri = vscode.Uri.joinPath(extensionUri, "icons/fetch-client.png"); + varPanel.iconPath = iconUri; + + const nonce = getNonce(); + const title = `newvar@:@${id}`; + + varPanel.webview.html = ` + + + + + + ${title} + + + +
+ + + `; + + varPanel.webview.onDidReceiveMessage((reqData: any) => { + if (reqData.type === requestTypes.getVariableItemRequest) { + GetVariableById(reqData.data.id, reqData.data.isGlobal, varPanel.webview); + GetCollectionsByVariable(reqData.data.id, varPanel.webview); + } else if (reqData.type === requestTypes.updateVariableRequest) { + UpdateVariable(reqData.data, varPanel.webview); + } else if (reqData.type === requestTypes.saveVariableRequest) { + SaveVariable(reqData.data, varPanel.webview, sideBarProvider.view); + } else if (reqData.type === requestTypes.getAllVariableRequest) { + GetAllVariable(varPanel.webview); + } + }); + }); + + return disposable; + +}; diff --git a/src/utils/validators/fetchClientCollectionValidator.ts b/src/utils/validators/fetchClientCollectionValidator.ts index cf4b61f..4f77ba9 100644 --- a/src/utils/validators/fetchClientCollectionValidator.ts +++ b/src/utils/validators/fetchClientCollectionValidator.ts @@ -1,1307 +1,1307 @@ // Stores the currently-being-typechecked object for error messages. let obj: any = null; export class FetchClientDataProxy { - public readonly app: string; - public readonly id: string; - public readonly name: string; - public readonly version: string; - public readonly type: string; - public readonly createdTime: string; - public readonly exportedDate: string; - public readonly data: DataEntityProxy[] | null; - public readonly settings: SettingsProxy | null; - public static Parse(d: string): FetchClientDataProxy { - return FetchClientDataProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): FetchClientDataProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.app, false, field + ".app"); - checkStringValue(d.app, field + ".app", "Fetch Client"); - checkString(d.id, false, field + ".id"); - checkString(d.name, false, field + ".name"); - checkString(d.version, false, field + ".version"); - checkString(d.type, false, field + ".type"); - checkStringValue(d.type, field + ".type", "collections"); - checkString(d.createdTime, false, field + ".createdTime"); - checkString(d.exportedDate, false, field + ".exportedDate"); - checkArray(d.data, field + ".data"); - if (d.data) { - for (let i = 0; i < d.data.length; i++) { - d.data[i] = DataEntityProxy.Create(d.data[i], field + ".data" + "[" + i + "]"); - } - } - if (d.data === undefined) { - d.data = null; - } - if (d.settings) { - d.settings = SettingsProxy.Create(d.settings, field + ".settings"); - } - return new FetchClientDataProxy(d); - } - private constructor(d: any) { - this.app = d.app; - this.id = d.id; - this.name = d.name; - this.version = d.version; - this.type = d.type; - this.createdTime = d.createdTime; - this.exportedDate = d.exportedDate; - this.data = d.data; - this.settings = d.settings; - } + public readonly app: string; + public readonly id: string; + public readonly name: string; + public readonly version: string; + public readonly type: string; + public readonly createdTime: string; + public readonly exportedDate: string; + public readonly data: DataEntityProxy[] | null; + public readonly settings: SettingsProxy | null; + public static Parse(d: string): FetchClientDataProxy { + return FetchClientDataProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): FetchClientDataProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.app, false, field + ".app"); + checkStringValue(d.app, field + ".app", "Fetch Client"); + checkString(d.id, false, field + ".id"); + checkString(d.name, false, field + ".name"); + checkString(d.version, false, field + ".version"); + checkString(d.type, false, field + ".type"); + checkStringValue(d.type, field + ".type", "collections"); + checkString(d.createdTime, false, field + ".createdTime"); + checkString(d.exportedDate, false, field + ".exportedDate"); + checkArray(d.data, field + ".data"); + if (d.data) { + for (let i = 0; i < d.data.length; i++) { + d.data[i] = DataEntityProxy.Create(d.data[i], field + ".data" + "[" + i + "]"); + } + } + if (d.data === undefined) { + d.data = null; + } + if (d.settings) { + d.settings = SettingsProxy.Create(d.settings, field + ".settings"); + } + return new FetchClientDataProxy(d); + } + private constructor(d: any) { + this.app = d.app; + this.id = d.id; + this.name = d.name; + this.version = d.version; + this.type = d.type; + this.createdTime = d.createdTime; + this.exportedDate = d.exportedDate; + this.data = d.data; + this.settings = d.settings; + } } export class DataEntityProxy { - public readonly id: string; - public readonly name: string; - public readonly type: string | null; - public readonly createdTime: string; - public readonly data: DataEntity1Proxy[] | null; - public readonly settings: Settings1Proxy | null; - public readonly url: string | null; - public readonly method: string | null; - public readonly params: TableDataEntity[] | null; - public readonly auth: AuthProxy | null; - public readonly headers: HeadersEntityProxy[] | null; - public readonly body: BodyProxy | null; - public readonly tests: TestsEntityProxy[] | null; - public readonly setvar: SetvarEntityProxy[] | null; - public readonly notes: string | null; - public readonly preFetch: PreFetchProxy | null; - public static Parse(d: string): DataEntityProxy { - return DataEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): DataEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.id, false, field + ".id"); - checkString(d.name, false, field + ".name"); - checkString(d.type, true, field + ".type"); - if (d.type === undefined) { - d.type = null; - } - checkString(d.createdTime, false, field + ".createdTime"); - checkArray(d.data, field + ".data"); - if (d.data) { - for (let i = 0; i < d.data.length; i++) { - d.data[i] = DataEntity1Proxy.Create(d.data[i], field + ".data" + "[" + i + "]"); - } - } - if (d.data === undefined) { - d.data = null; - } - d.settings = Settings1Proxy.Create(d.settings, field + ".settings"); - if (d.settings === undefined) { - d.settings = null; - } - checkString(d.url, true, field + ".url"); - if (d.url === undefined) { - d.url = null; - } - checkString(d.method, true, field + ".method"); - if (d.method === undefined) { - d.method = null; - } - checkArray(d.params, field + ".params"); - if (d.params) { - for (let i = 0; i < d.params.length; i++) { - d.params[i] = TableDataEntity.Create(d.params[i], field + ".params" + "[" + i + "]"); - } - } - if (d.params === undefined) { - d.params = null; - } - d.auth = AuthProxy.Create(d.auth, field + ".auth"); - if (d.auth === undefined) { - d.auth = null; - } - checkArray(d.headers, field + ".headers"); - if (d.headers) { - for (let i = 0; i < d.headers.length; i++) { - d.headers[i] = HeadersEntityProxy.Create(d.headers[i], field + ".headers" + "[" + i + "]"); - } - } - if (d.headers === undefined) { - d.headers = null; - } - d.body = BodyProxy.Create(d.body, field + ".body"); - if (d.body === undefined) { - d.body = null; - } - checkArray(d.tests, field + ".tests"); - if (d.tests) { - for (let i = 0; i < d.tests.length; i++) { - d.tests[i] = TestsEntityProxy.Create(d.tests[i], field + ".tests" + "[" + i + "]"); - } - } - if (d.tests === undefined) { - d.tests = null; - } - checkArray(d.setvar, field + ".setvar"); - if (d.setvar) { - for (let i = 0; i < d.setvar.length; i++) { - d.setvar[i] = SetvarEntityProxy.Create(d.setvar[i], field + ".setvar" + "[" + i + "]"); - } - } - if (d.setvar === undefined) { - d.setvar = null; - } - checkString(d.notes, true, field + ".notes"); - if (d.notes === undefined) { - d.notes = null; - } - d.preFetch = PreFetchProxy.Create(d.preFetch, field + ".preFetch"); - if (d.preFetch === undefined) { - d.preFetch = null; - } - return new DataEntityProxy(d); - } - private constructor(d: any) { - this.id = d.id; - this.name = d.name; - this.type = d.type; - this.createdTime = d.createdTime; - this.data = d.data; - this.settings = d.settings; - this.url = d.url; - this.method = d.method; - this.params = d.params; - this.auth = d.auth; - this.headers = d.headers; - this.body = d.body; - this.tests = d.tests; - this.setvar = d.setvar; - this.notes = d.notes; - this.preFetch = d.preFetch; - } + public readonly id: string; + public readonly name: string; + public readonly type: string | null; + public readonly createdTime: string; + public readonly data: DataEntity1Proxy[] | null; + public readonly settings: Settings1Proxy | null; + public readonly url: string | null; + public readonly method: string | null; + public readonly params: TableDataEntity[] | null; + public readonly auth: AuthProxy | null; + public readonly headers: HeadersEntityProxy[] | null; + public readonly body: BodyProxy | null; + public readonly tests: TestsEntityProxy[] | null; + public readonly setvar: SetvarEntityProxy[] | null; + public readonly notes: string | null; + public readonly preFetch: PreFetchProxy | null; + public static Parse(d: string): DataEntityProxy { + return DataEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): DataEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.id, false, field + ".id"); + checkString(d.name, false, field + ".name"); + checkString(d.type, true, field + ".type"); + if (d.type === undefined) { + d.type = null; + } + checkString(d.createdTime, false, field + ".createdTime"); + checkArray(d.data, field + ".data"); + if (d.data) { + for (let i = 0; i < d.data.length; i++) { + d.data[i] = DataEntity1Proxy.Create(d.data[i], field + ".data" + "[" + i + "]"); + } + } + if (d.data === undefined) { + d.data = null; + } + d.settings = Settings1Proxy.Create(d.settings, field + ".settings"); + if (d.settings === undefined) { + d.settings = null; + } + checkString(d.url, true, field + ".url"); + if (d.url === undefined) { + d.url = null; + } + checkString(d.method, true, field + ".method"); + if (d.method === undefined) { + d.method = null; + } + checkArray(d.params, field + ".params"); + if (d.params) { + for (let i = 0; i < d.params.length; i++) { + d.params[i] = TableDataEntity.Create(d.params[i], field + ".params" + "[" + i + "]"); + } + } + if (d.params === undefined) { + d.params = null; + } + d.auth = AuthProxy.Create(d.auth, field + ".auth"); + if (d.auth === undefined) { + d.auth = null; + } + checkArray(d.headers, field + ".headers"); + if (d.headers) { + for (let i = 0; i < d.headers.length; i++) { + d.headers[i] = HeadersEntityProxy.Create(d.headers[i], field + ".headers" + "[" + i + "]"); + } + } + if (d.headers === undefined) { + d.headers = null; + } + d.body = BodyProxy.Create(d.body, field + ".body"); + if (d.body === undefined) { + d.body = null; + } + checkArray(d.tests, field + ".tests"); + if (d.tests) { + for (let i = 0; i < d.tests.length; i++) { + d.tests[i] = TestsEntityProxy.Create(d.tests[i], field + ".tests" + "[" + i + "]"); + } + } + if (d.tests === undefined) { + d.tests = null; + } + checkArray(d.setvar, field + ".setvar"); + if (d.setvar) { + for (let i = 0; i < d.setvar.length; i++) { + d.setvar[i] = SetvarEntityProxy.Create(d.setvar[i], field + ".setvar" + "[" + i + "]"); + } + } + if (d.setvar === undefined) { + d.setvar = null; + } + checkString(d.notes, true, field + ".notes"); + if (d.notes === undefined) { + d.notes = null; + } + d.preFetch = PreFetchProxy.Create(d.preFetch, field + ".preFetch"); + if (d.preFetch === undefined) { + d.preFetch = null; + } + return new DataEntityProxy(d); + } + private constructor(d: any) { + this.id = d.id; + this.name = d.name; + this.type = d.type; + this.createdTime = d.createdTime; + this.data = d.data; + this.settings = d.settings; + this.url = d.url; + this.method = d.method; + this.params = d.params; + this.auth = d.auth; + this.headers = d.headers; + this.body = d.body; + this.tests = d.tests; + this.setvar = d.setvar; + this.notes = d.notes; + this.preFetch = d.preFetch; + } } export class DataEntity1Proxy { - public readonly id: string; - public readonly name: string; - public readonly type: string | null; - public readonly createdTime: string; - public readonly data: DataEntity2Proxy[] | null; - public readonly settings: Settings2Proxy | null; - public readonly url: string | null; - public readonly method: string | null; - public readonly params: TableDataEntity[] | null; - public readonly auth: Auth1Proxy | null; - public readonly headers: TableDataEntity[] | null; - public readonly body: Body1Proxy | null; - public readonly tests: TestsEntityProxy[] | null; - public readonly setvar: SetvarEntityProxy[] | null; - public readonly notes: string | null; - public static Parse(d: string): DataEntity1Proxy { - return DataEntity1Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): DataEntity1Proxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.id, false, field + ".id"); - checkString(d.name, false, field + ".name"); - checkString(d.type, true, field + ".type"); - if (d.type === undefined) { - d.type = null; - } - checkString(d.createdTime, false, field + ".createdTime"); - checkArray(d.data, field + ".data"); - if (d.data) { - for (let i = 0; i < d.data.length; i++) { - d.data[i] = DataEntity2Proxy.Create(d.data[i], field + ".data" + "[" + i + "]"); - } - } - if (d.data === undefined) { - d.data = null; - } - d.settings = Settings2Proxy.Create(d.settings, field + ".settings"); - if (d.settings === undefined) { - d.settings = null; - } - checkString(d.url, true, field + ".url"); - if (d.url === undefined) { - d.url = null; - } - checkString(d.method, true, field + ".method"); - if (d.method === undefined) { - d.method = null; - } - checkArray(d.params, field + ".params"); - if (d.params) { - for (let i = 0; i < d.params.length; i++) { - d.params[i] = TableDataEntity.Create(d.params[i], field + ".params" + "[" + i + "]"); - } - } - if (d.params === undefined) { - d.params = null; - } - d.auth = Auth1Proxy.Create(d.auth, field + ".auth"); - if (d.auth === undefined) { - d.auth = null; - } - checkArray(d.headers, field + ".headers"); - if (d.headers) { - for (let i = 0; i < d.headers.length; i++) { - d.headers[i] = TableDataEntity.Create(d.headers[i], field + ".headers" + "[" + i + "]"); - } - } - if (d.headers === undefined) { - d.headers = null; - } - d.body = Body1Proxy.Create(d.body, field + ".body"); - if (d.body === undefined) { - d.body = null; - } - checkArray(d.tests, field + ".tests"); - if (d.tests) { - for (let i = 0; i < d.tests.length; i++) { - d.tests[i] = TestsEntityProxy.Create(d.tests[i], field + ".tests" + "[" + i + "]"); - } - } - if (d.tests === undefined) { - d.tests = null; - } - checkArray(d.setvar, field + ".setvar"); - if (d.setvar) { - for (let i = 0; i < d.setvar.length; i++) { - d.setvar[i] = SetvarEntityProxy.Create(d.setvar[i], field + ".setvar" + "[" + i + "]"); - } - } - if (d.setvar === undefined) { - d.setvar = null; - } - checkString(d.notes, true, field + ".notes"); - if (d.notes === undefined) { - d.notes = null; - } - return new DataEntity1Proxy(d); - } - private constructor(d: any) { - this.id = d.id; - this.name = d.name; - this.type = d.type; - this.createdTime = d.createdTime; - this.data = d.data; - this.settings = d.settings; - this.url = d.url; - this.method = d.method; - this.params = d.params; - this.auth = d.auth; - this.headers = d.headers; - this.body = d.body; - this.tests = d.tests; - this.setvar = d.setvar; - this.notes = d.notes; - } + public readonly id: string; + public readonly name: string; + public readonly type: string | null; + public readonly createdTime: string; + public readonly data: DataEntity2Proxy[] | null; + public readonly settings: Settings2Proxy | null; + public readonly url: string | null; + public readonly method: string | null; + public readonly params: TableDataEntity[] | null; + public readonly auth: Auth1Proxy | null; + public readonly headers: TableDataEntity[] | null; + public readonly body: Body1Proxy | null; + public readonly tests: TestsEntityProxy[] | null; + public readonly setvar: SetvarEntityProxy[] | null; + public readonly notes: string | null; + public static Parse(d: string): DataEntity1Proxy { + return DataEntity1Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): DataEntity1Proxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.id, false, field + ".id"); + checkString(d.name, false, field + ".name"); + checkString(d.type, true, field + ".type"); + if (d.type === undefined) { + d.type = null; + } + checkString(d.createdTime, false, field + ".createdTime"); + checkArray(d.data, field + ".data"); + if (d.data) { + for (let i = 0; i < d.data.length; i++) { + d.data[i] = DataEntity2Proxy.Create(d.data[i], field + ".data" + "[" + i + "]"); + } + } + if (d.data === undefined) { + d.data = null; + } + d.settings = Settings2Proxy.Create(d.settings, field + ".settings"); + if (d.settings === undefined) { + d.settings = null; + } + checkString(d.url, true, field + ".url"); + if (d.url === undefined) { + d.url = null; + } + checkString(d.method, true, field + ".method"); + if (d.method === undefined) { + d.method = null; + } + checkArray(d.params, field + ".params"); + if (d.params) { + for (let i = 0; i < d.params.length; i++) { + d.params[i] = TableDataEntity.Create(d.params[i], field + ".params" + "[" + i + "]"); + } + } + if (d.params === undefined) { + d.params = null; + } + d.auth = Auth1Proxy.Create(d.auth, field + ".auth"); + if (d.auth === undefined) { + d.auth = null; + } + checkArray(d.headers, field + ".headers"); + if (d.headers) { + for (let i = 0; i < d.headers.length; i++) { + d.headers[i] = TableDataEntity.Create(d.headers[i], field + ".headers" + "[" + i + "]"); + } + } + if (d.headers === undefined) { + d.headers = null; + } + d.body = Body1Proxy.Create(d.body, field + ".body"); + if (d.body === undefined) { + d.body = null; + } + checkArray(d.tests, field + ".tests"); + if (d.tests) { + for (let i = 0; i < d.tests.length; i++) { + d.tests[i] = TestsEntityProxy.Create(d.tests[i], field + ".tests" + "[" + i + "]"); + } + } + if (d.tests === undefined) { + d.tests = null; + } + checkArray(d.setvar, field + ".setvar"); + if (d.setvar) { + for (let i = 0; i < d.setvar.length; i++) { + d.setvar[i] = SetvarEntityProxy.Create(d.setvar[i], field + ".setvar" + "[" + i + "]"); + } + } + if (d.setvar === undefined) { + d.setvar = null; + } + checkString(d.notes, true, field + ".notes"); + if (d.notes === undefined) { + d.notes = null; + } + return new DataEntity1Proxy(d); + } + private constructor(d: any) { + this.id = d.id; + this.name = d.name; + this.type = d.type; + this.createdTime = d.createdTime; + this.data = d.data; + this.settings = d.settings; + this.url = d.url; + this.method = d.method; + this.params = d.params; + this.auth = d.auth; + this.headers = d.headers; + this.body = d.body; + this.tests = d.tests; + this.setvar = d.setvar; + this.notes = d.notes; + } } export class DataEntity2Proxy { - public readonly id: string; - public readonly url: string; - public readonly name: string; - public readonly createdTime: string; - public readonly method: string; - public readonly params: TableDataEntity[] | null; - public readonly auth: Auth2Proxy; - public readonly headers: TableDataEntity[] | null; - public readonly body: Body2Proxy; - public readonly tests: TestsEntityProxy[] | null; - public readonly setvar: SetvarEntityProxy[] | null; - public readonly notes: string; - public static Parse(d: string): DataEntity2Proxy { - return DataEntity2Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): DataEntity2Proxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.id, false, field + ".id"); - checkString(d.url, false, field + ".url"); - checkString(d.name, false, field + ".name"); - checkString(d.createdTime, false, field + ".createdTime"); - checkString(d.method, false, field + ".method"); - checkArray(d.params, field + ".params"); - if (d.params) { - for (let i = 0; i < d.params.length; i++) { - d.params[i] = TableDataEntity.Create(d.params[i], field + ".params" + "[" + i + "]"); - } - } - if (d.params === undefined) { - d.params = null; - } - d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); - checkArray(d.headers, field + ".headers"); - if (d.headers) { - for (let i = 0; i < d.headers.length; i++) { - d.headers[i] = TableDataEntity.Create(d.headers[i], field + ".headers" + "[" + i + "]"); - } - } - if (d.headers === undefined) { - d.headers = null; - } - d.body = Body2Proxy.Create(d.body, field + ".body"); - checkArray(d.tests, field + ".tests"); - if (d.tests) { - for (let i = 0; i < d.tests.length; i++) { - d.tests[i] = TestsEntityProxy.Create(d.tests[i], field + ".tests" + "[" + i + "]"); - } - } - if (d.tests === undefined) { - d.tests = null; - } - checkArray(d.setvar, field + ".setvar"); - if (d.setvar) { - for (let i = 0; i < d.setvar.length; i++) { - d.setvar[i] = SetvarEntityProxy.Create(d.setvar[i], field + ".setvar" + "[" + i + "]"); - } - } - if (d.setvar === undefined) { - d.setvar = null; - } - checkString(d.notes, false, field + ".notes"); - return new DataEntity2Proxy(d); - } - private constructor(d: any) { - this.id = d.id; - this.url = d.url; - this.name = d.name; - this.createdTime = d.createdTime; - this.method = d.method; - this.params = d.params; - this.auth = d.auth; - this.headers = d.headers; - this.body = d.body; - this.tests = d.tests; - this.setvar = d.setvar; - this.notes = d.notes; - } + public readonly id: string; + public readonly url: string; + public readonly name: string; + public readonly createdTime: string; + public readonly method: string; + public readonly params: TableDataEntity[] | null; + public readonly auth: Auth2Proxy; + public readonly headers: TableDataEntity[] | null; + public readonly body: Body2Proxy; + public readonly tests: TestsEntityProxy[] | null; + public readonly setvar: SetvarEntityProxy[] | null; + public readonly notes: string; + public static Parse(d: string): DataEntity2Proxy { + return DataEntity2Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): DataEntity2Proxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.id, false, field + ".id"); + checkString(d.url, false, field + ".url"); + checkString(d.name, false, field + ".name"); + checkString(d.createdTime, false, field + ".createdTime"); + checkString(d.method, false, field + ".method"); + checkArray(d.params, field + ".params"); + if (d.params) { + for (let i = 0; i < d.params.length; i++) { + d.params[i] = TableDataEntity.Create(d.params[i], field + ".params" + "[" + i + "]"); + } + } + if (d.params === undefined) { + d.params = null; + } + d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); + checkArray(d.headers, field + ".headers"); + if (d.headers) { + for (let i = 0; i < d.headers.length; i++) { + d.headers[i] = TableDataEntity.Create(d.headers[i], field + ".headers" + "[" + i + "]"); + } + } + if (d.headers === undefined) { + d.headers = null; + } + d.body = Body2Proxy.Create(d.body, field + ".body"); + checkArray(d.tests, field + ".tests"); + if (d.tests) { + for (let i = 0; i < d.tests.length; i++) { + d.tests[i] = TestsEntityProxy.Create(d.tests[i], field + ".tests" + "[" + i + "]"); + } + } + if (d.tests === undefined) { + d.tests = null; + } + checkArray(d.setvar, field + ".setvar"); + if (d.setvar) { + for (let i = 0; i < d.setvar.length; i++) { + d.setvar[i] = SetvarEntityProxy.Create(d.setvar[i], field + ".setvar" + "[" + i + "]"); + } + } + if (d.setvar === undefined) { + d.setvar = null; + } + checkString(d.notes, false, field + ".notes"); + return new DataEntity2Proxy(d); + } + private constructor(d: any) { + this.id = d.id; + this.url = d.url; + this.name = d.name; + this.createdTime = d.createdTime; + this.method = d.method; + this.params = d.params; + this.auth = d.auth; + this.headers = d.headers; + this.body = d.body; + this.tests = d.tests; + this.setvar = d.setvar; + this.notes = d.notes; + } } export class TableDataEntity { - public readonly isChecked: boolean; - public readonly key: string; - public readonly value: string; - public static Parse(d: string): TableDataEntity { - return TableDataEntity.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): TableDataEntity { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkBoolean(d.isChecked, false, field + ".isChecked"); - checkString(d.key, false, field + ".key"); - checkString(d.value, false, field + ".value"); - return new TableDataEntity(d); - } - private constructor(d: any) { - this.isChecked = d.isChecked; - this.key = d.key; - this.value = d.value; - } + public readonly isChecked: boolean; + public readonly key: string; + public readonly value: string; + public static Parse(d: string): TableDataEntity { + return TableDataEntity.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): TableDataEntity { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkBoolean(d.isChecked, false, field + ".isChecked"); + checkString(d.key, false, field + ".key"); + checkString(d.value, false, field + ".value"); + return new TableDataEntity(d); + } + private constructor(d: any) { + this.isChecked = d.isChecked; + this.key = d.key; + this.value = d.value; + } } export class Auth2Proxy { - public readonly authType: string; - public readonly userName: string; - public readonly password: string; - public readonly addTo: string; - public readonly showPwd: boolean; - public readonly tokenPrefix: string; - public readonly aws: AwsProxy; - public readonly oauth: OauthProxy; - public static Parse(d: string): Auth2Proxy { - return Auth2Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): Auth2Proxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.authType, false, field + ".authType"); - checkString(d.userName, false, field + ".userName"); - checkString(d.password, false, field + ".password"); - checkString(d.addTo, false, field + ".addTo"); - checkBoolean(d.showPwd, false, field + ".showPwd"); - checkString(d.tokenPrefix, false, field + ".tokenPrefix"); - d.aws = AwsProxy.Create(d.aws, field + ".aws"); - d.oauth = OauthProxy.Create(d.oauth, field + ".oauth"); - return new Auth2Proxy(d); - } - private constructor(d: any) { - this.authType = d.authType; - this.userName = d.userName; - this.password = d.password; - this.addTo = d.addTo; - this.showPwd = d.showPwd; - this.tokenPrefix = d.tokenPrefix; - this.aws = d.aws; - this.oauth = d.oauth; - } + public readonly authType: string; + public readonly userName: string; + public readonly password: string; + public readonly addTo: string; + public readonly showPwd: boolean; + public readonly tokenPrefix: string; + public readonly aws: AwsProxy; + public readonly oauth: OauthProxy; + public static Parse(d: string): Auth2Proxy { + return Auth2Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): Auth2Proxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.authType, false, field + ".authType"); + checkString(d.userName, false, field + ".userName"); + checkString(d.password, false, field + ".password"); + checkString(d.addTo, false, field + ".addTo"); + checkBoolean(d.showPwd, false, field + ".showPwd"); + checkString(d.tokenPrefix, false, field + ".tokenPrefix"); + d.aws = AwsProxy.Create(d.aws, field + ".aws"); + d.oauth = OauthProxy.Create(d.oauth, field + ".oauth"); + return new Auth2Proxy(d); + } + private constructor(d: any) { + this.authType = d.authType; + this.userName = d.userName; + this.password = d.password; + this.addTo = d.addTo; + this.showPwd = d.showPwd; + this.tokenPrefix = d.tokenPrefix; + this.aws = d.aws; + this.oauth = d.oauth; + } } export class AwsProxy { - public readonly service: string; - public readonly region: string; - public readonly accessKey: string; - public readonly secretAccessKey: string; - public readonly sessionToken: string; - public static Parse(d: string): AwsProxy { - return AwsProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): AwsProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.service, false, field + ".service"); - checkString(d.region, false, field + ".region"); - checkString(d.accessKey, false, field + ".accessKey"); - checkString(d.secretAccessKey, false, field + ".secretAccessKey"); - checkString(d.sessionToken, false, field + ".sessionToken"); - return new AwsProxy(d); - } - private constructor(d: any) { - this.service = d.service; - this.region = d.region; - this.accessKey = d.accessKey; - this.secretAccessKey = d.secretAccessKey; - this.sessionToken = d.sessionToken; - } + public readonly service: string; + public readonly region: string; + public readonly accessKey: string; + public readonly secretAccessKey: string; + public readonly sessionToken: string; + public static Parse(d: string): AwsProxy { + return AwsProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): AwsProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.service, false, field + ".service"); + checkString(d.region, false, field + ".region"); + checkString(d.accessKey, false, field + ".accessKey"); + checkString(d.secretAccessKey, false, field + ".secretAccessKey"); + checkString(d.sessionToken, false, field + ".sessionToken"); + return new AwsProxy(d); + } + private constructor(d: any) { + this.service = d.service; + this.region = d.region; + this.accessKey = d.accessKey; + this.secretAccessKey = d.secretAccessKey; + this.sessionToken = d.sessionToken; + } } export class OauthProxy { - public readonly clientAuth: string; - public readonly clientId: string; - public readonly clientSecret: string; - public readonly grantType: string; - public readonly password: string; - public readonly scope: string; - public readonly tokenName: string; - public readonly tokenUrl: string; - public readonly username: string; - public readonly advancedOpt: AdvancedOptProxy; - public static Parse(d: string): OauthProxy { - return OauthProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): OauthProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.clientAuth, false, field + ".clientAuth"); - checkString(d.clientId, false, field + ".clientId"); - checkString(d.clientSecret, false, field + ".clientSecret"); - checkString(d.grantType, false, field + ".grantType"); - checkString(d.password, false, field + ".password"); - checkString(d.scope, false, field + ".scope"); - checkString(d.tokenName, false, field + ".tokenName"); - checkString(d.tokenUrl, false, field + ".tokenUrl"); - checkString(d.username, false, field + ".username"); - d.advancedOpt = AdvancedOptProxy.Create(d.advancedOpt, field + ".advancedOpt"); - return new OauthProxy(d); - } - private constructor(d: any) { - this.clientAuth = d.clientAuth; - this.clientId = d.clientId; - this.clientSecret = d.clientSecret; - this.grantType = d.grantType; - this.password = d.password; - this.scope = d.scope; - this.tokenName = d.tokenName; - this.tokenUrl = d.tokenUrl; - this.username = d.username; - this.advancedOpt = d.advancedOpt; - } + public readonly clientAuth: string; + public readonly clientId: string; + public readonly clientSecret: string; + public readonly grantType: string; + public readonly password: string; + public readonly scope: string; + public readonly tokenName: string; + public readonly tokenUrl: string; + public readonly username: string; + public readonly advancedOpt: AdvancedOptProxy; + public static Parse(d: string): OauthProxy { + return OauthProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): OauthProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.clientAuth, false, field + ".clientAuth"); + checkString(d.clientId, false, field + ".clientId"); + checkString(d.clientSecret, false, field + ".clientSecret"); + checkString(d.grantType, false, field + ".grantType"); + checkString(d.password, false, field + ".password"); + checkString(d.scope, false, field + ".scope"); + checkString(d.tokenName, false, field + ".tokenName"); + checkString(d.tokenUrl, false, field + ".tokenUrl"); + checkString(d.username, false, field + ".username"); + d.advancedOpt = AdvancedOptProxy.Create(d.advancedOpt, field + ".advancedOpt"); + return new OauthProxy(d); + } + private constructor(d: any) { + this.clientAuth = d.clientAuth; + this.clientId = d.clientId; + this.clientSecret = d.clientSecret; + this.grantType = d.grantType; + this.password = d.password; + this.scope = d.scope; + this.tokenName = d.tokenName; + this.tokenUrl = d.tokenUrl; + this.username = d.username; + this.advancedOpt = d.advancedOpt; + } } export class AdvancedOptProxy { - public readonly audience: string; - public readonly resource: string; - public static Parse(d: string): AdvancedOptProxy { - return AdvancedOptProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): AdvancedOptProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.audience, false, field + ".audience"); - checkString(d.resource, false, field + ".resource"); - return new AdvancedOptProxy(d); - } - private constructor(d: any) { - this.audience = d.audience; - this.resource = d.resource; - } + public readonly audience: string; + public readonly resource: string; + public static Parse(d: string): AdvancedOptProxy { + return AdvancedOptProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): AdvancedOptProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.audience, false, field + ".audience"); + checkString(d.resource, false, field + ".resource"); + return new AdvancedOptProxy(d); + } + private constructor(d: any) { + this.audience = d.audience; + this.resource = d.resource; + } } export class Body2Proxy { - public readonly bodyType: string; - public readonly formdata: TableDataEntity[] | null; - public readonly urlencoded: TableDataEntity[] | null; - public readonly raw: RawProxy; - public readonly binary: BinaryProxy; - public readonly graphql: GraphqlProxy; - public static Parse(d: string): Body2Proxy { - return Body2Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): Body2Proxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.bodyType, false, field + ".bodyType"); - checkArray(d.formdata, field + ".formdata"); - if (d.formdata) { - for (let i = 0; i < d.formdata.length; i++) { - d.formdata[i] = TableDataEntity.Create(d.formdata[i], field + ".formdata" + "[" + i + "]"); - } - } - if (d.formdata === undefined) { - d.formdata = null; - } - checkArray(d.urlencoded, field + ".urlencoded"); - if (d.urlencoded) { - for (let i = 0; i < d.urlencoded.length; i++) { - d.urlencoded[i] = TableDataEntity.Create(d.urlencoded[i], field + ".urlencoded" + "[" + i + "]"); - } - } - if (d.urlencoded === undefined) { - d.urlencoded = null; - } - d.raw = RawProxy.Create(d.raw, field + ".raw"); - d.binary = BinaryProxy.Create(d.binary, field + ".binary"); - d.graphql = GraphqlProxy.Create(d.graphql, field + ".graphql"); - return new Body2Proxy(d); - } - private constructor(d: any) { - this.bodyType = d.bodyType; - this.formdata = d.formdata; - this.urlencoded = d.urlencoded; - this.raw = d.raw; - this.binary = d.binary; - this.graphql = d.graphql; - } + public readonly bodyType: string; + public readonly formdata: TableDataEntity[] | null; + public readonly urlencoded: TableDataEntity[] | null; + public readonly raw: RawProxy; + public readonly binary: BinaryProxy; + public readonly graphql: GraphqlProxy; + public static Parse(d: string): Body2Proxy { + return Body2Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): Body2Proxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.bodyType, false, field + ".bodyType"); + checkArray(d.formdata, field + ".formdata"); + if (d.formdata) { + for (let i = 0; i < d.formdata.length; i++) { + d.formdata[i] = TableDataEntity.Create(d.formdata[i], field + ".formdata" + "[" + i + "]"); + } + } + if (d.formdata === undefined) { + d.formdata = null; + } + checkArray(d.urlencoded, field + ".urlencoded"); + if (d.urlencoded) { + for (let i = 0; i < d.urlencoded.length; i++) { + d.urlencoded[i] = TableDataEntity.Create(d.urlencoded[i], field + ".urlencoded" + "[" + i + "]"); + } + } + if (d.urlencoded === undefined) { + d.urlencoded = null; + } + d.raw = RawProxy.Create(d.raw, field + ".raw"); + d.binary = BinaryProxy.Create(d.binary, field + ".binary"); + d.graphql = GraphqlProxy.Create(d.graphql, field + ".graphql"); + return new Body2Proxy(d); + } + private constructor(d: any) { + this.bodyType = d.bodyType; + this.formdata = d.formdata; + this.urlencoded = d.urlencoded; + this.raw = d.raw; + this.binary = d.binary; + this.graphql = d.graphql; + } } export class RawProxy { - public readonly data: string; - public readonly lang: string; - public static Parse(d: string): RawProxy { - return RawProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): RawProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.data, false, field + ".data"); - checkString(d.lang, false, field + ".lang"); - return new RawProxy(d); - } - private constructor(d: any) { - this.data = d.data; - this.lang = d.lang; - } + public readonly data: string; + public readonly lang: string; + public static Parse(d: string): RawProxy { + return RawProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): RawProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.data, false, field + ".data"); + checkString(d.lang, false, field + ".lang"); + return new RawProxy(d); + } + private constructor(d: any) { + this.data = d.data; + this.lang = d.lang; + } } export class BinaryProxy { - public readonly fileName: string; - public readonly data: DataProxy; - public readonly contentTypeOption: string; - public static Parse(d: string): BinaryProxy { - return BinaryProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): BinaryProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.fileName, false, field + ".fileName"); - d.data = DataProxy.Create(d.data, field + ".data"); - checkString(d.contentTypeOption, false, field + ".contentTypeOption"); - return new BinaryProxy(d); - } - private constructor(d: any) { - this.fileName = d.fileName; - this.data = d.data; - this.contentTypeOption = d.contentTypeOption; - } + public readonly fileName: string; + public readonly data: DataProxy; + public readonly contentTypeOption: string; + public static Parse(d: string): BinaryProxy { + return BinaryProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): BinaryProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.fileName, false, field + ".fileName"); + d.data = DataProxy.Create(d.data, field + ".data"); + checkString(d.contentTypeOption, false, field + ".contentTypeOption"); + return new BinaryProxy(d); + } + private constructor(d: any) { + this.fileName = d.fileName; + this.data = d.data; + this.contentTypeOption = d.contentTypeOption; + } } export class DataProxy { - public static Parse(d: string): DataProxy { - return DataProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): DataProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - return new DataProxy(d); - } - private constructor(d: any) { - } + public static Parse(d: string): DataProxy { + return DataProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): DataProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + return new DataProxy(d); + } + private constructor(_d: any) { + } } export class GraphqlProxy { - public readonly query: string; - public readonly variables: string; - public static Parse(d: string): GraphqlProxy { - return GraphqlProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): GraphqlProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.query, false, field + ".query"); - checkString(d.variables, false, field + ".variables"); - return new GraphqlProxy(d); - } - private constructor(d: any) { - this.query = d.query; - this.variables = d.variables; - } + public readonly query: string; + public readonly variables: string; + public static Parse(d: string): GraphqlProxy { + return GraphqlProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): GraphqlProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.query, false, field + ".query"); + checkString(d.variables, false, field + ".variables"); + return new GraphqlProxy(d); + } + private constructor(d: any) { + this.query = d.query; + this.variables = d.variables; + } } export class TestsEntityProxy { - public readonly parameter: string; - public readonly action: string; - public readonly expectedValue: string; - public static Parse(d: string): TestsEntityProxy { - return TestsEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): TestsEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.parameter, false, field + ".parameter"); - checkString(d.action, false, field + ".action"); - checkString(d.expectedValue, false, field + ".expectedValue"); - return new TestsEntityProxy(d); - } - private constructor(d: any) { - this.parameter = d.parameter; - this.action = d.action; - this.expectedValue = d.expectedValue; - } + public readonly parameter: string; + public readonly action: string; + public readonly expectedValue: string; + public static Parse(d: string): TestsEntityProxy { + return TestsEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): TestsEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.parameter, false, field + ".parameter"); + checkString(d.action, false, field + ".action"); + checkString(d.expectedValue, false, field + ".expectedValue"); + return new TestsEntityProxy(d); + } + private constructor(d: any) { + this.parameter = d.parameter; + this.action = d.action; + this.expectedValue = d.expectedValue; + } } export class SetvarEntityProxy { - public readonly parameter: string; - public readonly key: string; - public readonly variableName: string; - public static Parse(d: string): SetvarEntityProxy { - return SetvarEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): SetvarEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.parameter, false, field + ".parameter"); - checkString(d.key, false, field + ".key"); - checkString(d.variableName, false, field + ".variableName"); - return new SetvarEntityProxy(d); - } - private constructor(d: any) { - this.parameter = d.parameter; - this.key = d.key; - this.variableName = d.variableName; - } + public readonly parameter: string; + public readonly key: string; + public readonly variableName: string; + public static Parse(d: string): SetvarEntityProxy { + return SetvarEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): SetvarEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.parameter, false, field + ".parameter"); + checkString(d.key, false, field + ".key"); + checkString(d.variableName, false, field + ".variableName"); + return new SetvarEntityProxy(d); + } + private constructor(d: any) { + this.parameter = d.parameter; + this.key = d.key; + this.variableName = d.variableName; + } } export class Settings2Proxy { - public readonly auth: Auth2Proxy; - public static Parse(d: string): Settings2Proxy | null { - return Settings2Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): Settings2Proxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); - return new Settings2Proxy(d); - } - private constructor(d: any) { - this.auth = d.auth; - } + public readonly auth: Auth2Proxy; + public static Parse(d: string): Settings2Proxy | null { + return Settings2Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): Settings2Proxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); + return new Settings2Proxy(d); + } + private constructor(d: any) { + this.auth = d.auth; + } } export class Auth1Proxy { - public readonly authType: string; - public readonly userName: string; - public readonly password: string; - public readonly addTo: string; - public readonly showPwd: boolean; - public readonly tokenPrefix: string; - public readonly aws: AwsProxy; - public readonly oauth: OauthProxy; - public static Parse(d: string): Auth1Proxy | null { - return Auth1Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): Auth1Proxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - checkString(d.authType, false, field + ".authType"); - checkString(d.userName, false, field + ".userName"); - checkString(d.password, false, field + ".password"); - checkString(d.addTo, false, field + ".addTo"); - checkBoolean(d.showPwd, false, field + ".showPwd"); - checkString(d.tokenPrefix, false, field + ".tokenPrefix"); - d.aws = AwsProxy.Create(d.aws, field + ".aws"); - d.oauth = OauthProxy.Create(d.oauth, field + ".oauth"); - return new Auth1Proxy(d); - } - private constructor(d: any) { - this.authType = d.authType; - this.userName = d.userName; - this.password = d.password; - this.addTo = d.addTo; - this.showPwd = d.showPwd; - this.tokenPrefix = d.tokenPrefix; - this.aws = d.aws; - this.oauth = d.oauth; - } + public readonly authType: string; + public readonly userName: string; + public readonly password: string; + public readonly addTo: string; + public readonly showPwd: boolean; + public readonly tokenPrefix: string; + public readonly aws: AwsProxy; + public readonly oauth: OauthProxy; + public static Parse(d: string): Auth1Proxy | null { + return Auth1Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): Auth1Proxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + checkString(d.authType, false, field + ".authType"); + checkString(d.userName, false, field + ".userName"); + checkString(d.password, false, field + ".password"); + checkString(d.addTo, false, field + ".addTo"); + checkBoolean(d.showPwd, false, field + ".showPwd"); + checkString(d.tokenPrefix, false, field + ".tokenPrefix"); + d.aws = AwsProxy.Create(d.aws, field + ".aws"); + d.oauth = OauthProxy.Create(d.oauth, field + ".oauth"); + return new Auth1Proxy(d); + } + private constructor(d: any) { + this.authType = d.authType; + this.userName = d.userName; + this.password = d.password; + this.addTo = d.addTo; + this.showPwd = d.showPwd; + this.tokenPrefix = d.tokenPrefix; + this.aws = d.aws; + this.oauth = d.oauth; + } } export class Body1Proxy { - public readonly bodyType: string; - public readonly formdata: TableDataEntity[] | null; - public readonly urlencoded: TableDataEntity[] | null; - public readonly raw: RawProxy; - public readonly binary: BinaryProxy; - public readonly graphql: GraphqlProxy; - public static Parse(d: string): Body1Proxy | null { - return Body1Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): Body1Proxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - checkString(d.bodyType, false, field + ".bodyType"); - checkArray(d.formdata, field + ".formdata"); - if (d.formdata) { - for (let i = 0; i < d.formdata.length; i++) { - d.formdata[i] = TableDataEntity.Create(d.formdata[i], field + ".formdata" + "[" + i + "]"); - } - } - if (d.formdata === undefined) { - d.formdata = null; - } - checkArray(d.urlencoded, field + ".urlencoded"); - if (d.urlencoded) { - for (let i = 0; i < d.urlencoded.length; i++) { - d.urlencoded[i] = TableDataEntity.Create(d.urlencoded[i], field + ".urlencoded" + "[" + i + "]"); - } - } - if (d.urlencoded === undefined) { - d.urlencoded = null; - } - d.raw = RawProxy.Create(d.raw, field + ".raw"); - d.binary = BinaryProxy.Create(d.binary, field + ".binary"); - d.graphql = GraphqlProxy.Create(d.graphql, field + ".graphql"); - return new Body1Proxy(d); - } - private constructor(d: any) { - this.bodyType = d.bodyType; - this.formdata = d.formdata; - this.urlencoded = d.urlencoded; - this.raw = d.raw; - this.binary = d.binary; - this.graphql = d.graphql; - } + public readonly bodyType: string; + public readonly formdata: TableDataEntity[] | null; + public readonly urlencoded: TableDataEntity[] | null; + public readonly raw: RawProxy; + public readonly binary: BinaryProxy; + public readonly graphql: GraphqlProxy; + public static Parse(d: string): Body1Proxy | null { + return Body1Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): Body1Proxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + checkString(d.bodyType, false, field + ".bodyType"); + checkArray(d.formdata, field + ".formdata"); + if (d.formdata) { + for (let i = 0; i < d.formdata.length; i++) { + d.formdata[i] = TableDataEntity.Create(d.formdata[i], field + ".formdata" + "[" + i + "]"); + } + } + if (d.formdata === undefined) { + d.formdata = null; + } + checkArray(d.urlencoded, field + ".urlencoded"); + if (d.urlencoded) { + for (let i = 0; i < d.urlencoded.length; i++) { + d.urlencoded[i] = TableDataEntity.Create(d.urlencoded[i], field + ".urlencoded" + "[" + i + "]"); + } + } + if (d.urlencoded === undefined) { + d.urlencoded = null; + } + d.raw = RawProxy.Create(d.raw, field + ".raw"); + d.binary = BinaryProxy.Create(d.binary, field + ".binary"); + d.graphql = GraphqlProxy.Create(d.graphql, field + ".graphql"); + return new Body1Proxy(d); + } + private constructor(d: any) { + this.bodyType = d.bodyType; + this.formdata = d.formdata; + this.urlencoded = d.urlencoded; + this.raw = d.raw; + this.binary = d.binary; + this.graphql = d.graphql; + } } export class Settings1Proxy { - public readonly auth: Auth2Proxy; - public static Parse(d: string): Settings1Proxy | null { - return Settings1Proxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): Settings1Proxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); - return new Settings1Proxy(d); - } - private constructor(d: any) { - this.auth = d.auth; - } + public readonly auth: Auth2Proxy; + public static Parse(d: string): Settings1Proxy | null { + return Settings1Proxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): Settings1Proxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); + return new Settings1Proxy(d); + } + private constructor(d: any) { + this.auth = d.auth; + } } export class AuthProxy { - public readonly authType: string; - public readonly userName: string; - public readonly password: string; - public readonly addTo: string; - public readonly showPwd: boolean; - public readonly tokenPrefix: string; - public readonly aws: AwsProxy | null; - public readonly oauth: OauthProxy | null; - public static Parse(d: string): AuthProxy | null { - return AuthProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): AuthProxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - checkString(d.authType, false, field + ".authType"); - checkString(d.userName, false, field + ".userName"); - checkString(d.password, false, field + ".password"); - checkString(d.addTo, false, field + ".addTo"); - checkBoolean(d.showPwd, false, field + ".showPwd"); - checkString(d.tokenPrefix, false, field + ".tokenPrefix"); - d.aws = AwsProxy.Create(d.aws, field + ".aws"); - d.oauth = OauthProxy.Create(d.oauth, field + ".oauth"); - return new AuthProxy(d); - } - private constructor(d: any) { - this.authType = d.authType; - this.userName = d.userName; - this.password = d.password; - this.addTo = d.addTo; - this.showPwd = d.showPwd; - this.tokenPrefix = d.tokenPrefix; - this.aws = d.aws; - this.oauth = d.oauth; - } + public readonly authType: string; + public readonly userName: string; + public readonly password: string; + public readonly addTo: string; + public readonly showPwd: boolean; + public readonly tokenPrefix: string; + public readonly aws: AwsProxy | null; + public readonly oauth: OauthProxy | null; + public static Parse(d: string): AuthProxy | null { + return AuthProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): AuthProxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + checkString(d.authType, false, field + ".authType"); + checkString(d.userName, false, field + ".userName"); + checkString(d.password, false, field + ".password"); + checkString(d.addTo, false, field + ".addTo"); + checkBoolean(d.showPwd, false, field + ".showPwd"); + checkString(d.tokenPrefix, false, field + ".tokenPrefix"); + d.aws = AwsProxy.Create(d.aws, field + ".aws"); + d.oauth = OauthProxy.Create(d.oauth, field + ".oauth"); + return new AuthProxy(d); + } + private constructor(d: any) { + this.authType = d.authType; + this.userName = d.userName; + this.password = d.password; + this.addTo = d.addTo; + this.showPwd = d.showPwd; + this.tokenPrefix = d.tokenPrefix; + this.aws = d.aws; + this.oauth = d.oauth; + } } export class HeadersEntityProxy { - public readonly isChecked: boolean; - public readonly isFixed: boolean | null; - public readonly key: string; - public readonly value: string; - public static Parse(d: string): HeadersEntityProxy { - return HeadersEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): HeadersEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkBoolean(d.isChecked, false, field + ".isChecked"); - checkBoolean(d.isFixed, true, field + ".isFixed"); - if (d.isFixed === undefined) { - d.isFixed = null; - } - checkString(d.key, false, field + ".key"); - checkString(d.value, false, field + ".value"); - return new HeadersEntityProxy(d); - } - private constructor(d: any) { - this.isChecked = d.isChecked; - this.isFixed = d.isFixed; - this.key = d.key; - this.value = d.value; - } + public readonly isChecked: boolean; + public readonly isFixed: boolean | null; + public readonly key: string; + public readonly value: string; + public static Parse(d: string): HeadersEntityProxy { + return HeadersEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): HeadersEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkBoolean(d.isChecked, false, field + ".isChecked"); + checkBoolean(d.isFixed, true, field + ".isFixed"); + if (d.isFixed === undefined) { + d.isFixed = null; + } + checkString(d.key, false, field + ".key"); + checkString(d.value, false, field + ".value"); + return new HeadersEntityProxy(d); + } + private constructor(d: any) { + this.isChecked = d.isChecked; + this.isFixed = d.isFixed; + this.key = d.key; + this.value = d.value; + } } export class BodyProxy { - public readonly bodyType: string; - public readonly formdata: TableDataEntity[] | null; - public readonly urlencoded: TableDataEntity[] | null; - public readonly raw: RawProxy; - public readonly binary: BinaryProxy; - public readonly graphql: GraphqlProxy; - public static Parse(d: string): BodyProxy | null { - return BodyProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): BodyProxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - checkString(d.bodyType, false, field + ".bodyType"); - checkArray(d.formdata, field + ".formdata"); - if (d.formdata) { - for (let i = 0; i < d.formdata.length; i++) { - d.formdata[i] = TableDataEntity.Create(d.formdata[i], field + ".formdata" + "[" + i + "]"); - } - } - if (d.formdata === undefined) { - d.formdata = null; - } - checkArray(d.urlencoded, field + ".urlencoded"); - if (d.urlencoded) { - for (let i = 0; i < d.urlencoded.length; i++) { - d.urlencoded[i] = TableDataEntity.Create(d.urlencoded[i], field + ".urlencoded" + "[" + i + "]"); - } - } - if (d.urlencoded === undefined) { - d.urlencoded = null; - } - d.raw = RawProxy.Create(d.raw, field + ".raw"); - d.binary = BinaryProxy.Create(d.binary, field + ".binary"); - d.graphql = GraphqlProxy.Create(d.graphql, field + ".graphql"); - return new BodyProxy(d); - } - private constructor(d: any) { - this.bodyType = d.bodyType; - this.formdata = d.formdata; - this.urlencoded = d.urlencoded; - this.raw = d.raw; - this.binary = d.binary; - this.graphql = d.graphql; - } + public readonly bodyType: string; + public readonly formdata: TableDataEntity[] | null; + public readonly urlencoded: TableDataEntity[] | null; + public readonly raw: RawProxy; + public readonly binary: BinaryProxy; + public readonly graphql: GraphqlProxy; + public static Parse(d: string): BodyProxy | null { + return BodyProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): BodyProxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + checkString(d.bodyType, false, field + ".bodyType"); + checkArray(d.formdata, field + ".formdata"); + if (d.formdata) { + for (let i = 0; i < d.formdata.length; i++) { + d.formdata[i] = TableDataEntity.Create(d.formdata[i], field + ".formdata" + "[" + i + "]"); + } + } + if (d.formdata === undefined) { + d.formdata = null; + } + checkArray(d.urlencoded, field + ".urlencoded"); + if (d.urlencoded) { + for (let i = 0; i < d.urlencoded.length; i++) { + d.urlencoded[i] = TableDataEntity.Create(d.urlencoded[i], field + ".urlencoded" + "[" + i + "]"); + } + } + if (d.urlencoded === undefined) { + d.urlencoded = null; + } + d.raw = RawProxy.Create(d.raw, field + ".raw"); + d.binary = BinaryProxy.Create(d.binary, field + ".binary"); + d.graphql = GraphqlProxy.Create(d.graphql, field + ".graphql"); + return new BodyProxy(d); + } + private constructor(d: any) { + this.bodyType = d.bodyType; + this.formdata = d.formdata; + this.urlencoded = d.urlencoded; + this.raw = d.raw; + this.binary = d.binary; + this.graphql = d.graphql; + } } export class PreFetchProxy { - public readonly requests: RequestsEntityProxy[] | null; - public static Parse(d: string): PreFetchProxy | null { - return PreFetchProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): PreFetchProxy | null { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - return null; - } else if (typeof(d) !== 'object') { - throwNotObject(field, d, true); - } else if (Array.isArray(d)) { - throwIsArray(field, d, true); - } - checkArray(d.requests, field + ".requests"); - if (d.requests) { - for (let i = 0; i < d.requests.length; i++) { - d.requests[i] = RequestsEntityProxy.Create(d.requests[i], field + ".requests" + "[" + i + "]"); - } - } - if (d.requests === undefined) { - d.requests = null; - } - return new PreFetchProxy(d); - } - private constructor(d: any) { - this.requests = d.requests; - } + public readonly requests: RequestsEntityProxy[] | null; + public static Parse(d: string): PreFetchProxy | null { + return PreFetchProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): PreFetchProxy | null { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + return null; + } else if (typeof(d) !== 'object') { + throwNotObject(field, d, true); + } else if (Array.isArray(d)) { + throwIsArray(field, d, true); + } + checkArray(d.requests, field + ".requests"); + if (d.requests) { + for (let i = 0; i < d.requests.length; i++) { + d.requests[i] = RequestsEntityProxy.Create(d.requests[i], field + ".requests" + "[" + i + "]"); + } + } + if (d.requests === undefined) { + d.requests = null; + } + return new PreFetchProxy(d); + } + private constructor(d: any) { + this.requests = d.requests; + } } export class RequestsEntityProxy { - public readonly reqId: string; - public readonly parentId: string; - public readonly colId: string; - public readonly order: number; - public readonly condition: ConditionEntityProxy[] | null; - public static Parse(d: string): RequestsEntityProxy { - return RequestsEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): RequestsEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof(d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.reqId, false, field + ".reqId"); - checkString(d.parentId, false, field + ".parentId"); - checkString(d.colId, false, field + ".colId"); - checkNumber(d.order, false, field + ".order"); - checkArray(d.condition, field + ".condition"); - if (d.condition) { - for (let i = 0; i < d.condition.length; i++) { - d.condition[i] = ConditionEntityProxy.Create(d.condition[i], field + ".condition" + "[" + i + "]"); - } - } - if (d.condition === undefined) { - d.condition = null; - } - return new RequestsEntityProxy(d); - } - private constructor(d: any) { - this.reqId = d.reqId; - this.parentId = d.parentId; - this.colId = d.colId; - this.order = d.order; - this.condition = d.condition; - } + public readonly reqId: string; + public readonly parentId: string; + public readonly colId: string; + public readonly order: number; + public readonly condition: ConditionEntityProxy[] | null; + public static Parse(d: string): RequestsEntityProxy { + return RequestsEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): RequestsEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof(d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.reqId, false, field + ".reqId"); + checkString(d.parentId, false, field + ".parentId"); + checkString(d.colId, false, field + ".colId"); + checkNumber(d.order, false, field + ".order"); + checkArray(d.condition, field + ".condition"); + if (d.condition) { + for (let i = 0; i < d.condition.length; i++) { + d.condition[i] = ConditionEntityProxy.Create(d.condition[i], field + ".condition" + "[" + i + "]"); + } + } + if (d.condition === undefined) { + d.condition = null; + } + return new RequestsEntityProxy(d); + } + private constructor(d: any) { + this.reqId = d.reqId; + this.parentId = d.parentId; + this.colId = d.colId; + this.order = d.order; + this.condition = d.condition; + } } export class ConditionEntityProxy { - public readonly parameter: string; - public readonly action: string; - public readonly expectedValue: string; - public readonly customParameter: string | null; - public static Parse(d: string): ConditionEntityProxy { - return ConditionEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): ConditionEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof(d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.parameter, false, field + ".parameter"); - checkString(d.action, false, field + ".action"); - checkString(d.expectedValue, false, field + ".expectedValue"); - checkString(d.customParameter, true, field + ".customParameter"); - if (d.customParameter === undefined) { - d.customParameter = null; - } - return new ConditionEntityProxy(d); - } - private constructor(d: any) { - this.parameter = d.parameter; - this.action = d.action; - this.expectedValue = d.expectedValue; - this.customParameter = d.customParameter; - } + public readonly parameter: string; + public readonly action: string; + public readonly expectedValue: string; + public readonly customParameter: string | null; + public static Parse(d: string): ConditionEntityProxy { + return ConditionEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): ConditionEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof(d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.parameter, false, field + ".parameter"); + checkString(d.action, false, field + ".action"); + checkString(d.expectedValue, false, field + ".expectedValue"); + checkString(d.customParameter, true, field + ".customParameter"); + if (d.customParameter === undefined) { + d.customParameter = null; + } + return new ConditionEntityProxy(d); + } + private constructor(d: any) { + this.parameter = d.parameter; + this.action = d.action; + this.expectedValue = d.expectedValue; + this.customParameter = d.customParameter; + } } export class SettingsProxy { - public readonly auth: Auth2Proxy; - public static Parse(d: string): SettingsProxy { - return SettingsProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): SettingsProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof (d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); - return new SettingsProxy(d); - } - private constructor(d: any) { - this.auth = d.auth; - } + public readonly auth: Auth2Proxy; + public static Parse(d: string): SettingsProxy { + return SettingsProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): SettingsProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof (d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + d.auth = Auth2Proxy.Create(d.auth, field + ".auth"); + return new SettingsProxy(d); + } + private constructor(d: any) { + this.auth = d.auth; + } } function throwNull2NonNull(field: string, d: any): never { - return errorHelper(field, d, "non-nullable object", false); + return errorHelper(field, d, "non-nullable object", false); } function throwNotObject(field: string, d: any, nullable: boolean): never { - return errorHelper(field, d, "object", nullable); + return errorHelper(field, d, "object", nullable); } function throwIsArray(field: string, d: any, nullable: boolean): never { - return errorHelper(field, d, "object", nullable); + return errorHelper(field, d, "object", nullable); } function checkArray(d: any, field: string): void { - if (!Array.isArray(d) && d !== null && d !== undefined) { - errorHelper(field, d, "array", true); - } + if (!Array.isArray(d) && d !== null && d !== undefined) { + errorHelper(field, d, "array", true); + } } function checkNumber(d: any, nullable: boolean, field: string): void { - if (typeof(d) !== 'number' && (!nullable || (nullable && d !== null && d !== undefined))) { - errorHelper(field, d, "number", nullable); - } + if (typeof(d) !== 'number' && (!nullable || (nullable && d !== null && d !== undefined))) { + errorHelper(field, d, "number", nullable); + } } function checkBoolean(d: any, nullable: boolean, field: string): void { - if (typeof (d) !== 'boolean' && (!nullable || (nullable && d !== null && d !== undefined))) { - errorHelper(field, d, "boolean", nullable); - } + if (typeof (d) !== 'boolean' && (!nullable || (nullable && d !== null && d !== undefined))) { + errorHelper(field, d, "boolean", nullable); + } } function checkString(d: any, nullable: boolean, field: string): void { - if (typeof (d) !== 'string' && (!nullable || (nullable && d !== null && d !== undefined))) { - errorHelper(field, d, "string", nullable); - } + if (typeof (d) !== 'string' && (!nullable || (nullable && d !== null && d !== undefined))) { + errorHelper(field, d, "string", nullable); + } } function errorHelper(field: string, d: any, type: string, nullable: boolean): never { - if (nullable) { - type += ", null, or undefined"; - } - throw new TypeError("Expected '" + type + "' at '" + field + "' but found: " + JSON.stringify(d) + "\nFull object:\n" + JSON.stringify(obj)); + if (nullable) { + type += ", null, or undefined"; + } + throw new TypeError("Expected '" + type + "' at '" + field + "' but found: " + JSON.stringify(d) + "\nFull object:\n" + JSON.stringify(obj)); } function checkStringValue(d: any, field: string, value: string): void { - if (d !== value) { - errorHelper(field, d, value, false); - } + if (d !== value) { + errorHelper(field, d, value, false); + } } diff --git a/src/utils/validators/fetchClientVariableValidator.ts b/src/utils/validators/fetchClientVariableValidator.ts index bb96886..366de3f 100644 --- a/src/utils/validators/fetchClientVariableValidator.ts +++ b/src/utils/validators/fetchClientVariableValidator.ts @@ -1,131 +1,131 @@ let obj: any = null; export class FetchClientVariableProxy { - public readonly app: string; - public readonly id: string; - public readonly name: string; - public readonly version: string; - public readonly type: string; - public readonly createdTime: string; - public readonly exportedDate: string; - public readonly isActive: boolean; - public readonly data: DataEntityProxy[] | null; - public static Parse(d: string): FetchClientVariableProxy { - return FetchClientVariableProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): FetchClientVariableProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof(d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkString(d.app, false, field + ".app"); - checkStringValue(d.app, field + ".app", "Fetch Client"); - checkString(d.id, false, field + ".id"); - checkString(d.name, false, field + ".name"); - checkString(d.version, false, field + ".version"); - checkString(d.type, false, field + ".type"); - checkStringValue(d.type, field + ".type", "variables"); - checkString(d.createdTime, false, field + ".createdTime"); - checkString(d.exportedDate, false, field + ".exportedDate"); - checkBoolean(d.isActive, false, field + ".isActive"); - checkArray(d.data, field + ".data"); - if (d.data) { - for (let i = 0; i < d.data.length; i++) { - d.data[i] = DataEntityProxy.Create(d.data[i], field + ".data" + "[" + i + "]"); - } - } - if (d.data === undefined) { - d.data = null; - } - return new FetchClientVariableProxy(d); - } - private constructor(d: any) { - this.app = d.app; - this.id = d.id; - this.name = d.name; - this.version = d.version; - this.type = d.type; - this.createdTime = d.createdTime; - this.exportedDate = d.exportedDate; - this.isActive = d.isActive; - this.data = d.data; - } + public readonly app: string; + public readonly id: string; + public readonly name: string; + public readonly version: string; + public readonly type: string; + public readonly createdTime: string; + public readonly exportedDate: string; + public readonly isActive: boolean; + public readonly data: DataEntityProxy[] | null; + public static Parse(d: string): FetchClientVariableProxy { + return FetchClientVariableProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): FetchClientVariableProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof(d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkString(d.app, false, field + ".app"); + checkStringValue(d.app, field + ".app", "Fetch Client"); + checkString(d.id, false, field + ".id"); + checkString(d.name, false, field + ".name"); + checkString(d.version, false, field + ".version"); + checkString(d.type, false, field + ".type"); + checkStringValue(d.type, field + ".type", "variables"); + checkString(d.createdTime, false, field + ".createdTime"); + checkString(d.exportedDate, false, field + ".exportedDate"); + checkBoolean(d.isActive, false, field + ".isActive"); + checkArray(d.data, field + ".data"); + if (d.data) { + for (let i = 0; i < d.data.length; i++) { + d.data[i] = DataEntityProxy.Create(d.data[i], field + ".data" + "[" + i + "]"); + } + } + if (d.data === undefined) { + d.data = null; + } + return new FetchClientVariableProxy(d); + } + private constructor(d: any) { + this.app = d.app; + this.id = d.id; + this.name = d.name; + this.version = d.version; + this.type = d.type; + this.createdTime = d.createdTime; + this.exportedDate = d.exportedDate; + this.isActive = d.isActive; + this.data = d.data; + } } export class DataEntityProxy { - public readonly isChecked: boolean; - public readonly key: string; - public readonly value: string; - public static Parse(d: string): DataEntityProxy { - return DataEntityProxy.Create(JSON.parse(d)); - } - public static Create(d: any, field: string = 'root'): DataEntityProxy { - if (!field) { - obj = d; - field = "root"; - } - if (d === null || d === undefined) { - throwNull2NonNull(field, d); - } else if (typeof(d) !== 'object') { - throwNotObject(field, d, false); - } else if (Array.isArray(d)) { - throwIsArray(field, d, false); - } - checkBoolean(d.isChecked, false, field + ".isChecked"); - checkString(d.key, false, field + ".key"); - checkStringOrNumber(d.value, false, field + ".value"); - return new DataEntityProxy(d); - } - private constructor(d: any) { - this.isChecked = d.isChecked; - this.key = d.key; - this.value = d.value; - } + public readonly isChecked: boolean; + public readonly key: string; + public readonly value: string; + public static Parse(d: string): DataEntityProxy { + return DataEntityProxy.Create(JSON.parse(d)); + } + public static Create(d: any, field: string = 'root'): DataEntityProxy { + if (!field) { + obj = d; + field = "root"; + } + if (d === null || d === undefined) { + throwNull2NonNull(field, d); + } else if (typeof(d) !== 'object') { + throwNotObject(field, d, false); + } else if (Array.isArray(d)) { + throwIsArray(field, d, false); + } + checkBoolean(d.isChecked, false, field + ".isChecked"); + checkString(d.key, false, field + ".key"); + checkStringOrNumber(d.value, false, field + ".value"); + return new DataEntityProxy(d); + } + private constructor(d: any) { + this.isChecked = d.isChecked; + this.key = d.key; + this.value = d.value; + } } function throwNull2NonNull(field: string, d: any): never { - return errorHelper(field, d, "non-nullable object", false); + return errorHelper(field, d, "non-nullable object", false); } function throwNotObject(field: string, d: any, nullable: boolean): never { - return errorHelper(field, d, "object", nullable); + return errorHelper(field, d, "object", nullable); } function throwIsArray(field: string, d: any, nullable: boolean): never { - return errorHelper(field, d, "object", nullable); + return errorHelper(field, d, "object", nullable); } function checkArray(d: any, field: string): void { - if (!Array.isArray(d) && d !== null && d !== undefined) { - errorHelper(field, d, "array", true); - } + if (!Array.isArray(d) && d !== null && d !== undefined) { + errorHelper(field, d, "array", true); + } } function checkBoolean(d: any, nullable: boolean, field: string): void { - if (typeof(d) !== 'boolean' && (!nullable || (nullable && d !== null && d !== undefined))) { - errorHelper(field, d, "boolean", nullable); - } + if (typeof(d) !== 'boolean' && (!nullable || (nullable && d !== null && d !== undefined))) { + errorHelper(field, d, "boolean", nullable); + } } function checkString(d: any, nullable: boolean, field: string): void { - if (typeof(d) !== 'string' && (!nullable || (nullable && d !== null && d !== undefined))) { - errorHelper(field, d, "string", nullable); - } + if (typeof(d) !== 'string' && (!nullable || (nullable && d !== null && d !== undefined))) { + errorHelper(field, d, "string", nullable); + } } function checkStringOrNumber(d: any, nullable: boolean, field: string): void { - if ((typeof(d) !== 'string' && typeof(d) !== 'number') && (!nullable || (nullable && d !== null && d !== undefined))) { - errorHelper(field, d, "stringORnumber", nullable); - } + if ((typeof(d) !== 'string' && typeof(d) !== 'number') && (!nullable || (nullable && d !== null && d !== undefined))) { + errorHelper(field, d, "stringORnumber", nullable); + } } function errorHelper(field: string, d: any, type: string, nullable: boolean): never { - if (nullable) { - type += ", null, or undefined"; - } - throw new TypeError("Expected '" + type + "' at '" + field + "' but found:\n" + JSON.stringify(d) + "\n\nFull object:\n" + JSON.stringify(obj)); + if (nullable) { + type += ", null, or undefined"; + } + throw new TypeError("Expected '" + type + "' at '" + field + "' but found:\n" + JSON.stringify(d) + "\n\nFull object:\n" + JSON.stringify(obj)); } function checkStringValue(d: any, field: string, value: string): void { - if (d !== value) { - errorHelper(field, d, value, false); - } -} \ No newline at end of file + if (d !== value) { + errorHelper(field, d, value, false); + } +} diff --git a/src/utils/vscodeConfig.ts b/src/utils/vscodeConfig.ts index 25e7886..69838de 100644 --- a/src/utils/vscodeConfig.ts +++ b/src/utils/vscodeConfig.ts @@ -2,106 +2,128 @@ import * as vscode from 'vscode'; import { responseTypes } from './configuration'; import { getExtLocalDbPath } from './db/getExtDbPath'; +let variableEncryptionConfiguration = false; + function getFetchClientConfiguration(): vscode.WorkspaceConfiguration { - return vscode.workspace.getConfiguration('fetch-client'); + return vscode.workspace.getConfiguration('fetch-client'); } export function getLayoutConfiguration(): any { - let config = getFetchClientConfiguration(); - let layoutConfig = config.get("layout", "Horizontal Split"); - return { type: responseTypes.layoutConfigResponse, layoutConfigData: layoutConfig }; + let config = getFetchClientConfiguration(); + let layoutConfig = config.get("layout", "Horizontal Split"); + return { type: responseTypes.layoutConfigResponse, layoutConfigData: layoutConfig }; } export function getConfiguration(): any { - let config = getFetchClientConfiguration(); - const theme = vscode.window.activeColorTheme.kind; - return { type: responseTypes.configResponse, configData: JSON.stringify(config), theme: theme }; + let config = getFetchClientConfiguration(); + const theme = vscode.window.activeColorTheme.kind; + return { type: responseTypes.configResponse, configData: JSON.stringify(config), theme: theme }; } export function getVSCodeTheme(): any { - const theme = vscode.window.activeColorTheme.kind; - return { type: responseTypes.themeResponse, theme: theme }; + const theme = vscode.window.activeColorTheme.kind; + return { type: responseTypes.themeResponse, theme: theme }; } export function getSSLConfiguration(): boolean { - let config = getFetchClientConfiguration(); - let sslCheck = config.get("SSLCheck", true); - return sslCheck; + let config = getFetchClientConfiguration(); + let sslCheck = config.get("SSLCheck", true); + return sslCheck; } export function getHistoryLimitConfiguration(): string { - let config = getFetchClientConfiguration(); - let limit = config.get("historyLimit", "25"); - return limit; + let config = getFetchClientConfiguration(); + let limit = config.get("historyLimit", "25"); + return limit; } export function getTimeOutConfiguration(): number { - let config = getFetchClientConfiguration(); - let limit = config.get("timeOut", 120000); - return limit; + let config = getFetchClientConfiguration(); + let limit = config.get("timeOut", 120000); + return limit; } export function getHeadersConfiguration(): boolean { - let config = getFetchClientConfiguration(); - let headerCase = config.get("headersCaseSensitive", true); - return headerCase; + let config = getFetchClientConfiguration(); + let headerCase = config.get("headersCaseSensitive", true); + return headerCase; } export function getProtocolConfiguration(): string { - let config = getFetchClientConfiguration(); - let limit = config.get("defaultProtocol", "http"); - return limit; + let config = getFetchClientConfiguration(); + let limit = config.get("defaultProtocol", "http"); + return limit; } export function getRequestTabOption(): boolean { - let config = getFetchClientConfiguration(); - let option = config.get("separateRequestTab", false); - return option; + let config = getFetchClientConfiguration(); + let option = config.get("separateRequestTab", false); + return option; } export function getLogOption(): boolean { - let config = getFetchClientConfiguration(); - let option = config.get("log", false); - return option; + let config = getFetchClientConfiguration(); + let option = config.get("log", false); + return option; } export function getRunMainRequestOption(): boolean { - let config = getFetchClientConfiguration(); - let option = config.get("runMainRequest", true); - return option; + let config = getFetchClientConfiguration(); + let option = config.get("runMainRequest", true); + return option; } export function getSaveToWorkspaceConfiguration(): boolean { - let config = getFetchClientConfiguration(); - let keepInLocal = config.get("saveToWorkspace", false); - return keepInLocal; + let config = getFetchClientConfiguration(); + let keepInLocal = config.get("saveToWorkspace", false); + return keepInLocal; } export function getWorkspacePathConfiguration(): string { - let config = getFetchClientConfiguration(); - let localPath = config.get("workspacePath", ""); - return localPath; + let config = getFetchClientConfiguration(); + let localPath = config.get("workspacePath", ""); + return localPath; +} + +export const setVariableEncryptionConfiguration = (enabled: boolean) => { + variableEncryptionConfiguration = enabled; +}; + +export function getVariableEncryptionConfiguration(): boolean { + return variableEncryptionConfiguration; +} + +export function getVariableEncryptionFCConfiguration(): boolean { + let config = getFetchClientConfiguration(); + let encrypt = config.get("encryptedVariables", false); + return encrypt; +} + +export function getExportVariableEncryptionConfiguration(): boolean { + let config = getFetchClientConfiguration(); + let encrypt = config.get("encryptedVariablesInExport", false); + return encrypt; } export function updateSaveToWorkspaceConfiguration(value: boolean) { - let config = getFetchClientConfiguration(); - config.update("saveToWorkspace", value); + let config = getFetchClientConfiguration(); + config.update("saveToWorkspace", value); - if (value) { - updateWorkspacePathConfiguration(getExtLocalDbPath()); - } - else { - updateWorkspacePathConfiguration(""); - } + if (value) { + updateWorkspacePathConfiguration(getExtLocalDbPath()); + } + else { + updateWorkspacePathConfiguration(""); + } } export function updateWorkspacePathConfiguration(value: string) { - let config = getFetchClientConfiguration(); - config.update("workspacePath", value); + let config = getFetchClientConfiguration(); + config.update("workspacePath", value); } export function responseLimitConfiguration() { - let config = getFetchClientConfiguration(); - let responseLimit = config.get("responseLimit", 5); - return responseLimit * 1048576; + let config = getFetchClientConfiguration(); + let responseLimit = config.get("responseLimit", 5); + return responseLimit * 1048576; } diff --git a/tsconfig.json b/tsconfig.json index ffcdc39..b1f034c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,11 +13,16 @@ "rootDir": ".", "resolveJsonModule": true, "skipLibCheck": true, - "strict": false /* enable all strict type-checking options */ - /* Additional Checks */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ + "strict": false, + "noUnusedParameters": true, + "noUnusedLocals": true, + "noFallthroughCasesInSwitch": true, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "noImplicitOverride": true, + "noImplicitThis": true, + // "strictNullChecks": true + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ }, "exclude": [ "node_modules", diff --git a/vsc-extension-quickstart.md b/vsc-extension-quickstart.md index 92c3b0e..cc9144a 100644 --- a/vsc-extension-quickstart.md +++ b/vsc-extension-quickstart.md @@ -390,7 +390,7 @@ Fetch client provides the quick access of History, collection and Environment va

Import Curl Menu -
+
Import Curl
Import Curl Request @@ -498,7 +498,7 @@ DO NOT ENTER/EDIT MANUALLY in the below settings. Configuration will be done aut

- Fetch Client settings + Fetch Client settings
## 🚀 Tech Stack diff --git a/webpack.config.js b/webpack.config.js index 02689cb..9ea755a 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -9,131 +9,131 @@ const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const TerserPlugin = require("terser-webpack-plugin"); const commonConfig = (webpackEnv) => { - const isEnvDevelopment = webpackEnv === "development"; - const isEnvProduction = webpackEnv === "production"; + const isEnvDevelopment = webpackEnv === "development"; + const isEnvProduction = webpackEnv === "production"; - return { - mode: isEnvProduction ? "production" : isEnvDevelopment && "development", - bail: isEnvProduction, - devtool: isEnvProduction - ? "source-map" - : isEnvDevelopment && "eval-cheap-module-source-map", - resolve: { - fallback: { - buffer: require.resolve("buffer"), - path: require.resolve("path-browserify"), - url: require.resolve("url"), - }, - extensions: [".ts", ".tsx", ".js"], - }, - module: { - rules: [ - { - oneOf: [ - { - test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], - loader: require.resolve("url-loader"), - }, - { - test: /\.svg$/, - use: [ - require.resolve("@svgr/webpack"), - require.resolve("url-loader"), - ], - }, - { - test: /\.tsx?$/, - exclude: /node_modules/, - loader: require.resolve("ts-loader"), - }, - { - test: /\.css$/, - use: [ - MiniCssExtractPlugin.loader, - { - loader: require.resolve("css-loader"), - options: { - importLoaders: 1, - sourceMap: isEnvProduction || isEnvDevelopment, - }, - }, - ], - sideEffects: true, - }, - { - test: /\.(woff|woff2|eot|ttf|otf)$/i, - type: 'asset/resource' - }, - { - test: /\.m?js/, - resolve: { - fullySpecified: false - } - }, - { - loader: require.resolve("file-loader"), - exclude: [/\.(js|mjs|jsx|ts|tsx|cjs)$/, /\.html$/, /\.json$/], - } - ], - }, - ], - }, - optimization: { - minimize: true, - minimizer: [ - new TerserPlugin({ - terserOptions: { - format: { - comments: false, - }, - }, - extractComments: false, - }), - ], - }, - plugins: [ - new MiniCssExtractPlugin({ - filename: "ignore.css", - }), - ], - }; + return { + mode: isEnvProduction ? "production" : isEnvDevelopment && "development", + bail: isEnvProduction, + devtool: isEnvProduction + ? "source-map" + : isEnvDevelopment && "eval-cheap-module-source-map", + resolve: { + fallback: { + buffer: require.resolve("buffer"), + path: require.resolve("path-browserify"), + url: require.resolve("url"), + }, + extensions: [".ts", ".tsx", ".js"], + }, + module: { + rules: [ + { + oneOf: [ + { + test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], + loader: require.resolve("url-loader"), + }, + { + test: /\.svg$/, + use: [ + require.resolve("@svgr/webpack"), + require.resolve("url-loader"), + ], + }, + { + test: /\.tsx?$/, + exclude: /node_modules/, + loader: require.resolve("ts-loader"), + }, + { + test: /\.css$/, + use: [ + MiniCssExtractPlugin.loader, + { + loader: require.resolve("css-loader"), + options: { + importLoaders: 1, + sourceMap: isEnvProduction || isEnvDevelopment, + }, + }, + ], + sideEffects: true, + }, + { + test: /\.(woff|woff2|eot|ttf|otf)$/i, + type: 'asset/resource' + }, + { + test: /\.m?js/, + resolve: { + fullySpecified: false + } + }, + { + loader: require.resolve("file-loader"), + exclude: [/\.(js|mjs|jsx|ts|tsx|cjs)$/, /\.html$/, /\.json$/], + } + ], + }, + ], + }, + optimization: { + minimize: true, + minimizer: [ + new TerserPlugin({ + terserOptions: { + format: { + comments: false, + }, + }, + extractComments: false, + }), + ], + }, + plugins: [ + new MiniCssExtractPlugin({ + filename: "ignore.css", + }), + ], + }; }; const extensionConfig = (webpackEnv) => { - return { - ...commonConfig(webpackEnv), - target: "node", - entry: "./src/extension.ts", - output: { - path: path.resolve(__dirname, "dist"), - filename: "extension.js", - libraryTarget: "commonjs2", - }, - externals: { vscode: "commonjs vscode" }, - }; + return { + ...commonConfig(webpackEnv), + target: "node", + entry: "./src/extension.ts", + output: { + path: path.resolve(__dirname, "dist"), + filename: "extension.js", + libraryTarget: "commonjs2", + }, + externals: { vscode: "commonjs vscode" }, + }; }; function fetchClientUIConfig(webpackEnv) { - return { - ...commonConfig(webpackEnv), - entry: "./src/fetch-client-ui/index.tsx", - output: { - path: path.resolve(__dirname, "dist"), - filename: "fetch-client-ui.js" - }, - plugins: [ - new MiniCssExtractPlugin(), - new MonacoWebpackPlugin({ - languages: [ - 'cpp', 'csharp', 'dart', 'go', 'java', 'javascript', 'json', 'kotlin', 'ruby' , 'typescript', 'html', 'xml', 'php', 'python', 'shell', 'swift', 'graphql', 'restructuredtext' - ] - }), - new webpack.ProvidePlugin({ - Buffer: ["buffer", "Buffer"], - process: "process/browser", - }), - ], - }; + return { + ...commonConfig(webpackEnv), + entry: "./src/fetch-client-ui/index.tsx", + output: { + path: path.resolve(__dirname, "dist"), + filename: "fetch-client-ui.js" + }, + plugins: [ + new MiniCssExtractPlugin(), + new MonacoWebpackPlugin({ + languages: [ + 'cpp', 'csharp', 'dart', 'go', 'java', 'javascript', 'json', 'kotlin', 'ruby', 'typescript', 'html', 'xml', 'php', 'python', 'shell', 'swift', 'graphql', 'restructuredtext' + ] + }), + new webpack.ProvidePlugin({ + Buffer: ["buffer", "Buffer"], + process: "process/browser", + }), + ], + }; } -module.exports = [extensionConfig, fetchClientUIConfig]; \ No newline at end of file +module.exports = [extensionConfig, fetchClientUIConfig];