Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
[Feat: GraphQL sidebar] GraphQL History (#1528)
Osheen Sachdev0b00842c5011
diff --git a/components/history/__tests__/GraphqlCard.spec.js b/components/history/__tests__/GraphqlCard.spec.jsnew file mode 100644index 000000000..347ab716b--- /dev/null+++ b/components/history/__tests__/GraphqlCard.spec.js@@ -0,0 +1,109 @@+import GraphqlCard from "../graphql/Card"+import { mount } from "@vue/test-utils"++const factory = (props) => {+ return mount(GraphqlCard, {+ propsData: props,+ stubs: {+ "v-popover": {+ template: "<div><slot /><slot name='popover' :is-open=true /></div>",+ },+ },+ mocks: {+ $t: (text) => text,+ },+ directives: {+ tooltip() {+ /* stub */+ },+ closePopover() {+ /* stub */+ },+ },+ })+}++const url = "https://dummydata.com"+const query = `query getUser($uid: String!) {+ user(uid: $uid) {+ name+ }+}`++describe("GraphqlCard", () => {+ test("Mounts properly if props are given", () => {+ const wrapper = factory({+ entry: {+ type: "graphql",+ url: url,+ query: query,+ star: false,+ },+ })+ expect(wrapper).toBeTruthy()+ })++ test("toggle-star emitted on clicking on star button", async () => {+ const wrapper = factory({+ entry: {+ type: "graphql",+ url: url,+ query: query,+ star: true,+ },+ })++ wrapper.find("button[data-testid='star_button']").trigger("click")+ expect(wrapper.emitted("toggle-star")).toBeTruthy()+ })++ test("query expands on clicking the show more button", async () => {+ const wrapper = factory({+ entry: {+ type: "graphql",+ url: url,+ query: query,+ star: true,+ },+ })+ expect(wrapper.vm.query).toStrictEqual([+ `query getUser($uid: String!) {`,+ ` user(uid: $uid) {`,+ `...`,+ ])+ await wrapper.find("button[data-testid='query_expand']").trigger("click")+ expect(wrapper.vm.query).toStrictEqual([+ `query getUser($uid: String!) {`,+ ` user(uid: $uid) {`,+ ` name`,+ ` }`,+ `}`,+ ])+ })++ test("use-entry emit on clicking the restore button", async () => {+ const wrapper = factory({+ entry: {+ type: "graphql",+ url: url,+ query: query,+ star: true,+ },+ })+ await wrapper.find("button[data-testid='restore_history_entry']").trigger("click")+ expect(wrapper.emitted("use-entry")).toBeTruthy()+ })++ test("delete-entry emit on clicking the delete button", async () => {+ const wrapper = factory({+ entry: {+ type: "graphql",+ url: url,+ query: query,+ star: true,+ },+ })+ await wrapper.find("button[data-testid=delete_history_entry]").trigger("click")+ expect(wrapper.emitted("delete-entry")).toBeTruthy()+ })+})diff --git a/components/history/__tests__/History.spec.js b/components/history/__tests__/History.spec.jsnew file mode 100644index 000000000..43d2b57a0--- /dev/null+++ b/components/history/__tests__/History.spec.js@@ -0,0 +1,285 @@+import History from "../"+import { fb } from "~/helpers/fb"+import { shallowMount } from "@vue/test-utils"+import HistoryRestCard from "../rest/Card"++const restHistory = [+ {+ id: "0",+ type: "rest",+ },+ {+ id: "1",+ type: "rest",+ },+ {+ id: "2",+ type: "rest",+ },+]++const graphqlHistory = [+ {+ id: "0",+ type: "graphql",+ },+ {+ id: "1",+ type: "graphql",+ },+ {+ id: "2",+ type: "graphql",+ },+]++var localStorageMock = (function () {+ var store = {+ history: JSON.stringify(restHistory),+ graphqlHistory: JSON.stringify(graphqlHistory),+ }+ return {+ getItem: function (key) {+ return store[key]+ },+ setItem: jest.fn(),+ clear: jest.fn(),+ removeItem: jest.fn(),+ }+})()+Object.defineProperty(window, "localStorage", { value: localStorageMock })++jest.mock("~/helpers/fb", () => ({+ __esModule: true,++ fb: {+ currentUser: null,+ currentHistory: restHistory,+ currentGraphqlHistory: graphqlHistory,+ clearHistory: jest.fn(),+ clearGraphqlHistory: jest.fn(),+ deleteHistory: jest.fn(),+ deleteGraphqlHistory: jest.fn(),+ },+}))++const factory = (props) => {+ return shallowMount(History, {+ propsData: props,+ stubs: {+ "v-popover": {+ template: "<div><slot /><slot name='popover' :is-open=true /></div>",+ },+ HistoryRestCard: {+ template: "<div data-testid='rest_card' />",+ },+ HistoryGraphqlCard: {+ template: "<div data-testid='graphql_card' />",+ },+ AppSection: {+ template: "<div><slot /></div>",+ },+ },+ mocks: {+ $t: (text) => text,+ $toast: {+ error() {},+ },+ },+ directives: {+ tooltip() {+ /* stub */+ },+ closePopover() {+ /* stub */+ },+ },+ })+}++beforeEach(() => {+ fb.clearHistory.mockClear()+ fb.clearGraphqlHistory.mockClear()+ fb.deleteHistory.mockClear()+ fb.deleteGraphqlHistory.mockClear()+ window.localStorage.setItem.mockClear()+})++describe("Mount History", () => {+ test("Mounts rest history without login", async () => {+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper).toBeTruthy()+ })+ test("Mounts rest history with login", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper).toBeTruthy()+ })++ test("Mounts graphql history without login", async () => {+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper).toBeTruthy()+ })+ test("Mounts graphql history with login", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper).toBeTruthy()+ })+})++describe("Clear History", () => {+ test("Clear rest history without login", async () => {+ fb.currentUser = null+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper.vm.filteredHistory).toStrictEqual(restHistory)+ await wrapper.find("button[data-testid='clear_history']").trigger("click")+ await wrapper.find("button[data-testid='confirm_clear_history']").trigger("click")+ expect(fb.clearHistory).not.toHaveBeenCalled()+ expect(window.localStorage.setItem).toHaveBeenCalledWith("history", JSON.stringify([]))+ })+ test("Clear rest history with login", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper.vm.filteredHistory).toStrictEqual(restHistory)+ await wrapper.find("button[data-testid='clear_history']").trigger("click")+ await wrapper.find("button[data-testid='confirm_clear_history']").trigger("click")+ expect(fb.clearHistory).toHaveBeenCalledTimes(1)+ expect(window.localStorage.setItem).toHaveBeenCalledWith("history", JSON.stringify([]))+ })+ test("Dont confirm Clear rest history", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper.vm.filteredHistory).toStrictEqual(restHistory)+ await wrapper.find("button[data-testid='clear_history']").trigger("click")+ await wrapper.find("button[data-testid='reject_clear_history']").trigger("click")+ expect(fb.clearHistory).not.toHaveBeenCalled()+ expect(window.localStorage.setItem).not.toHaveBeenCalledWith("history", JSON.stringify([]))+ })++ test("Clear graphql history without login", async () => {+ fb.currentUser = null+ const wrapper = factory({+ page: "graphql",+ })+ expect(wrapper.vm.filteredHistory).toStrictEqual(graphqlHistory)+ await wrapper.find("button[data-testid='clear_history']").trigger("click")+ await wrapper.find("button[data-testid='confirm_clear_history']").trigger("click")+ expect(fb.clearGraphqlHistory).not.toHaveBeenCalled()+ expect(window.localStorage.setItem).toHaveBeenCalledWith("graphqlHistory", JSON.stringify([]))+ })+ test("Clear graphql history with login", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "graphql",+ })+ expect(wrapper.vm.filteredHistory).toStrictEqual(graphqlHistory)+ await wrapper.find("button[data-testid='clear_history']").trigger("click")+ await wrapper.find("button[data-testid='confirm_clear_history']").trigger("click")+ expect(fb.clearGraphqlHistory).toHaveBeenCalledTimes(1)+ expect(window.localStorage.setItem).toHaveBeenCalledWith("graphqlHistory", JSON.stringify([]))+ })+ test("Dont confirm Clear graphql history", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "graphql",+ })+ expect(wrapper.vm.filteredHistory).toStrictEqual(graphqlHistory)+ await wrapper.find("button[data-testid='clear_history']").trigger("click")+ await wrapper.find("button[data-testid='reject_clear_history']").trigger("click")+ expect(window.localStorage.setItem).not.toHaveBeenCalledWith(+ "graphqlHistory",+ JSON.stringify([])+ )+ })+})++describe("Use History", () => {+ test("use rest history", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper.findAll("div[data-testid='rest_card']").length).toEqual(restHistory.length)+ var index = restHistory.length - 1+ wrapper.findAll("div[data-testid='rest_card']").at(index).vm.$emit("use-entry")+ expect(wrapper.emitted("useHistory")).toBeTruthy()+ expect(wrapper.emitted("useHistory")[0]).toStrictEqual([restHistory[index]])+ })++ test("use graphql history", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "graphql",+ })+ expect(wrapper.findAll("div[data-testid='graphql_card']").length).toEqual(graphqlHistory.length)+ var index = restHistory.length - 1+ wrapper.findAll("div[data-testid='graphql_card']").at(index).vm.$emit("use-entry")+ expect(wrapper.emitted("useHistory")).toBeTruthy()+ expect(wrapper.emitted("useHistory")[0]).toStrictEqual([graphqlHistory[index]])+ })+})++describe("Delete History", () => {+ test("delete rest history with login", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper.findAll("div[data-testid='rest_card']").length).toEqual(restHistory.length)+ var index = 1+ wrapper.findAll("div[data-testid='rest_card']").at(index).vm.$emit("delete-entry")+ expect(fb.deleteHistory).toBeCalledWith(restHistory[index])+ })++ test("delete rest history without login", async () => {+ fb.currentUser = null+ const wrapper = factory({+ page: "rest",+ })+ expect(wrapper.findAll("div[data-testid='rest_card']").length).toEqual(restHistory.length)+ var index = 1+ wrapper.findAll("div[data-testid='rest_card']").at(index).vm.$emit("delete-entry")+ expect(window.localStorage.setItem).toBeCalledWith(+ "history",+ JSON.stringify(restHistory.filter((entry) => entry.id != index))+ )+ })+ test("delete graphql history with login", async () => {+ fb.currentUser = "user"+ const wrapper = factory({+ page: "graphql",+ })+ expect(wrapper.findAll("div[data-testid='graphql_card']").length).toEqual(graphqlHistory.length)+ var index = 1+ wrapper.findAll("div[data-testid='graphql_card']").at(index).vm.$emit("delete-entry")+ expect(fb.deleteGraphqlHistory).toBeCalledWith(graphqlHistory[index])+ })++ test("delete graphql history without login", async () => {+ fb.currentUser = null+ const wrapper = factory({+ page: "graphql",+ })+ expect(wrapper.findAll("div[data-testid='graphql_card']").length).toEqual(graphqlHistory.length)+ var index = 1+ wrapper.findAll("div[data-testid='graphql_card']").at(index).vm.$emit("delete-entry")+ expect(window.localStorage.setItem).toBeCalledWith(+ "graphqlHistory",+ JSON.stringify(graphqlHistory.filter((entry) => entry.id != index))+ )+ })+})diff --git a/components/history/__tests__/RestCard.spec.js b/components/history/__tests__/RestCard.spec.jsnew file mode 100644index 000000000..97e1f0fdc--- /dev/null+++ b/components/history/__tests__/RestCard.spec.js@@ -0,0 +1,58 @@+import RestCard from "../rest/Card"+import { mount } from "@vue/test-utils"++const factory = (props) => {+ return mount(RestCard, {+ propsData: props,+ stubs: {+ "v-popover": {+ template: "<div><slot /><slot name='popover' :is-open=true /></div>",+ },+ },+ mocks: {+ $t: (text) => text,+ },+ directives: {+ tooltip() {+ /* stub */+ },+ closePopover() {+ /* stub */+ },+ },+ })+}++const url = "https://dummydata.com/get"+const entry = {+ type: "rest",+ url: url,+ method: "GET",+ status: 200,+ star: false,+}+describe("RestCard", () => {+ test("Mounts properly if props are given", () => {+ const wrapper = factory({ entry })+ expect(wrapper).toBeTruthy()+ })++ test("toggle-star emitted on clicking on star button", async () => {+ const wrapper = factory({ entry })++ wrapper.find("button[data-testid='star_button']").trigger("click")+ expect(wrapper.emitted("toggle-star")).toBeTruthy()+ })++ test("use-entry emit on clicking the restore button", async () => {+ const wrapper = factory({ entry })+ await wrapper.find("button[data-testid='restore_history_entry']").trigger("click")+ expect(wrapper.emitted("use-entry")).toBeTruthy()+ })++ test("delete-entry emit on clicking the delete button", async () => {+ const wrapper = factory({ entry })+ await wrapper.find("button[data-testid=delete_history_entry]").trigger("click")+ expect(wrapper.emitted("delete-entry")).toBeTruthy()+ })+})diff --git a/components/history/graphql/Card.vue b/components/history/graphql/Card.vuenew file mode 100644index 000000000..7a5302c71--- /dev/null+++ b/components/history/graphql/Card.vue@@ -0,0 +1,147 @@+<template>+ <div>+ <div class="show-on-large-screen">+ <li>+ <input+ data-testid="'url'"+ :aria-label="$t('url')"+ type="text"+ readonly+ :value="entry.url"+ :placeholder="$t('empty_req_name')"+ class="bg-transparent"+ />+ </li>+ <button+ data-testid="star_button"+ class="icon"+ :class="{ stared: entry.star }"+ @click="$emit('toggle-star')"+ v-tooltip="{+ content: !entry.star ? $t('add_star') : $t('remove_star'),+ }"+ >+ <i class="material-icons">+ {{ entry.star ? "star" : "star_border" }}+ </i>+ </button>+ <button+ data-testid="query_expand"+ class="icon"+ @click="expand = !expand"+ v-tooltip="{+ content: expand ? $t('hide_more') : $t('show_more'),+ }"+ >+ <i class="material-icons">+ {{ expand ? "unfold_less" : "unfold_more" }}+ </i>+ </button>+ <v-popover>+ <button data-testid="options" class="tooltip-target icon" v-tooltip="$t('options')">+ <i class="material-icons">more_vert</i>+ </button>+ <template slot="popover">+ <div>+ <button+ data-testid="restore_history_entry"+ class="icon"+ @click="$emit('use-entry')"+ :aria-label="$t('restore')"+ v-close-popover+ >+ <i class="material-icons">restore</i>+ <span>{{ $t("restore") }}</span>+ </button>+ </div>+ <div>+ <button+ data-testid="delete_history_entry"+ class="icon"+ @click="$emit('delete-entry')"+ :aria-label="$t('delete')"+ v-close-popover+ >+ <i class="material-icons">delete</i>+ <span>{{ $t("delete") }}</span>+ </button>+ </div>+ </template>+ </v-popover>+ </div>+ <div class="show-on-large-screen">+ <li data-testid="'query'">+ <input+ v-for="(line, index) in query"+ :key="`line-${index}`"+ :aria-label="$t('query')"+ type="text"+ readonly+ :value="`${line}`"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ </div>+ <transition name="fade">+ <div v-if="showMore" class="show-on-large-screen">+ <li>+ <input+ :aria-label="$t('time')"+ type="text"+ readonly+ :value="entry.time"+ v-tooltip="entry.date"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ <li>+ <input+ :aria-label="$t('duration')"+ type="text"+ readonly+ :value="entry.duration"+ :placeholder="$t('no_duration')"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ <li>+ <input+ :aria-label="$t('prerequest_script')"+ type="text"+ readonly+ :value="entry.preRequestScript"+ :placeholder="$t('no_prerequest_script')"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ </div>+ </transition>+ </div>+</template>++<style scoped lang="scss">+.stared {+ color: #f8e81c !important;+}+</style>++<script>+export default {+ props: {+ entry: Object,+ showMore: Boolean,+ },+ data() {+ return {+ expand: false,+ }+ },+ computed: {+ query() {+ return this.expand+ ? this.entry.query.split("\n")+ : this.entry.query.split("\n").slice(0, 2).concat(["..."])+ },+ },+}+</script>diff --git a/components/http/History.vue b/components/history/index.vuesimilarity index 61%rename from components/http/History.vuerename to components/history/index.vueindex ee87ab1a8..9a77e5954 100644--- a/components/http/History.vue+++ b/components/history/index.vue@@ -13,127 +13,24 @@class="divide-y virtual-list divide-dashed divide-brdColor":class="{ filled: filteredHistory.length }">- <ul v-for="(entry, index) in filteredHistory" :key="index">- <div class="show-on-large-screen">- <span- class="p-2 m-2"- :class="findEntryStatus(entry).className"- :style="{ '--status-code': entry.status }"- >- {{ `${entry.method} \xA0 • \xA0 ${entry.status}` }}- </span>- <li>- <input- :aria-label="$t('token_req_name')"- type="text"- readonly- :value="entry.name"- :placeholder="$t('empty_req_name')"- class="bg-transparent"- />- </li>- <button- class="icon"- :class="{ stared: entry.star }"- @click="toggleStar(entry)"- v-tooltip="{- content: !entry.star ? $t('add_star') : $t('remove_star'),- }"- >- <i class="material-icons">- {{ entry.star ? "star" : "star_border" }}- </i>- </button>- <!-- <li>- <button- class="icon"- v-tooltip="{- content: !entry.usesScripts- ? 'No pre-request script'- : 'Used pre-request script'- }"- >- <i class="material-icons">- {{ !entry.usesScripts ? "http" : "code" }}- </i>- </button>- </li> -->- <v-popover>- <button class="tooltip-target icon" v-tooltip="$t('options')">- <i class="material-icons">more_vert</i>- </button>- <template slot="popover">- <div>- <button- class="icon"- @click="useHistory(entry)"- :aria-label="$t('edit')"- v-close-popover- >- <i class="material-icons">restore</i>- <span>{{ $t("restore") }}</span>- </button>- </div>- <div>- <button- class="icon"- @click="deleteHistory(entry)"- :aria-label="$t('delete')"- v-close-popover- >- <i class="material-icons">delete</i>- <span>{{ $t("delete") }}</span>- </button>- </div>- </template>- </v-popover>- </div>- <div class="show-on-large-screen">- <li>- <input- :aria-label="$t('url')"- type="text"- readonly- :value="`${entry.url}${entry.path}`"- :placeholder="$t('no_url')"- class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"- />- </li>- </div>- <transition name="fade">- <div v-if="showMore" class="show-on-large-screen">- <li>- <input- :aria-label="$t('time')"- type="text"- readonly- :value="entry.time"- v-tooltip="entry.date"- class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"- />- </li>- <li>- <input- :aria-label="$t('duration')"- type="text"- readonly- :value="entry.duration"- :placeholder="$t('no_duration')"- class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"- />- </li>- <li>- <input- :aria-label="$t('prerequest_script')"- type="text"- readonly- :value="entry.preRequestScript"- :placeholder="$t('no_prerequest_script')"- class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"- />- </li>- </div>- </transition>+ <ul v-for="(entry, index) in filteredHistory" :key="`entry-${index}`">+ <HistoryRestCard+ v-if="page == 'rest'"+ :entry="entry"+ :id="index"+ :showMore="showMore"+ @toggle-star="toggleStar(entry)"+ @delete-entry="deleteHistory(entry)"+ @use-entry="useHistory(entry)"+ />+ <HistoryGraphqlCard+ v-if="page == 'graphql'"+ :entry="entry"+ :showMore="showMore"+ @toggle-star="toggleStar(entry)"+ @delete-entry="deleteHistory(entry)"+ @use-entry="useHistory(entry)"+ /></ul></div><p :class="{ hidden: filteredHistory.length != 0 || history.length === 0 }" class="info">@@ -144,12 +41,17 @@</p><div v-if="history.length !== 0" class="rounded-b-lg bg-bgDarkColor"><div class="row-wrapper" v-if="!isClearingHistory">- <button class="icon" :disabled="history.length === 0" @click="enableHistoryClearing">+ <button+ data-testid="clear_history"+ class="icon"+ :disabled="history.length === 0"+ @click="enableHistoryClearing"+ ><i class="material-icons">clear_all</i><span>{{ $t("clear_all") }}</span></button><v-popover>- <button class="tooltip-target icon" v-tooltip="$t('sort')">+ <button v-if="this.page == 'rest'" class="tooltip-target icon" v-tooltip="$t('sort')"><i class="material-icons">sort</i></button><template slot="popover">@@ -203,10 +105,20 @@<div class="row-wrapper" v-else><p class="info"><i class="material-icons">help_outline</i> {{ $t("are_you_sure") }}</p><div>- <button class="icon" @click="clearHistory" v-tooltip="$t('yes')">+ <button+ data-testid="confirm_clear_history"+ class="icon"+ @click="clearHistory"+ v-tooltip="$t('yes')"+ ><i class="material-icons">done</i></button>- <button class="icon" @click="disableHistoryClearing" v-tooltip="$t('no')">+ <button+ data-testid="reject_clear_history"+ class="icon"+ @click="disableHistoryClearing"+ v-tooltip="$t('no')"+ ><i class="material-icons">close</i></button></div>@@ -218,36 +130,26 @@<style scoped lang="scss">.virtual-list {max-height: calc(100vh - 270px);-[readonly] {cursor: default;}}-.fade-enter-active,.fade-leave-active {transition: all 0.2s;}-.fade-enter,.fade-leave-to {opacity: 0;}--.stared {- color: #f8e81c !important;-}-ul,ol {flex-direction: column;}-@media (max-width: 720px) {.virtual-list.filled {min-height: 320px;}-.labels {display: none;}@@ -255,19 +157,23 @@ ol {</style><script>-import findStatusGroup from "~/helpers/findStatusGroup"import { fb } from "~/helpers/fb"const updateOnLocalStorage = (propertyName, property) =>window.localStorage.setItem(propertyName, JSON.stringify(property))export default {+ props: {+ page: String,+ },data() {return {history:fb.currentUser !== null? fb.currentHistory- : JSON.parse(window.localStorage.getItem("history")) || [],+ : JSON.parse(+ window.localStorage.getItem(this.page == "rest" ? "history" : "graphqlHistory")+ ) || [],filterText: "",showFilter: false,isClearingHistory: false,@@ -283,8 +189,12 @@ export default {filteredHistory() {this.history =fb.currentUser !== null- ? fb.currentHistory- : JSON.parse(window.localStorage.getItem("history")) || []+ ? this.page == "rest"+ ? fb.currentHistory+ : fb.currentGraphqlHistory+ : JSON.parse(+ window.localStorage.getItem(this.page == "rest" ? "history" : "graphqlHistory")+ ) || []return this.history.filter((entry) => {const filterText = this.filterText.toLowerCase()return Object.keys(entry).some((key) => {@@ -298,12 +208,12 @@ export default {methods: {async clearHistory() {if (fb.currentUser !== null) {- await fb.clearHistory()+ this.page == "rest" ? await fb.clearHistory() : await fb.clearGraphqlHistory()}this.history = []this.filterText = ""this.disableHistoryClearing()- updateOnLocalStorage("history", this.history)+ updateOnLocalStorage(this.page == "rest" ? "history" : "graphqlHistory", this.history)this.$toast.error(this.$t("history_deleted"), {icon: "delete",})@@ -311,30 +221,25 @@ export default {useHistory(entry) {this.$emit("useHistory", entry)},- findEntryStatus({ status }) {- const foundStatusGroup = findStatusGroup(status)- return (- foundStatusGroup || {- className: "",- }- )- },async deleteHistory(entry) {- if (fb.currentUser !== null) {- await fb.deleteHistory(entry)- }- this.history.splice(this.history.indexOf(entry), 1)if (this.history.length === 0) {this.filterText = ""}- updateOnLocalStorage("history", this.history)+ if (fb.currentUser !== null) {+ await (this.page == "rest" ? fb.deleteHistory(entry) : fb.deleteGraphqlHistory(entry))+ this.history = fb.currentHistory+ updateOnLocalStorage(this.page == "rest" ? "history" : "graphqlHistory", this.history)+ } else {+ this.history.splice(this.history.indexOf(entry), 1)+ updateOnLocalStorage(this.page == "rest" ? "history" : "graphqlHistory", this.history)+ }this.$toast.error(this.$t("deleted"), {icon: "delete",})},addEntry(entry) {this.history.push(entry)- updateOnLocalStorage("history", this.history)+ updateOnLocalStorage(this.page == "rest" ? "history" : "graphqlHistory", this.history)},enableHistoryClearing() {if (!this.history || !this.history.length) return@@ -409,10 +314,12 @@ export default {},async toggleStar(entry) {if (fb.currentUser !== null) {- await fb.toggleStar(entry, !entry.star)+ this.page == "rest"+ ? await fb.toggleStar(entry, !entry.star)+ : await fb.toggleGraphqlHistoryStar(entry, !entry.star)}entry.star = !entry.star- updateOnLocalStorage("history", this.history)+ updateOnLocalStorage(this.page == "rest" ? "history" : "graphqlHistory", this.history)},},}diff --git a/components/history/rest/Card.vue b/components/history/rest/Card.vuenew file mode 100644index 000000000..99461b651--- /dev/null+++ b/components/history/rest/Card.vue@@ -0,0 +1,160 @@+<template>+ <div>+ <div class="show-on-large-screen">+ <span+ class="p-2 m-2"+ :class="entryStatus.className"+ :style="{ '--status-code': entry.status }"+ >+ {{ `${entry.method} \xA0 • \xA0 ${entry.status}` }}+ </span>+ <li>+ <input+ :aria-label="$t('token_req_name')"+ type="text"+ readonly+ :value="entry.name"+ :placeholder="$t('empty_req_name')"+ class="bg-transparent"+ />+ </li>+ <button+ data-testid="star_button"+ class="icon"+ :class="{ stared: entry.star }"+ @click="$emit('toggle-star')"+ v-tooltip="{+ content: !entry.star ? $t('add_star') : $t('remove_star'),+ }"+ >+ <i class="material-icons">+ {{ entry.star ? "star" : "star_border" }}+ </i>+ </button>+ <!-- <li>+ <button+ class="icon"+ v-tooltip="{+ content: !entry.usesScripts+ ? 'No pre-request script'+ : 'Used pre-request script'+ }"+ >+ <i class="material-icons">+ {{ !entry.usesScripts ? "http" : "code" }}+ </i>+ </button>+ </li> -->+ <v-popover>+ <button class="tooltip-target icon" v-tooltip="$t('options')">+ <i class="material-icons">more_vert</i>+ </button>+ <template slot="popover">+ <div>+ <button+ data-testid="restore_history_entry"+ class="icon"+ @click="$emit('use-entry')"+ :aria-label="$t('edit')"+ v-close-popover+ >+ <i class="material-icons">restore</i>+ <span>{{ $t("restore") }}</span>+ </button>+ </div>+ <div>+ <button+ data-testid="delete_history_entry"+ class="icon"+ @click="$emit('delete-entry')"+ :aria-label="$t('delete')"+ v-close-popover+ >+ <i class="material-icons">delete</i>+ <span>{{ $t("delete") }}</span>+ </button>+ </div>+ </template>+ </v-popover>+ </div>+ <div class="show-on-large-screen">+ <li>+ <input+ :aria-label="$t('url')"+ type="text"+ readonly+ :value="`${entry.url}${entry.path}`"+ :placeholder="$t('no_url')"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ </div>+ <transition name="fade">+ <div v-if="showMore" class="show-on-large-screen">+ <li>+ <input+ :aria-label="$t('time')"+ type="text"+ readonly+ :value="entry.time"+ v-tooltip="entry.date"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ <li>+ <input+ :aria-label="$t('duration')"+ type="text"+ readonly+ :value="entry.duration"+ :placeholder="$t('no_duration')"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ <li>+ <input+ :aria-label="$t('prerequest_script')"+ type="text"+ readonly+ :value="entry.preRequestScript"+ :placeholder="$t('no_prerequest_script')"+ class="pt-0 mt-0 text-sm bg-transparent text-fgLightColor"+ />+ </li>+ </div>+ </transition>+ </div>+</template>++<style scoped lang="scss">+.stared {+ color: #f8e81c !important;+}+</style>++<script>+import findStatusGroup from "~/helpers/findStatusGroup"++export default {+ props: {+ entry: Object,+ showMore: Boolean,+ },+ data() {+ return {+ expand: false,+ }+ },+ computed: {+ entryStatus() {+ const foundStatusGroup = findStatusGroup(this.entry.status)+ console.log(foundStatusGroup)+ return (+ foundStatusGroup || {+ className: "",+ }+ )+ },+ },+}+</script>diff --git a/helpers/fb.js b/helpers/fb.jsindex 6fb20a65e..443470162 100644--- a/helpers/fb.js+++ b/helpers/fb.js@@ -30,6 +30,7 @@ export class FirebaseInstance {this.currentFeeds = []this.currentSettings = []this.currentHistory = []+ this.currentGraphqlHistory = []this.currentCollections = []this.currentEnvironments = []@@ -97,6 +98,19 @@ export class FirebaseInstance {this.currentHistory = history})+ this.usersCollection+ .doc(this.currentUser.uid)+ .collection("graphqlHistory")+ .onSnapshot((historyRef) => {+ const history = []+ historyRef.forEach((doc) => {+ const entry = doc.data()+ entry.id = doc.id+ history.push(entry)+ })+ this.currentGraphqlHistory = history+ })+this.usersCollection.doc(this.currentUser.uid).collection("collections")@@ -215,6 +229,17 @@ export class FirebaseInstance {}}+ async writeGraphqlHistory(entry) {+ const hs = entry++ try {+ await this.usersCollection.doc(this.currentUser.uid).collection("graphqlHistory").add(hs)+ } catch (e) {+ console.error("error inserting", hs, e)+ throw e+ }+ }+async deleteHistory(entry) {try {await this.usersCollection@@ -228,6 +253,19 @@ export class FirebaseInstance {}}+ async deleteGraphqlHistory(entry) {+ try {+ await this.usersCollection+ .doc(this.currentUser.uid)+ .collection("graphqlHistory")+ .doc(entry.id)+ .delete()+ } catch (e) {+ console.error("error deleting", entry, e)+ throw e+ }+ }+async clearHistory() {const { docs } = await this.usersCollection.doc(this.currentUser.uid)@@ -237,6 +275,15 @@ export class FirebaseInstance {await Promise.all(docs.map((e) => this.deleteHistory(e)))}+ async clearGraphqlHistory() {+ const { docs } = await this.usersCollection+ .doc(this.currentUser.uid)+ .collection("graphqlHistory")+ .get()++ await Promise.all(docs.map((e) => this.deleteGraphqlHistory(e)))+ }+async toggleStar(entry, value) {try {await this.usersCollection@@ -251,6 +298,20 @@ export class FirebaseInstance {}}+ async toggleGraphqlHistoryStar(entry, value) {+ try {+ await this.usersCollection+ .doc(this.currentUser.uid)+ .collection("graphqlHistory")+ .doc(entry.id)+ .update({ star: value })+ } catch (e) {+ console.error("error deleting", entry, e)++ throw e+ }+ }+async writeCollections(collection) {const cl = {updatedOn: new Date(),diff --git a/package-lock.json b/package-lock.jsonindex d768f6934..537b916db 100644--- a/package-lock.json+++ b/package-lock.json@@ -10947,6 +10947,12 @@"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz","integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA=="},+ "nan": {+ "version": "2.14.2",+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.2.tgz",+ "integrity": "sha512-M2ufzIiINKCuDfBSAUr1vWQ+vuVcA9kqx8JJUsbQi6yf1uGRyb7HfpdfUr5qLXf3B/t8dPvcjhKMmlfnP47EzQ==",+ "optional": true+ },"nanoid": {"version": "3.1.20","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.20.tgz",@@ -16734,7 +16740,8 @@"integrity": "sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw==","optional": true,"requires": {- "bindings": "^1.5.0"+ "bindings": "^1.5.0",+ "nan": "^2.12.1"}},"glob-parent": {diff --git a/pages/graphql.vue b/pages/graphql.vueindex 5720a4455..8f83da682 100644--- a/pages/graphql.vue+++ b/pages/graphql.vue@@ -318,79 +318,102 @@</div><aside class="sticky-inner inner-right lg:max-w-md">- <AppSection class="purple" :label="$t('docs')" ref="docs" no-legend>- <section class="flex-col">- <input- type="text"- :placeholder="$t('search')"- v-model="graphqlFieldsFilterText"- class="rounded-t-lg"- />- <SmartTabs ref="gqlTabs" styles="m-4">- <div class="gqlTabs">- <SmartTab- v-if="queryFields.length > 0"- :id="'queries'"- :label="$t('queries')"- :selected="true"- >- <div v-for="field in filteredQueryFields" :key="field.name">- <GraphqlField :gqlField="field" :jumpTypeCallback="handleJumpToType" />+ <SmartTabs>+ <SmartTab :id="'docs'" :label="`Docs`" :selected="true">+ <AppSection class="purple" :label="$t('docs')" ref="docs" no-legend>+ <section class="flex-col">+ <input+ type="text"+ :placeholder="$t('search')"+ v-model="graphqlFieldsFilterText"+ class="rounded-t-lg"+ />+ <SmartTabs ref="gqlTabs" styles="m-4">+ <div class="gqlTabs">+ <SmartTab+ v-if="queryFields.length > 0"+ :id="'queries'"+ :label="$t('queries')"+ :selected="true"+ >+ <div v-for="field in filteredQueryFields" :key="field.name">+ <GraphqlField :gqlField="field" :jumpTypeCallback="handleJumpToType" />+ </div>+ </SmartTab>++ <SmartTab+ v-if="mutationFields.length > 0"+ :id="'mutations'"+ :label="$t('mutations')"+ >+ <div v-for="field in filteredMutationFields" :key="field.name">+ <GraphqlField :gqlField="field" :jumpTypeCallback="handleJumpToType" />+ </div>+ </SmartTab>++ <SmartTab+ v-if="subscriptionFields.length > 0"+ :id="'subscriptions'"+ :label="$t('subscriptions')"+ >+ <div v-for="field in filteredSubscriptionFields" :key="field.name">+ <GraphqlField :gqlField="field" :jumpTypeCallback="handleJumpToType" />+ </div>+ </SmartTab>++ <SmartTab+ v-if="graphqlTypes.length > 0"+ :id="'types'"+ :label="$t('types')"+ ref="typesTab"+ >+ <div v-for="type in filteredGraphqlTypes" :key="type.name">+ <GraphqlType+ :gqlType="type"+ :gqlTypes="graphqlTypes"+ :isHighlighted="isGqlTypeHighlighted({ gqlType: type })"+ :highlightedFields="getGqlTypeHighlightedFields({ gqlType: type })"+ :jumpTypeCallback="handleJumpToType"+ />+ </div>+ </SmartTab></div>- </SmartTab>+ </SmartTabs>+ </section>+ <p+ v-if="+ queryFields.length === 0 &&+ mutationFields.length === 0 &&+ subscriptionFields.length === 0 &&+ graphqlTypes.length === 0+ "+ class="info"+ >+ {{ $t("send_request_first") }}+ </p>+ </AppSection>+ </SmartTab>++ <SmartTab :id="'history'" :label="$t('history')">+ <History+ @useHistory="handleUseHistory"+ ref="graphqlHistoryComponent"+ :page="'graphql'"+ />+ </SmartTab>- <SmartTab- v-if="mutationFields.length > 0"- :id="'mutations'"- :label="$t('mutations')"- >- <div v-for="field in filteredMutationFields" :key="field.name">- <GraphqlField :gqlField="field" :jumpTypeCallback="handleJumpToType" />- </div>- </SmartTab>+ <!-- <SmartTab :id="'collections'" :label="$t('collections')">+ <Collections />+ </SmartTab>- <SmartTab- v-if="subscriptionFields.length > 0"- :id="'subscriptions'"- :label="$t('subscriptions')"- >- <div v-for="field in filteredSubscriptionFields" :key="field.name">- <GraphqlField :gqlField="field" :jumpTypeCallback="handleJumpToType" />- </div>- </SmartTab>+ <SmartTab :id="'env'" :label="$t('environments')">+ <Environments @use-environment="useSelectedEnvironment($event)" />+ </SmartTab>- <SmartTab- v-if="graphqlTypes.length > 0"- :id="'types'"- :label="$t('types')"- ref="typesTab"- >- <div v-for="type in filteredGraphqlTypes" :key="type.name">- <GraphqlType- :gqlType="type"- :gqlTypes="graphqlTypes"- :isHighlighted="isGqlTypeHighlighted({ gqlType: type })"- :highlightedFields="getGqlTypeHighlightedFields({ gqlType: type })"- :jumpTypeCallback="handleJumpToType"- />- </div>- </SmartTab>- </div>- </SmartTabs>- </section>-- <p- v-if="- queryFields.length === 0 &&- mutationFields.length === 0 &&- subscriptionFields.length === 0 &&- graphqlTypes.length === 0- "- class="info"- >- {{ $t("send_request_first") }}- </p>- </AppSection>+ <SmartTab :id="'notes'" :label="$t('notes')">+ <HttpNotes />+ </SmartTab> -->+ </SmartTabs></aside></div></div>@@ -412,6 +435,7 @@ import * as gql from "graphql"import { commonHeaders } from "~/helpers/headers"import { getPlatformSpecialKey } from "~/helpers/platformutils"import { sendNetworkRequest } from "~/helpers/network"+import { fb } from "~/helpers/fb"export default {data() {@@ -429,6 +453,7 @@ export default {graphqlFieldsFilterText: undefined,isPollingSchema: false,timeoutSubscription: null,+ activeSidebar: true,settings: {SCROLL_INTO_ENABLED:@@ -528,6 +553,17 @@ export default {next()},methods: {+ useSelectedEnvironment(event) {+ console.log("use selected environment")+ },+ handleUseHistory(entry) {+ this.url = entry.url+ this.headers = entry.headers+ this.gqlQueryString = entry.query+ this.response = entry.responseText+ this.variableString = entry.variables+ this.schema = ""+ },isGqlTypeHighlighted({ gqlType }) {if (!this.graphqlFieldsFilterText) return false@@ -683,7 +719,13 @@ export default {},data: JSON.stringify({ query: gqlQueryString, variables }),}-+ let entry = {+ url: this.url,+ query: gqlQueryString,+ variables: this.variableString,+ star: false,+ headers: this.headers,+ }const res = await sendNetworkRequest(reqOptions, this.$store)// HACK: Temporary trailing null character issue from the extension fix@@ -696,6 +738,20 @@ export default {this.$toast.info(this.$t("finished_in", { duration }), {icon: "done",})++ entry = {+ ...entry,+ response: this.response,+ date: new Date().toLocaleDateString(),+ time: new Date().toLocaleTimeString(),+ }++ this.$refs.graphqlHistoryComponent.addEntry(entry)+ if (fb.currentUser !== null && fb.currentSettings[2]) {+ if (fb.currentSettings[2].value) {+ fb.writeGraphqlHistory(entry)+ }+ }} catch (error) {this.response = `${error}. ${this.$t("check_console_details")}`this.$nuxt.$loading.finish()diff --git a/pages/index.vue b/pages/index.vueindex 361a3b46e..4d1c44996 100644--- a/pages/index.vue+++ b/pages/index.vue@@ -532,7 +532,7 @@<section><SmartTabs><SmartTab :id="'history'" :label="$t('history')" :selected="true">- <HttpHistory @useHistory="handleUseHistory" ref="historyComponent" />+ <History :page="'rest'" @useHistory="handleUseHistory" ref="historyComponent" /></SmartTab><SmartTab :id="'collections'" :label="$t('collections')">