How to call collector customize module in MARKLOGIC-DHF 5.6.1 - marklogic-dhf

I need to call external collector customize module in DHF 5.6.1.
How can I do that?
When I passed module in source query, it works but in main.sjs, I can only see 'uri' is coming within 'content' object. I can't see 'value' and 'context' within content object . Am I doing right or not? Is there a proper way to achieve it?

if you wish to see a 'value' and 'context' within the content object, those aren't returned out-of-the-box and should be configured in your main.sjs that is being referenced.
For example, this is one instance of the 'value' and 'context' can be configured and returned with your custom module (obviously it is generating a different use case but the concept should still apply)
function main(content, options) {
const inputDocument = content.value;
let additionalContent = [];
let myNodeList = inputDocument.getElementsByTagName("person");
if(myNodeList && myNodeList.length){
for(var i = 0; i < myNodeList.length; i++){
additionalContent.push({
uri: `/integration/analytics/${i}.json`,
value: myNodeList[i],
context: content.context
})
}
}
return additionalContent;
}
module.exports = {
main
};

Related

nodejs express server get request log symbols value [duplicate]

I have an object in NodeJS (a socket to be accurate).
When I print it, I see that one of the entries is this:
[Symbol(asyncId)]: 2781 // the numeric value changes
How can I obtain the value of such key?
I've tried socket['[Symbol(asyncId)]'] but got undefined.
The expression socket.[Symbol(asyncId)] would obviously not work.
You will not be able to access it directly by key, unless you have a reference to the actual: Symbol('asyncId'), because every Symbol is unique
The Symbol() function returns a value of type symbol, has static
properties that expose several members of built-in objects, has static
methods that expose the global symbol registry, and resembles a
built-in object class but is incomplete as a constructor because it
does not support the syntax "new Symbol()".
What you can do is loop through the object's own property keys, using Reflect.ownKeys, which will include normal properties & symbols, and then obtain that reference.
You can also use: Object.getOwnPropertySymbols()
function getObject() {
// You don't have access to this symbol, outside of this scope.
const symbol = Symbol('asyncId');
return {
foo: 'bar',
[symbol]: 42
};
}
const obj = getObject();
console.log(obj);
console.log(obj[Symbol('asyncId')]); // undefined
// or Object.getOwnPropertySymbols(obj)
const symbolKey = Reflect.ownKeys(obj)
.find(key => key.toString() === 'Symbol(asyncId)')
console.log(obj[symbolKey]); // 42
NOTE: The object can have multiple keys where key.toString() === 'Symbol(asyncId)', this won't be usual, but be aware, so you may want to use other function other than .find if that's the case.
NOTE II:
You should not change the value of that property, since it's supposed to be for internal access only, even if the property is not read only.
function getObject() {
// You don't have access to this symbol, outside of this scope.
const symbol = Symbol('asyncId');
const symbol2 = Symbol('asyncId');
return {
foo: 'bar',
[symbol]: 'the value I don\'t want',
[symbol2]: 'the value I want'
};
}
const obj = getObject();
const symbolKey = Reflect.ownKeys(obj)
.find(key => key.toString() === 'Symbol(asyncId)')
console.log(obj[symbolKey]); // the value I don't want
console.log('=== All values ===');
Reflect.ownKeys(obj)
.forEach(key => console.log(obj[key]));
Use Object.getOwnPropertySymbols(obj) and iterate over it
You need to store the Symbol in advance and use it as accessor for the object.
Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose. Some further explanation about purpose and usage can be found in the glossary entry for Symbol.
var asyncId = 42,
symbol = Symbol(asyncId),
object = { [symbol]: 2781 };
console.log(object[symbol]);
console.log(symbol.toString());

requests module returns JSON with items unordered

When I'm using node's requests module this way:
router.get('http://[some_api_url]')
res.send()
I get different JSON ordered in contrary to viewing the JSON via browser.
For example, via res.send() I get:
[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]
Whereas via browser I see it as supposed to be:
[{"key2":"value2","key1":"value1"},{"key2":"value2","key1":"value1"}],
The function is this:
getAllEvnets:async(req, res)=> {
let event = []
try{
var listEvent = await events.findAll()
for (let i = 0; i < listEvent.length; i++) {
event.push({
id: listEvent[i].id_event,
start: listEvent[i].debut,
end : listEvent[i].fin,
title: listEvent[i].title,
color: {red: {
primary: '#ad2121',
secondary: '#FAE3E3'}
},
actions: ''
})
}
res.json(event)
}
catch(err){
res.send(err.message)
}
}
ECMAscript says...
The mechanics and order of enumerating the properties ... is not
specified.
So there is no guarantee that it will be ordered. Anyway usually it dont need it to be ordered you acces it with an dot notation like key1.value1. No matter if its the first property in the object or the last one, it doenst matter.

How to update a module.exports properly?

I have this file that stores some of my environment variables.
Let's call it generalEnv.js
module.exports = {
CONSTANT_1: process.env.CONSTANT_1,
CONSTANT_2: process.env.CONSTANT_2
};
When the app initializes, I don't put the value of process.env.CONSTANT_1 in the env variables yet because I have to look into some places first if it exists(mongodb for instance). If it does not exists on mongodb, I will add a value into process.env.CONSTANT_1 and I was expecting that the value will reflect on generalEnv now.
When I tried accessing the CONSTANT_1 in another file.
Let's call it getConstantOne.js
const { CONSTANT_1 } = require('./generalEnv');
module.exports = () => {
// I was expecting that CONSTANT_1 will have a value here now
if(!CONSTANT_1) {
// do something
}
return CONSTANT_1
}
it does not reflect.. how do I update the closure of generalEnv.js for process.env.CONSTANT_1 to reflect on CONSTANT_1?
When assigning to a variable (or a value in an object/element in an array), the assignment will replace the value, not modify it. Therefore, any "copies" of that value will not be affected, and remain the same. Consider this example:
let a = 0;
let b = a;
a = 1;
What happens to b? Answer: Its value is 0.
To work around this we need some way of modifying the value instead of replacing it. Unfortunately, "primitive types" (strings/numbers/booleans etc.) cannot be modified in javascript. There are types that can be modified however, such as objects. You could solve this by wrapping your variables in an object called "env".
let env: {
CONSTANT_1: process.env.CONSTANT_1,
CONSTANT_2: process.env.CONSTANT_2
}
modules.exports = { env }
and then to modify:
env.CONSTANT_1 = "new value"
and to access:
if (!env.CONSTANT_1) { ... }

FabricJs - How do I Add properties to each object

I need to introduce few additional properties to existing object properties set.
like:
ID
Geo Location
etc
Whenever I draw a shape, I need to add additional properties to the shape and need to get from toDataLessJSON()
As of version 1.7.0 levon's code stopped working. All you need to do is to fix as follows:
// Save additional attributes in Serialization
fabric.Object.prototype.toObject = (function (toObject) {
return function (properties) {
return fabric.util.object.extend(toObject.call(this, properties), {
textID: this.textID
});
};
})(fabric.Object.prototype.toObject);
You have to receive properties argument and pass it on to toObject.
Here's a code for adding custom properties and saving them in JSON serialization for any object on canvas. (I used standard javascript object properties, but it works for me)
canvas.myImages = {};
fabric.Image.fromURL('SOME-IMAGE-URL.jpg', function(img) {
canvas.myImages.push(img);
var i = canvas.myImages.length-1;
canvas.myImages[i].ID = 1; // add your custom attributes
canvas.myImages[i].GeoLocation = [40, 40];
canvas.add(canvas.myImages[i]);
canvas.renderAll();
});
And you then include the custom attribute in object serialization.
// Save additional attributes in Serialization
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
textID: this.textID
});
};
})(fabric.Object.prototype.toObject);
// Test Serialization
var json = JSON.stringify(canvas.toDatalessJSON());
console.log(json);
canvas.clear();
// and load everything from the same json
canvas.loadFromDatalessJSON(json, function() {
// making sure to render canvas at the end
canvas.renderAll();
}

Object.defineProperty on any property [duplicate]

I am aware of how to create getters and setters for properties whose names one already knows, by doing something like this:
// A trivial example:
function MyObject(val){
this.count = 0;
this.value = val;
}
MyObject.prototype = {
get value(){
return this.count < 2 ? "Go away" : this._value;
},
set value(val){
this._value = val + (++this.count);
}
};
var a = new MyObject('foo');
alert(a.value); // --> "Go away"
a.value = 'bar';
alert(a.value); // --> "bar2"
Now, my question is, is it possible to define sort of catch-all getters and setters like these? I.e., create getters and setters for any property name which isn't already defined.
The concept is possible in PHP using the __get() and __set() magic methods (see the PHP documentation for information on these), so I'm really asking is there a JavaScript equivalent to these?
Needless to say, I'd ideally like a solution that is cross-browser compatible.
This changed as of the ES2015 (aka "ES6") specification: JavaScript now has proxies. Proxies let you create objects that are true proxies for (facades on) other objects. Here's a simple example that turns any property values that are strings to all caps on retrieval, and returns "missing" instead of undefined for a property that doesn't exist:
"use strict";
if (typeof Proxy == "undefined") {
throw new Error("This browser doesn't support Proxy");
}
let original = {
example: "value",
};
let proxy = new Proxy(original, {
get(target, name, receiver) {
if (Reflect.has(target, name)) {
let rv = Reflect.get(target, name, receiver);
if (typeof rv === "string") {
rv = rv.toUpperCase();
}
return rv;
}
return "missing";
}
});
console.log(`original.example = ${original.example}`); // "original.example = value"
console.log(`proxy.example = ${proxy.example}`); // "proxy.example = VALUE"
console.log(`proxy.unknown = ${proxy.unknown}`); // "proxy.unknown = missing"
original.example = "updated";
console.log(`original.example = ${original.example}`); // "original.example = updated"
console.log(`proxy.example = ${proxy.example}`); // "proxy.example = UPDATED"
Operations you don't override have their default behavior. In the above, all we override is get, but there's a whole list of operations you can hook into.
In the get handler function's arguments list:
target is the object being proxied (original, in our case).
name is (of course) the name of the property being retrieved, which is usually a string but could also be a Symbol.
receiver is the object that should be used as this in the getter function if the property is an accessor rather than a data property. In the normal case this is the proxy or something that inherits from it, but it can be anything since the trap may be triggered by Reflect.get.
This lets you create an object with the catch-all getter and setter feature you want:
"use strict";
if (typeof Proxy == "undefined") {
throw new Error("This browser doesn't support Proxy");
}
let obj = new Proxy({}, {
get(target, name, receiver) {
if (!Reflect.has(target, name)) {
console.log("Getting non-existent property '" + name + "'");
return undefined;
}
return Reflect.get(target, name, receiver);
},
set(target, name, value, receiver) {
if (!Reflect.has(target, name)) {
console.log(`Setting non-existent property '${name}', initial value: ${value}`);
}
return Reflect.set(target, name, value, receiver);
}
});
console.log(`[before] obj.example = ${obj.example}`);
obj.example = "value";
console.log(`[after] obj.example = ${obj.example}`);
The output of the above is:
Getting non-existent property 'example'
[before] obj.example = undefined
Setting non-existent property 'example', initial value: value
[after] obj.example = value
Note how we get the "non-existent" message when we try to retrieve example when it doesn't yet exist, and again when we create it, but not after that.
Answer from 2011 (obsoleted by the above, still relevant to environments limited to ES5 features like Internet Explorer):
No, JavaScript doesn't have a catch-all property feature. The accessor syntax you're using is covered in Section 11.1.5 of the spec, and doesn't offer any wildcard or something like that.
You could, of course, implement a function to do it, but I'm guessing you probably don't want to use f = obj.prop("example"); rather than f = obj.example; and obj.prop("example", value); rather than obj.example = value; (which would be necessary for the function to handle unknown properties).
FWIW, the getter function (I didn't bother with setter logic) would look something like this:
MyObject.prototype.prop = function(propName) {
if (propName in this) {
// This object or its prototype already has this property,
// return the existing value.
return this[propName];
}
// ...Catch-all, deal with undefined property here...
};
But again, I can't imagine you'd really want to do that, because of how it changes how you use the object.
Preface:
T.J. Crowder's answer mentions a Proxy, which will be needed for a catch-all getter/setter for properties which don't exist, as the OP was asking for. Depending on what behavior is actually wanted with dynamic getters/setters, a Proxy may not actually be necessary though; or, potentially, you may want to use a combination of a Proxy with what I'll show you below.
(P.S. I have experimented with Proxy thoroughly in Firefox on Linux recently and have found it to be very capable, but also somewhat confusing/difficult to work with and get right. More importantly, I have also found it to be quite slow (at least in relation to how optimized JavaScript tends to be nowadays) - I'm talking in the realm of deca-multiples slower.)
To implement dynamically created getters and setters specifically, you can use Object.defineProperty() or Object.defineProperties(). This is also quite fast.
The gist is that you can define a getter and/or setter on an object like so:
let obj = {};
let val = 0;
Object.defineProperty(obj, 'prop', { //<- This object is called a "property descriptor".
//Alternatively, use: `get() {}`
get: function() {
return val;
},
//Alternatively, use: `set(newValue) {}`
set: function(newValue) {
val = newValue;
}
});
//Calls the getter function.
console.log(obj.prop);
let copy = obj.prop;
//Etc.
//Calls the setter function.
obj.prop = 10;
++obj.prop;
//Etc.
Several things to note here:
You cannot use the value property in the property descriptor (not shown above) simultaneously with get and/or set; from the docs:
Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.
Thus, you'll note that I created a val property outside of the Object.defineProperty() call/property descriptor. This is standard behavior.
As per the error here, don't set writable to true in the property descriptor if you use get or set.
You might want to consider setting configurable and enumerable, however, depending on what you're after; from the docs:
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
Defaults to false.
enumerable
true if and only if this property shows up during enumeration of the properties on the corresponding object.
Defaults to false.
On this note, these may also be of interest:
Object.getOwnPropertyNames(obj): gets all properties of an object, even non-enumerable ones (AFAIK this is the only way to do so!).
Object.getOwnPropertyDescriptor(obj, prop): gets the property descriptor of an object, the object that was passed to Object.defineProperty() above.
obj.propertyIsEnumerable(prop);: for an individual property on a specific object instance, call this function on the object instance to determine whether the specific property is enumerable or not.
The following could be an original approach to this problem:
var obj = {
emptyValue: null,
get: function(prop){
if(typeof this[prop] == "undefined")
return this.emptyValue;
else
return this[prop];
},
set: function(prop,value){
this[prop] = value;
}
}
In order to use it the properties should be passed as strings.
So here is an example of how it works:
//To set a property
obj.set('myProperty','myValue');
//To get a property
var myVar = obj.get('myProperty');
Edit:
An improved, more object-oriented approach based on what I proposed is the following:
function MyObject() {
var emptyValue = null;
var obj = {};
this.get = function(prop){
return (typeof obj[prop] == "undefined") ? emptyValue : obj[prop];
};
this.set = function(prop,value){
obj[prop] = value;
};
}
var newObj = new MyObject();
newObj.set('myProperty','MyValue');
alert(newObj.get('myProperty'));
You can see it working here.
I was looking for something and I figured out on my own.
/*
This function takes an object and converts to a proxy object.
It also takes care of proxying nested objectsa and array.
*/
let getProxy = (original) => {
return new Proxy(original, {
get(target, name, receiver) {
let rv = Reflect.get(target, name, receiver);
return rv;
},
set(target, name, value, receiver) {
// Proxies new objects
if(typeof value === "object"){
value = getProxy(value);
}
return Reflect.set(target, name, value, receiver);
}
})
}
let first = {};
let proxy = getProxy(first);
/*
Here are the tests
*/
proxy.name={} // object
proxy.name.first={} // nested object
proxy.name.first.names=[] // nested array
proxy.name.first.names[0]={first:"vetri"} // nested array with an object
/*
Here are the serialised values
*/
console.log(JSON.stringify(first)) // {"name":{"first":{"names":[{"first":"vetri"}]}}}
console.log(JSON.stringify(proxy)) // {"name":{"first":{"names":[{"first":"vetri"}]}}}
var x={}
var propName = 'value'
var get = Function("return this['" + propName + "']")
var set = Function("newValue", "this['" + propName + "'] = newValue")
var handler = { 'get': get, 'set': set, enumerable: true, configurable: true }
Object.defineProperty(x, propName, handler)
this works for me

Resources