All files / src/lib save-collection.js

30% Statements 6/20
0% Branches 0/7
0% Functions 0/10
35.29% Lines 6/17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95                    1x                           1x                 1x                       1x                       1x                               1x                                          
import { findBy, pipe } from './../helper/util'
import { Collections } from 'postman-sdk'
 
 
/**
 * Gets all postman collections
 *
 * @returns {Promise<*>} Promise that resolves with the collections object
 * @throws Error
 */
const getCollection = async () => {
	try {
		return Collections.get()
	} catch (error) {
		throw new Error(`Unexpected error occurred: ${error.message}`)
	}
}
 
/**
 * Checks if a collection exists on postman
 *
 * @param {object} collection The current collection
 * @returns {Promise<object|boolean>} The collection object if it exists false otherwise
 */
const collectionExists = collection => collections =>
	findBy(collections.collections, 'name', collection.info.name)
 
/**
 * Updates a new collection
 *
 * @param {object} collection The collection object
 * @returns {function(*=): *} A function
 */
const updateCollection = collection => async exists =>
	!exists
		? Promise.resolve(exists)
		: await Collections.put(exists.uid, { collection })
 
 
/**
 * Create a new collection on postman
 *
 * @param {object} collection The collection object
 * @returns {function(*): *} A function
 */
const createCollection = collection => async exists =>
	exists === null
		? await Collections.post({ collection })
		: Promise.resolve(exists)
 
 
/**
 * Checks if the request resulted in an error
 *
 * @param {object} results THe results object
 * @returns {object} The results object
 */
const checkForError = results => {
	if (results.error) {
		throw new Error(
			'Could not save collection to Postman: ' + results.error.message
		)
	}
 
	return Promise.resolve(results)
}
 
/**
 * Creates a suvvess response
 *
 * @param {object} results The results object
 * @returns {object} A suvvess response object
 */
const respond = results =>
	Promise.resolve({
		message: 'Collection created!',
		results
	})
 
/**
 * Saves a collection to Postman
 *
 * @param {Object} collection The collection object
 * @returns {Promise<Object|Boolean>} The newly created collection or false
 */
export default async (collection, environments = null) =>
	await pipe(
		getCollection,
		collectionExists(collection),
		updateCollection(collection),
		createCollection(collection),
		checkForError,
		respond
	)(collection.info.name)