UNPKG

2.78 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
18/**
19 * Sets a value in an object using a nested key
20 * @param {object} params The object to assign the value in.
21 * @param {string} key The key of the value. A period is used to denote inner keys.
22 * @param {*} value The value to set.
23 * @returns {object} The params argument.
24 * @example
25 * let o = {foo: {bar: 1}};
26 * putNestedValue(o, 'foo.bar', 2); // {foo: {bar: 2}}
27 * putNestedValue(o, 'foo.inner.key', 'this creates an inner object');
28 * // {{foo: {bar: 2}, inner: {key: 'this creates an inner object'}}}
29 */
30function putNestedValue(params, key, value) {
31 let chain = key.split(/[\[\]]+/).filter(i => i.length);
32 let outer = params;
33 let lastKey = chain.pop();
34 for (let j = 0; j < chain.length; j++) {
35 let innerKey = chain[j];
36 let inner = outer[innerKey];
37 if (inner == null) {
38 inner = {};
39 outer[innerKey] = inner;
40 }
41 outer = inner;
42 }
43 outer[lastKey] = value;
44 return params;
45}
46
47module.exports = function (new_config, new_value) {
48 if ((cloudinary_config == null) || new_config === true) {
49 if (cloudinary_config == null) {
50 cloudinary_config = {};
51 } else {
52 Object.keys(cloudinary_config).forEach(key => delete cloudinary_config[key]);
53 }
54
55
56 let cloudinary_url = process.env.CLOUDINARY_URL;
57 if (cloudinary_url != null) {
58 let uri = url.parse(cloudinary_url, true);
59 let parsedConfig = {
60 cloud_name: uri.host,
61 api_key: uri.auth && uri.auth.split(":")[0],
62 api_secret: uri.auth && uri.auth.split(":")[1],
63 private_cdn: uri.pathname != null,
64 secure_distribution: uri.pathname && uri.pathname.substring(1),
65 };
66 entries(parsedConfig).forEach(([key, value]) => {
67 if (value !== undefined) {
68 cloudinary_config[key] = value;
69 }
70 });
71 if (uri.query != null) {
72 entries(uri.query).forEach(([key, value]) => putNestedValue(cloudinary_config, key, value));
73 }
74 }
75 }
76 if (!isUndefined(new_value)) {
77 cloudinary_config[new_config] = new_value;
78 } else if (isString(new_config)) {
79 return cloudinary_config[new_config];
80 } else if (isObject(new_config)) {
81 extend(cloudinary_config, new_config);
82 }
83 return cloudinary_config;
84};