hopp.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { pipe, flow } from "fp-ts/function"
  2. import * as TE from "fp-ts/TaskEither"
  3. import * as O from "fp-ts/Option"
  4. import * as RA from "fp-ts/ReadonlyArray"
  5. import {
  6. translateToNewRESTCollection,
  7. HoppCollection,
  8. HoppRESTRequest,
  9. } from "@hoppscotch/data"
  10. import _isPlainObject from "lodash/isPlainObject"
  11. import { step } from "../steps"
  12. import { defineImporter, IMPORTER_INVALID_FILE_FORMAT } from "."
  13. import { safeParseJSON } from "~/helpers/functional/json"
  14. export default defineImporter({
  15. id: "hoppscotch",
  16. name: "import.from_json",
  17. icon: "folder-plus",
  18. applicableTo: ["my-collections", "team-collections", "url-import"],
  19. steps: [
  20. step({
  21. stepName: "FILE_IMPORT",
  22. metadata: {
  23. caption: "import.from_json_description",
  24. acceptedFileTypes: "application/json",
  25. },
  26. }),
  27. ] as const,
  28. importer: ([content]) =>
  29. pipe(
  30. safeParseJSON(content),
  31. O.chain(
  32. flow(
  33. makeCollectionsArray,
  34. RA.map(
  35. flow(
  36. O.fromPredicate(isValidCollection),
  37. O.map(translateToNewRESTCollection)
  38. )
  39. ),
  40. O.sequenceArray,
  41. O.map(RA.toArray)
  42. )
  43. ),
  44. TE.fromOption(() => IMPORTER_INVALID_FILE_FORMAT)
  45. ),
  46. })
  47. /**
  48. * checks if a value is a plain object
  49. */
  50. const isPlainObject = (value: any): value is object => _isPlainObject(value)
  51. /**
  52. * checks if a collection matches the schema for a hoppscotch collection.
  53. * as of now we are only checking if the collection has a "v" key in it.
  54. */
  55. const isValidCollection = (
  56. collection: unknown
  57. ): collection is HoppCollection<HoppRESTRequest> =>
  58. isPlainObject(collection) && "v" in collection
  59. /**
  60. * convert single collection object into an array so it can be handled the same as multiple collections
  61. */
  62. const makeCollectionsArray = (collections: unknown | unknown[]): unknown[] =>
  63. Array.isArray(collections) ? collections : [collections]