refactor: improve import export scripting in environment and graphql

This commit is contained in:
liyasthomas
2021-12-21 12:57:23 +05:30
parent 43dace6248
commit a517b571d6
3 changed files with 479 additions and 457 deletions

View File

@@ -1,7 +1,7 @@
<template> <template>
<SmartModal <SmartModal
v-if="show" v-if="show"
:title="`${$t('modal.import_export')} ${$t('modal.collections')}`" :title="`${t('modal.import_export')} ${t('modal.collections')}`"
max-width="sm:max-w-md" max-width="sm:max-w-md"
@close="hideModal" @close="hideModal"
> >
@@ -9,7 +9,7 @@
<ButtonSecondary <ButtonSecondary
v-if="mode == 'import_from_my_collections'" v-if="mode == 'import_from_my_collections'"
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.go_back')" :title="t('action.go_back')"
svg="arrow-left" svg="arrow-left"
@click.native=" @click.native="
() => { () => {
@@ -32,13 +32,13 @@
<template #trigger> <template #trigger>
<ButtonSecondary <ButtonSecondary
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.more')" :title="t('action.more')"
svg="more-vertical" svg="more-vertical"
/> />
</template> </template>
<SmartItem <SmartItem
icon="assignment_returned" icon="assignment_returned"
:label="$t('import.from_gist')" :label="t('import.from_gist')"
@click.native=" @click.native="
() => { () => {
readCollectionGist() readCollectionGist()
@@ -65,7 +65,7 @@
: false : false
" "
icon="assignment_turned_in" icon="assignment_turned_in"
:label="$t('export.create_secret_gist')" :label="t('export.create_secret_gist')"
@click.native=" @click.native="
() => { () => {
createCollectionGist() createCollectionGist()
@@ -81,48 +81,46 @@
<div v-if="mode == 'import_export'" class="flex flex-col space-y-2 px-2"> <div v-if="mode == 'import_export'" class="flex flex-col space-y-2 px-2">
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.preserve_current')" :title="t('action.preserve_current')"
svg="folder-plus" svg="folder-plus"
:label="$t('import.json')" :label="t('import.json')"
@click.native="openDialogChooseFileToImportFrom" @click.native="openDialogChooseFileToImportFrom"
/> />
<input <input
ref="inputChooseFileToImportFrom" ref="inputChooseFileToImportFrom"
class="input" class="input"
type="file" type="file"
style="display: none"
accept="application/json" accept="application/json"
@change="importFromJSON" @change="importFromJSON"
/> />
<SmartItem <SmartItem
v-if="collectionsType.type == 'team-collections'" v-if="collectionsType.type == 'team-collections'"
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.preserve_current')" :title="t('action.preserve_current')"
svg="user" svg="user"
:label="$t('import.from_my_collections')" :label="t('import.from_my_collections')"
@click.native="mode = 'import_from_my_collections'" @click.native="mode = 'import_from_my_collections'"
/> />
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.replace_current')" :title="t('action.replace_current')"
svg="file" svg="file"
:label="$t('action.replace_json')" :label="t('action.replace_json')"
@click.native="openDialogChooseFileToReplaceWith" @click.native="openDialogChooseFileToReplaceWith"
/> />
<input <input
ref="inputChooseFileToReplaceWith" ref="inputChooseFileToReplaceWith"
class="input" class="input"
type="file" type="file"
style="display: none"
accept="application/json" accept="application/json"
@change="replaceWithJSON" @change="replaceWithJSON"
/> />
<hr /> <hr />
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.download_file')" :title="t('action.download_file')"
svg="download" svg="download"
:label="$t('export.as_json')" :label="t('export.as_json')"
@click.native="exportJSON" @click.native="exportJSON"
/> />
</div> </div>
@@ -168,7 +166,7 @@
<ButtonPrimary <ButtonPrimary
:disabled="mySelectedCollectionID == undefined" :disabled="mySelectedCollectionID == undefined"
svg="folder-plus" svg="folder-plus"
:label="$t('import.title')" :label="t('import.title')"
@click.native="importFromMyCollections" @click.native="importFromMyCollections"
/> />
</span> </span>
@@ -347,6 +345,7 @@ type PostmanCollection = {
}[] }[]
folders?: any folders?: any
} }
const parsePostmanCollection = ({ info, name, item }: PostmanCollection) => { const parsePostmanCollection = ({ info, name, item }: PostmanCollection) => {
const hoppscotchCollection: Collection<HoppRESTRequest> = makeCollection({ const hoppscotchCollection: Collection<HoppRESTRequest> = makeCollection({
name: "", name: "",

View File

@@ -1,7 +1,7 @@
<template> <template>
<SmartModal <SmartModal
v-if="show" v-if="show"
:title="`${$t('modal.import_export')} ${$t('modal.collections')}`" :title="`${t('modal.import_export')} ${t('modal.collections')}`"
max-width="sm:max-w-md" max-width="sm:max-w-md"
@close="hideModal" @close="hideModal"
> >
@@ -11,17 +11,17 @@
<template #trigger> <template #trigger>
<ButtonSecondary <ButtonSecondary
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.more')" :title="t('action.more')"
svg="more-vertical" svg="more-vertical"
/> />
</template> </template>
<SmartItem <SmartItem
icon="assignment_returned" icon="assignment_returned"
:label="$t('import.from_gist')" :label="t('import.from_gist')"
@click.native=" @click.native="
() => { () => {
readCollectionGist() readCollectionGist()
$refs.options.tippy().hide() options.tippy().hide()
} }
" "
/> />
@@ -29,10 +29,10 @@
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title=" :title="
!currentUser !currentUser
? $t('export.require_github') ? `${t('export.require_github')}`
: currentUser.provider !== 'github.com' : currentUser.provider !== 'github.com'
? $t('export.require_github') ? `${t('export.require_github')}`
: null : undefined
" "
> >
<SmartItem <SmartItem
@@ -44,11 +44,11 @@
: false : false
" "
icon="assignment_turned_in" icon="assignment_turned_in"
:label="$t('export.create_secret_gist')" :label="t('export.create_secret_gist')"
@click.native=" @click.native="
() => { () => {
createCollectionGist() createCollectionGist()
$refs.options.tippy().hide() options.tippy().hide()
} }
" "
/> />
@@ -60,9 +60,9 @@
<div class="flex flex-col space-y-2 px-2"> <div class="flex flex-col space-y-2 px-2">
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.preserve_current')" :title="t('action.preserve_current')"
svg="folder-plus" svg="folder-plus"
:label="$t('import.json')" :label="t('import.json')"
@click.native="openDialogChooseFileToImportFrom" @click.native="openDialogChooseFileToImportFrom"
/> />
<input <input
@@ -74,9 +74,9 @@
/> />
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.replace_current')" :title="t('action.replace_current')"
svg="file" svg="file"
:label="$t('action.replace_json')" :label="t('action.replace_json')"
@click.native="openDialogChooseFileToReplaceWith" @click.native="openDialogChooseFileToReplaceWith"
/> />
<input <input
@@ -89,9 +89,9 @@
<hr /> <hr />
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.download_file')" :title="t('action.download_file')"
svg="download" svg="download"
:label="$t('export.as_json')" :label="t('export.as_json')"
@click.native="exportJSON" @click.native="exportJSON"
/> />
</div> </div>
@@ -99,295 +99,221 @@
</SmartModal> </SmartModal>
</template> </template>
<script> <script setup lang="ts">
import { defineComponent } from "@nuxtjs/composition-api" import { computed, ref } from "@nuxtjs/composition-api"
import { currentUser$ } from "~/helpers/fb/auth" import { currentUser$ } from "~/helpers/fb/auth"
import { useReadonlyStream } from "~/helpers/utils/composables" import {
useAxios,
useI18n,
useReadonlyStream,
useToast,
} from "~/helpers/utils/composables"
import { import {
graphqlCollections$, graphqlCollections$,
setGraphqlCollections, setGraphqlCollections,
appendGraphqlCollections, appendGraphqlCollections,
} from "~/newstore/collections" } from "~/newstore/collections"
export default defineComponent({ defineProps<{
props: { show: boolean
show: Boolean, }>()
},
setup() { const emit = defineEmits<{
return { (e: "hide-modal"): void
collections: useReadonlyStream(graphqlCollections$, []), }>()
currentUser: useReadonlyStream(currentUser$, null),
const axios = useAxios()
const toast = useToast()
const t = useI18n()
const collections = useReadonlyStream(graphqlCollections$, [])
const currentUser = useReadonlyStream(currentUser$, null)
// Template refs
const options = ref<any>()
const inputChooseFileToReplaceWith = ref<HTMLInputElement>()
const inputChooseFileToImportFrom = ref<HTMLInputElement>()
const collectionJson = computed(() => {
return JSON.stringify(collections.value, null, 2)
})
const createCollectionGist = async () => {
if (!currentUser.value) {
toast.error(t("profile.no_permission").toString())
return
} }
},
computed: { try {
collectionJson() { const res = await axios.$post(
return JSON.stringify(this.collections, null, 2)
},
},
methods: {
async createCollectionGist() {
await this.$axios
.$post(
"https://api.github.com/gists", "https://api.github.com/gists",
{ {
files: { files: {
"hoppscotch-collections.json": { "hoppscotch-collections.json": {
content: this.collectionJson, content: collectionJson.value,
}, },
}, },
}, },
{ {
headers: { headers: {
Authorization: `token ${this.currentUser.accessToken}`, Authorization: `token ${currentUser.value.accessToken}`,
Accept: "application/vnd.github.v3+json", Accept: "application/vnd.github.v3+json",
}, },
} }
) )
.then((res) => {
this.$toast.success(this.$t("export.gist_created")) toast.success(t("export.gist_created").toString())
window.open(res.html_url) window.open(res.html_url)
}) } catch (e) {
.catch((e) => { toast.error(t("error.something_went_wrong").toString())
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e) console.error(e)
}) }
}, }
async readCollectionGist() {
const gist = prompt(this.$t("import.gist_url")) const fileImported = () => {
toast.success(t("state.file_imported").toString())
}
const failedImport = () => {
toast.error(t("import.failed").toString())
}
const readCollectionGist = async () => {
const gist = prompt(t("import.gist_url").toString())
if (!gist) return if (!gist) return
await this.$axios
.$get(`https://api.github.com/gists/${gist.split("/").pop()}`, { try {
const { files } = (await axios.$get(
`https://api.github.com/gists/${gist.split("/").pop()}`,
{
headers: { headers: {
Accept: "application/vnd.github.v3+json", Accept: "application/vnd.github.v3+json",
}, },
}) }
.then(({ files }) => { )) as {
files: {
[fileName: string]: {
content: any
}
}
}
const collections = JSON.parse(Object.values(files)[0].content) const collections = JSON.parse(Object.values(files)[0].content)
setGraphqlCollections(collections) setGraphqlCollections(collections)
this.fileImported() fileImported()
}) } catch (e) {
.catch((e) => { failedImport()
this.failedImport()
console.error(e) console.error(e)
})
},
hideModal() {
this.$emit("hide-modal")
},
openDialogChooseFileToReplaceWith() {
this.$refs.inputChooseFileToReplaceWith.click()
},
openDialogChooseFileToImportFrom() {
this.$refs.inputChooseFileToImportFrom.click()
},
replaceWithJSON() {
const reader = new FileReader()
reader.onload = ({ target }) => {
const content = target.result
let collections = JSON.parse(content)
if (collections[0]) {
const [name, folders, requests] = Object.keys(collections[0])
if (
name === "name" &&
folders === "folders" &&
requests === "requests"
) {
// Do nothing
} }
} else if ( }
collections.info &&
collections.info.schema.includes("v2.1.0") const hideModal = () => {
emit("hide-modal")
}
const openDialogChooseFileToReplaceWith = () => {
if (inputChooseFileToReplaceWith.value)
inputChooseFileToReplaceWith.value.click()
}
const openDialogChooseFileToImportFrom = () => {
if (inputChooseFileToImportFrom.value)
inputChooseFileToImportFrom.value.click()
}
const replaceWithJSON = () => {
if (!inputChooseFileToReplaceWith.value) return
if (
!inputChooseFileToReplaceWith.value.files ||
inputChooseFileToReplaceWith.value.files.length === 0
) { ) {
collections = [this.parsePostmanCollection(collections)] toast.show(t("action.choose_file").toString())
} else {
this.failedImport()
return return
} }
setGraphqlCollections(collections)
this.fileImported()
}
reader.readAsText(this.$refs.inputChooseFileToReplaceWith.files[0])
this.$refs.inputChooseFileToReplaceWith.value = ""
},
importFromJSON() {
const reader = new FileReader() const reader = new FileReader()
reader.onload = ({ target }) => { reader.onload = ({ target }) => {
const content = target.result const content = target!.result as string | null
let collections = JSON.parse(content)
if (!content) {
toast.show(t("action.choose_file").toString())
return
}
const collections = JSON.parse(content)
// TODO: File validation
if (collections[0]) { if (collections[0]) {
const [name, folders, requests] = Object.keys(collections[0]) const [name, folders, requests] = Object.keys(collections[0])
if ( if (name === "name" && folders === "folders" && requests === "requests") {
name === "name" &&
folders === "folders" &&
requests === "requests"
) {
// Do nothing // Do nothing
} }
} else if (
collections.info &&
collections.info.schema.includes("v2.1.0")
) {
// replace the variables, postman uses {{var}}, Hoppscotch uses <<var>>
collections = JSON.parse(
content.replaceAll(/{{([a-z]+)}}/gi, "<<$1>>")
)
collections = [this.parsePostmanCollection(collections)]
} else { } else {
this.failedImport() failedImport()
}
setGraphqlCollections(collections)
fileImported()
}
reader.readAsText(inputChooseFileToReplaceWith.value.files[0])
inputChooseFileToReplaceWith.value.value = ""
}
const importFromJSON = () => {
if (!inputChooseFileToImportFrom.value) return
if (
!inputChooseFileToImportFrom.value.files ||
inputChooseFileToImportFrom.value.files.length === 0
) {
toast.show(t("action.choose_file").toString())
return
}
const reader = new FileReader()
reader.onload = ({ target }) => {
const content = target!.result as string | null
if (!content) {
toast.show(t("action.choose_file").toString())
return
}
const collections = JSON.parse(content)
if (collections[0]) {
const [name, folders, requests] = Object.keys(collections[0])
if (name === "name" && folders === "folders" && requests === "requests") {
// Do nothing
}
} else {
failedImport()
return return
} }
appendGraphqlCollections(collections) appendGraphqlCollections(collections)
this.fileImported() fileImported()
} }
reader.readAsText(this.$refs.inputChooseFileToImportFrom.files[0]) reader.readAsText(inputChooseFileToImportFrom.value.files[0])
this.$refs.inputChooseFileToImportFrom.value = "" inputChooseFileToImportFrom.value.value = ""
}, }
exportJSON() {
const dataToWrite = this.collectionJson const exportJSON = () => {
const dataToWrite = collectionJson.value
const file = new Blob([dataToWrite], { type: "application/json" }) const file = new Blob([dataToWrite], { type: "application/json" })
const a = document.createElement("a") const a = document.createElement("a")
const url = URL.createObjectURL(file) const url = URL.createObjectURL(file)
a.href = url a.href = url
// TODO get uri from meta
a.download = `${url.split("/").pop().split("#")[0].split("?")[0]}.json` // TODO: get uri from meta
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
document.body.appendChild(a) document.body.appendChild(a)
a.click() a.click()
this.$toast.success(this.$t("state.download_started")) toast.success(t("state.download_started").toString())
setTimeout(() => { setTimeout(() => {
document.body.removeChild(a) document.body.removeChild(a)
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
}, 1000) }, 1000)
},
fileImported() {
this.$toast.success(this.$t("state.file_imported"))
},
failedImport() {
this.$toast.error(this.$t("import.failed"))
},
parsePostmanCollection({ info, name, item }) {
const hoppscotchCollection = {
name: "",
folders: [],
requests: [],
} }
hoppscotchCollection.name = info ? info.name : name
if (item && item.length > 0) {
for (const collectionItem of item) {
if (collectionItem.request) {
if (
Object.prototype.hasOwnProperty.call(
hoppscotchCollection,
"folders"
)
) {
hoppscotchCollection.name = info ? info.name : name
hoppscotchCollection.requests.push(
this.parsePostmanRequest(collectionItem)
)
} else {
hoppscotchCollection.name = name || ""
hoppscotchCollection.requests.push(
this.parsePostmanRequest(collectionItem)
)
}
} else if (this.hasFolder(collectionItem)) {
hoppscotchCollection.folders.push(
this.parsePostmanCollection(collectionItem)
)
} else {
hoppscotchCollection.requests.push(
this.parsePostmanRequest(collectionItem)
)
}
}
}
return hoppscotchCollection
},
parsePostmanRequest({ name, request }) {
const pwRequest = {
url: "",
path: "",
method: "",
auth: "",
httpUser: "",
httpPassword: "",
passwordFieldType: "password",
bearerToken: "",
headers: [],
params: [],
bodyParams: [],
rawParams: "",
rawInput: false,
contentType: "",
requestType: "",
name: "",
}
pwRequest.name = name
const requestObjectUrl = request.url.raw.match(
/^(.+:\/\/[^/]+|{[^/]+})(\/[^?]+|).*$/
)
if (requestObjectUrl) {
pwRequest.url = requestObjectUrl[1]
pwRequest.path = requestObjectUrl[2] ? requestObjectUrl[2] : ""
}
pwRequest.method = request.method
const itemAuth = request.auth ? request.auth : ""
const authType = itemAuth ? itemAuth.type : ""
if (authType === "basic") {
pwRequest.auth = "Basic Auth"
pwRequest.httpUser =
itemAuth.basic[0].key === "username"
? itemAuth.basic[0].value
: itemAuth.basic[1].value
pwRequest.httpPassword =
itemAuth.basic[0].key === "password"
? itemAuth.basic[0].value
: itemAuth.basic[1].value
} else if (authType === "oauth2") {
pwRequest.auth = "OAuth 2.0"
pwRequest.bearerToken =
itemAuth.oauth2[0].key === "accessToken"
? itemAuth.oauth2[0].value
: itemAuth.oauth2[1].value
} else if (authType === "bearer") {
pwRequest.auth = "Bearer Token"
pwRequest.bearerToken = itemAuth.bearer[0].value
}
const requestObjectHeaders = request.header
if (requestObjectHeaders) {
pwRequest.headers = requestObjectHeaders
for (const header of pwRequest.headers) {
delete header.name
delete header.type
}
}
const requestObjectParams = request.url.query
if (requestObjectParams) {
pwRequest.params = requestObjectParams
for (const param of pwRequest.params) {
delete param.disabled
}
}
if (request.body) {
if (request.body.mode === "urlencoded") {
const params = request.body.urlencoded
pwRequest.bodyParams = params || []
for (const param of pwRequest.bodyParams) {
delete param.type
}
} else if (request.body.mode === "raw") {
pwRequest.rawInput = true
pwRequest.rawParams = request.body.raw
}
}
return pwRequest
},
hasFolder(item) {
return Object.prototype.hasOwnProperty.call(item, "item")
},
},
})
</script> </script>

View File

@@ -1,7 +1,7 @@
<template> <template>
<SmartModal <SmartModal
v-if="show" v-if="show"
:title="`${$t('modal.import_export')} ${$t('environment.title')}`" :title="`${t('modal.import_export')} ${t('environment.title')}`"
max-width="sm:max-w-md" max-width="sm:max-w-md"
@close="hideModal" @close="hideModal"
> >
@@ -11,17 +11,17 @@
<template #trigger> <template #trigger>
<ButtonSecondary <ButtonSecondary
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.more')" :title="t('action.more')"
svg="more-vertical" svg="more-vertical"
/> />
</template> </template>
<SmartItem <SmartItem
icon="assignment_returned" icon="assignment_returned"
:label="$t('import.from_gist')" :label="t('import.from_gist')"
@click.native=" @click.native="
() => { () => {
readEnvironmentGist() readEnvironmentGist()
$refs.options.tippy().hide() options.tippy().hide()
} }
" "
/> />
@@ -29,10 +29,10 @@
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title=" :title="
!currentUser !currentUser
? $t('export.require_github') ? `${t('export.require_github')}`
: currentUser.provider !== 'github.com' : currentUser.provider !== 'github.com'
? $t('export.require_github') ? `${t('export.require_github')}`
: null : undefined
" "
> >
<SmartItem <SmartItem
@@ -44,11 +44,11 @@
: false : false
" "
icon="assignment_turned_in" icon="assignment_turned_in"
:label="$t('export.create_secret_gist')" :label="t('export.create_secret_gist')"
@click.native=" @click.native="
() => { () => {
createEnvironmentGist() createEnvironmentGist()
$refs.options.tippy().hide() options.tippy().hide()
} }
" "
/> />
@@ -60,9 +60,9 @@
<div class="flex flex-col space-y-2 px-2"> <div class="flex flex-col space-y-2 px-2">
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.preserve_current')" :title="t('action.preserve_current')"
svg="folder-plus" svg="folder-plus"
:label="$t('import.json')" :label="t('import.json')"
@click.native="openDialogChooseFileToImportFrom" @click.native="openDialogChooseFileToImportFrom"
/> />
<input <input
@@ -74,9 +74,9 @@
/> />
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.replace_current')" :title="t('action.replace_current')"
svg="file" svg="file"
:label="$t('action.replace_json')" :label="t('action.replace_json')"
@click.native="openDialogChooseFileToReplaceWith" @click.native="openDialogChooseFileToReplaceWith"
/> />
<input <input
@@ -89,9 +89,9 @@
<hr /> <hr />
<SmartItem <SmartItem
v-tippy="{ theme: 'tooltip' }" v-tippy="{ theme: 'tooltip' }"
:title="$t('action.download_file')" :title="t('action.download_file')"
svg="download" svg="download"
:label="$t('export.as_json')" :label="t('export.as_json')"
@click.native="exportJSON" @click.native="exportJSON"
/> />
</div> </div>
@@ -99,146 +99,243 @@
</SmartModal> </SmartModal>
</template> </template>
<script> <script setup lang="ts">
import { defineComponent } from "@nuxtjs/composition-api" import { computed, ref } from "@nuxtjs/composition-api"
import { currentUser$ } from "~/helpers/fb/auth" import { currentUser$ } from "~/helpers/fb/auth"
import { useReadonlyStream } from "~/helpers/utils/composables" import {
useAxios,
useI18n,
useReadonlyStream,
useToast,
} from "~/helpers/utils/composables"
import { import {
environments$, environments$,
replaceEnvironments, replaceEnvironments,
appendEnvironments, appendEnvironments,
Environment,
} from "~/newstore/environments" } from "~/newstore/environments"
export default defineComponent({ defineProps<{
props: { show: boolean
show: Boolean, }>()
},
setup() { const emit = defineEmits<{
return { (e: "hide-modal"): void
environments: useReadonlyStream(environments$, []), }>()
currentUser: useReadonlyStream(currentUser$, null),
const axios = useAxios()
const toast = useToast()
const t = useI18n()
const environments = useReadonlyStream(environments$, [])
const currentUser = useReadonlyStream(currentUser$, null)
// Template refs
const options = ref<any>()
const inputChooseFileToReplaceWith = ref<HTMLInputElement>()
const inputChooseFileToImportFrom = ref<HTMLInputElement>()
const environmentJson = computed(() => {
return JSON.stringify(environments.value, null, 2)
})
const createEnvironmentGist = async () => {
if (!currentUser.value) {
toast.error(t("profile.no_permission").toString())
return
} }
},
computed: { try {
environmentJson() { const res = await axios.$post(
return JSON.stringify(this.environments, null, 2)
},
},
methods: {
async createEnvironmentGist() {
await this.$axios
.$post(
"https://api.github.com/gists", "https://api.github.com/gists",
{ {
files: { files: {
"hoppscotch-environments.json": { "hoppscotch-environments.json": {
content: this.environmentJson, content: environmentJson.value,
}, },
}, },
}, },
{ {
headers: { headers: {
Authorization: `token ${this.currentUser.accessToken}`, Authorization: `token ${currentUser.value.accessToken}`,
Accept: "application/vnd.github.v3+json", Accept: "application/vnd.github.v3+json",
}, },
} }
) )
.then((res) => {
this.$toast.success(this.$t("export.gist_created")) toast.success(t("export.gist_created").toString())
window.open(res.html_url) window.open(res.html_url)
}) } catch (e) {
.catch((e) => { toast.error(t("error.something_went_wrong").toString())
this.$toast.error(this.$t("error.something_went_wrong"))
console.error(e) console.error(e)
}) }
}, }
async readEnvironmentGist() {
const gist = prompt(this.$t("import.gist_url")) const fileImported = () => {
toast.success(t("state.file_imported").toString())
}
const failedImport = () => {
toast.error(t("import.failed").toString())
}
const readEnvironmentGist = async () => {
const gist = prompt(t("import.gist_url").toString())
if (!gist) return if (!gist) return
await this.$axios
.$get(`https://api.github.com/gists/${gist.split("/").pop()}`, { try {
const { files } = (await axios.$get(
`https://api.github.com/gists/${gist.split("/").pop()}`,
{
headers: { headers: {
Accept: "application/vnd.github.v3+json", Accept: "application/vnd.github.v3+json",
}, },
}) }
.then(({ files }) => { )) as {
files: {
[fileName: string]: {
content: any
}
}
}
const environments = JSON.parse(Object.values(files)[0].content) const environments = JSON.parse(Object.values(files)[0].content)
replaceEnvironments(environments) replaceEnvironments(environments)
this.fileImported() fileImported()
}) } catch (e) {
.catch((e) => { failedImport()
this.failedImport()
console.error(e) console.error(e)
})
},
hideModal() {
this.$emit("hide-modal")
},
openDialogChooseFileToReplaceWith() {
this.$refs.inputChooseFileToReplaceWith.click()
},
openDialogChooseFileToImportFrom() {
this.$refs.inputChooseFileToImportFrom.click()
},
replaceWithJSON() {
const reader = new FileReader()
reader.onload = ({ target }) => {
const content = target.result
const environments = JSON.parse(content)
replaceEnvironments(environments)
} }
reader.readAsText(this.$refs.inputChooseFileToReplaceWith.files[0]) }
this.fileImported()
this.$refs.inputChooseFileToReplaceWith.value = "" const hideModal = () => {
}, emit("hide-modal")
importFromJSON() { }
const reader = new FileReader()
reader.onload = ({ target }) => { const openDialogChooseFileToReplaceWith = () => {
const content = target.result if (inputChooseFileToReplaceWith.value)
const importFileObj = JSON.parse(content) inputChooseFileToReplaceWith.value.click()
}
const openDialogChooseFileToImportFrom = () => {
if (inputChooseFileToImportFrom.value)
inputChooseFileToImportFrom.value.click()
}
const replaceWithJSON = () => {
if (!inputChooseFileToReplaceWith.value) return
if ( if (
importFileObj._postman_variable_scope === "environment" || !inputChooseFileToReplaceWith.value.files ||
importFileObj._postman_variable_scope === "globals" inputChooseFileToReplaceWith.value.files.length === 0
) { ) {
this.importFromPostman(importFileObj) toast.show(t("action.choose_file").toString())
return
}
const reader = new FileReader()
reader.onload = ({ target }) => {
const content = target!.result as string | null
if (!content) {
toast.show(t("action.choose_file").toString())
return
}
const environments = JSON.parse(content)
// TODO: File validation
if (environments[0]) {
const [name, variables] = Object.keys(environments[0])
if (name === "name" && variables === "variables") {
// Do nothing
}
} else { } else {
this.importFromHoppscotch(importFileObj) failedImport()
}
replaceEnvironments(environments)
fileImported()
}
reader.readAsText(inputChooseFileToReplaceWith.value.files[0])
inputChooseFileToReplaceWith.value.value = ""
}
const importFromJSON = () => {
if (!inputChooseFileToImportFrom.value) return
if (
!inputChooseFileToImportFrom.value.files ||
inputChooseFileToImportFrom.value.files.length === 0
) {
toast.show(t("action.choose_file").toString())
return
}
const reader = new FileReader()
reader.onload = ({ target }) => {
const content = target!.result as string | null
if (!content) {
toast.show(t("action.choose_file").toString())
return
}
const environments = JSON.parse(content)
if (
environments._postman_variable_scope === "environment" ||
environments._postman_variable_scope === "globals"
) {
importFromPostman(environments)
} else if (environments[0]) {
const [name, variables] = Object.keys(environments[0])
if (name === "name" && variables === "variables") {
// Do nothing
}
importFromHoppscotch(environments)
} else {
failedImport()
} }
} }
reader.readAsText(this.$refs.inputChooseFileToImportFrom.files[0])
this.$refs.inputChooseFileToImportFrom.value = "" reader.readAsText(inputChooseFileToImportFrom.value.files[0])
}, inputChooseFileToImportFrom.value.value = ""
importFromHoppscotch(environments) { }
const importFromHoppscotch = (environments: Environment[]) => {
appendEnvironments(environments) appendEnvironments(environments)
this.fileImported() fileImported()
}, }
importFromPostman({ name, values }) {
const environment = { name, variables: [] } const importFromPostman = ({
values.forEach(({ key, value }) => name,
environment.variables.push({ key, value }) values,
) }: {
name: string
values: { key: string; value: string }[]
}) => {
const environment: Environment = { name, variables: [] }
values.forEach(({ key, value }) => environment.variables.push({ key, value }))
const environments = [environment] const environments = [environment]
this.importFromHoppscotch(environments) importFromHoppscotch(environments)
}, }
exportJSON() {
const dataToWrite = this.environmentJson const exportJSON = () => {
const dataToWrite = environmentJson.value
const file = new Blob([dataToWrite], { type: "application/json" }) const file = new Blob([dataToWrite], { type: "application/json" })
const a = document.createElement("a") const a = document.createElement("a")
const url = URL.createObjectURL(file) const url = URL.createObjectURL(file)
a.href = url a.href = url
// TODO get uri from meta
a.download = `${url.split("/").pop().split("#")[0].split("?")[0]}.json` // TODO: get uri from meta
a.download = `${url.split("/").pop()!.split("#")[0].split("?")[0]}.json`
document.body.appendChild(a) document.body.appendChild(a)
a.click() a.click()
this.$toast.success(this.$t("state.download_started")) toast.success(t("state.download_started").toString())
setTimeout(() => { setTimeout(() => {
document.body.removeChild(a) document.body.removeChild(a)
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
}, 1000) }, 1000)
}, }
fileImported() {
this.$toast.success(this.$t("state.file_imported"))
},
},
})
</script> </script>