feat: import collections from URL (#2262)

Co-authored-by: Andrew Bastin <andrewbastin.k@gmail.com>
This commit is contained in:
Akash K
2022-05-03 17:54:47 +05:30
committed by GitHub
parent c20339d222
commit 4ef2844a22
13 changed files with 239 additions and 59 deletions

View File

@@ -1,13 +1,22 @@
import { pipe } from "fp-ts/function"
import { pipe, flow } from "fp-ts/function"
import * as TE from "fp-ts/TaskEither"
import * as E from "fp-ts/Either"
import { translateToNewRESTCollection } from "@hoppscotch/data"
import * as O from "fp-ts/Option"
import * as RA from "fp-ts/ReadonlyArray"
import {
translateToNewRESTCollection,
HoppCollection,
HoppRESTRequest,
} from "@hoppscotch/data"
import _isPlainObject from "lodash/isPlainObject"
import { step } from "../steps"
import { defineImporter, IMPORTER_INVALID_FILE_FORMAT } from "."
import { safeParseJSON } from "~/helpers/functional/json"
export default defineImporter({
id: "hoppscotch",
name: "import.from_json",
icon: "folder-plus",
applicableTo: ["my-collections", "team-collections", "url-import"],
steps: [
step({
stepName: "FILE_IMPORT",
@@ -19,16 +28,40 @@ export default defineImporter({
] as const,
importer: ([content]) =>
pipe(
E.tryCatch(
() => {
const x = JSON.parse(content)
return Array.isArray(x)
? x.map((coll: any) => translateToNewRESTCollection(coll))
: [translateToNewRESTCollection(x)]
},
() => IMPORTER_INVALID_FILE_FORMAT
safeParseJSON(content),
O.chain(
flow(
makeCollectionsArray,
RA.map(
flow(
O.fromPredicate(isValidCollection),
O.map(translateToNewRESTCollection)
)
),
O.sequenceArray,
O.map(RA.toArray)
)
),
TE.fromEither
TE.fromOption(() => IMPORTER_INVALID_FILE_FORMAT)
),
})
/**
* checks if a value is a plain object
*/
const isPlainObject = (value: any): value is object => _isPlainObject(value)
/**
* checks if a collection matches the schema for a hoppscotch collection.
* as of now we are only checking if the collection has a "v" key in it.
*/
const isValidCollection = (
collection: unknown
): collection is HoppCollection<HoppRESTRequest> =>
isPlainObject(collection) && "v" in collection
/**
* convert single collection object into an array so it can be handled the same as multiple collections
*/
const makeCollectionsArray = (collections: unknown | unknown[]): unknown[] =>
Array.isArray(collections) ? collections : [collections]