RequestOptions.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <template>
  2. <div>
  3. <SmartTabs styles="sticky bg-primary top-upperPrimaryStickyFold z-10">
  4. <template #actions>
  5. <ButtonSecondary
  6. :label="`${t('request.run')}`"
  7. svg="play"
  8. class="rounded-none !text-accent"
  9. @click.native="runQuery()"
  10. />
  11. <ButtonSecondary
  12. ref="saveRequest"
  13. :label="`${t('request.save')}`"
  14. class="rounded-none"
  15. @click.native="saveRequest"
  16. />
  17. </template>
  18. <SmartTab :id="'query'" :label="`${t('tab.query')}`" :selected="true">
  19. <AppSection label="query">
  20. <div
  21. class="
  22. bg-primary
  23. border-dividerLight
  24. top-upperSecondaryStickyFold
  25. gqlRunQuery
  26. sticky
  27. z-10
  28. flex
  29. items-center
  30. justify-between
  31. flex-1
  32. pl-4
  33. border-b
  34. "
  35. >
  36. <label class="font-semibold text-secondaryLight">
  37. {{ t("request.query") }}
  38. </label>
  39. <div class="flex">
  40. <ButtonSecondary
  41. v-tippy="{ theme: 'tooltip' }"
  42. to="https://docs.hoppscotch.io/graphql/#queries"
  43. blank
  44. :title="t('app.wiki')"
  45. svg="help-circle"
  46. />
  47. <ButtonSecondary
  48. v-tippy="{ theme: 'tooltip' }"
  49. :title="t('action.prettify')"
  50. :svg="`${prettifyQueryIcon}`"
  51. @click.native="prettifyQuery"
  52. />
  53. <ButtonSecondary
  54. v-tippy="{ theme: 'tooltip' }"
  55. :title="t('action.copy')"
  56. :svg="`${copyQueryIcon}`"
  57. @click.native="copyQuery"
  58. />
  59. </div>
  60. </div>
  61. <div ref="queryEditor"></div>
  62. </AppSection>
  63. </SmartTab>
  64. <SmartTab :id="'variables'" :label="`${t('tab.variables')}`">
  65. <AppSection label="variables">
  66. <div
  67. class="
  68. bg-primary
  69. border-dividerLight
  70. top-upperSecondaryStickyFold
  71. sticky
  72. z-10
  73. flex
  74. items-center
  75. justify-between
  76. flex-1
  77. pl-4
  78. border-b
  79. "
  80. >
  81. <label class="font-semibold text-secondaryLight">
  82. {{ t("request.variables") }}
  83. </label>
  84. <div class="flex">
  85. <ButtonSecondary
  86. v-tippy="{ theme: 'tooltip' }"
  87. to="https://docs.hoppscotch.io/graphql/#queries"
  88. blank
  89. :title="t('app.wiki')"
  90. svg="help-circle"
  91. />
  92. <ButtonSecondary
  93. v-tippy="{ theme: 'tooltip' }"
  94. :title="t('action.copy')"
  95. :svg="`${copyVariablesIcon}`"
  96. @click.native="copyVariables"
  97. />
  98. </div>
  99. </div>
  100. <div ref="variableEditor"></div>
  101. </AppSection>
  102. </SmartTab>
  103. <SmartTab :id="'headers'" :label="`${t('tab.headers')}`">
  104. <AppSection label="headers">
  105. <div
  106. class="
  107. bg-primary
  108. border-dividerLight
  109. top-upperSecondaryStickyFold
  110. sticky
  111. z-10
  112. flex
  113. items-center
  114. justify-between
  115. flex-1
  116. pl-4
  117. border-b
  118. "
  119. >
  120. <label class="font-semibold text-secondaryLight">
  121. {{ t("tab.headers") }}
  122. </label>
  123. <div class="flex">
  124. <ButtonSecondary
  125. v-tippy="{ theme: 'tooltip' }"
  126. to="https://docs.hoppscotch.io/graphql/#headers"
  127. blank
  128. :title="t('app.wiki')"
  129. svg="help-circle"
  130. />
  131. <ButtonSecondary
  132. v-tippy="{ theme: 'tooltip' }"
  133. :title="t('action.clear_all')"
  134. svg="trash-2"
  135. @click.native="clearContent()"
  136. />
  137. <ButtonSecondary
  138. v-tippy="{ theme: 'tooltip' }"
  139. :title="t('state.bulk_mode')"
  140. svg="edit"
  141. :class="{ '!text-accent': bulkMode }"
  142. @click.native="bulkMode = !bulkMode"
  143. />
  144. <ButtonSecondary
  145. v-tippy="{ theme: 'tooltip' }"
  146. :title="t('add.new')"
  147. svg="plus"
  148. :disabled="bulkMode"
  149. @click.native="addRequestHeader"
  150. />
  151. </div>
  152. </div>
  153. <div v-if="bulkMode" ref="bulkEditor"></div>
  154. <div v-else>
  155. <div
  156. v-for="(header, index) in headers"
  157. :key="`header-${String(index)}`"
  158. class="
  159. divide-dividerLight
  160. border-dividerLight
  161. flex
  162. border-b
  163. divide-x
  164. "
  165. >
  166. <SmartAutoComplete
  167. :placeholder="`${t('count.header', { count: index + 1 })}`"
  168. :source="commonHeaders"
  169. :spellcheck="false"
  170. :value="header.key"
  171. autofocus
  172. styles="
  173. bg-transparent
  174. flex
  175. flex-1
  176. py-1
  177. px-4
  178. truncate
  179. "
  180. class="!flex flex-1"
  181. @input="
  182. updateRequestHeader(index, {
  183. key: $event,
  184. value: header.value,
  185. active: header.active,
  186. })
  187. "
  188. />
  189. <input
  190. class="flex flex-1 px-4 py-2 bg-transparent"
  191. :placeholder="`${t('count.value', { count: index + 1 })}`"
  192. :name="`value ${String(index)}`"
  193. :value="header.value"
  194. autofocus
  195. @change="
  196. updateRequestHeader(index, {
  197. key: header.key,
  198. value: $event.target.value,
  199. active: header.active,
  200. })
  201. "
  202. />
  203. <span>
  204. <ButtonSecondary
  205. v-tippy="{ theme: 'tooltip' }"
  206. :title="
  207. header.hasOwnProperty('active')
  208. ? header.active
  209. ? t('action.turn_off')
  210. : t('action.turn_on')
  211. : t('action.turn_off')
  212. "
  213. :svg="
  214. header.hasOwnProperty('active')
  215. ? header.active
  216. ? 'check-circle'
  217. : 'circle'
  218. : 'check-circle'
  219. "
  220. color="green"
  221. @click.native="
  222. updateRequestHeader(index, {
  223. key: header.key,
  224. value: header.value,
  225. active: !header.active,
  226. })
  227. "
  228. />
  229. </span>
  230. <span>
  231. <ButtonSecondary
  232. v-tippy="{ theme: 'tooltip' }"
  233. :title="t('action.remove')"
  234. svg="trash"
  235. color="red"
  236. @click.native="removeRequestHeader(index)"
  237. />
  238. </span>
  239. </div>
  240. <div
  241. v-if="headers.length === 0"
  242. class="
  243. flex
  244. text-secondaryLight
  245. flex-col
  246. items-center
  247. justify-center
  248. p-4
  249. "
  250. >
  251. <img
  252. :src="`/images/states/${$colorMode.value}/add_category.svg`"
  253. loading="lazy"
  254. class="
  255. object-contain
  256. inline-flex
  257. flex-col
  258. object-center
  259. w-16
  260. h-16
  261. my-4
  262. "
  263. :alt="`${t('empty.headers')}`"
  264. />
  265. <span class="pb-4 text-center">
  266. {{ t("empty.headers") }}
  267. </span>
  268. <ButtonSecondary
  269. :label="`${t('add.new')}`"
  270. filled
  271. svg="plus"
  272. class="mb-4"
  273. @click.native="addRequestHeader"
  274. />
  275. </div>
  276. </div>
  277. </AppSection>
  278. </SmartTab>
  279. </SmartTabs>
  280. <CollectionsSaveRequest
  281. mode="graphql"
  282. :show="showSaveRequestModal"
  283. @hide-modal="hideRequestModal"
  284. />
  285. </div>
  286. </template>
  287. <script setup lang="ts">
  288. import { onMounted, ref, watch } from "@nuxtjs/composition-api"
  289. import clone from "lodash/clone"
  290. import * as gql from "graphql"
  291. import { copyToClipboard } from "~/helpers/utils/clipboard"
  292. import {
  293. useNuxt,
  294. useReadonlyStream,
  295. useStream,
  296. useI18n,
  297. useToast,
  298. } from "~/helpers/utils/composables"
  299. import {
  300. addGQLHeader,
  301. gqlHeaders$,
  302. gqlQuery$,
  303. gqlResponse$,
  304. gqlURL$,
  305. gqlVariables$,
  306. removeGQLHeader,
  307. setGQLHeaders,
  308. setGQLQuery,
  309. setGQLResponse,
  310. setGQLVariables,
  311. updateGQLHeader,
  312. } from "~/newstore/GQLSession"
  313. import { commonHeaders } from "~/helpers/headers"
  314. import { GQLConnection } from "~/helpers/GQLConnection"
  315. import { makeGQLHistoryEntry, addGraphqlHistoryEntry } from "~/newstore/history"
  316. import { logHoppRequestRunToAnalytics } from "~/helpers/fb/analytics"
  317. import { getCurrentStrategyID } from "~/helpers/network"
  318. import { GQLHeader, makeGQLRequest } from "~/helpers/types/HoppGQLRequest"
  319. import { useCodemirror } from "~/helpers/editor/codemirror"
  320. import jsonLinter from "~/helpers/editor/linting/json"
  321. import { createGQLQueryLinter } from "~/helpers/editor/linting/gqlQuery"
  322. import queryCompleter from "~/helpers/editor/completion/gqlQuery"
  323. const t = useI18n()
  324. const props = defineProps<{
  325. conn: GQLConnection
  326. }>()
  327. const toast = useToast()
  328. const nuxt = useNuxt()
  329. const bulkMode = ref(false)
  330. const bulkHeaders = ref("")
  331. watch(bulkHeaders, () => {
  332. try {
  333. const transformation = bulkHeaders.value.split("\n").map((item) => ({
  334. key: item.substring(0, item.indexOf(":")).trim().replace(/^\/\//, ""),
  335. value: item.substring(item.indexOf(":") + 1).trim(),
  336. active: !item.trim().startsWith("//"),
  337. }))
  338. setGQLHeaders(transformation as GQLHeader[])
  339. } catch (e) {
  340. toast.error(`${t("error.something_went_wrong")}`)
  341. console.error(e)
  342. }
  343. })
  344. const url = useReadonlyStream(gqlURL$, "")
  345. const gqlQueryString = useStream(gqlQuery$, "", setGQLQuery)
  346. const variableString = useStream(gqlVariables$, "", setGQLVariables)
  347. const headers = useStream(gqlHeaders$, [], setGQLHeaders)
  348. const bulkEditor = ref<any | null>(null)
  349. useCodemirror(bulkEditor, bulkHeaders, {
  350. extendedEditorConfig: {
  351. mode: "text/x-yaml",
  352. placeholder: `${t("state.bulk_mode_placeholder")}`,
  353. },
  354. linter: null,
  355. completer: null,
  356. })
  357. const variableEditor = ref<any | null>(null)
  358. useCodemirror(variableEditor, variableString, {
  359. extendedEditorConfig: {
  360. mode: "application/ld+json",
  361. placeholder: `${t("request.variables")}`,
  362. },
  363. linter: jsonLinter,
  364. completer: null,
  365. })
  366. const queryEditor = ref<any | null>(null)
  367. const schemaString = useReadonlyStream(props.conn.schema$, null)
  368. useCodemirror(queryEditor, gqlQueryString, {
  369. extendedEditorConfig: {
  370. mode: "graphql",
  371. placeholder: `${t("request.query")}`,
  372. },
  373. linter: createGQLQueryLinter(schemaString),
  374. completer: queryCompleter(schemaString),
  375. })
  376. const copyQueryIcon = ref("copy")
  377. const prettifyQueryIcon = ref("wand")
  378. const copyVariablesIcon = ref("copy")
  379. const showSaveRequestModal = ref(false)
  380. watch(
  381. headers,
  382. () => {
  383. if (!bulkMode.value)
  384. if (
  385. (headers.value[headers.value.length - 1]?.key !== "" ||
  386. headers.value[headers.value.length - 1]?.value !== "") &&
  387. headers.value.length
  388. )
  389. addRequestHeader()
  390. },
  391. { deep: true }
  392. )
  393. const editBulkHeadersLine = (index: number, item?: GQLHeader | null) => {
  394. bulkHeaders.value = headers.value
  395. .reduce((all, header, pIndex) => {
  396. const current =
  397. index === pIndex && item != null
  398. ? `${item.active ? "" : "//"}${item.key}: ${item.value}`
  399. : `${header.active ? "" : "//"}${header.key}: ${header.value}`
  400. return [...all, current]
  401. }, [])
  402. .join("\n")
  403. }
  404. const clearBulkEditor = () => {
  405. bulkHeaders.value = ""
  406. }
  407. onMounted(() => {
  408. if (!headers.value?.length) {
  409. addRequestHeader()
  410. }
  411. })
  412. const copyQuery = () => {
  413. copyToClipboard(gqlQueryString.value)
  414. copyQueryIcon.value = "check"
  415. toast.success(`${t("state.copied_to_clipboard")}`)
  416. setTimeout(() => (copyQueryIcon.value = "copy"), 1000)
  417. }
  418. const response = useStream(gqlResponse$, "", setGQLResponse)
  419. const runQuery = async () => {
  420. const startTime = Date.now()
  421. nuxt.value.$loading.start()
  422. response.value = "loading"
  423. try {
  424. const runURL = clone(url.value)
  425. const runHeaders = clone(headers.value)
  426. const runQuery = clone(gqlQueryString.value)
  427. const runVariables = clone(variableString.value)
  428. const responseText = await props.conn.runQuery(
  429. runURL,
  430. runHeaders,
  431. runQuery,
  432. runVariables
  433. )
  434. const duration = Date.now() - startTime
  435. nuxt.value.$loading.finish()
  436. response.value = JSON.stringify(JSON.parse(responseText), null, 2)
  437. addGraphqlHistoryEntry(
  438. makeGQLHistoryEntry({
  439. request: makeGQLRequest({
  440. name: "",
  441. url: runURL,
  442. query: runQuery,
  443. headers: runHeaders,
  444. variables: runVariables,
  445. }),
  446. response: response.value,
  447. star: false,
  448. })
  449. )
  450. toast.success(`${t("state.finished_in", { duration })}`)
  451. } catch (e: any) {
  452. response.value = `${e}`
  453. nuxt.value.$loading.finish()
  454. toast.error(
  455. `${t("error.something_went_wrong")}. ${t("error.check_console_details")}`,
  456. {}
  457. )
  458. console.error(e)
  459. }
  460. logHoppRequestRunToAnalytics({
  461. platform: "graphql-query",
  462. strategy: getCurrentStrategyID(),
  463. })
  464. }
  465. const hideRequestModal = () => {
  466. showSaveRequestModal.value = false
  467. }
  468. const prettifyQuery = () => {
  469. try {
  470. gqlQueryString.value = gql.print(gql.parse(gqlQueryString.value))
  471. prettifyQueryIcon.value = "check"
  472. } catch (e) {
  473. toast.error(`${t("error.gql_prettify_invalid_query")}`)
  474. prettifyQueryIcon.value = "info"
  475. }
  476. setTimeout(() => (prettifyQueryIcon.value = "wand"), 1000)
  477. }
  478. const saveRequest = () => {
  479. showSaveRequestModal.value = true
  480. }
  481. const copyVariables = () => {
  482. copyToClipboard(variableString.value)
  483. copyVariablesIcon.value = "check"
  484. toast.success(`${t("state.copied_to_clipboard")}`)
  485. setTimeout(() => (copyVariablesIcon.value = "copy"), 1000)
  486. }
  487. const addRequestHeader = () => {
  488. const empty = { key: "", value: "", active: true }
  489. const index = headers.value.length
  490. addGQLHeader(empty)
  491. editBulkHeadersLine(index, empty)
  492. }
  493. const updateRequestHeader = (
  494. index: number,
  495. item: { key: string; value: string; active: boolean }
  496. ) => {
  497. updateGQLHeader(index, item)
  498. editBulkHeadersLine(index, item)
  499. }
  500. const removeRequestHeader = (index: number) => {
  501. const headersBeforeDeletion = headers.value
  502. removeGQLHeader(index)
  503. editBulkHeadersLine(index, null)
  504. const deletedItem = headersBeforeDeletion[index]
  505. if (deletedItem.key || deletedItem.value) {
  506. toast.success(`${t("state.deleted")}`, {
  507. action: [
  508. {
  509. text: `${t("action.undo")}`,
  510. onClick: (_, toastObject) => {
  511. setGQLHeaders(headersBeforeDeletion as GQLHeader[])
  512. editBulkHeadersLine(index, deletedItem)
  513. toastObject.goAway(0)
  514. },
  515. },
  516. ],
  517. })
  518. }
  519. }
  520. const clearContent = () => {
  521. headers.value = []
  522. clearBulkEditor()
  523. }
  524. </script>