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
<template>
<HoppSmartTabs
v-model="selectedOptionTab"
styles="sticky overflow-x-auto flex-shrink-0 bg-primary top-upperPrimaryStickyFold z-10 border-b-0"
:render-inactive-tabs="true"
>
<HoppSmartTab
v-if="showTab('query')"
:id="'query'"
:label="`${t('tab.query')}`"
:indicator="request.query && request.query.length > 0 ? true : false"
>
<GqlQuery
v-model="request.query"
:show-run-actions="showRunActions"
:subscription-state="subscriptionState"
:envs="envs"
:tab-id="tabId"
@run-query="runQuery"
@stop-query="stopQuery"
@save-request="() => invokeAction('request-response.save')"
@cursor-position="updateCursorPos"
/>
</HoppSmartTab>
<HoppSmartTab
v-if="showTab('variables')"
:id="'variables'"
:label="`${t('tab.variables')}`"
:indicator="
request.variables && request.variables.length > 0 ? true : false
"
>
<GqlVariable
v-model="request.variables"
:show-run-actions="showRunActions"
:subscription-state="subscriptionState"
:envs="envs"
@run-query="runQuery"
@stop-query="stopQuery"
@save-request="() => invokeAction('request-response.save')"
/>
</HoppSmartTab>
<HoppSmartTab
v-if="showTab('headers')"
:id="'headers'"
:label="`${t('tab.headers')}`"
:info="activeGQLHeadersCount === 0 ? null : `${activeGQLHeadersCount}`"
>
<GqlHeaders
v-model="request"
:inherited-properties="inheritedProperties"
:envs="envs"
@change-tab="changeOptionTab"
/>
</HoppSmartTab>
<HoppSmartTab
v-if="showTab('authorization')"
:id="'authorization'"
:label="`${t('tab.authorization')}`"
>
<GqlAuthorization
v-model="request.auth"
:inherited-properties="inheritedProperties"
:envs="envs"
/>
</HoppSmartTab>
<!-- Script tabs are guarded on the request SHAPE (not just the filter):
saved-example originalRequest models never carry script fields -->
<HoppSmartTab
v-if="showTab('preRequestScript') && 'preRequestScript' in request"
:id="'preRequestScript'"
:label="`${t('tab.pre_request_script')}`"
:indicator="
hasActualScript(request.preRequestScript) ||
hasInheritedPreRequestScripts
"
>
<HttpPreRequestScript
v-model="request.preRequestScript"
:is-active="selectedOptionTab === 'preRequestScript'"
:inherited-properties="inheritedProperties"
/>
</HoppSmartTab>
<HoppSmartTab
v-if="showTab('tests') && 'testScript' in request"
:id="'tests'"
:label="`${t('tab.post_request_script')}`"
:indicator="
hasActualScript(request.testScript) || hasInheritedTestScripts
"
>
<HttpTests
v-model="request.testScript"
:is-active="selectedOptionTab === 'tests'"
:inherited-properties="inheritedProperties"
/>
</HoppSmartTab>
</HoppSmartTabs>
</template>
<script setup lang="ts">
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import {
HoppGQLAuth,
HoppGQLRequest,
HoppGQLResponseOriginalRequest,
} from "@hoppscotch/data"
import { useVModel } from "@vueuse/core"
import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"
import * as gql from "graphql"
import { clone, cloneDeep } from "lodash-es"
import { computed, watch } from "vue"
import { defineActionHandler, invokeAction } from "~/helpers/actions"
import {
GQLTabConnectionService,
type GQLResponseEvent,
} from "~/services/gql-tab-connection.service"
import { HoppTestResult } from "~/helpers/types/HoppTestResult"
import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"
import { AggregateEnvironment } from "~/newstore/environments"
import { completePageProgress, startPageProgress } from "~/modules/loadingbar"
import { platform } from "~/platform"
import { KernelInterceptorService } from "~/services/kernel-interceptor.service"
import { useService } from "dioc/vue"
import { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"
type GqlRequestOptionsModel = HoppGQLRequest | HoppGQLResponseOriginalRequest
const interceptorService = useService(KernelInterceptorService)
const gqlTabConn = useService(GQLTabConnectionService)
const t = useI18n()
const toast = useToast()
const props = withDefaults(
defineProps<{
modelValue: GqlRequestOptionsModel
response?: GQLResponseEvent[] | null
optionTab?: GQLOptionTabs
// Written via update:testResults only (v-model target) — declared so the
// binding doesn't fall through as a stringified DOM attribute
testResults?: HoppTestResult | null
tabId?: string
url?: string
inheritedProperties?: HoppInheritedProperty
showRunActions?: boolean
/**
* Filter which sub-tabs are visible. Used by the embed renderer to
* honour the share-er's customize selections. `undefined` shows all
* tabs (default for the live editor).
*/
properties?: string[]
// Embed-only env scope; `undefined` uses the global aggregate envs
envs?: AggregateEnvironment[]
}>(),
{
response: null,
optionTab: "query",
testResults: undefined,
tabId: "",
url: "",
showRunActions: true,
properties: undefined,
envs: undefined,
}
)
const emit = defineEmits<{
(e: "update:modelValue", value: GqlRequestOptionsModel): void
(e: "update:optionTab", value: GQLOptionTabs): void
(e: "update:response", value: GQLResponseEvent[]): void
(e: "update:testResults", value: HoppTestResult | null | undefined): void
(e: "cursor-position", pos: number): void
}>()
const selectedOptionTab = useVModel(props, "optionTab", emit)
const request = useVModel(props, "modelValue", emit)
// Show a tab when `properties` is absent (live editor — all four) OR the tab
// is explicitly listed. An empty `properties` array would otherwise hide every
// tab — `.includes(...)` returns false for all queries, and the `?? true`
// short-circuit on the v-if only catches `undefined`/`null`. That edge case
// happens when the share-er disables every customize toggle.
const showTab = (id: GQLOptionTabs) => {
if (props.properties === undefined) return true
if (props.properties.length === 0) return true
return props.properties.includes(id)
}
// Yellow indicator dots when a collection ancestor contributes scripts —
// mirrors http/RequestOptions.vue
const hasInheritedPreRequestScripts = computed(
() =>
props.inheritedProperties?.scripts?.some((script) =>
hasActualScript(script.preRequestScript)
) ?? false
)
const hasInheritedTestScripts = computed(
() =>
props.inheritedProperties?.scripts?.some((script) =>
hasActualScript(script.testScript)
) ?? false
)
const subscriptionState = computed(() =>
props.tabId
? gqlTabConn.getTabSubscriptionState(props.tabId).value
: undefined
)
const stopQuery = () => {
if (!props.tabId) return
gqlTabConn.unsubscribeTab(props.tabId)
}
const activeGQLHeadersCount = computed(
() =>
request.value.headers.filter(
(x) => x.active && (x.key !== "" || x.value !== "")
).length
)
const runQuery = async (
definition: gql.OperationDefinitionNode | null = null
) => {
if (!props.tabId) return
const startTime = Date.now()
startPageProgress()
// Hoisted so the catch can tell subscription runs apart — their
// testResults must stay untouched on failure too
let runDefinition: gql.OperationDefinitionNode | null = null
try {
const runURL = clone(props.url)
const runQueryStr = clone(request.value.query)
const runVariables = clone(request.value.variables)
// Cursor-less invocations (ctrl-enter, unparseable-at-cursor) pass no
// definition — derive it from the document being run, or the run would
// execute and STAMP saved examples as operationType "query" regardless
// of the actual operation
runDefinition =
definition ??
(() => {
try {
return (
gql
.parse(runQueryStr)
.definitions.find(
(d): d is gql.OperationDefinitionNode =>
d.kind === "OperationDefinition"
) ?? null
)
} catch (_e) {
return null
}
})()
// Deep-freeze the whole request at click time (like url/query/variables)
// so edits during the run's awaits can't change what's sent — auth
// editors mutate nested fields in place, so a shallow clone wouldn't hold
const runRequest = cloneDeep(request.value) as HoppGQLRequest
const runInheritedAuth = cloneDeep(
props.inheritedProperties?.auth.inheritedAuth
) as HoppGQLAuth | undefined
const inheritedHeaders = cloneDeep(
props.inheritedProperties?.headers.map(
(header) => header.inheritedHeader
) ?? []
)
const runInheritedVariables = cloneDeep(
props.inheritedProperties?.variables
)
const runInheritedScripts = cloneDeep(props.inheritedProperties?.scripts)
// `testResults` — including the in-flight `null` sentinel — is written by
// GQLTabConnectionService (see `setTabTestResults`). It can't be emitted
// from here: the response pane is gated behind `testResults !== null`, and
// this component unmounts whenever its tab isn't the active one, so a run
// finishing in the background would strand the sentinel and leave the
// Results pane spinning until the next run.
const runResult = await gqlTabConn.runTabGQLOperation(props.tabId, {
name: runRequest.name,
url: runURL,
request: runRequest,
inheritedHeaders,
inheritedAuth: runInheritedAuth,
inheritedVariables: runInheritedVariables,
inheritedScripts: runInheritedScripts,
query: runQueryStr,
variables: runVariables,
operationName: runDefinition?.name?.value,
operationType: runDefinition?.operation ?? "query",
// A scoped env list is only ever passed by embeds — isolate their
// runs from the viewer's stored environments too
isolatedEnvs: props.envs !== undefined,
})
const duration = Date.now() - startTime
completePageProgress()
if (runResult?.preScriptFailed) {
// No request was sent — a success toast would contradict the script
// error shown in the response panel (REST's script_fail behavior)
toast.error(`${t("error.script_fail")}`)
} else {
// Subscriptions only just OPENED at this point (runTabGQLOperation
// returns as soon as the socket is initiated) — "finished in Xms" would
// be false; the response panel's subscribing/streaming states carry the
// feedback instead
if (runDefinition?.operation !== "subscription") {
toast.success(`${t("state.finished_in", { duration })}`)
}
// `auth` is always truthy (authType "none" included) — only toast when
// auth actually rode the connection_init payload (same snapshot the
// operation received)
const auth = runRequest.auth
const effectiveAuth =
auth.authType === "inherit" ? runInheritedAuth : auth
if (
runDefinition?.operation === "subscription" &&
effectiveAuth &&
effectiveAuth.authActive &&
effectiveAuth.authType !== "none" &&
effectiveAuth.authType !== "inherit"
) {
toast.success(t("authorization.graphql_headers"))
}
}
} catch (e: any) {
completePageProgress()
console.error(e)
}
platform.analytics?.logEvent({
type: "HOPP_REQUEST_RUN",
platform: "graphql-query",
strategy: interceptorService.current.value!.id,
})
}
if (props.tabId) {
const tabMessageEvent = gqlTabConn.getTabMessageEvent(props.tabId)
watch(
() => tabMessageEvent.value,
(event) => {
if (event === "reset") {
emit("update:response", [])
return
}
if (!event) return
try {
// A subscription stream accumulates into the log; anything else —
// query/mutation result or a run-level error — concludes a discrete
// run and replaces the panel. Events carry the operationType of the
// run they belong to, so a query failure replaces even while an
// older subscription log is still on screen. Subscription events
// append only when their log is actually rendered (the renderers
// key off `response[0]`) and replace otherwise — errors stay
// visible instead of hiding behind a stale result, and a stream
// whose log was displaced (e.g. by a connection error) restores
// itself on the next frame.
const current = props.response ?? []
const head = current[0]
const logOnScreen =
head?.type === "response" && head.operationType === "subscription"
const appendsToLog =
event.operationType === "subscription" && logOnScreen
emit("update:response", appendsToLog ? [...current, event] : [event])
} catch (error) {
console.error(error)
}
},
{ deep: true }
)
watch(
() => {
const ctx = gqlTabConn.getTabConnectionState(props.tabId)
return { error: ctx.error, state: ctx.state }
},
(newVal) => {
if (
newVal.error &&
(newVal.state === "DISCONNECTED" || newVal.state === "ERROR")
) {
const response = [
{
type: "error",
error: {
message: newVal.error.message(t),
type: newVal.error.type,
component: newVal.error.component,
},
},
]
emit("update:response", response)
}
},
{ deep: true }
)
}
const updateCursorPos = (pos: number) => {
emit("cursor-position", pos)
}
const clearGQLQuery = () => {
request.value.query = ""
}
const changeOptionTab = (e: GQLOptionTabs) => {
selectedOptionTab.value = e
}
const runActionsActive = computed(() => props.showRunActions)
/** The named operation; null if absent, undefined if the query doesn't parse. */
const findOperationByName = (name: string) => {
try {
return (
gql
.parse(request.value.query)
.definitions.find(
(d): d is gql.OperationDefinitionNode =>
d.kind === "OperationDefinition" && d.name?.value === name
) ?? null
)
} catch (_e) {
return undefined
}
}
/**
* Runs the named operation (multi-operation documents); without a name,
* runQuery falls back to the document's first operation.
*/
const runNamedOperation = (name?: string) => {
if (!name) return runQuery()
const definition = findOperationByName(name)
if (definition) return runQuery(definition)
// Unparseable before env templating: send as before, the server decides.
if (definition === undefined) return runQuery()
// A name that doesn't resolve must not run another operation.
if (props.tabId) {
gqlTabConn.getTabMessageEvent(props.tabId).value = {
type: "error",
error: {
type: "operation_not_found",
message: `No operation named "${name}" in the query.`,
},
}
}
}
defineActionHandler(
"request.send-cancel",
(payload) => runNamedOperation(payload?.operationName),
runActionsActive
)
defineActionHandler("request.reset", clearGQLQuery, runActionsActive)
defineActionHandler("request.open-tab", ({ tab }) => {
selectedOptionTab.value = tab as GQLOptionTabs
})
</script>
<style lang="scss" scoped>
:deep(.cm-panels) {
@apply top-upperPrimaryStickyFold #{!important};
}
</style>