Check if a string is in a json object - javascript

I'm trying to check if a string is in a JSON object with javascript. I don't know if it is possible or I have to convert something. Here is the part of the code with the if statement in which I want to check if data.userName (the string) is in users (the JSON object)
function validation() {
var userName_login = document.getElementById("username").value;
var password_login = document.getElementById("password").value;
var data = {
userName: userName_login,
password: password_login
};
doJSONRequest("GET", "/users/", null, data, function(users) {
if (data.userName) {
}
})
}
And the doJSONRequest function is:
function doJSONRequest(method, url, headers, data, callback) {
if (arguments.length != 5) {
throw new Error('Illegal argument count');
}
doRequestChecks(method, true, data);
var r = new XMLHttpRequest();
r.open(method, url, true);
doRequestSetHeaders(r, method, headers);
r.onreadystatechange = function() {
if (r.readyState != 4 || (r.status != 200 && r.status != 201 && r.status != 204)) {
return;
} else {
if (isJSON(r.responseText))
callback(JSON.parse(r.responseText));
else
callback();
}
};
var dataToSend = null;
if (!("undefined" == typeof data) && !(data === null))
dataToSend = JSON.stringify(data);
r.send(dataToSend);
}

function checkForValue(json, value) {
for (key in json) {
if (typeof (json[key]) === "object") {
return checkForValue(json[key], value);
} else if (json[key] === value) {
return true;
}
}
return false;
}
check if Json string has value in JS

Just try to parse it using JSON.parse, if the parse was successful return true else return false:
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}

Related

Javascript RangeError on website proxy RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599]

Image Here
Hello! I am trying to add a search bar that acts like a proxy at the top of my website. Whenever I input a website like https://stackoverflow.com I receive an error on the website. RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599] (Note: I am using the ultraviolet service) If you'd like to test yourself the website is https://lun.netlify.app also no errors seem to appear in the console log.
importScripts('/uv/uv.bundle.js');
importScripts('/uv/uv.config.js');
class UVServiceWorker extends EventEmitter {
constructor(config = __uv$config) {
super();
if (!config.bare) config.bare = '/bare/';
this.addresses = typeof config.bare === 'string' ? [ new URL(config.bare, location) ] : config.bare.map(str => new URL(str, location));
this.headers = {
csp: [
'cross-origin-embedder-policy',
'cross-origin-opener-policy',
'cross-origin-resource-policy',
'content-security-policy',
'content-security-policy-report-only',
'expect-ct',
'feature-policy',
'origin-isolation',
'strict-transport-security',
'upgrade-insecure-requests',
'x-content-type-options',
'x-download-options',
'x-frame-options',
'x-permitted-cross-domain-policies',
'x-powered-by',
'x-xss-protection',
],
forward: [
'accept-encoding',
'connection',
'content-length',
'content-type',
'user-agent',
],
};
this.method = {
empty: [
'GET',
'HEAD'
]
};
this.statusCode = {
empty: [
204,
304,
],
};
this.config = config;
};
async fetch({ request }) {
if (!request.url.startsWith(location.origin + (this.config.prefix || '/service/'))) {
return fetch(request);
};
try {
const ultraviolet = new Ultraviolet(this.config);
if (typeof this.config.construct === 'function') {
this.config.construct(ultraviolet, 'service');
};
const db = await ultraviolet.cookie.db();
ultraviolet.meta.origin = location.origin;
ultraviolet.meta.base = ultraviolet.meta.url = new URL(ultraviolet.sourceUrl(request.url));
const requestCtx = new RequestContext(
request,
this,
ultraviolet,
!this.method.empty.includes(request.method.toUpperCase()) ? await request.blob() : null
);
if (ultraviolet.meta.url.protocol === 'blob:') {
requestCtx.blob = true;
requestCtx.base = requestCtx.url = new URL(requestCtx.url.pathname);
};
if (request.referrer && request.referrer.startsWith(location.origin)) {
const referer = new URL(ultraviolet.sourceUrl(request.referrer));
if (ultraviolet.meta.url.origin !== referer.origin && request.mode === 'cors') {
requestCtx.headers.origin = referer.origin;
};
requestCtx.headers.referer = referer.href;
};
const cookies = await ultraviolet.cookie.getCookies(db) || [];
const cookieStr = ultraviolet.cookie.serialize(cookies, ultraviolet.meta, false);
const browser = Ultraviolet.Bowser.getParser(self.navigator.userAgent).getBrowserName();
if (browser === 'Firefox' && !(request.destination === 'iframe' || request.destination === 'document')) {
requestCtx.forward.shift();
};
if (cookieStr) requestCtx.headers.cookie = cookieStr;
const reqEvent = new HookEvent(requestCtx, null, null);
this.emit('request', reqEvent);
if (reqEvent.intercepted) return reqEvent.returnValue;
const response = await fetch(requestCtx.send);
if (response.status === 500) {
return Promise.reject('');
};
const responseCtx = new ResponseContext(requestCtx, response, this);
const resEvent = new HookEvent(responseCtx, null, null);
this.emit('beforemod', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
for (const name of this.headers.csp) {
if (responseCtx.headers[name]) delete responseCtx.headers[name];
};
if (responseCtx.headers.location) {
responseCtx.headers.location = ultraviolet.rewriteUrl(responseCtx.headers.location);
};
if (responseCtx.headers['set-cookie']) {
Promise.resolve(ultraviolet.cookie.setCookies(responseCtx.headers['set-cookie'], db, ultraviolet.meta)).then(() => {
self.clients.matchAll().then(function (clients){
clients.forEach(function(client){
client.postMessage({
msg: 'updateCookies',
url: ultraviolet.meta.url.href,
});
});
});
});
delete responseCtx.headers['set-cookie'];
};
if (responseCtx.body) {
switch(request.destination) {
case 'script':
case 'worker':
responseCtx.body = `if (!self.__uv && self.importScripts) importScripts('${__uv$config.bundle}', '${__uv$config.config}', '${__uv$config.handler}');\n`;
responseCtx.body += ultraviolet.js.rewrite(
await response.text()
);
break;
case 'style':
responseCtx.body = ultraviolet.rewriteCSS(
await response.text()
);
break;
case 'iframe':
case 'document':
if (isHtml(ultraviolet.meta.url, (responseCtx.headers['content-type'] || ''))) {
responseCtx.body = ultraviolet.rewriteHtml(
await response.text(),
{
document: true ,
injectHead: ultraviolet.createHtmlInject(
this.config.handler,
this.config.bundle,
this.config.config,
ultraviolet.cookie.serialize(cookies, ultraviolet.meta, true),
request.referrer
)
}
);
};
};
};
if (requestCtx.headers.accept === 'text/event-stream') {
responseCtx.headers['content-type'] = 'text/event-stream';
};
this.emit('response', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
return new Response(responseCtx.body, {
headers: responseCtx.headers,
status: responseCtx.status,
statusText: responseCtx.statusText,
});
} catch(err) {
return new Response(err.toString(), {
status: 500,
});
};
};
getBarerResponse(response) {
const headers = {};
const raw = JSON.parse(response.headers.get('x-bare-headers'));
for (const key in raw) {
headers[key.toLowerCase()] = raw[key];
};
return {
headers,
status: +response.headers.get('x-bare-status'),
statusText: response.headers.get('x-bare-status-text'),
body: !this.statusCode.empty.includes(+response.headers.get('x-bare-status')) ? response.body : null,
};
};
get address() {
return this.addresses[Math.floor(Math.random() * this.addresses.length)];
};
static Ultraviolet = Ultraviolet;
};
self.UVServiceWorker = UVServiceWorker;
class ResponseContext {
constructor(request, response, worker) {
const { headers, status, statusText, body } = !request.blob ? worker.getBarerResponse(response) : {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
body: response.body,
};
this.request = request;
this.raw = response;
this.ultraviolet = request.ultraviolet;
this.headers = headers;
this.status = status;
this.statusText = statusText;
this.body = body;
};
get url() {
return this.request.url;
}
get base() {
return this.request.base;
};
set base(val) {
this.request.base = val;
};
};
class RequestContext {
constructor(request, worker, ultraviolet, body = null) {
this.ultraviolet = ultraviolet;
this.request = request;
this.headers = Object.fromEntries([...request.headers.entries()]);
this.method = request.method;
this.forward = [...worker.headers.forward];
this.address = worker.address;
this.body = body || null;
this.redirect = request.redirect;
this.credentials = 'omit';
this.mode = request.mode === 'cors' ? request.mode : 'same-origin';
this.blob = false;
};
get send() {
return new Request((!this.blob ? this.address.href + 'v1/' : 'blob:' + location.origin + this.url.pathname), {
method: this.method,
headers: {
'x-bare-protocol': this.url.protocol,
'x-bare-host': this.url.hostname,
'x-bare-path': this.url.pathname + this.url.search,
'x-bare-port': this.url.port || (this.url.protocol === 'https:' ? '443' : '80'),
'x-bare-headers': JSON.stringify(this.headers),
'x-bare-forward-headers': JSON.stringify(this.forward),
},
redirect: this.redirect,
credentials: this.credentials,
mode: location.origin !== this.address.origin ? 'cors' : this.mode,
body: this.body
});
};
get url() {
return this.ultraviolet.meta.url;
};
set url(val) {
this.ultraviolet.meta.url = val;
};
get base() {
return this.ultraviolet.meta.base;
};
set base(val) {
this.ultraviolet.meta.base = val;
};
}
function isHtml(url, contentType = '') {
return (Ultraviolet.mime.contentType((contentType || url.pathname)) || 'text/html').split(';')[0] === 'text/html';
};
class HookEvent {
#intercepted;
#returnValue;
constructor(data = {}, target = null, that = null) {
this.#intercepted = false;
this.#returnValue = null;
this.data = data;
this.target = target;
this.that = that;
};
get intercepted() {
return this.#intercepted;
};
get returnValue() {
return this.#returnValue;
};
respondWith(input) {
this.#returnValue = input;
this.#intercepted = true;
};
};
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
throw er;
}
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err;
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
emitter.addEventListener(name, function wrapListener(arg) {
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}

Error while executing async get of Outlook item property

Why am I getting Could not complete the operation due to error 80043200 sometimes while getting Outlook item property (for example, Subject) in email Compose mode?
Call stack:
Error
at n.prototype.execute (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:86635)
at u.DDA.OutlookAppOm.prototype.callOutlookDispatcher (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:150300)
at u.DDA.OutlookAppOm.prototype.invokeHostMethod (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:150169)
at u.DDA.OutlookAppOm.prototype._standardInvokeHostMethod$i$0 (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:148443)
at r.ComposeSubject.prototype.getAsync (appsforoffice.microsoft.com/lib/1.1/hosted/outlook-win32-16.02.js:11:190544)
We use following code for getting a field from an Outlook item:
sfMailApp.OfficeManager.prototype._reloadField = function (name, defaultValue) {
var deferred = $.Deferred();
defaultValue = defaultValue || '';
var item = this.getItem();
if (item.isFake) {
deferred.resolve('');
return deferred.promise();
}
var field = item[name];
if (field && this._isComposeMode && field.getAsync) {
var _this = this;
try {
field.getAsync(function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
_this[name] = _this._processOfficeData(result.value) || defaultValue;
deferred.resolve(_this[name]);
}
else {
_this._onError(result);
deferred.reject();
}
});
} catch (e) {
deferred.reject();
}
} else {
this[name] = this._processOfficeData(field) || defaultValue;
deferred.resolve(this[name]);
}
return deferred.promise();}
Code for getItem function:
sfMailApp.OfficeManager.prototype.getItem = function () {
var item = Office && Office.context && Office.context.mailbox && Office.context.mailbox.item ? Office.context.mailbox.item : null;
if (!item) {
item = {
isFake: true
}
}
return item;}
One more error we're getting sometimes while trying to get user identity token:
{"name":"AccessRestricted","message":"Internal protocol error: -2147467259'.","code":9017 }
How should we handle that?

sessionStorage data not persisting in another or new tab

I am using sessionStorage to get some data and able to use it to create a link and append it to the page.
(function() {
var rep_info = document.getElementById('rep-info'),
session = sessionStorage.getItem('ngStorage-getRepInfo'),
obj = JSON.parse(session),
vanity_name = obj.profile.data.vanityName,
your_URL = 'https://foo.com/';
console.log(obj.profile.data.vanityName);
rep_info.insertAdjacentHTML('afterbegin', 'foo.com/' + vanity_name + '');
})();
However if I copy and paste the URL of the page which contains the script above, it doesn't fire. Instead I get this error.
Uncaught TypeError: Cannot read property 'profile' of null
But when I do a refresh, the script fires.
I should mention this page/site is accessed via user authentification i.e. username & password.
I found this solution, but I couldn't figure out how to get it going.
Thanks in advance!
UPDATE 2-1-2017
I included the library I referenced and my attempt at using to solve my problem, it's right after the module.
var LocalStoreManager = (function() {
function LocalStoreManager() {
var _this = this;
this.syncKeys = [];
this.reservedKeys = ['sync_keys', 'addToSyncKeys', 'removeFromSyncKeys',
'getSessionStorage', 'setSessionStorage', 'addToSessionStorage', 'removeFromSessionStorage', 'clearAllSessionsStorage', 'raiseDBEvent'
];
this.sessionStorageTransferHandler = function(event) {
if (!event.newValue)
return;
if (event.key == 'getSessionStorage') {
if (sessionStorage.length) {
localStorage.setItem('setSessionStorage', JSON.stringify(sessionStorage));
localStorage.removeItem('setSessionStorage');
}
} else if (event.key == 'setSessionStorage') {
if (!_this.syncKeys.length)
_this.loadSyncKeys();
var data = JSON.parse(event.newValue);
for (var key in data) {
if (_this.syncKeysContains(key))
sessionStorage.setItem(key, data[key]);
}
} else if (event.key == 'addToSessionStorage') {
var data = JSON.parse(event.newValue);
_this.addToSessionStorageHelper(data["data"], data["key"]);
} else if (event.key == 'removeFromSessionStorage') {
_this.removeFromSessionStorageHelper(event.newValue);
} else if (event.key == 'clearAllSessionsStorage' && sessionStorage.length) {
_this.clearInstanceSessionStorage();
} else if (event.key == 'addToSyncKeys') {
_this.addToSyncKeysHelper(event.newValue);
} else if (event.key == 'removeFromSyncKeys') {
_this.removeFromSyncKeysHelper(event.newValue);
}
};
}
//Todo: Implement EventListeners for the various event operations and a SessionStorageEvent for specific data keys
LocalStoreManager.prototype.initialiseStorageSyncListener = function() {
if (LocalStoreManager.syncListenerInitialised == true)
return;
LocalStoreManager.syncListenerInitialised = true;
window.addEventListener("storage", this.sessionStorageTransferHandler, false);
this.syncSessionStorage();
};
LocalStoreManager.prototype.deinitialiseStorageSyncListener = function() {
window.removeEventListener("storage", this.sessionStorageTransferHandler, false);
LocalStoreManager.syncListenerInitialised = false;
};
LocalStoreManager.prototype.syncSessionStorage = function() {
localStorage.setItem('getSessionStorage', '_dummy');
localStorage.removeItem('getSessionStorage');
};
LocalStoreManager.prototype.clearAllStorage = function() {
this.clearAllSessionsStorage();
this.clearLocalStorage();
};
LocalStoreManager.prototype.clearAllSessionsStorage = function() {
this.clearInstanceSessionStorage();
localStorage.removeItem(LocalStoreManager.DBKEY_SYNC_KEYS);
localStorage.setItem('clearAllSessionsStorage', '_dummy');
localStorage.removeItem('clearAllSessionsStorage');
};
LocalStoreManager.prototype.clearInstanceSessionStorage = function() {
sessionStorage.clear();
this.syncKeys = [];
};
LocalStoreManager.prototype.clearLocalStorage = function() {
localStorage.clear();
};
LocalStoreManager.prototype.addToSessionStorage = function(data, key) {
this.addToSessionStorageHelper(data, key);
this.addToSyncKeysBackup(key);
localStorage.setItem('addToSessionStorage', JSON.stringify({ key: key, data: data }));
localStorage.removeItem('addToSessionStorage');
};
LocalStoreManager.prototype.addToSessionStorageHelper = function(data, key) {
this.addToSyncKeysHelper(key);
sessionStorage.setItem(key, data);
};
LocalStoreManager.prototype.removeFromSessionStorage = function(keyToRemove) {
this.removeFromSessionStorageHelper(keyToRemove);
this.removeFromSyncKeysBackup(keyToRemove);
localStorage.setItem('removeFromSessionStorage', keyToRemove);
localStorage.removeItem('removeFromSessionStorage');
};
LocalStoreManager.prototype.removeFromSessionStorageHelper = function(keyToRemove) {
sessionStorage.removeItem(keyToRemove);
this.removeFromSyncKeysHelper(keyToRemove);
};
LocalStoreManager.prototype.testForInvalidKeys = function(key) {
if (!key)
throw new Error("key cannot be empty");
if (this.reservedKeys.some(function(x) {
return x == key;
}))
throw new Error("The storage key \"" + key + "\" is reserved and cannot be used. Please use a different key");
};
LocalStoreManager.prototype.syncKeysContains = function(key) {
return this.syncKeys.some(function(x) {
return x == key;
});
};
LocalStoreManager.prototype.loadSyncKeys = function() {
if (this.syncKeys.length)
return;
this.syncKeys = this.getSyncKeysFromStorage();
};
LocalStoreManager.prototype.getSyncKeysFromStorage = function(defaultValue) {
if (defaultValue === void 0) { defaultValue = []; }
var data = localStorage.getItem(LocalStoreManager.DBKEY_SYNC_KEYS);
if (data == null)
return defaultValue;
else
return JSON.parse(data);
};
LocalStoreManager.prototype.addToSyncKeys = function(key) {
this.addToSyncKeysHelper(key);
this.addToSyncKeysBackup(key);
localStorage.setItem('addToSyncKeys', key);
localStorage.removeItem('addToSyncKeys');
};
LocalStoreManager.prototype.addToSyncKeysBackup = function(key) {
var storedSyncKeys = this.getSyncKeysFromStorage();
if (!storedSyncKeys.some(function(x) {
return x == key;
})) {
storedSyncKeys.push(key);
localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys));
}
};
LocalStoreManager.prototype.removeFromSyncKeysBackup = function(key) {
var storedSyncKeys = this.getSyncKeysFromStorage();
var index = storedSyncKeys.indexOf(key);
if (index > -1) {
storedSyncKeys.splice(index, 1);
localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys));
}
};
LocalStoreManager.prototype.addToSyncKeysHelper = function(key) {
if (!this.syncKeysContains(key))
this.syncKeys.push(key);
};
LocalStoreManager.prototype.removeFromSyncKeys = function(key) {
this.removeFromSyncKeysHelper(key);
this.removeFromSyncKeysBackup(key);
localStorage.setItem('removeFromSyncKeys', key);
localStorage.removeItem('removeFromSyncKeys');
};
LocalStoreManager.prototype.removeFromSyncKeysHelper = function(key) {
var index = this.syncKeys.indexOf(key);
if (index > -1) {
this.syncKeys.splice(index, 1);
}
};
LocalStoreManager.prototype.saveSessionData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSyncKeys(key);
localStorage.removeItem(key);
sessionStorage.setItem(key, data);
};
LocalStoreManager.prototype.saveSyncedSessionData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
localStorage.removeItem(key);
this.addToSessionStorage(data, key);
};
LocalStoreManager.prototype.savePermanentData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSessionStorage(key);
localStorage.setItem(key, data);
};
LocalStoreManager.prototype.moveDataToSessionStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.saveSessionData(data, key);
};
LocalStoreManager.prototype.moveDataToSyncedSessionStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.saveSyncedSessionData(data, key);
};
LocalStoreManager.prototype.moveDataToPermanentStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.savePermanentData(data, key);
};
LocalStoreManager.prototype.getData = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = sessionStorage.getItem(key);
if (data == null)
data = localStorage.getItem(key);
return data;
};
LocalStoreManager.prototype.getDataObject = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
var data = this.getData(key);
if (data != null)
return JSON.parse(data);
else
return null;
};
LocalStoreManager.prototype.deleteData = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSessionStorage(key);
localStorage.removeItem(key);
};
return LocalStoreManager;
})();
(function() {
var localStorageMangerInstance = new LocalStoreManager();
localStorageMangerInstance.initialiseStorageSyncListener();
var data = localStorageMangerInstance.getData('ngStorage-getRepInfo'),
obj = JSON.parse(data),
vanity_name = obj.profile.data.vanityName;
localStorageMangerInstance.saveSyncedSessionData(obj, obj.profile.data.vanityName);
var rep_info = document.getElementById('rep-info'),
your_avon_URL = 'https://youravon.com/';
rep_info.insertAdjacentHTML('afterbegin', 'youravon.com/' + vanity_name + '');
console.log(vanity_name);
console.log(obj.profile.data.vanityName);
})();

Refactor Node.JS callbacks for DRY code

Both find calls inside the ifs have callbacks that start by function(e, docs).
What would be a clean way to refactor it to be DRYer?
Thanks.
if (connection_id == null) {
id_connectionsCollection.find({}, {}, function (e, docs) {
if (e) {
return callback(e);
}
var connectionDetails = null;
if (docs == null || docs.length == 0) {//if no connections found, use default from config
connectionDetails = defaultConnectionDetails
}
else {
connectionDetails = docs[0];//just get the first one
}
return callback(null, connectionDetails);
});
}
else {
id_connectionsCollection.find({name: connection_id}, {sort: {updated_at: -1}}, function (e, docs) {
if (e) {
return callback(e);
}
var connectionDetails = null;
if (docs == null || docs.length == 0) {
connectionDetails = defaultConnectionDetails;
}
else {
connectionDetails = docs[0];//just get the first one
}
return callback(null, connectionDetails);
});
}
The most obvious way to DRY your code is to extract your callback to a named function that can be passed as your callback on the last arg of your find method:
// Can probably think of a better name here...
doCallback = function(e, docs) {
if (e)
return callback(e);
var connectionDetails = null;
if (docs == null || docs.length == 0)
connectionDetails = defaultConnectionDetails;
else
connectionDetails = docs[0];//just get the first one
return callback(null, connectionDetails);
}
if (connection_id == null)
id_connectionsCollection.find({}, {}, doCallback);
else
id_connectionsCollection.find({name: connection_id}, {sort: {updated_at: -1}}, doCallback);

How can I create empty JSON keys (nested or not) using a string?

I currently have this code built in JS, but it's really, really ugly.
Is there any better way to approach it?
The way it works basically is pushing a string like app.chat.test to be the key, and value like teststr.
I test the lengths to see if the "parent" key is there, otherwise we build it.
function constructJson(jsonKey, jsonValue){
//REWRITE!!!!!!!!
let jsonObj = langFile;
let jsonKeyArr = jsonKey.split('.')
if (jsonKeyArr.length === 1) {
if (valToAdd === undefined) {
if (jsonObj[jsonKey] === undefined) {
jsonObj[jsonKey] = {}
}
} else {
if (jsonObj[jsonKey] === undefined) {
jsonObj[jsonKey] = valToAdd
}
}
} else if (jsonKeyArr.length === 2) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = jsonValue
}
} else if (jsonKeyArr.length === 3) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = jsonValue
}
} else if (jsonKeyArr.length === 4) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = jsonValue
}
} else if (jsonKeyArr.length === 5) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] = jsonValue
}
} else if (jsonKeyArr.length > 5) {
return console.log("Length over 5 not supported yet!")
}
return jsonObj;
}
Regards.
OF course it's possible, a simple loop will perfeclty do the job.
function constructJson(jsonKey, jsonValue){
//REWRITE!!!!!!!!
langFile = {a:{}, foo:{}};// remove this for your own code
var jsonObj = langFile;
var jsonKeyArr = jsonKey.split('.');
var currentValue = jsonObj;
for(var i = 0; i < jsonKeyArr.length;i++){
if(currentValue[jsonKeyArr[i]]===undefined){
currentValue[jsonKeyArr[i]] = {};
}
if(i < jsonKeyArr.length-1){
currentValue = currentValue[jsonKeyArr[i]];
}else{
currentValue[jsonKeyArr[i]] = jsonValue;
}
}
return jsonObj;
}
alert(JSON.stringify(constructJson("a.b.cd.ef", "toto")));
I just assigning to a temporary variable each sublevel. When i'm on the last i'm assigning the value.
Yes you can, using the javascript reduce function on the array created from the splitted string.
function namespaceCreateExceptLast(representationOfElementToCreate, baseNamespace) {
var tokens;
if (typeof representationOfElementToCreate !== 'string')
throw new Error('Expecting string as first parameter');
if (baseNamespace === undefined)
baseNamespace = window;
tokens = representationOfElementToCreate.split('.');
// Remove the last element (which will contain the value)
tokens.pop();
// Use reduce to create part by part your new object
return tokens.reduce(function (prev, property) {
if (typeof prev !== 'object') {
throw Error('One property is already defined but not an object, namespace creation has failed', property);
return undefined;
} else {
if (!prev[property])
prev[property] = {};
return prev[property];
}
}, baseNamespace);
};
Then you can have:
function constructJson(jsonKey, jsonValue){
let jsonObj = langFile;
var lastItem = namespaceCreateExceptLast(jsonKey, jsonObj);
var lastKey = jsonKey.substring(jsonKey.lastIndexOf('.') + 1);
lastItem[lastKey] = jsonValue;
}
I have added some comments and exceptions to help you understand how it's done, but it's mainly based on the reduce function which you can easily get help for (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce).

Categories