node-config change delimiter from dot to colon - node-config

Im migrating my config from another library to node-config.
I have two questions:
The old library uses config.get('a:b'); to get some value, but node-config use a single dot as a delimiter: config.get('a.b');.
Is there is a way to configure it to use : to save my time and refactor my code?
Is there is a way to set a runtime values. e.g. config.set('key', 'val');?

Done it by:
1. wrap node-config in a new js file
2. proxied the get, has and set methods methods
Something like that:
const config = require('config');
const inMemDict = {};
const toNewKey = key => {
return key && key.split(':').join('.');
};
const { get: origGet, has: origHas } = config;
config.get = function (key, ...args) {
key = toNewKey(key);
if(typeof inMemDict[key] !== 'undefined') {
return inMemDict[key];
}
return origGet.apply(config, [key, ...args]);
};
config.has = function (key, ...args) {
key = toNewKey(key);
if(typeof inMemDict[key] !== 'undefined') {
return inMemDict[key];
}
return origHas.apply(config, [key, ...args]);
};
config.set = function (key, val) {
if(!key) return;
inMemDict[toNewKey(key)] = val;
};
module.exports = config;

Related

CosmosDB-Raise Exception from Stored Proc if Etag does not match

I am trying to upsert document using below Stored Proc . I am passing different types of document in input having same partition key. Some if them are for create and some of them needs to be updated only if Etag matches. If e-Tag does not match my requirement is to throw exception from Stored Procedure which I need to handle in my Java code. Can someone please help me what changes I should make in below SP to handle that.
function createEvent(items) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var count = 0;
if (!items) throw new Error("The array is undefined or null.");
var numItems = items.length;
if (numItems == 0) {
getContext().getResponse().setBody(0);
return;
}
tryCreate(items[count], callback);
function tryCreate(item, callback) {
var options = { disableAutomaticIdGeneration: false };
var isAccepted = collection.upsertDocument(collectionLink, item, options, callback);
if (!isAccepted) getContext().getResponse().setBody(count);
}
function callback(err, item, options) {
if (err) throw err;
count++;
if (count >= numItems) {
getContext().getResponse().setBody(count);
} else {
tryCreate(items[count], callback);
}
}
}

Single sign on failing with LinkedIn account to a microsoft website

We are seeing an issue with users unable to access our production and PPE apps via LinkedIn sign in. The redirection is not happening to specified redirect URL once users provides user name and password. The network trace shows login is successful but not going to redirect URL. This has been working last 4 years or so and suddenly started failing in both environments from yesterday.
Bummer. Something went wrong
We tried verifying the network trace and a support case is raised to LinkedIn with recording. Finally we are redirected to raise the issue here.
I had the same issue and found that it was caused by using JSON.stringify to "overload" the state parameter with other parameters. In my case, I add other parameters in the following way:
providerCfg.auth_params.state = JSON.stringify({
state: providerCfg.auth_params.state,
redirectPageUrl,
redirectParams,
userTypeBit,
isLogin
})
const authUrl = new URL(providerCfg.auth_url)
Object.entries(providerCfg.auth_params).forEach(([key, val]) => {
authUrl.searchParams.append(key, encodeURIComponent(val))
})
return buildURL(providerCfg.auth_url, providerCfg.auth_params)
When I removed the call to JSON.stringify and just passed in a state parameter, the oauth flow worked correctly. Obviously, the other parameters that I passed in were important so I created my own functions to serialize and deserialize the values. The code below works well for anything other than deeply nested objects. You will need to update the metaDataCfg based on your own requirements.
const META_STRING_DELIMITER = '|'
const serializeBasicObject = (targetObj) => {
if (!targetObj) {
return ''
}
return Object.entries(targetObj).reduce((objString, [key, val]) => {
const param = `${key}=${val || ''}`
if (!objString.length) {
return param
}
return `${objString}${META_STRING_DELIMITER}${param}`
}, '')
}
const deserializeBasicObject = (targetStr) => {
if (!targetStr) {
return ''
}
const keyValPairs = targetStr.split(META_STRING_DELIMITER)
return keyValPairs.reduce((targetObj, keyValPair) => {
const splitIdx = keyValPair.indexOf('=')
const key = keyValPair.slice(0, splitIdx)
targetObj[key] = keyValPair.slice(splitIdx + 1, keyValPair.length)
return targetObj
}, {})
}
const metaDataCfg = {
state: {},
redirectPageUrl: {},
redirectParams: {
serialize: serializeBasicObject,
deserialize: deserializeBasicObject
},
userTypeBit: { deserialize: Number },
isLogin: { deserialize: dataUtil.getBoolean }
}
const getMetaString = (metaData) => {
return Object.entries(metaDataCfg).reduce((metaString, [metaDataKey, cfg]) => {
const val = (cfg.serialize) ? cfg.serialize(metaData[metaDataKey]) : metaData[metaDataKey]
const param = `${metaDataKey}=${dataUtil.isNil(val) ? '' : val}`
if (!metaString.length) {
return param
}
return `${metaString}${META_STRING_DELIMITER}${param}`
}, '')
}
export const getDataFromMetaString = (metaString) => {
const params = metaString.split(META_STRING_DELIMITER)
const data = params.reduce((metaData, param) => {
const splitIdx = param.indexOf('=')
const key = param.slice(0, splitIdx)
let val = param.slice(splitIdx + 1, param.length)
if (dataUtil.isNil(val) || !val.length) {
return metaData
}
const deserializer = metaDataCfg[key].deserialize
if (deserializer && val) {
val = deserializer(val)
}
metaData[key] = val
return metaData
}, {})
return data
}

How to set the templateUrl in a component in Angular2?

How can I set the templateUrl in code? E.g., if I have
#Component({
selector: 'search-load',
templateUrl: '/loads/search'
})
I want:
#Component({
selector: 'search-load',
templateUrl: this.language+ 'loads/search'
})
where templateUrl is a mvc path.
Thank you.
You cannot this in component declaration like this since its outside of component's scope but this is how I do something like this
In my component:
#Component({
selector: 'live-auction-stats',
templateUrl: BaseConfigurations.baseTemplatePath + '/auction-stats.html',
})
And In my BaseConfigurations.ts file, I have
export abstract class BaseConfigurations
{
public baseTemplatePath: string = location.origin + '/app/templates'; //you can configure here
....
//other base configurations..
....
}
After a long searching i found that node_modules\#angular\platform-browser-dynamic\bundles\platform-browser-dynamic.umd.js is the responsible for loading template by url
so i can add some params to url dynamically like this :
var lang = JSON.parse(localStorage.getItem("Accept-Language"));
xhr.open('GET', lang+url, true);
then the final file will be :
(function(System, SystemJS) {/**
* #license Angular v2.2.3
* (c) 2010-2016 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('#angular/compiler'), require('#angular/core'), require('#angular/platform-browser')) :
typeof define === 'function' && define.amd ? define(['exports', '#angular/compiler', '#angular/core', '#angular/platform-browser'], factory) :
(factory((global.ng = global.ng || {}, global.ng.platformBrowserDynamic = global.ng.platformBrowserDynamic || {}),global.ng.compiler,global.ng.core,global.ng.platformBrowser));
}(this, function (exports,_angular_compiler,_angular_core,_angular_platformBrowser) { 'use strict';
var INTERNAL_BROWSER_PLATFORM_PROVIDERS = _angular_platformBrowser.__platform_browser_private__.INTERNAL_BROWSER_PLATFORM_PROVIDERS;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ResourceLoaderImpl = (function (_super) {
__extends(ResourceLoaderImpl, _super);
function ResourceLoaderImpl() {
_super.apply(this, arguments);
}
ResourceLoaderImpl.prototype.get = function (url) {
var resolve;
var reject;
var promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
var xhr = new XMLHttpRequest();
var lang = JSON.parse(localStorage.getItem("Accept-Language"));
xhr.open('GET', lang+url, true);
xhr.responseType = 'text';
xhr.onload = function () {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec (supported
// by IE10)
var response = xhr.response || xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : 0;
}
if (200 <= status && status <= 300) {
resolve(response);
}
else {
reject("Failed to load " + url);
}
};
xhr.onerror = function () { reject("Failed to load " + url); };
xhr.send();
return promise;
};
ResourceLoaderImpl.decorators = [
{ type: _angular_core.Injectable },
];
/** #nocollapse */
ResourceLoaderImpl.ctorParameters = [];
return ResourceLoaderImpl;
}(_angular_compiler.ResourceLoader));
var INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS = [
INTERNAL_BROWSER_PLATFORM_PROVIDERS,
{
provide: _angular_core.COMPILER_OPTIONS,
useValue: { providers: [{ provide: _angular_compiler.ResourceLoader, useClass: ResourceLoaderImpl }] },
multi: true
},
];
/**
* #license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var globalScope;
if (typeof window === 'undefined') {
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
// TODO: Replace any with WorkerGlobalScope from lib.webworker.d.ts #3492
globalScope = self;
}
else {
globalScope = global;
}
}
else {
globalScope = window;
}
// Need to declare a new variable for global here since TypeScript
// exports the original value of the symbol.
var _global = globalScope;
// TODO: remove calls to assert in production environment
// Note: Can't just export this and import in in other files
// as `assert` is a reserved keyword in Dart
_global.assert = function assert(condition) {
// TODO: to be fixed properly via #2830, noop for now
};
/**
* #license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __extends$1 = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* An implementation of ResourceLoader that uses a template cache to avoid doing an actual
* ResourceLoader.
*
* The template cache needs to be built and loaded into window.$templateCache
* via a separate mechanism.
*/
var CachedResourceLoader = (function (_super) {
__extends$1(CachedResourceLoader, _super);
function CachedResourceLoader() {
_super.call(this);
this._cache = _global.$templateCache;
if (this._cache == null) {
throw new Error('CachedResourceLoader: Template cache was not found in $templateCache.');
}
}
CachedResourceLoader.prototype.get = function (url) {
if (this._cache.hasOwnProperty(url)) {
return Promise.resolve(this._cache[url]);
}
else {
return Promise.reject('CachedResourceLoader: Did not find cached template for ' + url);
}
};
return CachedResourceLoader;
}(_angular_compiler.ResourceLoader));
var __platform_browser_dynamic_private__ = {
INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS: INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
ResourceLoaderImpl: ResourceLoaderImpl
};
/**
* #experimental
*/
var RESOURCE_CACHE_PROVIDER = [{ provide: _angular_compiler.ResourceLoader, useClass: CachedResourceLoader }];
/**
* #stable
*/
var platformBrowserDynamic = _angular_core.createPlatformFactory(_angular_compiler.platformCoreDynamic, 'browserDynamic', INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS);
exports.RESOURCE_CACHE_PROVIDER = RESOURCE_CACHE_PROVIDER;
exports.platformBrowserDynamic = platformBrowserDynamic;
exports.__platform_browser_dynamic_private__ = __platform_browser_dynamic_private__;
}));
})(System, System);

Why am I getting this error in a basic Rails+Ember app?

I am trying to do a simple CRUD app using Ember + Rails and I'm getting the following error when trying to go to the /workouts route.
Error while loading route: TypeError {} ember.js?body=1:415
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
My code is located here: https://github.com/ecl1pse/ember-workouts
What am I doing wrong?
Edit: Upon further investigation I believe the culprit is
EmberWorkouts.WorkoutsRoute = Ember.Route.extend(
model: -> EmberWorkouts.Workout.find()
This doesn't actually return anything. How do I debug from there?
If I replace that with this
EmberWorkouts.WorkoutsRoute = Ember.Route.extend
model: -> [{title: 'hi'}, {title: 'damn'}]
The view actually renders content.
How do I get the model to collect from Rails properly?
Ember Data's interface has changed a little with the current release:
You can clear out the store.js file entirely. Ember Data will automatically set up a data store for you using the REST Adapter (unless you tell it otherwise).
Use model: -> #store.find('workout') instead.
I tested this with your app and it works.
If you haven't read through the Ember Data Guide in the last week or two (it's changed a lot), I would spend a few minutes on it.
The fix for this error (as of ember-data 1.0.0.beta.6) for me was to make sure that the JSON returned from the server included an "id" field for each model, BUT not to explicitly declare the id when setting up the Ember DS.Model.
jbuilder template:
json.scans do
json.array! #scans do |scan|
json.id scan.id # This prop has to be there
json.name scan.name
end
end
Ember model:
EmberApp.Scan = DS.Model.extend(
// Don't include the id prop here
name: DS.attr("string")
)

using the Advanced Compilation in google closure compiler

I am new in google closure compiler,and after read the documents in the closure tools site,I create a js and make the test.
However I found that even I use the Advanced Compilation level,the compiled codes are still easy to decompilated.
For example,this is the codes:
//2
window["_NameSpace_"]={};
window["_NameSpaceInternal_"]={};
(function() {
_NameSpaceInternal_.Class = function() {
var clazz = function() {
this["init"] && this["init"].apply(this, arguments);
};
var pros = {}, arg;
for(var c = 0, k = arguments.length; c < k; ++c) {
arg = arguments[c];
if( typeof arg === 'function') {
if(c == 0 && k > 1) {
var F = function() {
};
F.prototype = arg.prototype;
pros = new F;
arg = arg.prototype;
}
} else {
if(arg.init) {
clazz = arg["init"];
delete arg["init"]
}
}
}
for(var p in arg)
pros[p] = arg[p]
clazz.prototype = pros;
return clazz;
};
})();
(function(d){
d["Person"]=_NameSpaceInternal_.Class({
"init":function(name){
this.name=name;
},
"whatever":function(aaa){
}
});
})(_NameSpace_);
After compiled(I make a pretty format for human reading):
window.__MapNS__ = {};
window.__MapNSImpl__ = {};
__MapNSImpl__.a = function() {
function c() {
this.init && this.init.apply(this, arguments)
}
for (var b = {}, a, d = 0, e = arguments.length; d < e; ++d) if (a = arguments[d], "function" === typeof a) 0 == d && 1 < e && (b = function() {}, b.prototype = a.prototype, b = new b, a = a.prototype);
else {
a.b && (c = a.init, delete a.init)
}
if (!b || !a) throw Error("You must provide an object to copy from and to");
for (var f in a) b[f] = a[f];
c.prototype = b;
return c
};
(function(c) {
c.Person = __MapNSImpl__.a({
init: function(b) {
this.name = b
},
whatever:function(x){
}
})
})(__MapNS__);
Now,taks the class defination for "Person" for example, after compiled,all the methods for "Person" are clearly for hacker even these method have to be exposed.
But I wonder if I can make the compiled codes like this;
...........
var xx="init",xxx="whatever",xxxx=="Person";
c[xxxx] = __MapNSImpl__.a({
xx: function(b) {
this.name = b
},
xxx:function(x){
}
})
...........
Just like the google map's compress.
Any idea?
The exact answer you are looking for is to enable the AliasStrings pass in the compiler by either using the Java API or by making a custom build of the compiler. The pass is not enabled by default as it tends to produce larger code when accounting for gzip.
To actually get the same effect that most google products achieve, you'll need to make substantial changes to your code.
Define your objects and methods in the global scope. Assign them to namespaces after declaring them globally. You can use the output_wrapper flag to wrap the compiled code in a function to prevent global scope collisions. Example:
function a() {}; window['Namespace']['obj'] = a;
Define your objects directly - don't use a helper method. So instead of
var a = _NameSpaceInternal_.Class({"init":function(name){ this.name=name; });
You would use something like:
function a(){}; a.prototype.name = ""; a.prototype.init = function(name) { this.name=name; };
This avoids using quoted syntax and allows the compiler to rename your properties and methods.
For many more examples of coding style that compiles/renames optimally with Closure-compiler, see the Closure Library.

Resources