All files dependency-resolver.js

90.48% Statements 19/21
87.5% Branches 7/8
100% Functions 5/5
90.48% Lines 19/21
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                                22x   22x                     23x 1x     22x   22x 22x   22x 1x 1x     21x 21x 21x   21x               21x 21x   21x 21x 21x            
/**
 * © 2014 Liferay, Inc. <https://liferay.com>
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */
 
/**
 * A class that calls the server to resolve module dependencies.
 */
export default class DependencyResolver {
	/**
	 * Creates an instance of DependencyResolver class
	 * @constructor
	 * @param {Config} config
	 */
	constructor(config) {
		this._config = config;
 
		this._cachedResolutions = {};
	}
 
	/**
	 * Resolves modules dependencies
	 * @param {array} modules list of modules which dependencies should be
	 *     						resolved
	 * @return {array} list of module names, representing module dependencies
	 *     				(module name itself is being returned too)
	 */
	resolve(modules) {
		if (modules === undefined || modules.length == 0) {
			throw new Error(`Argument 'modules' cannot be undefined or empty`);
		}
 
		const config = this._config;
 
		return new Promise((resolve, reject) => {
			const resolution = this._cachedResolutions[modules];
 
			if (resolution) {
				resolve(resolution);
				return;
			}
 
			const modulesParam = `modules=${encodeURIComponent(modules)}`;
			let url = `${config.resolvePath}?${modulesParam}`;
			let options = {};
 
			Iif (url.length > config.urlMaxLength) {
				url = config.resolvePath;
				options = {
					method: 'POST',
					body: modulesParam,
				};
			}
 
			fetch(url, options)
				.then(response => response.text())
				.then(text => {
					const resolution = JSON.parse(text);
					this._cachedResolutions[modules] = resolution;
					resolve(resolution);
				})
				.catch(reject);
		});
	}
}