All files / src/lib save-environment.js

28.57% Statements 6/21
0% Branches 0/7
0% Functions 0/11
37.5% Lines 6/16
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                  1x                           1x                 1x                     1x                 1x                               1x                                    
import { Environments } from 'postman-sdk'
import { findBy, pipe } from '../helper/util'
 
/**
 * Gets all postman collections
 *
 * @returns {Promise<*>} Promise that resolves with the collections object
 * @throws Error
 */
const getEnvironments = async () => {
	try {
		return Environments.get()
	} catch (error) {
		throw new Error(`Unexpected error occurred: ${error.message}`)
	}
}
 
/**
 * Checks if a collection exists on postman
 *
 * @param {object} environment The current environment
 * @returns {Promise<object|boolean>} The collection object if it exists false otherwise
 */
const environmentExists = environment => environments =>
	findBy(environments.environments, 'name', environment.name)
 
/**
 * Updates a new collection
 *
 * @param {object} environment The environment object
 * @returns {function(*=): *} A function
 */
const updateEnvironment = environment => async exists =>
	!exists
		? Promise.resolve(exists)
		: await Environments.put(exists.uid, { environment })
 
/**
 * Create a new collection on postman
 *
 * @param {object} environment The environment object
 * @returns {function(*): *} A function
 */
const createEnvironment = environment => async exists =>
	!exists ? await Environments.post({ environment }) : 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 results
}
 
/**
 * Creates a suvvess response
 *
 * @param {object} results The results object
 * @returns {object} A suvvess response object
 */
const respond = results => Promise.resolve({
	message: 'Environments created!',
	results
})
 
/**
 * Saves a collection to Postman
 *
 * @param {Object} environments The collection object
 * @returns {Promise<Object|Boolean>} The newly created collection or false
 */
export default async (collection, environments = null) =>
    Promise.all(environments.map(async environment => await pipe(
        environmentExists(environment.environment),
        updateEnvironment(environment.environment),
        createEnvironment(environment.environment),
        checkForError,
        respond
    )(await getEnvironments())))