UNPKG

2.3 kBJavaScriptView Raw
1/***
2 * Assign a value to a nested object
3 * @function putNestedValue
4 * @param params the parent object - this argument will be modified!
5 * @param key key in the form nested[innerkey]
6 * @param value the value to assign
7 * @return the modified params object
8 */
9const url = require('url');
10const extend = require("lodash/extend");
11const isObject = require("lodash/isObject");
12const isString = require("lodash/isString");
13const isUndefined = require("lodash/isUndefined");
14const entries = require('./utils/entries');
15
16let cloudinary_config = void 0;
17
18function isNestedKey(key) {
19 return key.match(/\w+\[\w+\]/);
20}
21
22function putNestedValue(params, key, value) {
23 let chain = key.split(/[\[\]]+/).filter((i) => i.length);
24 let outer = params;
25 let lastKey = chain.pop();
26 for (let j = 0; j < chain.length; j++) {
27 let innerKey = chain[j];
28 let inner = outer[innerKey];
29 if (inner == null) {
30 inner = {};
31 outer[innerKey] = inner;
32 }
33 outer = inner;
34 }
35 return outer[lastKey] = value;
36}
37
38module.exports = function(new_config, new_value) {
39 if ((cloudinary_config == null) || new_config === true) {
40 if (cloudinary_config == null){
41 cloudinary_config = {};
42 } else {
43 Object.keys(cloudinary_config).forEach(key=> delete cloudinary_config[key]);
44 }
45
46
47 let cloudinary_url = process.env.CLOUDINARY_URL;
48 if (cloudinary_url != null) {
49
50 let uri = url.parse(cloudinary_url, true);
51 let parsedConfig = {
52 cloud_name: uri.host,
53 api_key: uri.auth && uri.auth.split(":")[0],
54 api_secret: uri.auth && uri.auth.split(":")[1],
55 private_cdn: uri.pathname != null,
56 secure_distribution: uri.pathname && uri.pathname.substring(1)
57 };
58 entries(parsedConfig).forEach(([key, value])=> {
59 if(value !== undefined) {
60 cloudinary_config[key] = value;
61 }
62 });
63 if (uri.query != null) {
64 entries(uri.query).forEach( ([key, value])=> putNestedValue(cloudinary_config, key, value));
65 }
66 }
67 }
68 if (!isUndefined(new_value)) {
69 cloudinary_config[new_config] = new_value;
70 } else if (isString(new_config)) {
71 return cloudinary_config[new_config];
72 } else if (isObject(new_config)) {
73 extend(cloudinary_config, new_config);
74 }
75 return cloudinary_config;
76};