feat: save api responses (#4382)

Co-authored-by: jamesgeorge007 <25279263+jamesgeorge007@users.noreply.github.com>
This commit is contained in:
Nivedin
2024-09-30 19:06:53 +05:30
committed by GitHub
parent fdf5bf34ed
commit 58857be650
84 changed files with 3080 additions and 321 deletions

View File

@@ -43,6 +43,7 @@
"rename": "Rename",
"restore": "Restore",
"save": "Save",
"save_as_example": "Save as example",
"scroll_to_bottom": "Scroll to bottom",
"scroll_to_top": "Scroll to top",
"search": "Search",
@@ -224,6 +225,7 @@
"remove_folder": "Are you sure you want to permanently delete this folder?",
"remove_history": "Are you sure you want to permanently delete all history?",
"remove_request": "Are you sure you want to permanently delete this request?",
"remove_response": "Are you sure you want to permanently delete this response?",
"remove_shared_request": "Are you sure you want to permanently delete this shared request?",
"remove_team": "Are you sure you want to delete this workspace?",
"remove_telemetry": "Are you sure you want to opt-out of Telemetry?",
@@ -391,7 +393,8 @@
"codegen": "{request_name} - code",
"graphql_response": "GraphQL-Response",
"lens": "{request_name} - response",
"realtime_response": "Realtime-Response"
"realtime_response": "Realtime-Response",
"response_interface": "Response-Interface"
},
"filter": {
"all": "All",
@@ -528,7 +531,9 @@
"confirm": "Confirm",
"customize_request": "Customize Request",
"edit_request": "Edit Request",
"edit_response": "Edit Response",
"import_export": "Import / Export",
"response_name": "Response Name",
"share_request": "Share Request"
},
"mqtt": {
@@ -595,6 +600,7 @@
},
"request": {
"added": "Request added",
"add": "Add Request",
"authorization": "Authorization",
"body": "Request Body",
"choose_language": "Choose language",
@@ -631,6 +637,7 @@
"rename": "Rename Request",
"renamed": "Request renamed",
"request_variables": "Request variables",
"response_name_exists": "Response name already exists",
"run": "Run",
"save": "Save",
"save_as": "Save as",
@@ -650,14 +657,18 @@
"response": {
"audio": "Audio",
"body": "Response Body",
"duplicated": "Response duplicated",
"duplicate_name_error": "Same name response already exists",
"filter_response_body": "Filter JSON response body (uses JSONPath syntax)",
"headers": "Headers",
"html": "HTML",
"image": "Image",
"json": "JSON",
"pdf": "PDF",
"please_save_request": "Save the request to create example",
"preview_html": "Preview HTML",
"raw": "Raw",
"renamed": "Response renamed",
"size": "Size",
"status": "Status",
"time": "Time",
@@ -666,7 +677,9 @@
"waiting_for_connection": "waiting for connection",
"xml": "XML",
"generate_data_schema": "Generate Data Schema",
"data_schema": "Data Schema"
"data_schema": "Data Schema",
"saved": "Response saved",
"invalid_name": "Please provide a name for the response"
},
"settings": {
"accent_color": "Accent color",

View File

@@ -49,6 +49,8 @@ declare module 'vue' {
CollectionsEdit: typeof import('./components/collections/Edit.vue')['default']
CollectionsEditFolder: typeof import('./components/collections/EditFolder.vue')['default']
CollectionsEditRequest: typeof import('./components/collections/EditRequest.vue')['default']
CollectionsEditResponse: typeof import('./components/collections/EditResponse.vue')['default']
CollectionsExampleResponse: typeof import('./components/collections/ExampleResponse.vue')['default']
CollectionsGraphql: typeof import('./components/collections/graphql/index.vue')['default']
CollectionsGraphqlAdd: typeof import('./components/collections/graphql/Add.vue')['default']
CollectionsGraphqlAddFolder: typeof import('./components/collections/graphql/AddFolder.vue')['default']
@@ -142,6 +144,11 @@ declare module 'vue' {
HttpBodyParameters: typeof import('./components/http/BodyParameters.vue')['default']
HttpCodegen: typeof import('./components/http/Codegen.vue')['default']
HttpCodegenModal: typeof import('./components/http/CodegenModal.vue')['default']
HttpExampleLenseBodyRenderer: typeof import('./components/http/example/LenseBodyRenderer.vue')['default']
HttpExampleResponse: typeof import('./components/http/example/Response.vue')['default']
HttpExampleResponseMeta: typeof import('./components/http/example/ResponseMeta.vue')['default']
HttpExampleResponseRequest: typeof import('./components/http/example/ResponseRequest.vue')['default']
HttpExampleResponseTab: typeof import('./components/http/example/ResponseTab.vue')['default']
HttpHeaders: typeof import('./components/http/Headers.vue')['default']
HttpImportCurl: typeof import('./components/http/ImportCurl.vue')['default']
HttpKeyValue: typeof import('./components/http/KeyValue.vue')['default']
@@ -157,6 +164,7 @@ declare module 'vue' {
HttpResponse: typeof import('./components/http/Response.vue')['default']
HttpResponseInterface: typeof import('./components/http/ResponseInterface.vue')['default']
HttpResponseMeta: typeof import('./components/http/ResponseMeta.vue')['default']
HttpSaveResponseName: typeof import('./components/http/SaveResponseName.vue')['default']
HttpSidebar: typeof import('./components/http/Sidebar.vue')['default']
HttpTabHead: typeof import('./components/http/TabHead.vue')['default']
HttpTestResult: typeof import('./components/http/TestResult.vue')['default']

View File

@@ -7,9 +7,9 @@
<icon-lucide-chevron-right class="flex flex-shrink-0" />
</template>
<span
v-if="request"
v-if="request && 'method' in request"
class="flex flex-shrink-0 truncate rounded-md border border-dividerDark px-1 text-tiny font-semibold"
:style="{ color: getMethodLabelColorClassOf(request) }"
:style="{ color: getMethodLabelColorClassOf(request.method) }"
>
{{ request.method.toUpperCase() }}
</span>

View File

@@ -92,6 +92,9 @@ watch(
() => props.show,
(show) => {
if (show) {
if (tabs.currentActiveTab.value.document.type === "example-response")
return
editingName.value = tabs.currentActiveTab.value.document.request.name
}
}

View File

@@ -62,7 +62,7 @@
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:icon="IconFilePlus"
:title="t('request.new')"
:title="t('request.add')"
class="hidden group-hover:inline-flex"
@click="emit('add-request')"
/>

View File

@@ -0,0 +1,95 @@
<template>
<HoppSmartModal
v-if="show"
dialog
:title="t('modal.edit_response')"
@close="hideModal"
>
<template #body>
<div class="flex gap-1">
<HoppSmartInput
v-model="editingName"
class="flex-grow"
placeholder=" "
:label="t('action.label')"
input-styles="floating-input"
@submit="editResponse"
/>
</div>
</template>
<template #footer>
<span class="flex space-x-2">
<HoppButtonPrimary
:label="t('action.save')"
:loading="loadingState"
outline
@click="editResponse"
/>
<HoppButtonSecondary
:label="t('action.cancel')"
outline
filled
@click="hideModal"
/>
</span>
</template>
</HoppSmartModal>
</template>
<script setup lang="ts">
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import { HoppRESTRequest } from "@hoppscotch/data"
import { useVModel } from "@vueuse/core"
const toast = useToast()
const t = useI18n()
const props = withDefaults(
defineProps<{
show: boolean
loadingState: boolean
modelValue?: string
requestContext: HoppRESTRequest | null
}>(),
{
show: false,
loadingState: false,
modelValue: "",
}
)
const emit = defineEmits<{
(e: "submit", name: string): void
(e: "hide-modal"): void
(e: "update:modelValue", value: string): void
}>()
const editingName = useVModel(props, "modelValue")
const editResponse = () => {
if (editingName.value.trim() === "") {
toast.error(t("response.invalid_name"))
return
}
const responses = props.requestContext?.responses || []
//check if any other response has the same name
const hasSameNameResponse = Object.keys(responses).some(
(key) => key === editingName.value
)
if (hasSameNameResponse) {
toast.error(t("request.response_name_exists"))
return
}
emit("submit", editingName.value)
}
const hideModal = () => {
editingName.value = ""
emit("hide-modal")
}
</script>

View File

@@ -0,0 +1,247 @@
<template>
<div
class="flex items-center w-full flex-1 justify-between cursor-pointer group"
@contextmenu.prevent="options?.tippy?.show()"
>
<div
class="pointer-events-auto flex min-w-0 flex-1 space-x-2 cursor-pointer items-center justify-center"
@click="selectResponse()"
>
<span
class="pointer-events-none flex w-10 px-2 items-center justify-start truncate relative"
>
<span
class="truncate text-tiny font-semibold relative"
:class="statusCategory.className"
>
{{ response.code ?? response.status }}
</span>
</span>
<span
class="pointer-events-none flex min-w-0 flex-1 items-center py-2 pr-2 transition group-hover:text-secondaryDark"
>
<span class="truncate font-semibold group-hover:text-secondaryDark">
{{ responseName }}
</span>
<span
v-if="isActiveExample"
v-tippy="{ theme: 'tooltip' }"
class="relative mx-3 flex h-1.5 w-1.5 flex-shrink-0"
:title="`${t('collection.request_in_use')}`"
>
<span
class="absolute inline-flex h-full w-full flex-shrink-0 animate-ping rounded-full bg-green-500 opacity-75"
>
</span>
<span
class="relative inline-flex h-1.5 w-1.5 flex-shrink-0 rounded-full bg-green-500"
></span>
</span>
</span>
</div>
<div v-if="!hasNoTeamAccess" class="flex">
<span>
<tippy
ref="options"
interactive
trigger="click"
theme="popover"
:on-shown="() => tippyActions!.focus()"
>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.more')"
:icon="IconMoreVertical"
class="!py-1"
/>
<template #content="{ hide }">
<div
ref="tippyActions"
class="flex flex-col focus:outline-none"
tabindex="0"
@keyup.e="edit?.$el.click()"
@keyup.d="duplicate?.$el.click()"
@keyup.delete="deleteAction?.$el.click()"
@keyup.escape="hide()"
>
<HoppSmartItem
ref="edit"
:icon="IconEdit"
:label="t('action.edit')"
:shortcut="['E']"
@click="
() => {
emit('edit-response', {
responseName: responseName,
responseID: saveContext.exampleID,
})
hide()
}
"
/>
<HoppSmartItem
ref="duplicate"
:icon="IconCopy"
:label="t('action.duplicate')"
:shortcut="['D']"
@click="
() => {
emit('duplicate-response', {
responseName: responseName,
responseID: saveContext.exampleID,
})
hide()
}
"
/>
<HoppSmartItem
ref="deleteAction"
:icon="IconTrash2"
:label="t('action.delete')"
:shortcut="['⌫']"
@click="
() => {
emit('remove-response', {
responseName: responseName,
responseID: saveContext.exampleID,
})
hide()
}
"
/>
</div>
</template>
</tippy>
</span>
</div>
</div>
</template>
<script setup lang="ts">
import IconMoreVertical from "~icons/lucide/more-vertical"
import IconEdit from "~icons/lucide/edit"
import IconCopy from "~icons/lucide/copy"
import IconTrash2 from "~icons/lucide/trash-2"
import { ref, PropType, computed } from "vue"
import { useI18n } from "@composables/i18n"
import { TippyComponent } from "vue-tippy"
import { useService } from "dioc/vue"
import { RESTTabService } from "~/services/tab/rest"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
import { HoppRESTSaveContext } from "~/helpers/rest/document"
import findStatusGroup from "@helpers/findStatusGroup"
const t = useI18n()
type CollectionType = "my-collections" | "team-collections"
type SaveContext = {
requestID: string | number
exampleID: string
parentID: string
collectionsType: CollectionType
saveRequest: boolean
}
const props = defineProps({
response: {
type: Object as PropType<HoppRESTRequestResponse>,
default: null,
required: true,
},
responseName: {
type: String,
default: "",
required: true,
},
hasNoTeamAccess: {
type: Boolean,
default: false,
required: false,
},
saveContext: {
type: Object as PropType<SaveContext>,
default: null,
required: false,
},
})
type ResponsePayload = {
responseName: string
responseID: string
}
const statusCategory = computed(() => {
return findStatusGroup(props.response.code ?? 0)
})
const emit = defineEmits<{
(event: "edit-response", payload: ResponsePayload): void
(event: "duplicate-response", payload: ResponsePayload): void
(event: "remove-response", payload: ResponsePayload): void
(event: "select-response", payload: ResponsePayload): void
}>()
const tabs = useService(RESTTabService)
const pathToIndex = (path: string) => {
const pathArr = path.split("/")
return pathArr[pathArr.length - 1]
}
const getSaveContext = (): HoppRESTSaveContext => {
if (props.saveContext.collectionsType === "my-collections") {
return {
originLocation: "user-collection",
folderPath: props.saveContext.parentID,
requestIndex: Number(pathToIndex(props.saveContext.requestID.toString())),
exampleID: props.saveContext.exampleID,
}
}
return {
originLocation: "team-collection",
requestID: props.saveContext.requestID.toString() as string,
collectionID: props.saveContext.parentID,
exampleID: props.saveContext.exampleID,
}
}
const active = computed(() => tabs.currentActiveTab.value.document.saveContext)
const isActiveExample = computed(() => {
const saveCtx = getSaveContext()
if (!saveCtx) return
if (saveCtx.originLocation === "team-collection") {
return (
active.value?.originLocation === "team-collection" &&
active.value?.requestID === saveCtx.requestID &&
active.value?.exampleID === saveCtx.exampleID
)
}
return (
active.value?.originLocation === "user-collection" &&
active.value?.folderPath === saveCtx.folderPath &&
active.value?.requestIndex === saveCtx.requestIndex &&
active.value?.exampleID === saveCtx.exampleID
)
})
const selectResponse = () => {
emit("select-response", {
responseName: props.responseName,
responseID: props.saveContext.exampleID,
})
}
const tippyActions = ref<HTMLButtonElement | null>(null)
const edit = ref<HTMLButtonElement | null>(null)
const deleteAction = ref<HTMLButtonElement | null>(null)
const options = ref<TippyComponent | null>(null)
const duplicate = ref<HTMLButtonElement | null>(null)
</script>

View File

@@ -105,7 +105,8 @@
})
"
@dragging="
(isDraging) => highlightChildren(isDraging ? node.id : null)
(isDraging: boolean) =>
highlightChildren(isDraging ? node.id : null)
"
@toggle-children="
() => {
@@ -187,7 +188,8 @@
})
"
@dragging="
(isDraging) => highlightChildren(isDraging ? node.id : null)
(isDraging: boolean) =>
highlightChildren(isDraging ? node.id : null)
"
@toggle-children="
() => {
@@ -228,6 +230,15 @@
request: node.data.data.data,
})
"
@edit-response="
emit('edit-response', {
folderPath: node.data.data.parentIndex,
requestIndex: pathToIndex(node.id),
request: node.data.data.data,
responseName: $event.responseName,
responseID: $event.responseID,
})
"
@duplicate-request="
node.data.type === 'requests' &&
emit('duplicate-request', {
@@ -235,6 +246,15 @@
request: node.data.data.data,
})
"
@duplicate-response="
emit('duplicate-response', {
folderPath: node.data.data.parentIndex,
requestIndex: pathToIndex(node.id),
request: node.data.data.data,
responseName: $event.responseName,
responseID: $event.responseID,
})
"
@remove-request="
node.data.type === 'requests' &&
emit('remove-request', {
@@ -242,6 +262,15 @@
requestIndex: pathToIndex(node.id),
})
"
@remove-response="
emit('remove-response', {
folderPath: node.data.data.parentIndex,
requestIndex: pathToIndex(node.id),
request: node.data.data.data,
responseName: $event.responseName,
responseID: $event.responseID,
})
"
@select-request="
node.data.type === 'requests' &&
selectRequest({
@@ -250,6 +279,15 @@
requestIndex: pathToIndex(node.id),
})
"
@select-response="
emit('select-response', {
responseName: $event.responseName,
responseID: $event.responseID,
request: node.data.data.data,
folderPath: node.data.data.parentIndex,
requestIndex: pathToIndex(node.id),
})
"
@share-request="
node.data.type === 'requests' &&
emit('share-request', {
@@ -431,6 +469,14 @@ const props = defineProps({
},
})
type ResponsePayload = {
folderPath: string
requestIndex: string
request: HoppRESTRequest
responseName: string
responseID: string
}
const emit = defineEmits<{
(event: "display-modal-add"): void
(
@@ -483,6 +529,7 @@ const emit = defineEmits<{
request: HoppRESTRequest
}
): void
(event: "edit-response", payload: ResponsePayload): void
(
event: "duplicate-request",
payload: {
@@ -490,6 +537,7 @@ const emit = defineEmits<{
request: HoppRESTRequest
}
): void
(event: "duplicate-response", payload: ResponsePayload): void
(event: "export-data", payload: HoppCollection): void
(event: "remove-collection", payload: string): void
(event: "remove-folder", payload: string): void
@@ -500,6 +548,7 @@ const emit = defineEmits<{
requestIndex: string
}
): void
(event: "remove-response", payload: ResponsePayload): void
(
event: "select-request",
payload: {
@@ -550,6 +599,7 @@ const emit = defineEmits<{
): void
(event: "select", payload: Picked | null): void
(event: "display-modal-import-export"): void
(event: "select-response", payload: ResponsePayload): void
}>()
const refFilterCollection = toRef(props, "filteredCollections")
@@ -600,7 +650,8 @@ const isActiveRequest = (folderPath: string, requestIndex: number) => {
(active) =>
active.originLocation === "user-collection" &&
active.folderPath === folderPath &&
active.requestIndex === requestIndex
active.requestIndex === requestIndex &&
active.exampleID === undefined
),
O.isSome
)

View File

@@ -13,7 +13,7 @@
@dragend="resetDragState"
></div>
<div
class="group flex items-stretch"
class="group flex items-center"
:draggable="!hasNoTeamAccess"
@drop="handelDrop"
@dragstart="dragStart"
@@ -22,13 +22,21 @@
@dragend="resetDragState"
@contextmenu.prevent="options?.tippy?.show()"
>
<div class="w-5 p-1 flex items-center justify-center">
<component
:is="isResponseVisible ? IconArrowDown : IconArrowRight"
v-if="request.responses && Object.keys(request.responses).length > 0"
class="svg-icons cursor-pointer hover:bg-primaryDark transition"
@click="toggleRequestResponse()"
/>
</div>
<div
class="pointer-events-auto flex min-w-0 flex-1 cursor-pointer items-center justify-center"
@click="selectRequest()"
>
<span
class="pointer-events-none flex w-16 items-center justify-center truncate px-2"
:style="{ color: getMethodLabelColorClassOf(request) }"
class="pointer-events-none flex w-12 items-center justify-start truncate px-2"
:style="{ color: getMethodLabelColorClassOf(request.method) }"
>
<component
:is="IconCheckCircle"
@@ -163,6 +171,33 @@
@dragleave="resetDragState"
@dragend="resetDragState"
></div>
<div v-if="isResponseVisible" class="flex">
<div
class="ml-[.6rem] flex w-0.5 transform cursor-nsResize bg-dividerLight transition hover:scale-x-125 hover:bg-dividerDark"
></div>
<div class="flex flex-col w-full pl-3">
<CollectionsExampleResponse
v-for="[index, [key, value]] of Object.entries(
Object.entries(request.responses)
)"
:key="key"
:response-name="key"
:response="value"
:save-context="{
requestID: requestID,
exampleID: index,
parentID: parentID,
collectionsType: collectionsType,
saveRequest: saveRequest,
}"
@edit-response="emit('edit-response', $event)"
@remove-response="emit('remove-response', $event)"
@duplicate-response="emit('duplicate-response', $event)"
@select-response="emit('select-response', $event)"
/>
</div>
</div>
</div>
</template>
@@ -174,6 +209,8 @@ import IconCopy from "~icons/lucide/copy"
import IconTrash2 from "~icons/lucide/trash-2"
import IconRotateCCW from "~icons/lucide/rotate-ccw"
import IconShare2 from "~icons/lucide/share-2"
import IconArrowRight from "~icons/lucide/chevron-right"
import IconArrowDown from "~icons/lucide/chevron-down"
import { ref, PropType, watch, computed } from "vue"
import { HoppRESTRequest } from "@hoppscotch/data"
import { useI18n } from "@composables/i18n"
@@ -247,8 +284,14 @@ const props = defineProps({
},
})
type ResponsePayload = {
responseName: string
responseID: string
}
const emit = defineEmits<{
(event: "edit-request"): void
(event: "edit-response", payload: ResponsePayload): void
(event: "duplicate-request"): void
(event: "remove-request"): void
(event: "select-request"): void
@@ -256,6 +299,10 @@ const emit = defineEmits<{
(event: "drag-request", payload: DataTransfer): void
(event: "update-request-order", payload: DataTransfer): void
(event: "update-last-request-order", payload: DataTransfer): void
(event: "duplicate-response", payload: ResponsePayload): void
(event: "remove-response", payload: ResponsePayload): void
(event: "select-response", payload: ResponsePayload): void
(event: "toggle-children"): void
}>()
const tippyActions = ref<HTMLButtonElement | null>(null)
@@ -269,6 +316,8 @@ const dragging = ref(false)
const ordering = ref(false)
const orderingLastItem = ref(false)
const isResponseVisible = ref(false)
const currentReorderingStatus = useReadonlyStream(currentReorderingStatus$, {
type: "collection",
id: "",
@@ -288,6 +337,11 @@ const selectRequest = () => {
emit("select-request")
}
const toggleRequestResponse = () => {
emit("toggle-children")
isResponseVisible.value = !isResponseVisible.value
}
const dragStart = ({ dataTransfer }: DragEvent) => {
if (dataTransfer) {
emit("drag-request", dataTransfer)

View File

@@ -149,7 +149,10 @@ const gqlRequestName = computedWithControl(
const restRequestName = computedWithControl(
() => RESTTabs.currentActiveTab.value,
() => RESTTabs.currentActiveTab.value.document.request.name
() =>
RESTTabs.currentActiveTab.value.document.type === "request"
? RESTTabs.currentActiveTab.value.document.request.name
: ""
)
const reqName = computed(() => {
@@ -166,7 +169,10 @@ const requestContext = computed(() => {
return props.request
}
if (props.mode === "rest") {
if (
props.mode === "rest" &&
RESTTabs.currentActiveTab.value.document.type === "request"
) {
return RESTTabs.currentActiveTab.value.document.request
}
@@ -184,7 +190,10 @@ const {
watch(
() => [RESTTabs.currentActiveTab.value, GQLTabs.currentActiveTab.value],
() => {
if (props.mode === "rest") {
if (
props.mode === "rest" &&
RESTTabs.currentActiveTab.value.document.type === "request"
) {
requestName.value =
RESTTabs.currentActiveTab.value?.document.request.name ?? ""
} else {
@@ -249,9 +258,15 @@ const saveRequestAs = async () => {
const requestUpdated =
props.mode === "rest"
? cloneDeep(RESTTabs.currentActiveTab.value.document.request)
? cloneDeep(
RESTTabs.currentActiveTab.value.document.type === "request"
? RESTTabs.currentActiveTab.value.document.request
: null
)
: cloneDeep(GQLTabs.currentActiveTab.value.document.request)
if (!requestUpdated) return
requestUpdated.name = requestName.value
if (picked.value.pickedType === "my-collection") {
@@ -263,13 +278,17 @@ const saveRequestAs = async () => {
requestUpdated
)
if (RESTTabs.currentActiveTab.value.document.type !== "request") return
RESTTabs.currentActiveTab.value.document = {
request: requestUpdated,
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: `${picked.value.collectionIndex}`,
requestIndex: insertionIndex,
exampleID: undefined,
},
}
@@ -303,6 +322,7 @@ const saveRequestAs = async () => {
RESTTabs.currentActiveTab.value.document = {
request: requestUpdated,
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: picked.value.folderPath,
@@ -341,6 +361,7 @@ const saveRequestAs = async () => {
RESTTabs.currentActiveTab.value.document = {
request: requestUpdated,
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: picked.value.folderPath,
@@ -541,6 +562,7 @@ const updateTeamCollectionOrFolder = (
RESTTabs.currentActiveTab.value.document = {
request: requestUpdated,
isDirty: false,
type: "request",
saveContext: {
originLocation: "team-collection",
requestID: createRequestInCollection.id,

View File

@@ -123,7 +123,7 @@
})
"
@dragging="
(isDraging) =>
(isDraging: boolean) =>
highlightChildren(isDraging ? node.data.data.data.id : null)
"
@toggle-children="
@@ -220,7 +220,7 @@
})
"
@dragging="
(isDraging) =>
(isDraging: boolean) =>
highlightChildren(isDraging ? node.data.data.data.id : null)
"
@toggle-children="
@@ -267,6 +267,15 @@
request: node.data.data.data.request,
})
"
@edit-response="
emit('edit-response', {
folderPath: node.data.data.parentIndex,
requestIndex: node.data.data.data.id,
request: node.data.data.data.request,
responseName: $event.responseName,
responseID: $event.responseID,
})
"
@duplicate-request="
node.data.type === 'requests' &&
emit('duplicate-request', {
@@ -274,6 +283,15 @@
request: node.data.data.data.request,
})
"
@duplicate-response="
emit('duplicate-response', {
folderPath: node.data.data.parentIndex,
requestIndex: node.data.data.data.id,
request: node.data.data.data.request,
responseName: $event.responseName,
responseID: $event.responseID,
})
"
@remove-request="
node.data.type === 'requests' &&
emit('remove-request', {
@@ -281,6 +299,15 @@
requestIndex: node.data.data.data.id,
})
"
@remove-response="
emit('remove-response', {
folderPath: node.data.data.parentIndex,
requestIndex: node.data.data.data.id,
request: node.data.data.data.request,
responseName: $event.responseName,
responseID: $event.responseID,
})
"
@select-request="
node.data.type === 'requests' &&
selectRequest({
@@ -289,6 +316,15 @@
folderPath: getPath(node.id),
})
"
@select-response="
emit('select-response', {
responseName: $event.responseName,
responseID: $event.responseID,
request: node.data.data.data.request,
folderPath: getPath(node.id),
requestIndex: node.data.data.data.id,
})
"
@share-request="
node.data.type === 'requests' &&
emit('share-request', {
@@ -488,6 +524,14 @@ const props = defineProps({
const isShowingSearchResults = computed(() => props.filterText.length > 0)
type ResponsePayload = {
folderPath: string
requestIndex: string
request: HoppRESTRequest
responseName: string
responseID: string
}
const emit = defineEmits<{
(
event: "add-request",
@@ -537,6 +581,7 @@ const emit = defineEmits<{
request: HoppRESTRequest
}
): void
(event: "edit-response", payload: ResponsePayload): void
(
event: "duplicate-request",
payload: {
@@ -544,6 +589,7 @@ const emit = defineEmits<{
request: HoppRESTRequest
}
): void
(event: "duplicate-response", payload: ResponsePayload): void
(event: "export-data", payload: TeamCollection): void
(event: "remove-collection", payload: string): void
(event: "remove-folder", payload: string): void
@@ -554,6 +600,7 @@ const emit = defineEmits<{
requestIndex: string
}
): void
(event: "remove-response", payload: ResponsePayload): void
(
event: "select-request",
payload: {
@@ -563,6 +610,7 @@ const emit = defineEmits<{
folderPath: string
}
): void
(event: "select-response", payload: ResponsePayload): void
(
event: "share-request",
payload: {
@@ -682,7 +730,8 @@ const isActiveRequest = (requestID: string) => {
O.filter(
(active) =>
active.originLocation === "team-collection" &&
active.requestID === requestID
active.requestID === requestID &&
active.exampleID === undefined
),
O.isSome
)
@@ -704,7 +753,7 @@ const selectRequest = (data: {
request: request,
requestIndex: requestIndex,
isActive: isActiveRequest(requestIndex),
folderPath: data.folderPath,
folderPath: data.folderPath ?? "",
})
}
}

View File

@@ -35,25 +35,29 @@
:picked="picked"
@add-folder="addFolder"
@add-request="addRequest"
@edit-request="editRequest"
@edit-collection="editCollection"
@edit-folder="editFolder"
@edit-response="editResponse"
@drop-request="dropRequest"
@drop-collection="dropCollection"
@display-modal-add="displayModalAdd(true)"
@display-modal-import-export="displayModalImportExport(true)"
@duplicate-collection="duplicateCollection"
@duplicate-request="duplicateRequest"
@duplicate-response="duplicateResponse"
@edit-properties="editProperties"
@export-data="exportData"
@remove-collection="removeCollection"
@remove-folder="removeFolder"
@remove-request="removeRequest"
@remove-response="removeResponse"
@share-request="shareRequest"
@drop-collection="dropCollection"
@select="selectPicked"
@select-response="selectResponse"
@select-request="selectRequest"
@update-request-order="updateRequestOrder"
@update-collection-order="updateCollectionOrder"
@edit-request="editRequest"
@duplicate-request="duplicateRequest"
@remove-request="removeRequest"
@select-request="selectRequest"
@select="selectPicked"
@drop-request="dropRequest"
@display-modal-add="displayModalAdd(true)"
@display-modal-import-export="displayModalImportExport(true)"
/>
<CollectionsTeamCollections
v-else
@@ -76,28 +80,32 @@
:request-move-loading="requestMoveLoading"
@add-request="addRequest"
@add-folder="addFolder"
@edit-collection="editCollection"
@edit-folder="editFolder"
@collection-click="handleCollectionClick"
@duplicate-collection="duplicateCollection"
@edit-properties="editProperties"
@export-data="exportData"
@remove-collection="removeCollection"
@remove-folder="removeFolder"
@share-request="shareRequest"
@edit-request="editRequest"
@duplicate-request="duplicateRequest"
@remove-request="removeRequest"
@select-request="selectRequest"
@select="selectPicked"
@duplicate-response="duplicateResponse"
@drop-request="dropRequest"
@drop-collection="dropCollection"
@update-request-order="updateRequestOrder"
@update-collection-order="updateCollectionOrder"
@expand-team-collection="expandTeamCollection"
@display-modal-add="displayModalAdd(true)"
@display-modal-import-export="displayModalImportExport(true)"
@collection-click="handleCollectionClick"
@edit-collection="editCollection"
@edit-folder="editFolder"
@edit-request="editRequest"
@edit-response="editResponse"
@edit-properties="editProperties"
@export-data="exportData"
@expand-team-collection="expandTeamCollection"
@remove-collection="removeCollection"
@remove-folder="removeFolder"
@remove-request="removeRequest"
@remove-response="removeResponse"
@run-collection="runCollectionHandler"
@share-request="shareRequest"
@select-request="selectRequest"
@select-response="selectResponse"
@select="selectPicked"
@update-request-order="updateRequestOrder"
@update-collection-order="updateCollectionOrder"
/>
<div
class="py-15 hidden flex-1 flex-col items-center justify-center bg-primaryDark px-4 text-secondaryLight"
@@ -148,6 +156,14 @@
@submit="updateEditingRequest"
@hide-modal="displayModalEditRequest(false)"
/>
<CollectionsEditResponse
v-model="editingResponseName"
:show="showModalEditResponse"
:request-context="editingRequest"
:loading-state="modalLoadingState"
@submit="updateEditingResponse"
@hide-modal="displayModalEditResponse(false)"
/>
<HoppSmartConfirmModal
:show="showConfirmModal"
:title="confirmModalTitle"
@@ -276,6 +292,7 @@ import { TeamWorkspace, WorkspaceService } from "~/services/workspace.service"
import { RESTOptionTabs } from "../http/RequestOptions.vue"
import { Collection as NodeCollection } from "./MyCollections.vue"
import { EditingProperties } from "./Properties.vue"
import { getDefaultRESTRequest } from "~/helpers/rest/default"
const t = useI18n()
const toast = useToast()
@@ -322,8 +339,11 @@ const editingFolderName = ref<string | null>(null)
const editingFolderPath = ref<string | null>(null)
const editingRequest = ref<HoppRESTRequest | null>(null)
const editingRequestName = ref("")
const editingResponseName = ref("")
const editingResponseOldName = ref("")
const editingRequestIndex = ref<number | null>(null)
const editingRequestID = ref<string | null>(null)
const editingResponseID = ref<string | null>(null)
const editingProperties = ref<EditingProperties>({
collection: null,
@@ -665,6 +685,7 @@ const showModalAddFolder = ref(false)
const showModalEditCollection = ref(false)
const showModalEditFolder = ref(false)
const showModalEditRequest = ref(false)
const showModalEditResponse = ref(false)
const showModalImportExport = ref(false)
const showModalEditProperties = ref(false)
const showConfirmModal = ref(false)
@@ -710,6 +731,12 @@ const displayModalEditRequest = (show: boolean) => {
if (!show) resetSelectedData()
}
const displayModalEditResponse = (show: boolean) => {
showModalEditResponse.value = show
if (!show) resetSelectedData()
}
const displayModalImportExport = (show: boolean) => {
showModalImportExport.value = show
@@ -796,12 +823,21 @@ const addRequest = (payload: {
}
const requestContext = computed(() => {
return tabs.currentActiveTab.value.document.request
return tabs.currentActiveTab.value.document.type === "request"
? tabs.currentActiveTab.value.document.request
: null
})
const onAddRequest = (requestName: string) => {
const request =
tabs.currentActiveTab.value.document.type === "request"
? tabs.currentActiveTab.value.document.request
: getDefaultRESTRequest()
if (!request) return
const newRequest = {
...cloneDeep(tabs.currentActiveTab.value.document.request),
...cloneDeep(request),
name: requestName,
}
@@ -815,6 +851,7 @@ const onAddRequest = (requestName: string) => {
tabs.createNewTab({
request: newRequest,
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: path,
@@ -869,6 +906,7 @@ const onAddRequest = (requestName: string) => {
tabs.createNewTab({
request: newRequest,
isDirty: false,
type: "request",
saveContext: {
originLocation: "team-collection",
requestID: createRequestInCollection.id,
@@ -1127,7 +1165,10 @@ const updateEditingRequest = (newName: string) => {
editRESTRequest(folderPath, requestIndex, requestUpdated)
if (possibleActiveTab) {
if (
possibleActiveTab &&
possibleActiveTab.value.document.type === "request"
) {
possibleActiveTab.value.document.request.name = requestUpdated.name
nextTick(() => {
possibleActiveTab.value.document.isDirty = false
@@ -1168,7 +1209,7 @@ const updateEditingRequest = (newName: string) => {
requestID,
})
if (possibleTab) {
if (possibleTab && possibleTab.value.document.type === "request") {
possibleTab.value.document.request.name = requestName
nextTick(() => {
possibleTab.value.document.isDirty = false
@@ -1177,6 +1218,171 @@ const updateEditingRequest = (newName: string) => {
}
}
type ResponseConfigPayload = {
folderPath: string | undefined
requestIndex: string
request: HoppRESTRequest
responseName: string
responseID: string
}
const editResponse = (payload: ResponseConfigPayload) => {
const { folderPath, requestIndex, request, responseID, responseName } =
payload
editingRequest.value = request
editingRequestName.value = request.name ?? ""
editingResponseID.value = responseID
editingResponseName.value = responseName
//need to store the old name for updating the response key
editingResponseOldName.value = responseName
if (collectionsType.value.type === "my-collections" && folderPath) {
editingFolderPath.value = folderPath
editingRequestIndex.value = parseInt(requestIndex)
} else {
editingRequestID.value = requestIndex
}
displayModalEditResponse(true)
}
const updateEditingResponse = (newName: string) => {
const request = cloneDeep(editingRequest.value)
if (!request) return
const responseOldName = editingResponseOldName.value
if (!responseOldName) return
if (responseOldName !== newName) {
// Convert object to entries array (preserving order)
const entries = Object.entries(request.responses)
// Replace the old key with the new key in the array
const updatedEntries = entries.map(([key, value]) =>
key === responseOldName
? [newName, { ...value, name: newName }]
: [key, value]
)
// Convert the array back into an object
request.responses = Object.fromEntries(updatedEntries)
}
if (collectionsType.value.type === "my-collections") {
const folderPath = editingFolderPath.value
const requestIndex = editingRequestIndex.value
if (folderPath === null || requestIndex === null) return
const possibleExampleActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "user-collection",
requestIndex,
folderPath,
exampleID: editingResponseID.value ?? undefined,
})
const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "user-collection",
requestIndex,
folderPath,
})
editRESTRequest(folderPath, requestIndex, request)
if (
possibleExampleActiveTab &&
possibleExampleActiveTab.value.document.type === "example-response"
) {
possibleExampleActiveTab.value.document.response.name = newName
nextTick(() => {
possibleExampleActiveTab.value.document.isDirty = false
possibleExampleActiveTab.value.document.saveContext = {
originLocation: "user-collection",
folderPath: folderPath,
requestIndex: requestIndex,
exampleID: editingResponseID.value!,
}
})
}
// update the request tab responses if it's open
if (
possibleRequestActiveTab &&
possibleRequestActiveTab.value.document.type === "request"
) {
possibleRequestActiveTab.value.document.request.responses =
request.responses
}
displayModalEditResponse(false)
toast.success(t("response.renamed"))
} else if (hasTeamWriteAccess.value) {
modalLoadingState.value = true
const requestID = editingRequestID.value
if (!requestID) return
const data = {
request: JSON.stringify(request),
title: request.name,
}
pipe(
updateTeamRequest(requestID, data),
TE.match(
(err: GQLError<string>) => {
toast.error(`${getErrorMessage(err)}`)
modalLoadingState.value = false
},
() => {
modalLoadingState.value = false
toast.success(t("response.renamed"))
displayModalEditResponse(false)
}
)
)()
const possibleActiveResponseTab = tabs.getTabRefWithSaveContext({
originLocation: "team-collection",
requestID,
exampleID: editingResponseID.value ?? undefined,
})
const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "team-collection",
requestID,
})
if (
possibleActiveResponseTab &&
possibleActiveResponseTab.value.document.type === "example-response"
) {
possibleActiveResponseTab.value.document.response.name = newName
nextTick(() => {
possibleActiveResponseTab.value.document.isDirty = false
possibleActiveResponseTab.value.document.saveContext = {
originLocation: "team-collection",
requestID,
exampleID: editingResponseID.value!,
}
})
}
// update the request tab responses if it's open
if (
possibleRequestActiveTab &&
possibleRequestActiveTab.value.document.type === "request"
) {
possibleRequestActiveTab.value.document.request.responses =
request.responses
}
}
}
const duplicateRequest = (payload: {
folderPath: string
request: HoppRESTRequest
@@ -1220,6 +1426,93 @@ const duplicateRequest = (payload: {
}
}
const duplicateResponse = (payload: ResponseConfigPayload) => {
const { folderPath, requestIndex, request, responseName } = payload
const response = request.responses[responseName]
if (!response || !folderPath || !requestIndex) return
const newName = `${responseName} - ${t("action.duplicate")}`
// if the new name is already taken, show a toast and return
if (Object.keys(request.responses).includes(newName)) {
toast.error(t("response.duplicate_name_error"))
return
}
const newResponse = {
...cloneDeep(response),
name: newName,
}
const updatedRequest = {
...request,
responses: {
...request.responses,
[newResponse.name]: newResponse,
},
}
if (collectionsType.value.type === "my-collections") {
editRESTRequest(folderPath, parseInt(requestIndex), updatedRequest)
toast.success(t("response.duplicated"))
const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "user-collection",
requestIndex: parseInt(requestIndex),
folderPath,
})
// update the request tab responses if it's open
if (
possibleRequestActiveTab &&
possibleRequestActiveTab.value.document.type === "request"
) {
possibleRequestActiveTab.value.document.request.responses =
updatedRequest.responses
}
} else if (hasTeamWriteAccess.value) {
duplicateRequestLoading.value = true
if (!collectionsType.value.selectedTeam) return
const data = {
request: JSON.stringify(updatedRequest),
title: request.name,
}
pipe(
updateTeamRequest(requestIndex, data),
TE.match(
(err: GQLError<string>) => {
toast.error(`${getErrorMessage(err)}`)
modalLoadingState.value = false
},
() => {
modalLoadingState.value = false
toast.success(t("response.duplicated"))
displayModalEditResponse(false)
}
)
)()
// update the request tab responses if it's open
const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "team-collection",
requestID: requestIndex,
})
if (
possibleRequestActiveTab &&
possibleRequestActiveTab.value.document.type === "request"
) {
possibleRequestActiveTab.value.document.request.responses =
updatedRequest.responses
}
}
}
const removeCollection = (id: string) => {
if (collectionsType.value.type === "my-collections")
editingCollectionIndex.value = parseInt(id)
@@ -1406,9 +1699,12 @@ const onRemoveRequest = () => {
})
// If there is a tab attached to this request, dissociate its state and mark it dirty
if (possibleTab) {
if (possibleTab && possibleTab.value.document.type === "request") {
possibleTab.value.document.saveContext = null
possibleTab.value.document.isDirty = true
// since the request is deleted, we need to remove the saved responses as well
possibleTab.value.document.request.responses = {}
}
const requestToRemove = navigateToFolderWithIndexPath(
@@ -1464,9 +1760,176 @@ const onRemoveRequest = () => {
requestID,
})
if (possibleTab) {
if (possibleTab && possibleTab.value.document.type === "request") {
possibleTab.value.document.saveContext = null
possibleTab.value.document.isDirty = true
// since the request is deleted, we need to remove the saved responses as well
possibleTab.value.document.request.responses = {}
}
}
}
const removeResponse = (payload: ResponseConfigPayload) => {
const { folderPath, requestIndex, request, responseID, responseName } =
payload
if (collectionsType.value.type === "my-collections" && folderPath) {
editingFolderPath.value = folderPath
editingRequestIndex.value = parseInt(requestIndex)
editingResponseID.value = responseID
editingRequest.value = request
editingResponseName.value = responseName
} else {
editingRequestID.value = requestIndex
editingResponseID.value = payload.responseID
editingRequest.value = request
editingResponseName.value = responseName
}
confirmModalTitle.value = `${t("confirm.remove_response")}`
displayConfirmModal(true)
}
const onRemoveResponse = () => {
const request = cloneDeep(editingRequest.value)
if (!request) return
const responseName = editingResponseName.value
const responseID = editingResponseID.value
delete request.responses[responseName]
const requestUpdated: HoppRESTRequest = {
...request,
}
if (collectionsType.value.type === "my-collections") {
const folderPath = editingFolderPath.value
const requestIndex = editingRequestIndex.value
if (folderPath === null || requestIndex === null) return
editRESTRequest(folderPath, requestIndex, requestUpdated)
const possibleActiveResponseTab = tabs.getTabRefWithSaveContext({
originLocation: "user-collection",
folderPath,
requestIndex,
exampleID: responseID ?? undefined,
})
const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "user-collection",
requestIndex,
folderPath,
})
// If there is a tab attached to this request, close it and set the active tab to the first one
if (
possibleActiveResponseTab &&
possibleActiveResponseTab.value.document.type === "example-response"
) {
const activeTabs = tabs.getActiveTabs()
// if the last tab is the one we are closing, we need to create a new tab
if (
activeTabs.value.length === 1 &&
activeTabs.value[0].id === possibleActiveResponseTab.value.id
) {
tabs.createNewTab({
request: getDefaultRESTRequest(),
isDirty: false,
type: "request",
saveContext: undefined,
})
tabs.closeTab(possibleActiveResponseTab.value.id)
} else {
tabs.closeTab(possibleActiveResponseTab.value.id)
tabs.setActiveTab(activeTabs.value[0].id)
}
}
// update the request tab responses if it's open
if (
possibleRequestActiveTab &&
possibleRequestActiveTab.value.document.type === "request"
) {
possibleRequestActiveTab.value.document.request.responses =
requestUpdated.responses
}
toast.success(t("state.deleted"))
displayConfirmModal(false)
} else if (hasTeamWriteAccess.value) {
const requestID = editingRequestID.value
if (!requestID) return
modalLoadingState.value = true
const data = {
request: JSON.stringify(requestUpdated),
title: request.name,
}
pipe(
updateTeamRequest(requestID, data),
TE.match(
(err: GQLError<string>) => {
toast.error(`${getErrorMessage(err)}`)
modalLoadingState.value = false
},
() => {
modalLoadingState.value = false
toast.success(t("state.deleted"))
displayConfirmModal(false)
}
)
)()
const possibleActiveResponseTab = tabs.getTabRefWithSaveContext({
originLocation: "team-collection",
requestID,
exampleID: responseID ?? undefined,
})
const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({
originLocation: "team-collection",
requestID,
})
// If there is a tab attached to this request, close it and set the active tab to the first one
if (
possibleActiveResponseTab &&
possibleActiveResponseTab.value.document.type === "example-response"
) {
const activeTabs = tabs.getActiveTabs()
// if the last tab is the one we are closing, we need to create a new tab
if (
activeTabs.value.length === 1 &&
activeTabs.value[0].id === possibleActiveResponseTab.value.id
) {
tabs.createNewTab({
request: getDefaultRESTRequest(),
isDirty: false,
type: "request",
saveContext: undefined,
})
tabs.closeTab(possibleActiveResponseTab.value.id)
} else {
tabs.closeTab(possibleActiveResponseTab.value.id)
tabs.setActiveTab(activeTabs.value[0].id)
}
}
// update the request tab responses if it's open
if (
possibleRequestActiveTab &&
possibleRequestActiveTab.value.document.type === "request"
) {
possibleRequestActiveTab.value.document.request.responses =
requestUpdated.responses
}
}
}
@@ -1516,10 +1979,12 @@ const selectRequest = (selectedRequest: {
tabs.createNewTab({
request: cloneDeep(request),
isDirty: false,
type: "request",
saveContext: {
originLocation: "team-collection",
requestID: requestIndex,
collectionID: folderPath,
exampleID: undefined,
},
inheritedProperties: inheritedProperties,
})
@@ -1541,6 +2006,7 @@ const selectRequest = (selectedRequest: {
tabs.createNewTab({
request: cloneDeep(request),
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: folderPath!,
@@ -1555,6 +2021,72 @@ const selectRequest = (selectedRequest: {
}
}
const selectResponse = (payload: {
folderPath: string
requestIndex: string
responseName: string
request: HoppRESTRequest
responseID: string
}) => {
const { folderPath, requestIndex, responseName, request, responseID } =
payload
const response = request.responses[responseName]
if (collectionsType.value.type === "my-collections") {
const possibleTab = tabs.getTabRefWithSaveContext({
originLocation: "user-collection",
requestIndex: parseInt(requestIndex),
folderPath: folderPath!,
exampleID: responseID,
})
if (possibleTab) {
tabs.setActiveTab(possibleTab.value.id)
} else {
tabs.createNewTab({
response: {
...cloneDeep(response),
name: responseName,
},
isDirty: false,
type: "example-response",
saveContext: {
originLocation: "user-collection",
folderPath: folderPath!,
requestIndex: parseInt(requestIndex),
exampleID: responseID,
},
})
}
} else {
const possibleTab = tabs.getTabRefWithSaveContext({
originLocation: "team-collection",
requestID: requestIndex,
exampleID: responseID,
})
if (possibleTab) {
tabs.setActiveTab(possibleTab.value.id)
} else {
tabs.createNewTab({
response: {
...cloneDeep(response),
name: responseName,
},
isDirty: false,
type: "example-response",
saveContext: {
originLocation: "team-collection",
requestID: requestIndex,
collectionID: folderPath,
exampleID: responseID,
},
})
}
}
}
/**
* Used to get the index of the request from the path
* @param path The path of the request
@@ -1593,7 +2125,7 @@ const dropRequest = (payload: {
})
// If there is a tab attached to this request, change save its save context
if (possibleTab) {
if (possibleTab && possibleTab.value.document.type === "request") {
possibleTab.value.document.saveContext = {
originLocation: "user-collection",
folderPath: destinationCollectionIndex,
@@ -1654,7 +2186,7 @@ const dropRequest = (payload: {
requestID: requestIndex,
})
if (possibleTab) {
if (possibleTab && possibleTab.value.document.type === "request") {
possibleTab.value.document.saveContext = {
originLocation: "team-collection",
requestID: requestIndex,
@@ -1872,6 +2404,13 @@ const dropToRoot = ({ dataTransfer }: DragEvent) => {
} else {
moveRESTFolder(collectionIndexDragged, null)
toast.success(`${t("collection.moved")}`)
const rootLength = myCollections.value.length
updateSaveContextForAffectedRequests(
collectionIndexDragged,
`${rootLength - 1}`
)
}
draggingToRoot.value = false
@@ -2352,6 +2891,7 @@ const resolveConfirmModal = (title: string | null) => {
if (title === `${t("confirm.remove_collection")}`) onRemoveCollection()
else if (title === `${t("confirm.remove_request")}`) onRemoveRequest()
else if (title === `${t("confirm.remove_folder")}`) onRemoveFolder()
else if (title === `${t("confirm.remove_response")}`) onRemoveResponse()
else {
console.error(
`Confirm modal title ${title} is not handled by the component`

View File

@@ -64,13 +64,13 @@ import { useStreamSubscriber } from "~/composables/stream"
import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"
import { runRESTRequest$ } from "~/helpers/RequestRunner"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
const toast = useToast()
const t = useI18n()
const props = defineProps<{
modelTab: HoppTab<HoppRESTDocument>
modelTab: HoppTab<HoppRequestDocument>
sharedRequestURL: string
}>()

View File

@@ -27,11 +27,11 @@
import { computed, useModel } from "vue"
import { ref } from "vue"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
import { RESTOptionTabs } from "../http/RequestOptions.vue"
const props = defineProps<{
modelTab: HoppTab<HoppRESTDocument>
modelTab: HoppTab<HoppRequestDocument>
properties: RESTOptionTabs[]
sharedRequestID: string
}>()

View File

@@ -75,6 +75,7 @@ import { InterceptorService } from "~/services/interceptor.service"
import { editGraphqlRequest } from "~/newstore/collections"
import { GQLTabService } from "~/services/tab/graphql"
import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"
import { HoppRESTHeaders } from "@hoppscotch/data"
const VALID_GQL_OPERATIONS = [
"query",
@@ -158,7 +159,10 @@ const runQuery = async (
let runHeaders: HoppGQLRequest["headers"] = []
if (inheritedHeaders) {
runHeaders = [...inheritedHeaders, ...clone(request.value.headers)]
runHeaders = [
...inheritedHeaders,
...clone(request.value.headers),
] as HoppRESTHeaders
} else {
runHeaders = clone(request.value.headers)
}
@@ -266,7 +270,7 @@ const changeOptionTab = (e: GQLOptionTabs) => {
}
defineActionHandler("request.send-cancel", runQuery)
defineActionHandler("request.save", saveRequest)
defineActionHandler("request-response.save", saveRequest)
defineActionHandler("request.save-as", () => {
showSaveRequestModal.value = true
})

View File

@@ -300,6 +300,7 @@ const useHistory = (entry: RESTHistoryEntry) => {
tabs.createNewTab({
request: entry.request,
isDirty: false,
type: "request",
})
}

View File

@@ -147,6 +147,8 @@ const handleImport = () => {
type: "HOPP_REST_IMPORT_CURL",
})
if (tabs.currentActiveTab.value.document.type === "example-response") return
tabs.currentActiveTab.value.document.request = req
} catch (e) {
console.error(e)

View File

@@ -263,7 +263,7 @@ import { useService } from "dioc/vue"
import { InspectionService } from "~/services/inspection"
import { InterceptorService } from "~/services/interceptor.service"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
import { RESTTabService } from "~/services/tab/rest"
import { getMethodLabelColor } from "~/helpers/rest/labelColoring"
import { WorkspaceService } from "~/services/workspace.service"
@@ -288,7 +288,7 @@ const toast = useToast()
const { subscribeToStream } = useStreamSubscriber()
const props = defineProps<{ modelValue: HoppTab<HoppRESTDocument> }>()
const props = defineProps<{ modelValue: HoppTab<HoppRequestDocument> }>()
const emit = defineEmits(["update:modelValue"])
const tab = useVModel(props, "modelValue", emit)
@@ -583,10 +583,10 @@ defineActionHandler("request.reset", clearContent)
defineActionHandler("request.share-request", shareRequest)
defineActionHandler("request.method.next", cycleDownMethod)
defineActionHandler("request.method.prev", cycleUpMethod)
defineActionHandler("request.save", saveRequest)
defineActionHandler("request-response.save", saveRequest)
defineActionHandler("request.save-as", (req) => {
showSaveRequestModal.value = true
if (req?.requestType === "rest") {
if (req?.requestType === "rest" && req.request) {
request.value = req.request
}
})

View File

@@ -50,26 +50,35 @@
/>
</HoppSmartTab>
<HoppSmartTab
v-if="properties?.includes('preRequestScript') ?? true"
v-if="showPreRequestScriptTab"
:id="'preRequestScript'"
:label="`${t('tab.pre_request_script')}`"
:indicator="
request.preRequestScript && request.preRequestScript.length > 0
'preRequestScript' in request &&
request.preRequestScript &&
request.preRequestScript.length > 0
? true
: false
"
>
<HttpPreRequestScript v-model="request.preRequestScript" />
<HttpPreRequestScript
v-if="'preRequestScript' in request"
v-model="request.preRequestScript"
/>
</HoppSmartTab>
<HoppSmartTab
v-if="properties?.includes('tests') ?? true"
v-if="showTestsTab"
:id="'tests'"
:label="`${t('tab.tests')}`"
:indicator="
request.testScript && request.testScript.length > 0 ? true : false
'testScript' in request &&
request.testScript &&
request.testScript.length > 0
? true
: false
"
>
<HttpTests v-model="request.testScript" />
<HttpTests v-if="'testScript' in request" v-model="request.testScript" />
</HoppSmartTab>
<HoppSmartTab
v-if="properties?.includes('requestVariables') ?? true"
@@ -85,7 +94,10 @@
<script setup lang="ts">
import { useI18n } from "@composables/i18n"
import { HoppRESTRequest } from "@hoppscotch/data"
import {
HoppRESTRequest,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import { useVModel } from "@vueuse/core"
import { computed } from "vue"
import { defineActionHandler } from "~/helpers/actions"
@@ -109,7 +121,7 @@ const t = useI18n()
// v-model integration with props and emit
const props = withDefaults(
defineProps<{
modelValue: HoppRESTRequest
modelValue: HoppRESTRequest | HoppRESTResponseOriginalRequest
optionTab: RESTOptionTabs
properties?: string[]
inheritedProperties?: HoppInheritedProperty
@@ -128,6 +140,17 @@ const emit = defineEmits<{
const request = useVModel(props, "modelValue", emit)
const selectedOptionTab = useVModel(props, "optionTab", emit)
const showPreRequestScriptTab = computed(() => {
return (
props.properties?.includes("preRequestScript") ??
"preRequestScript" in request.value
)
})
const showTestsTab = computed(() => {
return props.properties?.includes("tests") ?? "testScript" in request.value
})
const changeOptionTab = (e: RESTOptionTabs) => {
selectedOptionTab.value = e
}

View File

@@ -20,14 +20,14 @@ import { useVModel } from "@vueuse/core"
import { cloneDeep } from "lodash-es"
import { isEqualHoppRESTRequest } from "@hoppscotch/data"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
// TODO: Move Response and Request execution code to over here
const props = defineProps<{ modelValue: HoppTab<HoppRESTDocument> }>()
const props = defineProps<{ modelValue: HoppTab<HoppRequestDocument> }>()
const emit = defineEmits<{
(e: "update:modelValue", val: HoppTab<HoppRESTDocument>): void
(e: "update:modelValue", val: HoppTab<HoppRequestDocument>): void
}>()
const tab = useVModel(props, "modelValue", emit)

View File

@@ -4,22 +4,44 @@
<LensesResponseBodyRenderer
v-if="!loading && hasResponse"
v-model:document="doc"
@save-as-example="saveAsExample"
/>
</div>
<HttpSaveResponseName
v-model="responseName"
:show="showSaveResponseName"
@submit="onSaveAsExample"
@hide-modal="showSaveResponseName = false"
/>
</template>
<script setup lang="ts">
import { useVModel } from "@vueuse/core"
import { computed } from "vue"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { computed, ref } from "vue"
import { HoppRequestDocument } from "~/helpers/rest/document"
import { useResponseBody } from "@composables/lens-actions"
import { getStatusCodeReasonPhrase } from "~/helpers/utils/statusCodes"
import {
HoppRESTResponseOriginalRequest,
HoppRESTRequestResponse,
} from "@hoppscotch/data"
import { editRESTRequest } from "~/newstore/collections"
import { useToast } from "@composables/toast"
import { useI18n } from "@composables/i18n"
import { runMutation } from "~/helpers/backend/GQLClient"
import { UpdateRequestDocument } from "~/helpers/backend/graphql"
import * as E from "fp-ts/Either"
const t = useI18n()
const toast = useToast()
const props = defineProps<{
document: HoppRESTDocument
document: HoppRequestDocument
isEmbed: boolean
}>()
const emit = defineEmits<{
(e: "update:tab", val: HoppRESTDocument): void
(e: "update:tab", val: HoppRequestDocument): void
}>()
const doc = useVModel(props, "document", emit)
@@ -30,5 +52,97 @@ const hasResponse = computed(
doc.value.response?.type === "fail"
)
const responseName = ref("")
const showSaveResponseName = ref(false)
const loading = computed(() => doc.value.response?.type === "loading")
const saveAsExample = () => {
showSaveResponseName.value = true
}
const onSaveAsExample = () => {
const response = doc.value.response
if (response && response.type === "success") {
const { responseBodyText } = useResponseBody(response)
const statusText = getStatusCodeReasonPhrase(
response.statusCode,
response.statusText
)
const {
method,
endpoint,
headers,
body,
auth,
params,
name,
requestVariables,
} = response.req
const originalRequest: HoppRESTResponseOriginalRequest = {
v: "1",
method,
endpoint,
headers,
body,
auth,
params,
name,
requestVariables,
}
const resName = responseName.value.trim()
const responseObj: HoppRESTRequestResponse = {
status: statusText,
code: response.statusCode,
headers: response.headers,
body: responseBodyText.value,
name: resName,
originalRequest,
}
doc.value.request.responses = {
...doc.value.request.responses,
[resName]: responseObj,
}
showSaveResponseName.value = false
const saveCtx = doc.value.saveContext
if (!saveCtx) return
const req = doc.value.request
if (saveCtx.originLocation === "user-collection") {
try {
editRESTRequest(saveCtx.folderPath, saveCtx.requestIndex, req)
toast.success(`${t("response.saved")}`)
} catch (e) {
console.error(e)
}
} else {
runMutation(UpdateRequestDocument, {
requestID: saveCtx.requestID,
data: {
title: req.name,
request: JSON.stringify(req),
},
})().then((result) => {
if (E.isLeft(result)) {
toast.error(`${t("profile.no_permission")}`)
} else {
doc.value.isDirty = false
toast.success(`${t("request.saved")}`)
}
})
}
}
}
</script>

View File

@@ -179,10 +179,16 @@ const response = computed(() => {
const pageCategory = getCurrentPageCategory()
if (pageCategory === "rest") {
const res = restTabs.currentActiveTab.value.document.response
const doc = restTabs.currentActiveTab.value.document
if (doc.type === "request") {
const res = doc.response
if (res?.type === "success" || res?.type === "fail") {
response = getResponseBodyText(res.body)
}
} else {
const res = doc.response.body
response = res
}
}
if (pageCategory === "graphql") {
@@ -244,6 +250,7 @@ const filteredResponseInterfaces = computed(() => {
const { copyIcon, copyResponse } = useCopyResponse(interfaceCode)
const { downloadIcon, downloadResponse } = useDownloadResponse(
"",
interfaceCode
interfaceCode,
t("filename.response_interface")
)
</script>

View File

@@ -0,0 +1,81 @@
<template>
<HoppSmartModal
v-if="show"
dialog
:title="t('modal.response_name')"
@close="hideModal"
>
<template #body>
<div class="flex gap-1">
<HoppSmartInput
v-model="editingName"
class="flex-grow"
placeholder=" "
:label="t('action.label')"
input-styles="floating-input"
@submit="editRequest"
/>
</div>
</template>
<template #footer>
<span class="flex space-x-2">
<HoppButtonPrimary
:label="t('action.save')"
:loading="loadingState"
outline
@click="editRequest"
/>
<HoppButtonSecondary
:label="t('action.cancel')"
outline
filled
@click="hideModal"
/>
</span>
</template>
</HoppSmartModal>
</template>
<script setup lang="ts">
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import { useVModel } from "@vueuse/core"
const toast = useToast()
const t = useI18n()
const props = withDefaults(
defineProps<{
show: boolean
loadingState: boolean
modelValue?: string
}>(),
{
show: false,
loadingState: false,
modelValue: "",
}
)
const emit = defineEmits<{
(e: "submit", name: string): void
(e: "hide-modal"): void
(e: "update:modelValue", value: string): void
}>()
const editingName = useVModel(props, "modelValue")
const editRequest = () => {
if (editingName.value.trim() === "") {
toast.error(t("response.invalid_name"))
return
}
emit("submit", editingName.value)
}
const hideModal = () => {
editingName.value = ""
emit("hide-modal")
}
</script>

View File

@@ -1,17 +1,20 @@
<template>
<div
v-tippy="{ theme: 'tooltip', delay: [500, 20] }"
:title="tab.document.request.name"
:title="tabState.name"
class="flex items-center truncate px-2"
@dblclick="emit('open-rename-modal')"
@contextmenu.prevent="options?.tippy?.show()"
@click.middle="emit('close-tab')"
>
<span
class="text-tiny font-semibold mr-2"
:style="{ color: getMethodLabelColorClassOf(tab.document.request) }"
class="text-tiny font-semibold mr-2 p-1 rounded-sm relative"
:class="{
'border border-dashed border-primaryDark grayscale': isResponseExample,
}"
:style="{ color: getMethodLabelColorClassOf(tabState.method) }"
>
{{ tab.document.request.method }}
{{ tabState.method }}
</span>
<tippy
ref="options"
@@ -21,7 +24,7 @@
:on-shown="() => tippyActions!.focus()"
>
<span class="truncate">
{{ tab.document.request.name }}
{{ tabState.name }}
</span>
<template #content="{ hide }">
<div
@@ -36,6 +39,7 @@
@keyup.escape="hide()"
>
<HoppSmartItem
v-if="!isResponseExample"
ref="renameAction"
:icon="IconFileEdit"
:label="t('request.rename')"
@@ -48,6 +52,7 @@
"
/>
<HoppSmartItem
v-if="!isResponseExample"
ref="duplicateAction"
:icon="IconCopy"
:label="t('tab.duplicate')"
@@ -60,6 +65,7 @@
"
/>
<HoppSmartItem
v-if="!isResponseExample"
ref="shareRequestAction"
:icon="IconShare2"
:label="t('tab.share_tab_request')"
@@ -104,7 +110,7 @@
</template>
<script setup lang="ts">
import { ref } from "vue"
import { ref, computed } from "vue"
import { TippyComponent } from "vue-tippy"
import { getMethodLabelColorClassOf } from "~/helpers/rest/labelColoring"
import { useI18n } from "~/composables/i18n"
@@ -114,15 +120,37 @@ import IconFileEdit from "~icons/lucide/file-edit"
import IconCopy from "~icons/lucide/copy"
import IconShare2 from "~icons/lucide/share-2"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import {
HoppRequestDocument,
HoppSavedExampleDocument,
} from "~/helpers/rest/document"
const t = useI18n()
defineProps<{
tab: HoppTab<HoppRESTDocument>
const props = defineProps<{
tab: HoppTab<HoppRequestDocument | HoppSavedExampleDocument>
isRemovable: boolean
}>()
const tabState = computed(() => {
if (props.tab.document.type === "request") {
return {
name: props.tab.document.request.name,
method: props.tab.document.request.method,
request: props.tab.document.request,
}
}
return {
name: props.tab.document.response.name,
method: props.tab.document.response.originalRequest.method,
request: props.tab.document.response.originalRequest,
}
})
const isResponseExample = computed(() => {
return props.tab.document.type === "example-response"
})
const emit = defineEmits<{
(event: "open-rename-modal"): void
(event: "close-tab"): void

View File

@@ -0,0 +1,85 @@
<template>
<HoppSmartTabs
v-model="selectedLensTab"
styles="sticky overflow-x-auto flex-shrink-0 z-10 bg-primary top-lowerPrimaryStickyFold"
>
<HoppSmartTab
v-for="(lens, index) in validLenses"
:id="lens.renderer"
:key="`lens-${index}`"
:label="t(lens.lensName)"
class="flex h-full w-full flex-1 flex-col"
>
<component
:is="lensRendererFor(lens.renderer)"
v-model:response="doc.response"
:is-savable="false"
:is-editable="true"
@save-as-example="$emit('save-as-example')"
/>
</HoppSmartTab>
<HoppSmartTab
v-if="doc.response.headers"
id="headers"
:label="t('response.headers')"
:info="`${doc.response.headers.length}`"
class="flex flex-1 flex-col"
>
<LensesHeadersRenderer
v-model="doc.response.headers"
:is-editable="true"
/>
</HoppSmartTab>
</HoppSmartTabs>
</template>
<script setup lang="ts">
import { computed, ref, watch } from "vue"
import {
getSuitableLenses,
getLensRenderers,
Lens,
} from "~/helpers/lenses/lenses"
import { useI18n } from "@composables/i18n"
import { useVModel } from "@vueuse/core"
import {
HoppRequestDocument,
HoppSavedExampleDocument,
} from "~/helpers/rest/document"
const props = defineProps<{
document: HoppSavedExampleDocument
}>()
const emit = defineEmits<{
(e: "update:document", document: HoppRequestDocument): void
(e: "save-as-example"): void
}>()
const doc = useVModel(props, "document", emit)
const allLensRenderers = getLensRenderers()
function lensRendererFor(name: string) {
return allLensRenderers[name]
}
const t = useI18n()
const selectedLensTab = ref("")
const validLenses = computed(() => {
if (!doc.value.response) return []
return getSuitableLenses(doc.value.response)
})
watch(
validLenses,
(newLenses: Lens[]) => {
if (newLenses.length === 0 || selectedLensTab.value) return
selectedLensTab.value = newLenses[0].renderer
},
{ immediate: true }
)
</script>

View File

@@ -0,0 +1,23 @@
<template>
<HttpExampleResponseMeta v-model:response="doc.response" />
<HttpExampleLenseBodyRenderer v-model:document="doc" />
</template>
<script setup lang="ts">
import { useVModel } from "@vueuse/core"
import {
HoppRequestDocument,
HoppSavedExampleDocument,
} from "~/helpers/rest/document"
const props = defineProps<{
document: HoppSavedExampleDocument
isEmbed: boolean
}>()
const emit = defineEmits<{
(e: "update:tab", val: HoppRequestDocument): void
}>()
const doc = useVModel(props, "document", emit)
</script>

View File

@@ -0,0 +1,70 @@
<template>
<div
class="sticky top-0 z-50 flex-none flex-shrink-0 items-center justify-center whitespace-nowrap bg-primary p-4"
>
<div v-if="responseCtx" class="flex flex-1 flex-col">
<div class="flex items-center text-tiny font-semibold">
<div class="inline-flex flex-1 space-x-4">
<div class="flex-1 flex items-center space-x-2">
<span class="text-secondary"> {{ t("response.status") }}: </span>
<div class="flex-1 flex whitespace-nowrap max-w-xs">
<SmartEnvInput
v-model="status"
:auto-complete-source="getStatusCodeOptions"
class="flex-1 border border-divider"
@update:model-value="
(statusCode: string) => {
setResponseStatusCode(statusCode)
}
"
/>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref } from "vue"
import { useI18n } from "@composables/i18n"
import {
getFullStatusCodePhrase,
getStatusCodePhrase,
getStatusAndCode,
isValidStatusCode,
} from "~/helpers/utils/statusCodes"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
import { useVModel } from "@vueuse/core"
const t = useI18n()
const props = defineProps<{
response: HoppRESTRequestResponse
}>()
const emit = defineEmits<{
(e: "update:response", val: HoppRESTRequestResponse): void
}>()
const responseCtx = useVModel(props, "response", emit)
const status = ref(
getStatusCodePhrase(responseCtx.value.code, responseCtx.value.status)
)
const getStatusCodeOptions = computed(() => {
return getFullStatusCodePhrase()
})
const setResponseStatusCode = (statusCode: string) => {
if (!isValidStatusCode(statusCode)) {
responseCtx.value.status = statusCode
responseCtx.value.code = undefined
return
}
responseCtx.value.code = getStatusAndCode(statusCode).code
responseCtx.value.status = getStatusAndCode(statusCode).status
}
</script>

View File

@@ -0,0 +1,265 @@
<template>
<div
class="sticky top-0 z-20 flex-none flex-shrink-0 bg-primary p-4 sm:flex sm:flex-shrink-0 sm:space-x-2"
>
<div
class="min-w-[12rem] flex flex-1 whitespace-nowrap rounded border border-divider"
>
<div class="relative flex">
<label for="method">
<tippy
interactive
trigger="click"
theme="popover"
:on-shown="() => methodTippyActions.focus()"
>
<HoppSmartSelectWrapper>
<input
id="method"
class="flex w-26 cursor-pointer rounded-l bg-primaryLight px-4 py-2 font-semibold text-secondaryDark transition"
:value="tab.document.response.originalRequest.method"
:readonly="!isCustomMethod"
:placeholder="`${t('request.method')}`"
@input="onSelectMethod($event)"
/>
</HoppSmartSelectWrapper>
<template #content="{ hide }">
<div
ref="methodTippyActions"
class="flex flex-col focus:outline-none"
tabindex="0"
@keyup.escape="hide()"
>
<HoppSmartItem
v-for="(method, index) in methods"
:key="`method-${index}`"
:label="method"
:style="{
color: getMethodLabelColor(method),
}"
@click="
() => {
updateMethod(method)
hide()
}
"
/>
</div>
</template>
</tippy>
</label>
</div>
<div
class="flex flex-1 whitespace-nowrap rounded-r border-l border-divider bg-primaryLight transition"
>
<SmartEnvInput
v-model="tab.document.response.originalRequest.endpoint"
:placeholder="`${t('request.url_placeholder')}`"
:auto-complete-env="true"
:inspection-results="tabResults"
/>
</div>
</div>
<div class="mt-2 flex sm:mt-0 items-stretch space-x-2">
<HoppButtonPrimary
id="send"
v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"
title="Try"
label="Try"
class="min-w-[5rem] flex-1"
@click="tryExampleResponse"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"
:title="`${t(
'request.save'
)} <kbd>${getSpecialKey()}</kbd><kbd>S</kbd>`"
label="Save"
filled
:icon="IconSave"
class="flex-1 rounded"
@click="saveExample()"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { useI18n } from "@composables/i18n"
import { useVModel } from "@vueuse/core"
import { computed, ref } from "vue"
import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"
import { getDefaultRESTRequest } from "~/helpers/rest/default"
import { useService } from "dioc/vue"
import { InspectionService } from "~/services/inspection"
import { HoppTab } from "~/services/tab"
import { HoppSavedExampleDocument } from "~/helpers/rest/document"
import { RESTTabService } from "~/services/tab/rest"
import { getMethodLabelColor } from "~/helpers/rest/labelColoring"
import IconSave from "~icons/lucide/save"
import { editRESTRequest, restCollections$ } from "~/newstore/collections"
import { useReadonlyStream } from "~/composables/stream"
import { getRequestsByPath } from "~/helpers/collection/request"
import { HoppRESTRequest } from "@hoppscotch/data"
import { useToast } from "@composables/toast"
import { cloneDeep } from "lodash-es"
import { defineActionHandler } from "~/helpers/actions"
import * as E from "fp-ts/Either"
import { runMutation } from "~/helpers/backend/GQLClient"
import { UpdateRequestDocument } from "~/helpers/backend/graphql"
import { getSingleRequest } from "~/helpers/teams/TeamRequest"
const t = useI18n()
const methods = [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"OPTIONS",
"CONNECT",
"TRACE",
"CUSTOM",
]
const toast = useToast()
const props = defineProps<{ modelValue: HoppTab<HoppSavedExampleDocument> }>()
const emit = defineEmits(["update:modelValue"])
const tabs = useService(RESTTabService)
const tab = useVModel(props, "modelValue", emit)
const newMethod = computed(() => {
return tab.value.document.response.originalRequest.method
})
const tryExampleResponse = () => {
const {
endpoint,
method,
auth,
body,
headers,
name,
params,
requestVariables,
} = tab.value.document.response.originalRequest
tabs.createNewTab({
isDirty: false,
type: "request",
request: {
...getDefaultRESTRequest(),
endpoint,
method,
auth,
body,
headers,
name,
params,
requestVariables,
},
})
}
const myCollections = useReadonlyStream(restCollections$, [], "deep")
const saveExample = async () => {
const saveCtx = tab.value.document.saveContext
if (!saveCtx) {
return
}
const response = cloneDeep(tab.value.document.response)
if (saveCtx.originLocation === "user-collection") {
const request = cloneDeep(
getRequestsByPath(myCollections.value, saveCtx.folderPath)[
saveCtx.requestIndex
] as HoppRESTRequest
)
if (!request) return
const responseName = response.name
request.responses[responseName] = response
try {
editRESTRequest(saveCtx.folderPath, saveCtx.requestIndex, request)
tab.value.document.isDirty = false
} catch (e) {
console.error(e)
}
toast.success(`${t("response.saved")}`)
} else if (saveCtx.originLocation === "team-collection") {
const request = await getSingleRequest(saveCtx.requestID)
if (E.isRight(request)) {
const req = request.right.request
if (req) {
const parsedRequest: HoppRESTRequest = JSON.parse(req.request)
if (!parsedRequest) return
const responseName = response.name
parsedRequest.responses[responseName] = response
try {
runMutation(UpdateRequestDocument, {
requestID: saveCtx.requestID,
data: {
title: parsedRequest.name,
request: JSON.stringify(parsedRequest),
},
})().then((result) => {
if (E.isLeft(result)) {
toast.error(`${t("profile.no_permission")}`)
} else {
tab.value.document.isDirty = false
toast.success(`${t("response.saved")}`)
}
})
} catch (error) {
toast.error(`${t("error.something_went_wrong")}`)
console.error(error)
}
}
} else {
toast.error(`${t("error.something_went_wrong")}`)
}
}
}
// Template refs
const methodTippyActions = ref<any | null>(null)
const inspectionService = useService(InspectionService)
const updateMethod = (method: string) => {
tab.value.document.response.originalRequest.method = method
}
const onSelectMethod = (e: Event | any) => {
// type any because of value property not being recognized by TS in the event.target object. It is a valid property though.
updateMethod(e.target.value)
}
const isCustomMethod = computed(() => {
return (
tab.value.document.response.originalRequest.method === "CUSTOM" ||
!methods.includes(newMethod.value)
)
})
const tabResults = inspectionService.getResultViewFor(tabs.currentTabID.value)
defineActionHandler("request-response.save", saveExample)
</script>

View File

@@ -0,0 +1,48 @@
<template>
<AppPaneLayout layout-id="rest-primary">
<template #primary>
<HttpExampleResponseRequest v-model="tab" />
<HttpRequestOptions
v-model="tab.document.response.originalRequest"
v-model:option-tab="optionTabPreference"
/>
</template>
<template #secondary>
<HttpExampleResponse v-model:document="tab.document" :is-embed="false" />
</template>
</AppPaneLayout>
</template>
<script setup lang="ts">
import { watch, ref } from "vue"
import { useVModel } from "@vueuse/core"
import { cloneDeep } from "lodash-es"
import { HoppTab } from "~/services/tab"
import { HoppSavedExampleDocument } from "~/helpers/rest/document"
import { RESTOptionTabs } from "../RequestOptions.vue"
import { isEqual } from "lodash-es"
const props = defineProps<{ modelValue: HoppTab<HoppSavedExampleDocument> }>()
const emit = defineEmits<{
(e: "update:modelValue", val: HoppTab<HoppSavedExampleDocument>): void
}>()
const tab = useVModel(props, "modelValue", emit)
const optionTabPreference = ref<RESTOptionTabs>("params")
// TODO: Come up with a better dirty check
let oldResponse = cloneDeep(tab.value.document.response)
watch(
() => tab.value.document.response,
(updatedValue) => {
if (!tab.value.document.isDirty && !isEqual(oldResponse, updatedValue)) {
tab.value.document.isDirty = true
}
oldResponse = cloneDeep(updatedValue)
},
{ deep: true }
)
</script>

View File

@@ -19,7 +19,10 @@
<LensesHeadersRendererEntry
v-for="(header, index) in headers"
:key="index"
:header="header"
v-model:headerKey="header.key"
v-model:headerValue="header.value"
:is-editable="isEditable"
@delete-header="deleteHeader(index)"
/>
</div>
</template>
@@ -32,23 +35,35 @@ import { copyToClipboard } from "~/helpers/utils/clipboard"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import type { HoppRESTResponseHeader } from "~/helpers/types/HoppRESTResponse"
import { useVModel } from "@vueuse/core"
const t = useI18n()
const toast = useToast()
const props = defineProps<{
headers: HoppRESTResponseHeader[]
modelValue: HoppRESTResponseHeader[]
isEditable: boolean
}>()
const emit = defineEmits<{
(e: "update:modelValue"): void
}>()
const headers = useVModel(props, "modelValue", emit)
const copyIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(
IconCopy,
1000
)
const copyHeaders = () => {
copyToClipboard(JSON.stringify(props.headers))
copyToClipboard(JSON.stringify(props.modelValue))
copyIcon.value = IconCheck
toast.success(`${t("state.copied_to_clipboard")}`)
}
const deleteHeader = (index: number) => {
headers.value.splice(index, 1)
}
</script>

View File

@@ -2,25 +2,47 @@
<div
class="group flex divide-x divide-dividerLight border-b border-dividerLight"
>
<span class="flex min-w-0 flex-1 transition group-hover:text-secondaryDark">
<span
class="flex min-w-0 flex-1 px-4 py-2 transition group-hover:text-secondaryDark"
v-if="!isEntryEditable"
class="select-all truncate rounded-sm py-2 pl-4"
>
<span class="select-all truncate rounded-sm">
{{ header.key }}
{{ headerKey }}
</span>
<SmartEnvInput
v-else
:model-value="headerKey"
@update:model-value="emit('update:headerKey', $event)"
/>
</span>
<span
class="flex min-w-0 flex-1 justify-between py-2 pl-4 transition group-hover:text-secondaryDark"
class="flex min-w-0 flex-1 justify-between transition group-hover:text-secondaryDark"
>
<span class="select-all truncate rounded-sm">
{{ header.value }}
<span
v-if="!isEntryEditable"
class="select-all truncate rounded-sm py-2 pl-4"
>
{{ headerValue }}
</span>
<SmartEnvInput
v-else
:model-value="headerValue"
@update:model-value="emit('update:headerValue', $event)"
/>
<HoppButtonSecondary
v-tippy="{ theme: 'tooltip' }"
:title="t('action.copy')"
:icon="copyIcon"
class="hidden !py-0 group-hover:inline-flex"
@click="copyHeader(header.value)"
@click="copyHeader(headerValue)"
/>
<HoppButtonSecondary
v-if="isEntryEditable"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.delete')"
:icon="IconTrash"
class="hidden !py-0 group-hover:inline-flex"
@click="deleteHeader(headerKey)"
/>
</span>
</div>
@@ -28,21 +50,36 @@
<script setup lang="ts">
import IconCopy from "~icons/lucide/copy"
import IconTrash from "~icons/lucide/trash"
import IconCheck from "~icons/lucide/check"
import { refAutoReset } from "@vueuse/core"
import type { HoppRESTResponseHeader } from "~/helpers/types/HoppRESTResponse"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import { computed } from "vue"
const t = useI18n()
const toast = useToast()
defineProps<{
header: HoppRESTResponseHeader
const props = defineProps<{
headerKey: string
headerValue: string
isEditable: boolean
}>()
const emit = defineEmits<{
(e: "update:headerKey", value: string): void
(e: "update:headerValue", value: string): void
(e: "delete-header", key: string): void
}>()
// we can allow editing only if the header is not content-type
// because editing content-type can break lense
const isEntryEditable = computed(
() => props.isEditable && props.headerKey.toLowerCase() !== "content-type"
)
const copyIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(
IconCopy,
1000
@@ -53,4 +90,8 @@ const copyHeader = (headerValue: string) => {
copyIcon.value = IconCheck
toast.success(`${t("state.copied_to_clipboard")}`)
}
const deleteHeader = (headerKey: string) => {
emit("delete-header", headerKey)
}
</script>

View File

@@ -13,7 +13,10 @@
>
<component
:is="lensRendererFor(lens.renderer)"
:response="doc.response"
v-model:response="doc.response"
:is-savable="isSavable"
:is-editable="isEditable"
@save-as-example="$emit('save-as-example')"
/>
</HoppSmartTab>
<HoppSmartTab
@@ -23,9 +26,10 @@
:info="`${maybeHeaders.length}`"
class="flex flex-1 flex-col"
>
<LensesHeadersRenderer :headers="maybeHeaders" />
<LensesHeadersRenderer v-model="maybeHeaders" />
</HoppSmartTab>
<HoppSmartTab
v-if="!isEditable"
id="results"
:label="t('test.results')"
:indicator="showIndicator"
@@ -45,18 +49,24 @@ import {
} from "~/helpers/lenses/lenses"
import { useI18n } from "@composables/i18n"
import { useVModel } from "@vueuse/core"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
const props = defineProps<{
document: HoppRESTDocument
document: HoppRequestDocument
isEditable: boolean
}>()
const emit = defineEmits<{
(e: "update:document", document: HoppRESTDocument): void
(e: "update:document", document: HoppRequestDocument): void
(e: "save-as-example"): void
}>()
const doc = useVModel(props, "document", emit)
const isSavable = computed(() => {
return doc.value.response?.type === "success" && doc.value.saveContext
})
const showIndicator = computed(() => {
if (!doc.value.testResults) return false

View File

@@ -2,6 +2,7 @@
<div class="flex flex-1 flex-col">
<div
class="sticky top-lowerSecondaryStickyFold z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"
:class="{ 'py-2': !responseBodyText }"
>
<label class="truncate font-semibold text-secondaryLight">
{{ t("response.body") }}
@@ -33,6 +34,22 @@
:icon="downloadIcon"
@click="downloadResponse"
/>
<HoppButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
:title="
isSavable
? `${t(
'action.save_as_example'
)} <kbd>${getSpecialKey()}</kbd><kbd>E</kbd>`
: t('response.please_save_request')
"
:icon="IconSave"
:class="{
'opacity-75 cursor-not-allowed select-none': !isSavable,
}"
@click="isSavable ? saveAsExample() : null"
/>
<HoppButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
@@ -68,7 +85,7 @@ import {
useResponseBody,
} from "@composables/lens-actions"
import { useService } from "dioc/vue"
import { reactive, ref } from "vue"
import { reactive, ref, computed } from "vue"
import { useNestedSetting } from "~/composables/settings"
import { defineActionHandler } from "~/helpers/actions"
@@ -79,23 +96,44 @@ import { PersistenceService } from "~/services/persistence"
import IconEye from "~icons/lucide/eye"
import IconEyeOff from "~icons/lucide/eye-off"
import IconWrapText from "~icons/lucide/wrap-text"
import IconSave from "~icons/lucide/save"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
const t = useI18n()
const persistenceService = useService(PersistenceService)
const props = defineProps<{
response: HoppRESTResponse & { type: "success" | "fail" }
response:
| (HoppRESTResponse & { type: "success" | "fail" })
| HoppRESTRequestResponse
isSavable: boolean
isEditable: boolean
}>()
const emit = defineEmits<{
(e: "save-as-example"): void
}>()
const htmlResponse = ref<any | null>(null)
const WRAP_LINES = useNestedSetting("WRAP_LINES", "httpResponseBody")
const responseName = computed(() => {
if ("type" in props.response) {
if (props.response.type === "success" || props.response.type === "fail") {
return props.response.req.name
}
return "Untitled"
}
return props.response.name
})
const { responseBodyText } = useResponseBody(props.response)
const { downloadIcon, downloadResponse } = useDownloadResponse(
"text/html",
responseBodyText,
t("filename.lens", {
request_name: props.response.req.name,
request_name: responseName.value,
})
)
const defaultPreview =
@@ -116,13 +154,17 @@ const doTogglePreview = () => {
const { copyIcon, copyResponse } = useCopyResponse(responseBodyText)
const saveAsExample = () => {
emit("save-as-example")
}
useCodemirror(
htmlResponse,
responseBodyText,
reactive({
extendedEditorConfig: {
mode: "htmlmixed",
readOnly: true,
readOnly: !props.isEditable,
lineWrapping: WRAP_LINES,
},
linter: null,
@@ -134,6 +176,9 @@ useCodemirror(
defineActionHandler("response.preview.toggle", () => doTogglePreview())
defineActionHandler("response.file.download", () => downloadResponse())
defineActionHandler("response.copy", () => copyResponse())
defineActionHandler("response.save-as-example", () => {
props.isSavable ? saveAsExample() : null
})
</script>
<style lang="scss" scoped>

View File

@@ -1,17 +1,15 @@
<template>
<div
v-if="response.type === 'success' || response.type === 'fail'"
class="flex flex-1 flex-col"
>
<div v-if="showResponse" class="flex flex-1 flex-col">
<div
class="sticky top-lowerSecondaryStickyFold z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"
:class="{ 'py-2': !responseBodyText }"
>
<label class="truncate font-semibold text-secondaryLight">
{{ t("response.body") }}
</label>
<div class="flex items-center">
<HoppButtonSecondary
v-if="response.body"
v-if="showResponse"
v-tippy="{ theme: 'tooltip' }"
:title="t('state.linewrap')"
:class="{ '!text-accent': WRAP_LINES }"
@@ -19,7 +17,7 @@
@click.prevent="toggleNestedSetting('WRAP_LINES', 'httpResponseBody')"
/>
<HoppButtonSecondary
v-if="response.body"
v-if="showResponse"
v-tippy="{ theme: 'tooltip' }"
:title="t('action.filter')"
:icon="IconFilter"
@@ -27,7 +25,7 @@
@click.prevent="toggleFilterState"
/>
<HoppButtonSecondary
v-if="response.body"
v-if="showResponse"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
:title="`${t(
'action.download_file'
@@ -36,7 +34,23 @@
@click="downloadResponse"
/>
<HoppButtonSecondary
v-if="response.body"
v-if="showResponse && !isEditable"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
:title="
isSavable
? `${t(
'action.save_as_example'
)} <kbd>${getSpecialKey()}</kbd><kbd>E</kbd>`
: t('response.please_save_request')
"
:icon="IconSave"
:class="{
'opacity-75 cursor-not-allowed select-none': !isSavable,
}"
@click="isSavable ? saveAsExample() : null"
/>
<HoppButtonSecondary
v-if="showResponse"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
:title="`${t(
'action.copy'
@@ -45,7 +59,7 @@
@click="copyResponse"
/>
<tippy
v-if="response.body"
v-if="showResponse"
interactive
trigger="click"
theme="popover"
@@ -109,7 +123,7 @@
<span>{{ filterResponseError.error }}</span>
</div>
<HoppButtonSecondary
v-if="response.body"
v-if="showResponse"
v-tippy="{ theme: 'tooltip' }"
:title="t('app.wiki')"
:icon="IconHelpCircle"
@@ -234,6 +248,7 @@ import IconFilter from "~icons/lucide/filter"
import IconMore from "~icons/lucide/more-horizontal"
import IconHelpCircle from "~icons/lucide/help-circle"
import IconNetwork from "~icons/lucide/network"
import IconSave from "~icons/lucide/save"
import * as LJSON from "lossless-json"
import * as O from "fp-ts/Option"
import * as E from "fp-ts/Either"
@@ -258,14 +273,35 @@ import { defineActionHandler, invokeAction } from "~/helpers/actions"
import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"
import { useNestedSetting } from "~/composables/settings"
import { toggleNestedSetting } from "~/newstore/settings"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
const t = useI18n()
const props = defineProps<{
response: HoppRESTResponse
response: HoppRESTResponse | HoppRESTRequestResponse
isSavable: boolean
isEditable: boolean
}>()
const { responseBodyText } = useResponseBody(props.response)
const emit = defineEmits<{
(e: "save-as-example"): void
(e: "update:response", val: HoppRESTRequestResponse): void
}>()
const showResponse = computed(() => {
if ("type" in props.response) {
return props.response.type === "success" || props.response.type === "fail"
}
return "body" in props.response
})
const isHttpResponse = computed(() => {
return (
"type" in props.response &&
(props.response.type === "success" || props.response.type === "fail")
)
})
const toggleFilter = ref(false)
const filterQueryText = ref("")
@@ -274,18 +310,39 @@ type BodyParseError =
| { type: "JSON_PARSE_FAILED" }
| { type: "JSON_PATH_QUERY_FAILED"; error: Error }
const responseJsonObject = computed(() =>
pipe(
const responseJsonObject = computed(() => {
if (isHttpResponse.value) {
const { responseBodyText } = useResponseBody(
props.response as HoppRESTResponse
)
return pipe(
responseBodyText.value,
E.tryCatchK(
LJSON.parse,
(): BodyParseError => ({ type: "JSON_PARSE_FAILED" })
)
)
)
}
return undefined
})
const responseName = computed(() => {
if ("type" in props.response) {
if (props.response.type === "success") {
return props.response.req.name
}
return "Untitled"
}
return props.response.name
})
const { responseBodyText } = useResponseBody(props.response)
const jsonResponseBodyText = computed(() => {
if (filterQueryText.value.length > 0) {
if (filterQueryText.value.length > 0 && responseJsonObject.value) {
return pipe(
responseJsonObject.value,
E.chain((parsedJSON) =>
@@ -307,15 +364,19 @@ const jsonResponseBodyText = computed(() => {
return E.right(responseBodyText.value)
})
const jsonBodyText = computed(() =>
pipe(
const jsonBodyText = computed(() => {
const { responseBodyText } = useResponseBody(
props.response as HoppRESTResponse
)
return pipe(
jsonResponseBodyText.value,
E.getOrElse(() => responseBodyText.value),
O.tryCatchK(LJSON.parse),
O.map((val) => LJSON.stringify(val, undefined, 2)),
O.getOrElse(() => responseBodyText.value)
)
)
})
const ast = computed(() =>
pipe(
@@ -351,12 +412,16 @@ const filterResponseError = computed(() =>
)
)
const saveAsExample = () => {
emit("save-as-example")
}
const { copyIcon, copyResponse } = useCopyResponse(jsonBodyText)
const { downloadIcon, downloadResponse } = useDownloadResponse(
"application/json",
jsonBodyText,
t("filename.lens", {
request_name: props.response.req.name,
request_name: responseName.value,
})
)
@@ -372,12 +437,15 @@ const { cursor } = useCodemirror(
reactive({
extendedEditorConfig: {
mode: "application/ld+json",
readOnly: true,
readOnly: !props.isEditable,
lineWrapping: WRAP_LINES,
},
linter: null,
completer: null,
environmentHighlights: true,
onChange: (update: string) => {
emit("update:response", { ...props.response, body: update })
},
})
)
@@ -408,6 +476,9 @@ const toggleFilterState = () => {
defineActionHandler("response.file.download", () => downloadResponse())
defineActionHandler("response.copy", () => copyResponse())
defineActionHandler("response.save-as-example", () => {
props.isSavable ? saveAsExample() : null
})
</script>
<style lang="scss" scoped>

View File

@@ -1,7 +1,8 @@
<template>
<div class="flex flex-1 flex-col">
<div
class="sticky top-lowerSecondaryStickyFold z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"
class="sticky top-lowerSecondaryStickyFold z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4 py-1"
:class="{ 'py-2': !responseBodyText }"
>
<label class="truncate font-semibold text-secondaryLight">
{{ t("response.body") }}
@@ -24,6 +25,22 @@
:icon="downloadIcon"
@click="downloadResponse"
/>
<HoppButtonSecondary
v-if="showResponse && !isEditable"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
:title="
isSavable
? `${t(
'action.save_as_example'
)} <kbd>${getSpecialKey()}</kbd><kbd>E</kbd>`
: t('response.please_save_request')
"
:icon="IconSave"
:class="{
'opacity-75 cursor-not-allowed select-none': !isSavable,
}"
@click="isSavable ? saveAsExample() : null"
/>
<HoppButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
@@ -43,6 +60,7 @@
<script setup lang="ts">
import IconWrapText from "~icons/lucide/wrap-text"
import IconSave from "~icons/lucide/save"
import { ref, computed, reactive } from "vue"
import { flow, pipe } from "fp-ts/function"
import * as S from "fp-ts/string"
@@ -62,21 +80,53 @@ import { defineActionHandler } from "~/helpers/actions"
import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"
import { useNestedSetting } from "~/composables/settings"
import { toggleNestedSetting } from "~/newstore/settings"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
const t = useI18n()
const props = defineProps<{
response: HoppRESTResponse & { type: "success" | "fail" }
response:
| (HoppRESTResponse & { type: "success" | "fail" })
| HoppRESTRequestResponse
isEditable: boolean
isSavable: boolean
}>()
const emit = defineEmits<{
(
e: "update:response",
val:
| (HoppRESTResponse & { type: "success" | "fail" })
| HoppRESTRequestResponse
): void
(e: "save-as-example"): void
}>()
const { responseBodyText } = useResponseBody(props.response)
const isHttpResponse = computed(() => {
return (
"type" in props.response &&
(props.response.type === "success" || props.response.type === "fail")
)
})
const rawResponseBody = computed(() =>
props.response.type === "fail" || props.response.type === "success"
? props.response.body
: new ArrayBuffer(0)
isHttpResponse.value ? props.response.body : new ArrayBuffer(0)
)
const showResponse = computed(() => {
if ("type" in props.response) {
return props.response.type === "success" || props.response.type === "fail"
}
return "body" in props.response
})
const saveAsExample = () => {
emit("save-as-example")
}
const responseType = computed(() =>
pipe(
props.response,
@@ -93,11 +143,22 @@ const responseType = computed(() =>
)
)
const responseName = computed(() => {
if ("type" in props.response) {
if (props.response.type === "success" || props.response.type === "fail") {
return props.response.req.name
}
return "Untitled"
}
return props.response.name
})
const { downloadIcon, downloadResponse } = useDownloadResponse(
responseType.value,
rawResponseBody,
t("filename.lens", {
request_name: props.response.req.name,
request_name: responseName.value,
})
)
@@ -112,12 +173,15 @@ useCodemirror(
reactive({
extendedEditorConfig: {
mode: "text/plain",
readOnly: true,
readOnly: !props.isEditable,
lineWrapping: WRAP_LINES,
},
linter: null,
completer: null,
environmentHighlights: true,
onChange: (update: string) => {
emit("update:response", { ...props.response, body: update })
},
})
)

View File

@@ -24,6 +24,22 @@
:icon="downloadIcon"
@click="downloadResponse"
/>
<HoppButtonSecondary
v-if="response.body && !isEditable"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
:title="
isSavable
? `${t(
'action.save_as_example'
)} <kbd>${getSpecialKey()}</kbd><kbd>E</kbd>`
: t('response.please_save_request')
"
:icon="IconSave"
:class="{
'opacity-75 cursor-not-allowed select-none': !isSavable,
}"
@click="isSavable ? saveAsExample() : null"
/>
<HoppButtonSecondary
v-if="response.body"
v-tippy="{ theme: 'tooltip', allowHTML: true }"
@@ -43,6 +59,7 @@
<script setup lang="ts">
import IconWrapText from "~icons/lucide/wrap-text"
import IconSave from "~icons/lucide/save"
import { computed, ref, reactive } from "vue"
import { flow, pipe } from "fp-ts/function"
import * as S from "fp-ts/string"
@@ -62,17 +79,34 @@ import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"
import { objFieldMatches } from "~/helpers/functional/object"
import { useNestedSetting } from "~/composables/settings"
import { toggleNestedSetting } from "~/newstore/settings"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
const t = useI18n()
const props = defineProps<{
response: HoppRESTResponse & { type: "success" | "fail" }
response:
| (HoppRESTResponse & { type: "success" | "fail" })
| HoppRESTRequestResponse
isEditable: boolean
isSavable: boolean
}>()
const emit = defineEmits<{
(e: "save-as-example"): void
}>()
const { responseBodyText } = useResponseBody(props.response)
const responseType = computed(() =>
pipe(
const isHttpResponse = computed(() => {
return (
"type" in props.response &&
(props.response.type === "success" || props.response.type === "fail")
)
})
const responseType = computed(() => {
if (isHttpResponse.value) {
return pipe(
props.response,
O.fromPredicate(objFieldMatches("type", ["fail", "success"] as const)),
O.chain(
@@ -85,13 +119,27 @@ const responseType = computed(() =>
),
O.getOrElse(() => "text/plain")
)
)
}
return "text/plain"
})
const responseName = computed(() => {
if ("type" in props.response) {
if (props.response.type === "success") {
return props.response.req.name
}
return "Untitled"
}
return props.response.name
})
const { downloadIcon, downloadResponse } = useDownloadResponse(
responseType.value,
responseBodyText,
t("filename.lens", {
request_name: props.response.req.name,
request_name: responseName.value,
})
)
@@ -100,13 +148,17 @@ const { copyIcon, copyResponse } = useCopyResponse(responseBodyText)
const xmlResponse = ref<any | null>(null)
const WRAP_LINES = useNestedSetting("WRAP_LINES", "httpResponseBody")
const saveAsExample = () => {
emit("save-as-example")
}
useCodemirror(
xmlResponse,
responseBodyText,
reactive({
extendedEditorConfig: {
mode: "application/xml",
readOnly: true,
readOnly: !props.isEditable,
lineWrapping: WRAP_LINES,
},
linter: null,
@@ -117,4 +169,7 @@ useCodemirror(
defineActionHandler("response.file.download", () => downloadResponse())
defineActionHandler("response.copy", () => copyResponse())
defineActionHandler("response.save-as-example", () => {
props.isSavable ? saveAsExample() : null
})
</script>

View File

@@ -142,7 +142,7 @@ const parseRequest = computed(() =>
)
const requestLabelColor = computed(() =>
getMethodLabelColorClassOf(parseRequest.value)
getMethodLabelColorClassOf(parseRequest.value.method)
)
const customizeSharedRequest = () => {

View File

@@ -507,6 +507,7 @@ const openRequestInNewTab = (request: HoppRESTRequest) => {
restTab.createNewTab({
isDirty: false,
request,
type: "request",
})
}

View File

@@ -376,9 +376,15 @@ const envVars = computed(() => {
}
})
}
const requestVariables =
tabs.currentActiveTab.value.document.type === "example-response"
? tabs.currentActiveTab.value.document.response.originalRequest
.requestVariables
: tabs.currentActiveTab.value.document.request.requestVariables
return [
...tabs.currentActiveTab.value.document.request.requestVariables.map(
({ active, key, value }) =>
...requestVariables.map(({ active, key, value }) =>
active
? {
key,

View File

@@ -76,6 +76,7 @@ type CodeMirrorOptions = {
// callback on editor update
onUpdate?: (view: ViewUpdate) => void
onChange?: (value: string) => void
// callback on view initialization
onInit?: (view: EditorView) => void
@@ -337,8 +338,12 @@ export function useCodemirror(
cachedValue.value = update.state.doc
.toJSON()
.join(update.state.lineBreak)
if (!options.extendedEditorConfig.readOnly)
if (!options.extendedEditorConfig.readOnly) {
value.value = cachedValue.value
if (options.onChange) {
options.onChange(cachedValue.value)
}
}
}
}
}
@@ -415,6 +420,8 @@ export function useCodemirror(
doc: parseDoc(value.value, options.extendedEditorConfig.mode ?? ""),
extensions,
}),
// scroll to top when mounting
scrollTo: EditorView.scrollIntoView(0),
})
options.onInit?.(view.value)

View File

@@ -10,6 +10,7 @@ import IconCopy from "~icons/lucide/copy"
import IconDownload from "~icons/lucide/download"
import { useI18n } from "./i18n"
import { useToast } from "./toast"
import { HoppRESTRequestResponse } from "@hoppscotch/data"
export function useCopyInterface(responseBodyText: Ref<string>) {
const toast = useToast()
@@ -140,10 +141,13 @@ export function usePreview(
}
}
export function useResponseBody(response: HoppRESTResponse): {
export function useResponseBody(
response: HoppRESTResponse | HoppRESTRequestResponse
): {
responseBodyText: ComputedRef<string>
} {
const responseBodyText = computed(() => {
if ("type" in response) {
if (
response.type === "loading" ||
response.type === "network_fail" ||
@@ -152,6 +156,7 @@ export function useResponseBody(response: HoppRESTResponse): {
response.type === "extension_error"
)
return ""
}
return getResponseBodyText(response.body)
})
return {
@@ -159,7 +164,7 @@ export function useResponseBody(response: HoppRESTResponse): {
}
}
export function getResponseBodyText(body: ArrayBuffer): string {
export function getResponseBodyText(body: ArrayBuffer | string): string {
if (typeof body === "string") return body
const res = new TextDecoder("utf-8").decode(body)

View File

@@ -29,7 +29,7 @@ import {
getCombinedEnvVariables,
getFinalEnvsFromPreRequest,
} from "./preRequest"
import { HoppRESTDocument } from "./rest/document"
import { HoppRequestDocument } from "./rest/document"
import { HoppRESTResponse } from "./types/HoppRESTResponse"
import { HoppTestData, HoppTestResult } from "./types/HoppTestResult"
import { getEffectiveRESTRequest } from "./utils/EffectiveURL"
@@ -166,7 +166,7 @@ const filterNonEmptyEnvironmentVariables = (
}
export function runRESTRequest$(
tab: Ref<HoppTab<HoppRESTDocument>>
tab: Ref<HoppTab<HoppRequestDocument>>
): [
() => void,
Promise<

View File

@@ -4,7 +4,7 @@
import { Ref, onBeforeUnmount, onMounted, reactive, watch } from "vue"
import { BehaviorSubject } from "rxjs"
import { HoppRESTDocument } from "./rest/document"
import { HoppRequestDocument } from "./rest/document"
import { Environment, HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"
import { RESTOptionTabs } from "~/components/http/RequestOptions.vue"
import { HoppGQLSaveContext } from "./graphql/document"
@@ -16,7 +16,7 @@ export type HoppAction =
| "request.send-cancel" // Send/Cancel a Hoppscotch Request
| "request.reset" // Clear request data
| "request.share-request" // Share Request
| "request.save" // Save to Collections
| "request-response.save" // Save Request or Response
| "request.save-as" // Save As
| "request.rename" // Rename request on REST or GraphQL
| "request.method.next" // Select Next Method
@@ -64,6 +64,8 @@ export type HoppAction =
| "response.schema.toggle" // Toggle response data schema
| "response.file.download" // Download response as file
| "response.copy" // Copy response to clipboard
| "response.save" // Save response
| "response.save-as-example" // Save response as example
| "modals.login.toggle" // Login to Hoppscotch
| "history.clear" // Clear REST History
| "user.login" // Login to Hoppscotch
@@ -117,12 +119,12 @@ type HoppActionArgsMap = {
teamId: string
}
"rest.request.open": {
doc: HoppRESTDocument
doc: HoppRequestDocument
}
"request.save-as":
| {
requestType: "rest"
request: HoppRESTRequest
request: HoppRESTRequest | null
}
| {
requestType: "gql"

View File

@@ -186,6 +186,8 @@ export function updateInheritedPropertiesForAffectedRequests(
})
effectedTabs.map((tab) => {
if (!("inheritedProperties" in tab.value.document)) return
const inheritedParentID =
tab.value.document.inheritedProperties?.auth.parentID
@@ -239,6 +241,13 @@ function resetSaveContextForAffectedRequests(folderPath: string) {
for (const tab of tabs) {
tab.value.document.saveContext = null
tab.value.document.isDirty = true
if (tab.value.document.type === "request") {
// since the request is deleted, we need to remove the saved responses as well
tab.value.document.request.responses = {}
}
//
}
}
@@ -265,6 +274,11 @@ export async function resetTeamRequestsContext() {
if (E.isRight(data) && data.right.request === null) {
tab.value.document.saveContext = null
tab.value.document.isDirty = true
if (tab.value.document.type === "request") {
// since the request is deleted, we need to remove the saved responses as well
tab.value.document.request.responses = {}
}
}
}
}

View File

@@ -2,6 +2,7 @@ import {
HoppCollection,
HoppGQLRequest,
HoppRESTRequest,
RESTReqSchemaVersion,
} from "@hoppscotch/data"
import { getAffectedIndexes } from "./affectedIndex"
import { RESTTabService } from "~/services/tab/rest"
@@ -67,7 +68,7 @@ export function getRequestsByPath(
if (pathArray.length === 1) {
const latestVersionedRequests = currentCollection.requests.filter(
(req): req is HoppRESTRequest => req.v === "3"
(req): req is HoppRESTRequest => req.v === RESTReqSchemaVersion
)
return latestVersionedRequests
@@ -78,7 +79,7 @@ export function getRequestsByPath(
}
const latestVersionedRequests = currentCollection.requests.filter(
(req): req is HoppRESTRequest => req.v === "3"
(req): req is HoppRESTRequest => req.v === RESTReqSchemaVersion
)
return latestVersionedRequests

View File

@@ -39,6 +39,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -149,6 +150,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -167,6 +169,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -192,6 +195,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -223,6 +227,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -254,6 +259,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -285,6 +291,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -309,6 +316,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -331,6 +339,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -355,6 +364,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -389,6 +399,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -459,6 +470,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -488,6 +500,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -552,6 +565,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -600,6 +614,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -650,6 +665,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -665,6 +681,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -690,6 +707,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -708,6 +726,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -733,6 +752,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -751,6 +771,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -776,6 +797,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -799,6 +821,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -820,6 +843,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -842,6 +866,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -863,6 +888,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -895,6 +921,7 @@ const samples = [
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
{
@@ -928,6 +955,7 @@ data2: {"type":"test2","typeId":"123"}`,
preRequestScript: "",
testScript: "",
requestVariables: [],
responses: {},
}),
},
]

View File

@@ -202,5 +202,6 @@ export const parseCurlCommand = (curlCommand: string) => {
auth,
body: finalBody,
requestVariables: defaultRESTReq.requestVariables,
responses: {},
})
}

View File

@@ -265,8 +265,13 @@ export class HoppEnvironmentPlugin {
const aggregateEnvs = getAggregateEnvs()
const currentTab = restTabs.currentActiveTab.value
const currentTabRequest =
currentTab.document.type === "request"
? currentTab.document.request
: currentTab.document.response.originalRequest
watch(
currentTab.document.request,
currentTabRequest,
(reqVariables) => {
this.envs = [
...reqVariables.requestVariables.map(({ key, value }) => ({
@@ -290,14 +295,12 @@ export class HoppEnvironmentPlugin {
subscribeToStream(aggregateEnvsWithSecrets$, (envs) => {
this.envs = [
...currentTab.document.request.requestVariables.map(
({ key, value }) => ({
...currentTabRequest.requestVariables.map(({ key, value }) => ({
key,
value,
sourceEnv: "RequestVariable",
secret: false,
})
),
})),
...envs,
]

View File

@@ -1,4 +1,4 @@
export default function (responseStatus) {
export default function (responseStatus: number) {
if (responseStatus >= 100 && responseStatus < 200)
return {
name: "informational",

View File

@@ -230,6 +230,9 @@ const getHoppRequest = (req: InsomniaRequestResource): HoppRESTRequest =>
testScript: "",
requestVariables: getHoppReqVariables(req),
//insomnia doesn't have saved response
responses: {},
})
const getHoppFolder = (

View File

@@ -18,6 +18,8 @@ import {
makeCollection,
HoppRESTRequestVariable,
HoppRESTRequest,
HoppRESTRequestResponses,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import { pipe, flow } from "fp-ts/function"
import * as A from "fp-ts/Array"
@@ -26,7 +28,8 @@ import * as O from "fp-ts/Option"
import * as TE from "fp-ts/TaskEither"
import * as RA from "fp-ts/ReadonlyArray"
import { IMPORTER_INVALID_FILE_FORMAT } from "."
import { cloneDeep } from "lodash-es"
import { cloneDeep, isNumber } from "lodash-es"
import { getStatusCodeReasonPhrase } from "~/helpers/utils/statusCodes"
export const OPENAPI_DEREF_ERROR = "openapi/deref_error" as const
@@ -107,6 +110,105 @@ const parseOpenAPIVariables = (
)
)
const parseOpenAPIV3Responses = (
op: OpenAPIV3.OperationObject | OpenAPIV31.OperationObject,
originalRequest: HoppRESTResponseOriginalRequest
): HoppRESTRequestResponses => {
const responses = op.responses
if (!responses) return {}
const res: HoppRESTRequestResponses = {}
for (const [key, value] of Object.entries(responses)) {
const response = value as
| OpenAPIV3.ResponseObject
| OpenAPIV31.ResponseObject
// add support for schema key as well
const contentType = Object.keys(response.content ?? {})[0]
const body = response.content?.[contentType]
const name = response.description ?? key
const code = isNumber(key) ? Number(key) : 200
const status = getStatusCodeReasonPhrase(code)
const headers: HoppRESTHeader[] = [
{
key: "content-type",
value: contentType ?? "application/json",
description: "",
active: true,
},
]
res[name] = {
name,
status,
code,
headers,
body: JSON.stringify(body ?? ""),
originalRequest,
}
}
return res
}
const parseOpenAPIV2Responses = (
op: OpenAPIV2.OperationObject,
originalRequest: HoppRESTResponseOriginalRequest
): HoppRESTRequestResponses => {
const responses = op.responses
if (!responses) return {}
const res: HoppRESTRequestResponses = {}
for (const [key, value] of Object.entries(responses)) {
const response = value as OpenAPIV2.ResponseObject
// add support for schema key as well
const contentType = Object.keys(response.examples ?? {})[0]
const body = response.examples?.[contentType]
const name = response.description ?? key
const code = isNumber(Number(key)) ? Number(key) : 200
const status = getStatusCodeReasonPhrase(code)
const headers: HoppRESTHeader[] = [
{
key: "content-type",
value: contentType ?? "application/json",
description: "",
active: true,
},
]
res[name] = {
name,
status,
code,
headers,
body: body ?? "",
originalRequest,
}
}
return res
}
const parseOpenAPIResponses = (
doc: OpenAPI.Document,
op: OpenAPIOperationType,
originalRequest: HoppRESTResponseOriginalRequest
): HoppRESTRequestResponses =>
isOpenAPIV3Operation(doc, op)
? parseOpenAPIV3Responses(op, originalRequest)
: parseOpenAPIV2Responses(op, originalRequest)
const parseOpenAPIHeaders = (params: OpenAPIParamsType[]): HoppRESTHeader[] =>
pipe(
params,
@@ -657,6 +759,25 @@ const convertPathToHoppReqs = (
requestVariables: parseOpenAPIVariables(
(info.parameters as OpenAPIParamsType[] | undefined) ?? []
),
responses: parseOpenAPIResponses(doc, info, {
name: info.operationId ?? info.summary ?? "Untitled Request",
auth: parseOpenAPIAuth(doc, info),
body: parseOpenAPIBody(doc, info),
endpoint,
// We don't need to worry about reference types as the Dereferencing pass should remove them
params: parseOpenAPIParams(
(info.parameters as OpenAPIParamsType[] | undefined) ?? []
),
headers: parseOpenAPIHeaders(
(info.parameters as OpenAPIParamsType[] | undefined) ?? []
),
method: method.toUpperCase(),
requestVariables: parseOpenAPIVariables(
(info.parameters as OpenAPIParamsType[] | undefined) ?? []
),
v: "1",
}),
}),
metadata: {
tags: info.tags ?? [],

View File

@@ -30,6 +30,7 @@ import {
import { stringArrayJoin } from "~/helpers/functional/array"
import { PMRawLanguage } from "~/types/pm-coll-exts"
import { IMPORTER_INVALID_FILE_FORMAT } from "."
import { HoppRESTRequestResponses } from "@hoppscotch/data/dist/rest/v/8"
const safeParseJSON = (jsonStr: string) => O.tryCatch(() => JSON.parse(jsonStr))
@@ -77,9 +78,12 @@ const parseDescription = (descField?: string | DescriptionDefinition) => {
return descField.content
}
const getHoppReqHeaders = (item: Item): HoppRESTHeader[] =>
pipe(
item.request.headers.all(),
const getHoppReqHeaders = (
headers: Item["request"]["headers"] | null
): HoppRESTHeader[] => {
if (!headers) return []
return pipe(
headers.all(),
A.map((header) => {
const description = parseDescription(header.description)
@@ -91,10 +95,15 @@ const getHoppReqHeaders = (item: Item): HoppRESTHeader[] =>
}
})
)
}
const getHoppReqParams = (item: Item): HoppRESTParam[] => {
const getHoppReqParams = (
query: Item["request"]["url"]["query"] | null
): HoppRESTParam[] => {
{
if (!query) return []
return pipe(
item.request.url.query.all(),
query.all(),
A.filter(
(param): param is QueryParam & { key: string } =>
param.key !== undefined && param.key !== null && param.key.length > 0
@@ -110,11 +119,16 @@ const getHoppReqParams = (item: Item): HoppRESTParam[] => {
}
})
)
}
}
const getHoppReqVariables = (item: Item) => {
const getHoppReqVariables = (
variables: Item["request"]["url"]["variables"] | null
): HoppRESTRequestVariable[] => {
{
if (!variables) return []
return pipe(
item.request.url.variables.all(),
variables.all(),
A.filter(
(variable): variable is Variable =>
variable.key !== undefined &&
@@ -129,6 +143,47 @@ const getHoppReqVariables = (item: Item) => {
}
})
)
}
}
const getHoppResponses = (
responses: Item["responses"]
): HoppRESTRequestResponses => {
return Object.fromEntries(
pipe(
responses.all(),
A.map((response) => {
const res = {
name: response.name,
status: response.status,
body: response.body ?? "",
headers: getHoppReqHeaders(response.headers),
code: response.code,
originalRequest: {
auth: getHoppReqAuth(response.originalRequest?.auth),
body: getHoppReqBody({
body: response.originalRequest?.body,
headers: response.originalRequest?.headers ?? null,
}) ?? { contentType: null, body: null },
endpoint: getHoppReqURL(response.originalRequest?.url ?? null),
headers: getHoppReqHeaders(
response.originalRequest?.headers ?? null
),
method: response.originalRequest?.method ?? "",
name: response.originalRequest?.name ?? response.name,
params: getHoppReqParams(
response.originalRequest?.url.query ?? null
),
requestVariables: getHoppReqVariables(
response.originalRequest?.url.variables ?? null
),
v: "1" as const,
},
}
return [response.name, res]
})
)
)
}
type PMRequestAuthDef<
@@ -142,11 +197,11 @@ type PMRequestAuthDef<
const getVariableValue = (defs: VariableDefinition[], key: string) =>
defs.find((param) => param.key === key)?.value as string | undefined
const getHoppReqAuth = (item: Item): HoppRESTAuth => {
if (!item.request.auth) return { authType: "none", authActive: true }
const getHoppReqAuth = (hoppAuth: Item["request"]["auth"]): HoppRESTAuth => {
if (!hoppAuth) return { authType: "none", authActive: true }
// Cast to the type for more stricter checking down the line
const auth = item.request.auth as unknown as PMRequestAuthDef
const auth = hoppAuth as unknown as PMRequestAuthDef
if (auth.type === "basic") {
return {
@@ -217,10 +272,14 @@ const getHoppReqAuth = (item: Item): HoppRESTAuth => {
return { authType: "none", authActive: true }
}
const getHoppReqBody = (item: Item): HoppRESTReqBody => {
if (!item.request.body) return { contentType: null, body: null }
const body = item.request.body
const getHoppReqBody = ({
body,
headers,
}: {
body: Item["request"]["body"] | null
headers: Item["request"]["headers"] | null
}): HoppRESTReqBody => {
if (!body) return { contentType: null, body: null }
if (body.mode === "formdata") {
return {
@@ -262,7 +321,7 @@ const getHoppReqBody = (item: Item): HoppRESTReqBody => {
O.bind("contentType", () =>
pipe(
// Get the info from the content-type header
getHoppReqHeaders(item),
getHoppReqHeaders(headers),
A.findFirst(({ key }) => key.toLowerCase() === "content-type"),
O.map((x) => x.value),
@@ -315,23 +374,29 @@ const getHoppReqBody = (item: Item): HoppRESTReqBody => {
return { contentType: null, body: null }
}
const getHoppReqURL = (item: Item): string =>
pipe(
item.request.url.toString(false),
const getHoppReqURL = (url: Item["request"]["url"] | null): string => {
if (!url) return ""
return pipe(
url.toString(false),
S.replace(/\?.+/g, ""),
replacePMVarTemplating
)
}
const getHoppRequest = (item: Item): HoppRESTRequest => {
return makeRESTRequest({
name: item.name,
endpoint: getHoppReqURL(item),
endpoint: getHoppReqURL(item.request.url),
method: item.request.method.toUpperCase(),
headers: getHoppReqHeaders(item),
params: getHoppReqParams(item),
auth: getHoppReqAuth(item),
body: getHoppReqBody(item),
requestVariables: getHoppReqVariables(item),
headers: getHoppReqHeaders(item.request.headers),
params: getHoppReqParams(item.request.url.query),
auth: getHoppReqAuth(item.request.auth),
body: getHoppReqBody({
body: item.request.body,
headers: item.request.headers,
}),
requestVariables: getHoppReqVariables(item.request.url.variables),
responses: getHoppResponses(item.responses),
// TODO: Decide about this
preRequestScript: "",

View File

@@ -45,7 +45,7 @@ export const bindings: {
"ctrl-enter": "request.send-cancel",
"ctrl-i": "request.reset",
"ctrl-u": "request.share-request",
"ctrl-s": "request.save",
"ctrl-s": "request-response.save",
"ctrl-shift-s": "request.save-as",
"alt-up": "request.method.next",
"alt-down": "request.method.prev",
@@ -67,6 +67,7 @@ export const bindings: {
"ctrl-shift-p": "response.preview.toggle",
"ctrl-j": "response.file.download",
"ctrl-.": "response.copy",
"ctrl-e": "response.save-as-example",
"ctrl-shift-l": "editor.format",
}

View File

@@ -18,4 +18,5 @@ export const getDefaultRESTRequest = (): HoppRESTRequest => ({
body: null,
},
requestVariables: [],
responses: {},
})

View File

@@ -1,4 +1,4 @@
import { HoppRESTRequest } from "@hoppscotch/data"
import { HoppRESTRequest, HoppRESTRequestResponse } from "@hoppscotch/data"
import { HoppRESTResponse } from "../types/HoppRESTResponse"
import { HoppTestResult } from "../types/HoppTestResult"
import { RESTOptionTabs } from "~/components/http/RequestOptions.vue"
@@ -18,6 +18,10 @@ export type HoppRESTSaveContext =
* Index to the request
*/
requestIndex: number
/**
* ID of the example response
*/
exampleID?: string
}
| {
/**
@@ -36,13 +40,22 @@ export type HoppRESTSaveContext =
* ID of the collection loaded
*/
collectionID?: string
/**
* ID of the example response
*/
exampleID?: string
}
| null
/**
* Defines a live 'document' (something that is open and being edited) in the app
*/
export type HoppRESTDocument = {
export type HoppRequestDocument = {
/**
* The type of the document
*/
type: "request"
/**
* The request as it is in the document
*/
@@ -93,3 +106,32 @@ export type HoppRESTDocument = {
*/
cancelFunction?: () => void
}
export type HoppSavedExampleDocument = {
/**
* The type of the document
*/
type: "example-response"
/**
* The response as it is in the document
*/
response: HoppRESTRequestResponse
/**
* Info about where this response should be saved.
* This contains where the response is originated from basically.
*/
saveContext?: HoppRESTSaveContext
/**
* Whether the response has any unsaved changes
* (atleast as far as we can say)
*/
isDirty: boolean
}
/**
* Defines a live 'document' (something that is open and being edited) in the app
*/
export type HoppTabDocument = HoppSavedExampleDocument | HoppRequestDocument

View File

@@ -1,7 +1,6 @@
import { pipe } from "fp-ts/function"
import * as O from "fp-ts/Option"
import * as RR from "fp-ts/ReadonlyRecord"
import { HoppRESTRequest } from "@hoppscotch/data"
export const REQUEST_METHOD_LABEL_COLORS = {
get: "var(--method-get-color)",
@@ -16,13 +15,13 @@ export const REQUEST_METHOD_LABEL_COLORS = {
/**
* Returns the label color tailwind class for a request
* @param request The HoppRESTRequest object to get the value for
* @param method The HTTP VERB of the request
* @returns The class value for the given HTTP VERB, if not, a generic verb class
*/
export function getMethodLabelColorClassOf(request: HoppRESTRequest) {
export function getMethodLabelColorClassOf(method: string) {
return pipe(
REQUEST_METHOD_LABEL_COLORS,
RR.lookup(request.method.toLowerCase()),
RR.lookup(method.toLowerCase()),
O.getOrElseW(() => REQUEST_METHOD_LABEL_COLORS.default)
)
}

View File

@@ -1,6 +1,7 @@
import { HoppRESTRequest } from "@hoppscotch/data"
import { runGQLQuery } from "../backend/GQLClient"
import {
GetCollectionChildrenDocument,
GetCollectionRequestsDocument,
GetSingleRequestDocument,
} from "../backend/graphql"
@@ -30,3 +31,11 @@ export const getSingleRequest = (requestID: string) =>
requestID,
},
})
export const getCollectionChildCollections = (collectionID: string) =>
runGQLQuery({
query: GetCollectionChildrenDocument,
variables: {
collectionID,
},
})

View File

@@ -16,6 +16,7 @@ import {
getSingleRequest,
getCollectionChildRequests,
TeamRequest,
getCollectionChildCollections,
} from "./TeamRequest"
type CollectionSearchMeta = {

View File

@@ -99,3 +99,38 @@ export function getStatusCodeReasonPhrase(
return statusCodes[code] ?? "Unknown"
}
// return the status code like
// code • status
export const getFullStatusCodePhrase = () => {
return Object.keys(statusCodes).map((code) => {
return `${code}${statusCodes[code]}`
})
}
// return all status codes and their phrases
// like code • phrase
export const getStatusCodePhrase = (
code: number | undefined,
statusText: string
) => {
if (!code) return statusText
return `${code}${getStatusCodeReasonPhrase(code, statusText)}`
}
// return the status code and status
// like { code, status }
export const getStatusAndCode = (status: string) => {
const statusAndCode = status.split(" • ")
return {
code: Number(statusAndCode[0]),
status: statusAndCode[1],
}
}
// check if the status code is valid
export const isValidStatusCode = (status: string) => {
const allPhrases = getFullStatusCodePhrase()
return allPhrases.includes(status)
}

View File

@@ -355,6 +355,7 @@ executedResponses$.subscribe((res) => {
testScript: res.req.testScript,
requestVariables: res.req.requestVariables,
v: res.req.v,
responses: res.req.responses,
},
responseMeta: {
duration: res.meta.responseDuration,

View File

@@ -46,7 +46,7 @@ import {
safelyExtractRESTRequest,
} from "@hoppscotch/data"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
import { applySetting } from "~/newstore/settings"
import { useI18n } from "~/composables/i18n"
@@ -69,12 +69,13 @@ const sharedRequestDetails = useGQLQuery<
},
})
const tab = ref<HoppTab<HoppRESTDocument>>({
const tab = ref<HoppTab<HoppRequestDocument>>({
id: "0",
document: {
request: getDefaultRESTRequest(),
response: null,
isDirty: false,
type: "request",
},
})

View File

@@ -14,7 +14,7 @@
v-for="tab in activeTabs"
:id="tab.id"
:key="tab.id"
:label="tab.document.request.name"
:label="getTabName(tab)"
:is-removable="activeTabs.length > 1"
:close-visibility="'hover'"
>
@@ -45,6 +45,12 @@
</span>
</template>
<HttpRequestTab
v-if="tab.document.type === 'request'"
:model-value="tab"
@update:model-value="onTabUpdate"
/>
<HttpExampleResponseTab
v-else-if="tab.document.type === 'example-response'"
:model-value="tab"
@update:model-value="onTabUpdate"
/>
@@ -136,7 +142,7 @@ import { ResponseInspectorService } from "~/services/inspection/inspectors/respo
import { cloneDeep } from "lodash-es"
import { RESTTabService } from "~/services/tab/rest"
import { HoppTab } from "~/services/tab"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument, HoppTabDocument } from "~/helpers/rest/document"
const savingRequest = ref(false)
const confirmingCloseForTabID = ref<string | null>(null)
@@ -187,6 +193,8 @@ function bindRequestToURLParams() {
// We skip URL params parsing
if (Object.keys(query).length === 0 || query.code || query.error) return
if (tabs.currentActiveTab.value.document.type !== "request") return
const request = tabs.currentActiveTab.value.document.request
tabs.currentActiveTab.value.document.request = safelyExtractRESTRequest(
@@ -196,7 +204,7 @@ function bindRequestToURLParams() {
})
}
const onTabUpdate = (tab: HoppTab<HoppRESTDocument>) => {
const onTabUpdate = (tab: HoppTab<HoppRequestDocument>) => {
tabs.updateTab(tab)
}
@@ -204,6 +212,7 @@ const addNewTab = () => {
const tab = tabs.createNewTab({
request: getDefaultRESTRequest(),
isDirty: false,
type: "request",
})
tabs.setActiveTab(tab.id)
@@ -243,10 +252,11 @@ const closeOtherTabsAction = (tabID: string) => {
const duplicateTab = (tabID: string) => {
const tab = tabs.getTabRef(tabID)
if (tab.value) {
if (tab.value && tab.value.document.type === "request") {
const newTab = tabs.createNewTab({
request: cloneDeep(tab.value.document.request),
isDirty: true,
type: "request",
})
tabs.setActiveTab(newTab.id)
}
@@ -257,20 +267,33 @@ const onResolveConfirmCloseAllTabs = () => {
confirmingCloseAllTabs.value = false
}
const getTabName = (tab: HoppTab<HoppTabDocument>) => {
if (tab.document.type === "request") {
return tab.document.request.name
} else if (tab.document.type === "example-response") {
return tab.document.response.name
}
}
const requestToRename = computed(() => {
if (!renameTabID.value) return null
const tab = tabs.getTabRef(renameTabID.value)
return tab.value.document.request
return getTabName(tab.value)
})
const openReqRenameModal = (tabID?: string) => {
if (tabID) {
const tab = tabs.getTabRef(tabID)
if (tab.value.document.type !== "request") return
reqName.value = tab.value.document.request.name
renameTabID.value = tabID
} else {
const { id, document } = tabs.currentActiveTab.value
if (document.type !== "request") return
reqName.value = document.request.name
renameTabID.value = id
}
@@ -279,7 +302,7 @@ const openReqRenameModal = (tabID?: string) => {
const renameReqName = () => {
const tab = tabs.getTabRef(renameTabID.value ?? currentTabID.value)
if (tab.value) {
if (tab.value && tab.value.document.type === "request") {
tab.value.document.request.name = reqName.value
tabs.updateTab(tab.value)
}
@@ -302,7 +325,7 @@ const onCloseConfirmSaveTab = () => {
*/
const onResolveConfirmSaveTab = () => {
if (tabs.currentActiveTab.value.document.saveContext) {
invokeAction("request.save")
invokeAction("request-response.save")
if (confirmingCloseForTabID.value) {
tabs.closeTab(confirmingCloseForTabID.value)
@@ -326,7 +349,7 @@ const onSaveModalClose = () => {
const shareTabRequest = (tabID: string) => {
const tab = tabs.getTabRef(tabID)
if (tab.value) {
if (tab.value && tab.value.document.type === "request") {
if (currentUser.value) {
invokeAction("share.request", {
request: tab.value.document.request,

View File

@@ -138,6 +138,7 @@ const addRequestToTab = () => {
tabs.createNewTab({
request: safelyExtractRESTRequest(request, getDefaultRESTRequest()),
isDirty: false,
type: "request",
})
router.push({ path: "/" })

View File

@@ -76,6 +76,7 @@ describe("URLMenuService", () => {
expect(createNewTabFn).toHaveBeenCalledWith({
request: request,
isDirty: false,
type: "request",
})
})
})

View File

@@ -89,21 +89,25 @@ export class ParameterMenuService extends Service implements ContextMenu {
const tabService = getService(RESTTabService)
const currentActiveRequest =
tabService.currentActiveTab.value.document.type === "request"
? tabService.currentActiveTab.value.document.request
: tabService.currentActiveTab.value.document.response.originalRequest
// add the parameters to the current request parameters
tabService.currentActiveTab.value.document.request.params = [
...tabService.currentActiveTab.value.document.request.params,
currentActiveRequest.params = [
...currentActiveRequest.params,
...queryParams.map((param) => ({ ...param, description: "" })),
]
if (newURL) {
tabService.currentActiveTab.value.document.request.endpoint = newURL
currentActiveRequest.endpoint = newURL
} else {
// remove the parameter from the URL
const textRegex = new RegExp(`\\b${text.replace(/\?/g, "")}\\b`, "gi")
const sanitizedWord =
tabService.currentActiveTab.value.document.request.endpoint
const sanitizedWord = currentActiveRequest.endpoint
const newURL = sanitizedWord.replace(textRegex, "")
tabService.currentActiveTab.value.document.request.endpoint = newURL
currentActiveRequest.endpoint = newURL
}
}

View File

@@ -57,6 +57,7 @@ export class URLMenuService extends Service implements ContextMenu {
this.restTab.createNewTab({
request: request,
isDirty: false,
type: "request",
})
}

View File

@@ -1,4 +1,7 @@
import { HoppRESTRequest } from "@hoppscotch/data"
import {
HoppRESTRequest,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import { refDebounced } from "@vueuse/core"
import { Service } from "dioc"
import { computed, markRaw, reactive } from "vue"
@@ -89,7 +92,7 @@ export interface Inspector {
* @returns The ref to the inspector results
*/
getInspections: (
req: Readonly<Ref<HoppRESTRequest>>,
req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>,
res: Readonly<Ref<HoppRESTResponse | null | undefined>>
) => Ref<InspectorResult[]>
}
@@ -124,13 +127,22 @@ export class InspectionService extends Service {
watch(
() => [this.inspectors.entries(), this.restTab.currentActiveTab.value.id],
() => {
const reqRef = computed(
() => this.restTab.currentActiveTab.value.document.request
const currentTabRequest = computed(() =>
this.restTab.currentActiveTab.value.document.type === "request"
? this.restTab.currentActiveTab.value.document.request
: this.restTab.currentActiveTab.value.document.response
.originalRequest
)
const resRef = computed(
() => this.restTab.currentActiveTab.value.document.response
const currentTabResponse = computed(() =>
this.restTab.currentActiveTab.value.document.type === "request"
? this.restTab.currentActiveTab.value.document.response
: null
)
const reqRef = computed(() => currentTabRequest.value)
const resRef = computed(() => currentTabResponse.value)
const debouncedReq = refDebounced(reqRef, 1000, { maxWait: 2000 })
const debouncedRes = refDebounced(resRef, 1000, { maxWait: 2000 })

View File

@@ -8,7 +8,10 @@ import {
import { Service } from "dioc"
import { Ref, markRaw } from "vue"
import IconPlusCircle from "~icons/lucide/plus-circle"
import { HoppRESTRequest } from "@hoppscotch/data"
import {
HoppRESTRequest,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import {
AggregateEnvironment,
aggregateEnvsWithSecrets$,
@@ -71,8 +74,13 @@ export class EnvironmentInspectorService extends Service implements Inspector {
const currentTab = this.restTabs.currentActiveTab.value
const currentTabRequest =
currentTab.document.type === "request"
? currentTab.document.request
: currentTab.document.response.originalRequest
const environmentVariables = [
...currentTab.document.request.requestVariables,
...currentTabRequest.requestVariables,
...this.aggregateEnvsWithSecrets.value,
]
@@ -180,9 +188,14 @@ export class EnvironmentInspectorService extends Service implements Inspector {
const currentTab = this.restTabs.currentActiveTab.value
const currentTabRequest =
currentTab.document.type === "request"
? currentTab.document.request
: currentTab.document.response.originalRequest
const environmentVariables =
this.filterNonEmptyEnvironmentVariables([
...currentTab.document.request.requestVariables.map((env) => ({
...currentTabRequest.requestVariables.map((env) => ({
...env,
secret: false,
sourceEnv: "RequestVariable",
@@ -244,7 +257,10 @@ export class EnvironmentInspectorService extends Service implements Inspector {
"inspections.environment.add_environment_value"
),
apply: () => {
if (env.sourceEnv === "RequestVariable") {
if (
env.sourceEnv === "RequestVariable" &&
currentTab.document.type === "request"
) {
currentTab.document.optionTabPreference =
"requestVariables"
} else {
@@ -278,7 +294,9 @@ export class EnvironmentInspectorService extends Service implements Inspector {
return newErrors
}
getInspections(req: Readonly<Ref<HoppRESTRequest>>) {
getInspections(
req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>
) {
return computed(() => {
const results: InspectorResult[] = []

View File

@@ -1,7 +1,10 @@
import { Service } from "dioc"
import { InspectionService, Inspector, InspectorResult } from ".."
import { getI18n } from "~/modules/i18n"
import { HoppRESTRequest } from "@hoppscotch/data"
import {
HoppRESTRequest,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import { Ref, computed, markRaw } from "vue"
import IconAlertTriangle from "~icons/lucide/alert-triangle"
import { InterceptorService } from "~/services/interceptor.service"
@@ -32,10 +35,11 @@ export class HeaderInspectorService extends Service implements Inspector {
return cookieKeywords.includes(headerKey)
}
getInspections(req: Readonly<Ref<HoppRESTRequest>>) {
getInspections(
req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>
) {
return computed(() => {
const results: InspectorResult[] = []
const headers = req.value.headers
const headerKeys = Object.values(headers).map((header) => header.key)

View File

@@ -1,7 +1,10 @@
import { Service } from "dioc"
import { InspectionService, Inspector, InspectorResult } from ".."
import { getI18n } from "~/modules/i18n"
import { HoppRESTRequest } from "@hoppscotch/data"
import {
HoppRESTRequest,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import { markRaw } from "vue"
import IconAlertTriangle from "~icons/lucide/alert-triangle"
import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"
@@ -28,7 +31,7 @@ export class ResponseInspectorService extends Service implements Inspector {
}
getInspections(
_req: Readonly<Ref<HoppRESTRequest>>,
_req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>,
res: Readonly<Ref<HoppRESTResponse | null | undefined>>
) {
return computed(() => {

View File

@@ -6,7 +6,7 @@ import {
} from "@hoppscotch/data"
import { HoppGQLDocument } from "~/helpers/graphql/document"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
import { GQLHistoryEntry, RESTHistoryEntry } from "~/newstore/history"
import { SettingsDef, getDefaultSettings } from "~/newstore/settings"
import { SecretVariable } from "~/services/secret-environment.service"
@@ -41,6 +41,7 @@ export const REST_COLLECTIONS_MOCK: HoppCollection[] = [
testScript: "",
body: { contentType: null, body: null },
requestVariables: [],
responses: {},
},
],
auth: { authType: "none", authActive: true },
@@ -145,6 +146,7 @@ export const REST_HISTORY_MOCK: RESTHistoryEntry[] = [
testScript: "",
requestVariables: [],
v: RESTReqSchemaVersion,
responses: {},
},
responseMeta: { duration: 807, statusCode: 200 },
star: false,
@@ -193,7 +195,7 @@ export const GQL_TAB_STATE_MOCK: PersistableTabState<HoppGQLDocument> = {
],
}
export const REST_TAB_STATE_MOCK: PersistableTabState<HoppRESTDocument> = {
export const REST_TAB_STATE_MOCK: PersistableTabState<HoppRequestDocument> = {
lastActiveTabID: "e6e8d800-caa8-44a2-a6a6-b4765a3167aa",
orderedDocs: [
{
@@ -211,8 +213,10 @@ export const REST_TAB_STATE_MOCK: PersistableTabState<HoppRESTDocument> = {
testScript: "",
body: { contentType: null, body: null },
requestVariables: [],
responses: {},
},
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: "0",

View File

@@ -6,6 +6,7 @@ import {
HoppRESTAuth,
HoppRESTRequest,
HoppRESTHeaders,
HoppRESTRequestResponse,
} from "@hoppscotch/data"
import { entityReference } from "verzod"
import { z } from "zod"
@@ -497,6 +498,7 @@ const HoppRESTSaveContextSchema = z.nullable(
originLocation: z.literal("user-collection"),
folderPath: z.string(),
requestIndex: z.number(),
exampleID: z.optional(z.string()),
})
.strict(),
z
@@ -505,6 +507,7 @@ const HoppRESTSaveContextSchema = z.nullable(
requestID: z.string(),
teamID: z.optional(z.string()),
collectionID: z.optional(z.string()),
exampleID: z.optional(z.string()),
})
.strict(),
])
@@ -526,10 +529,11 @@ export const REST_TAB_STATE_SCHEMA = z
orderedDocs: z.array(
z.object({
tabID: z.string(),
doc: z
.object({
doc: z.union([
z.object({
// !Versioned entity
request: entityReference(HoppRESTRequest),
type: z.literal("request"),
isDirty: z.boolean(),
saveContext: z.optional(HoppRESTSaveContextSchema),
response: z.optional(z.nullable(HoppRESTResponseSchema)),
@@ -538,8 +542,14 @@ export const REST_TAB_STATE_SCHEMA = z
optionTabPreference: z.optional(z.enum(validRestOperations)),
inheritedProperties: z.optional(HoppInheritedPropertySchema),
cancelFunction: z.optional(z.function()),
})
.strict(),
}),
z.object({
type: z.literal("example-response"),
response: HoppRESTRequestResponse,
saveContext: z.optional(HoppRESTSaveContextSchema),
isDirty: z.boolean(),
}),
]),
})
),
})

View File

@@ -221,6 +221,7 @@ describe("HistorySpotlightSearcherService", () => {
doc: {
request: historyEntry.request,
isDirty: false,
type: "request",
},
})
})

View File

@@ -327,6 +327,7 @@ export class CollectionsSpotlightSearcherService
{
request: req,
isDirty: false,
type: "request",
saveContext: {
originLocation: "user-collection",
folderPath: folderPath.join("/"),

View File

@@ -19,7 +19,7 @@ import { shortDateTime } from "~/helpers/utils/date"
import { useStreamStatic } from "~/composables/stream"
import { activeActions$, invokeAction } from "~/helpers/actions"
import { map } from "rxjs/operators"
import { HoppRESTDocument } from "~/helpers/rest/document"
import { HoppRequestDocument } from "~/helpers/rest/document"
/**
* This searcher is responsible for searching through the history.
@@ -233,9 +233,10 @@ export class HistorySpotlightSearcherService
restHistoryStore.value.state[parseInt(result.id.split("-")[1])].request
invokeAction("rest.request.open", {
doc: <HoppRESTDocument>{
doc: <HoppRequestDocument>{
request: req,
isDirty: false,
type: "request",
},
})
} else {

View File

@@ -272,11 +272,14 @@ export class RequestSpotlightSearcherService extends StaticSpotlightSearcherServ
case "save_to_collections":
invokeAction("request.save-as", {
requestType: "rest",
request: this.restTab.currentActiveTab.value?.document.request,
request:
this.restTab.currentActiveTab.value?.document.type === "request"
? this.restTab.currentActiveTab.value?.document.request
: null,
})
break
case "save_request":
invokeAction("request.save")
invokeAction("request-response.save")
break
case "rename_request":
invokeAction("request.rename")

View File

@@ -237,6 +237,7 @@ export class TeamsSpotlightSearcherService
this.tabs.createNewTab({
request: cloneDeep(selectedRequest.request as HoppRESTRequest),
isDirty: false,
type: "request",
saveContext: {
originLocation: "team-collection",
requestID: selectedRequest.id,

View File

@@ -1,11 +1,11 @@
import { isEqual } from "lodash-es"
import { computed } from "vue"
import { getDefaultRESTRequest } from "~/helpers/rest/default"
import { HoppRESTDocument, HoppRESTSaveContext } from "~/helpers/rest/document"
import { HoppRESTSaveContext, HoppTabDocument } from "~/helpers/rest/document"
import { TabService } from "./tab"
import { Container } from "dioc"
export class RESTTabService extends TabService<HoppRESTDocument> {
export class RESTTabService extends TabService<HoppTabDocument> {
public static readonly ID = "REST_TAB_SERVICE"
// TODO: Moving this to `onServiceInit` breaks `persistableTabState`
@@ -16,6 +16,7 @@ export class RESTTabService extends TabService<HoppRESTDocument> {
this.tabMap.set("test", {
id: "test",
document: {
type: "request",
request: getDefaultRESTRequest(),
isDirty: false,
optionTabPreference: "params",
@@ -30,6 +31,14 @@ export class RESTTabService extends TabService<HoppRESTDocument> {
lastActiveTabID: this.currentTabID.value,
orderedDocs: this.tabOrdering.value.map((tabID) => {
const tab = this.tabMap.get(tabID)! // tab ordering is guaranteed to have value for this key
if (tab.document.type === "example-response") {
return {
tabID: tab.id,
doc: tab.document,
}
}
return {
tabID: tab.id,
doc: {
@@ -46,7 +55,8 @@ export class RESTTabService extends TabService<HoppRESTDocument> {
if (ctx?.originLocation === "team-collection") {
if (
tab.document.saveContext?.originLocation === "team-collection" &&
tab.document.saveContext.requestID === ctx.requestID
tab.document.saveContext.requestID === ctx.requestID &&
tab.document.saveContext.exampleID === ctx.exampleID
) {
return this.getTabRef(tab.id)
}

View File

@@ -14,7 +14,7 @@ import V4_VERSION from "./v/4"
import V5_VERSION from "./v/5"
import V6_VERSION, { HoppRESTReqBody } from "./v/6"
import V7_VERSION, { HoppRESTHeaders, HoppRESTParams } from "./v/7"
import V8_VERSION, { HoppRESTAuth } from "./v/8"
import V8_VERSION, { HoppRESTAuth, HoppRESTRequestResponses } from "./v/8"
export * from "./content-types"
@@ -48,6 +48,9 @@ export {
HoppRESTAuth,
HoppRESTAuthOAuth2,
PasswordGrantTypeParams,
HoppRESTResponseOriginalRequest,
HoppRESTRequestResponse,
HoppRESTRequestResponses,
} from "./v/8"
const versionedObject = z.object({
@@ -106,6 +109,7 @@ const HoppRESTRequestEq = Eq.struct<HoppRESTRequest>({
(arr) => arr.filter((v: any) => v.key !== "" && v.value !== ""),
lodashIsEqualEq
),
responses: lodashIsEqualEq,
})
export const RESTReqSchemaVersion = "8"
@@ -188,6 +192,14 @@ export function safelyExtractRESTRequest(
req.requestVariables = result.data
}
}
if ("responses" in x) {
const result = HoppRESTRequestResponses.safeParse(x.responses)
if (result.success) {
req.responses = result.data
}
}
}
return req
@@ -221,6 +233,7 @@ export function getDefaultRESTRequest(): HoppRESTRequest {
body: null,
},
requestVariables: [],
responses: {},
}
}

View File

@@ -1,11 +1,5 @@
import { defineVersion } from "verzod"
import { z } from "zod"
import {
HoppRESTAuth,
HoppRESTHeaders,
HoppRESTParams,
HoppRESTReqBody,
} from "./1"
import { V1_SCHEMA } from "./1"
export const HoppRESTRequestVariables = z.array(

View File

@@ -18,9 +18,15 @@ import {
import {
AuthCodeGrantTypeParams,
HoppRESTAuthAWSSignature,
HoppRESTHeaders,
HoppRESTParams,
V7_SCHEMA,
} from "./7"
import { StatusCodes } from "../../utils/statusCodes"
import { HoppRESTReqBody } from "./6"
import { HoppRESTRequestVariables } from "./2"
export const ClientCredentialsGrantTypeParams =
ClientCredentialsGrantTypeParamsOld.extend({
clientSecret: z.string().optional(),
@@ -61,9 +67,70 @@ export const HoppRESTAuth = z
export type HoppRESTAuth = z.infer<typeof HoppRESTAuth>
const V8_SCHEMA = V7_SCHEMA.extend({
const ValidCodes = z.union(
Object.keys(StatusCodes).map((code) => z.literal(parseInt(code))) as [
z.ZodLiteral<number>,
z.ZodLiteral<number>,
...z.ZodLiteral<number>[]
]
)
const HoppRESTResponseHeaders = z.array(
z.object({
key: z.string(),
value: z.string(),
})
)
export type HoppRESTResponseHeader = z.infer<typeof HoppRESTResponseHeaders>
/**
* The original request that was made to get this response
* Only the necessary fields are saved
*/
export const HoppRESTResponseOriginalRequest = z.object({
v: z.literal("1"),
name: z.string(),
method: z.string(),
endpoint: z.string(),
headers: HoppRESTHeaders,
params: HoppRESTParams,
body: HoppRESTReqBody,
auth: HoppRESTAuth,
requestVariables: HoppRESTRequestVariables,
})
export type HoppRESTResponseOriginalRequest = z.infer<
typeof HoppRESTResponseOriginalRequest
>
export const HoppRESTRequestResponse = z.object({
name: z.string(),
originalRequest: HoppRESTResponseOriginalRequest,
status: z.string(),
code: z.optional(ValidCodes),
headers: HoppRESTResponseHeaders,
body: z.string(),
})
export type HoppRESTRequestResponse = z.infer<typeof HoppRESTRequestResponse>
/**
* The responses saved for a request
* The key is the name of the response saved by the user
* The value is the response
*/
export const HoppRESTRequestResponses = z.record(
z.string(),
HoppRESTRequestResponse
)
export type HoppRESTRequestResponses = z.infer<typeof HoppRESTRequestResponses>
export const V8_SCHEMA = V7_SCHEMA.extend({
v: z.literal("8"),
auth: HoppRESTAuth,
responses: HoppRESTRequestResponses,
})
export default defineVersion({
@@ -74,6 +141,7 @@ export default defineVersion({
...old,
v: "8" as const,
// no need to update anything for HoppRESTAuth, because we loosened the previous schema by making `clientSecret` optional
responses: {},
}
},
})

View File

@@ -0,0 +1,101 @@
export const StatusCodes: {
[key: number]: string
} = {
// 1xx Informational
// Request received, continuing process.[2]
// This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. Since HTTP/1.0 did not define any 1xx status codes, servers must not send a 1xx response to an HTTP/1.0 client except under experimental conditions.
100: "Continue", // This means that the server has received the request headers, and that the client should proceed to send the request body (in the case of a request for which a body needs to be sent; for example, a POST request). If the request body is large, sending it to a server when a request has already been rejected based upon inappropriate headers is inefficient. To have a server check if the request could be accepted based on the request's headers alone, a client must send Expect: 100-continue as a header in its initial request[2] and check if a 100 Continue status code is received in response before continuing (or receive 417 Expectation Failed and not continue).[2]
101: "Switching Protocols", // This means the requester has asked the server to switch protocols and the server is acknowledging that it will do so.[2]
102: "Processing", // (WebDAV; RFC 2518) As a WebDAV request may contain many sub-requests involving file operations, it may take a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[3] This prevents the client from timing out and assuming the request was lost.
// 2xx Success
// This class of status codes indicates the action requested by the client was received, understood, accepted and processed successfully.
200: "OK", // Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.[2]
201: "Created", // The request has been fulfilled and resulted in a new resource being created.[2]
202: "Accepted", // The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.[2]
203: "Non-Authoritative Information", // (since HTTP/1.1) The server successfully processed the request, but is returning information that may be from another source.[2]
204: "No Content", // The server successfully processed the request, but is not returning any content.[2]
205: "Reset Content", // The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.[2]
206: "Partial Content", // The server is delivering only part of the resource due to a range header sent by the client. The range header is used by tools like wget to enable resuming of interrupted downloads, or split a download into multiple simultaneous streams.[2]
207: "Multi-Status", // (WebDAV; RFC 4918) The message body that follows is an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.[4]
208: "Already Reported", // (WebDAV; RFC 5842) The members of a DAV binding have already been enumerated in a previous reply to this request, and are not being included again.
226: "IM Used", // (RFC 3229) The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance. [5]
// 3xx Redirection
// The client must take additional action to complete the request.[2]
// This class of status code indicates that further action needs to be taken by the user agent in order to fulfil the request. The action required may be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A user agent should not automatically redirect a request more than five times, since such redirections usually indicate an infinite loop.
300: "Multiple Choices", // Indicates multiple options for the resource that the client may follow. It, for instance, could be used to present different format options for video, list files with different extensions, or word sense disambiguation.[2]
301: "Moved Permanently", // This and all future requests should be directed to the given URI.[2]
302: "Found", // This is an example of industry practice contradicting the standard.[2] The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"),[6] but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours.[7] However, some Web applications and frameworks use the 302 status code as if it were the 303.[citation needed]
303: "See Other", // (since HTTP/1.1) The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), it should be assumed that the server has received the data and the redirect should be issued with a separate GET message.[2]
304: "Not Modified", // Indicates the resource has not been modified since last requested.[2] Typically, the HTTP client provides a header like the If-Modified-Since header to provide a time against which to compare. Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.
305: "Use Proxy", // (since HTTP/1.1) Many HTTP clients (such as Mozilla[8] and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.[2]
306: "Switch Proxy", // No longer used.[2] Originally meant "Subsequent requests should use the specified proxy."[9]
307: "Temporary Redirect", // (since HTTP/1.1) In this case, the request should be repeated with another URI; however, future requests can still use the original URI.[2] In contrast to 302, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.
308: "Permanent Redirect", // (experimental Internet-Draft)[10] The request, and all future requests should be repeated using another URI. 307 and 308 (as proposed) parallel the behaviours of 302 and 301, but do not require the HTTP method to change. So, for example, submitting a form to a permanently redirected resource may continue smoothly.
// 4xx Client Error
// The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents should display any included entity to the user.
400: "Bad Request", // The request cannot be fulfilled due to bad syntax.[2]
401: "Unauthorized", // Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided.[2] The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource. See Basic access authentication and Digest access authentication.
402: "Payment Required", // Reserved for future use.[2] The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, but that has not happened, and this code is not usually used. As an example of its use, however, Apple's MobileMe service generates a 402 error ("httpStatusCode:402" in the Mac OS X Console log) if the MobileMe account is delinquent.[citation needed]
403: "Forbidden", // The request was a legal request, but the server is refusing to respond to it.[2] Unlike a 401 Unauthorized response, authenticating will make no difference.[2]
404: "Not Found", // The requested resource could not be found but may be available again in the future.[2] Subsequent requests by the client are permissible.
405: "Method Not Allowed", // A request was made of a resource using a request method not supported by that resource;[2] for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.
406: "Not Acceptable", // The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.[2]
407: "Proxy Authentication Required", // The client must first authenticate itself with the proxy.[2]
408: "Request Timeout", // The server timed out waiting for the request.[2] According to W3 HTTP specifications: "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
409: "Conflict", // Indicates that the request could not be processed because of conflict in the request, such as an edit conflict.[2]
410: "Gone", // Indicates that the resource requested is no longer available and will not be available again.[2] This should be used when a resource has been intentionally removed and the resource should be purged. Upon receiving a 410 status code, the client should not request the resource again in the future. Clients such as search engines should remove the resource from their indices. Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.
411: "Length Required", // The request did not specify the length of its content, which is required by the requested resource.[2]
412: "Precondition Failed", // The server does not meet one of the preconditions that the requester put on the request.[2]
413: "Request Entity Too Large", // The request is larger than the server is willing or able to process.[2]
414: "Request-URI Too Long", // The URI provided was too long for the server to process.[2]
415: "Unsupported Media Type", // The request entity has a media type which the server or resource does not support.[2] For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
416: "Requested Range Not Satisfiable", // The client has asked for a portion of the file, but the server cannot supply that portion.[2] For example, if the client asked for a part of the file that lies beyond the end of the file.[2]
417: "Expectation Failed", // The server cannot meet the requirements of the Expect request-header field.[2]
418: "I'm a teapot", // (RFC 2324) This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers. However, known implementations do exist.[11]
420: "Enhance Your Calm", // (Twitter) Returned by the Twitter Search and Trends API when the client is being rate limited.[12] Likely a reference to this number's association with marijuana. Other services may wish to implement the 429 Too Many Requests response code instead. The phrase "Enhance Your Calm" is a reference to Demolition Man (film). In the film, Sylvester Stallone's character John Spartan is a hot-head in a generally more subdued future, and is regularly told to "Enhance your calm" rather than a more common phrase like "calm down".
422: "Unprocessable Entity", // (WebDAV; RFC 4918) The request was well-formed but was unable to be followed due to semantic errors.[4]
423: "Locked", // (WebDAV; RFC 4918) The resource that is being accessed is locked.[4]
424: "Failed Dependency", // (WebDAV; RFC 4918) The request failed due to failure of a previous request (e.g. a PROPPATCH).[4]
425: "Unordered Collection", // (Internet draft) Defined in drafts of "WebDAV Advanced Collections Protocol",[14] but not present in "Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol".[15]
426: "Upgrade Required", // (RFC 2817) The client should switch to a different protocol such as TLS/1.0.[16]
428: "Precondition Required", // (RFC 6585) The origin server requires the request to be conditional. Intended to prevent "the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict."[17]
429: "Too Many Requests", // (RFC 6585) The user has sent too many requests in a given amount of time. Intended for use with rate limiting schemes.[17]
431: "Request Header Fields Too Large", // (RFC 6585) The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.[17]
444: "No Response", // (Nginx) Used in Nginx logs to indicate that the server has returned no information to the client and closed the connection (useful as a deterrent for malware).
449: "Retry With", // (Microsoft) A Microsoft extension. The request should be retried after performing the appropriate action.[18] Often search-engines or custom applications will ignore required parameters. Where no default action is appropriate, the Aviongoo website sends a "HTTP/1.1 449 Retry with valid parameters: param1, param2, . . ." response. The applications may choose to learn, or not.
450: "Blocked by Windows Parental Controls", // (Microsoft) A Microsoft extension. This error is given when Windows Parental Controls are turned on and are blocking access to the given webpage.[19]
451: "Unavailable For Legal Reasons", // (Internet draft) Defined in the internet draft "A New HTTP Status Code for Legally-restricted Resources",[20]. Intended to be used when resource access is denied for legal reasons, e.g. censorship or government-mandated blocked access. Likely a reference to the 1953 dystopian novel Fahrenheit 451, where books are outlawed.
499: "Client Closed Request", // (Nginx) Used in Nginx logs to indicate when the connection has been closed by client while the server is still processing its request, making server unable to send a status code back.[21]
// 5xx Server Error
// The server failed to fulfill an apparently valid request.[2]
// Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has encountered an error or is otherwise incapable of performing the request. Except when responding to a HEAD request, the server should include an entity containing an explanation of the error situation, and indicate whether it is a temporary or permanent condition. Likewise, user agents should display any included entity to the user. These response codes are applicable to any request method.
500: "Internal Server Error", // A generic error message, given when no more specific message is suitable.[2]
501: "Not Implemented", // The server either does not recognise the request method, or it lacks the ability to fulfill the request.[2]
502: "Bad Gateway", // The server was acting as a gateway or proxy and received an invalid response from the upstream server.[2]
503: "Service Unavailable", // The server is currently unavailable (because it is overloaded or down for maintenance).[2] Generally, this is a temporary state.
504: "Gateway Timeout", // The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.[2]
505: "HTTP Version Not Supported", // The server does not support the HTTP protocol version used in the request.[2]
506: "Variant Also Negotiates", // (RFC 2295) Transparent content negotiation for the request results in a circular reference.[22]
507: "Insufficient Storage", // (WebDAV; RFC 4918) The server is unable to store the representation needed to complete the request.[4]
508: "Loop Detected", // (WebDAV; RFC 5842) The server detected an infinite loop while processing the request (sent in lieu of 208).
509: "Bandwidth Limit Exceeded", // (Apache bw/limited extension) This status code, while used by many servers, is not specified in any RFCs.
510: "Not Extended", // (RFC 2774) Further extensions to the request are required for the server to fulfill it.[23]
511: "Network Authentication Required", // (RFC 6585) The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network (e.g. "captive portals" used to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).[17]
598: "Network read timeout error", // (Unknown) This status code is not specified in any RFCs, but is used by Microsoft Corp. HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.
599: "Network connect timeout error", // (Unknown) This status code is not specified in any RFCs, but is used by Microsoft Corp. HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.
} as const
export function getStatusCodeReasonPhrase(
code: number,
statusText?: string
): string {
// Return statusText if non-empty after trimming and add ellipsis if greater than 35 characters
const trimmedStatusText = statusText?.trim()
if (trimmedStatusText) {
return trimmedStatusText.length > 35
? `${trimmedStatusText.substring(0, 35)}...`
: trimmedStatusText
}
return StatusCodes[code] ?? "Unknown"
}

View File

@@ -131,6 +131,7 @@ function exportedCollectionToHoppCollection(
preRequestScript,
testScript,
requestVariables,
responses,
} = request
return {
v,
@@ -139,12 +140,13 @@ function exportedCollectionToHoppCollection(
endpoint,
method,
params,
requestVariables: requestVariables,
auth,
headers,
body,
preRequestScript,
testScript,
requestVariables,
responses,
}
}),
}

View File

@@ -153,6 +153,7 @@ function exportedCollectionToHoppCollection(
preRequestScript,
testScript,
requestVariables,
responses,
} = request
const resolvedParams = addDescriptionField(params)
@@ -171,6 +172,7 @@ function exportedCollectionToHoppCollection(
body,
preRequestScript,
testScript,
responses,
}
}),
auth: data.auth,