Call to external javascript function in Cloudant/CouchDB design doc - javascript

I have a design document written in javascript (someone else wrote this function) for a Cloudant database. This function is created to update a document. Within this document I want to first make a call to JSON.minify which I have found some code for online at https://www.npmjs.com/package/jsonminify
The code for the update function is below.. and I want to know how to make a call to JSON.minify from the code as suggested within the link provided: JSON.parse(JSON.minify(str));
Where I currently have _ref = JSON.parse(reqBody) I want to use _ref = JSON.prase(JSON.minify(reqBody));
Can someone tell me how I can call this external code from a design doc in Cloudant. (Cloudant works very similar to CouchDB in most cases, so I think it may be the same answer)
Thanks in advance!
function(doc, req) {
if (!doc) {
return [doc, JSON.stringify({ status: 'failed' })];
}
var reqBody=req.body;
_ref = JSON.parse(reqBody);
for (k in _ref) {
v = _ref[k];
if (k[0] === '/'){
nestedDoc = doc;
nestedKeys = k.split('/');
_ref1 = nestedKeys.slice(1, -1);
for (_i = 0, _len = _ref1.length; _i < _len; _i++){
nestedKey = _ref1[_i];
nestedDoc = ((_ref2 = nestedDoc[nestedKey]) != null ? _ref2 : nestedDoc[nestedKey] = {});
}
k = nestedKeys.slice(-1)[0];
if (v === '__delete__'){
delete nestedDoc[k];
}
continue;
}
if (v === '__delete__'){ delete doc[k]; }
else{ doc[k] = v; } }
return [ doc, JSON.stringify({ status: 'success' }) ];
}

You should be able to either include the source code at the top of your update function, or load it as a CommonJS module.
Have you tried either one?

Related

Cal.com vanilla javascript embed doesn't work with Svelte

I want to embed cal.com on a website build with SvelteKit, but I can't make it work with vanilla javascript instruction from the official documentation.
I followed official documentation for vanilla javascript. I've tried version for Next.js, and It worked flawless, but for some reason I can't make it done in svelte.
Last line Cal("init") throws error "Cannot find name 'Cal'." And on a server I'm getting "500 Internal Error"
<script>
(function (C, A, L) {
let p = function (a, ar) {
a.q.push(ar);
};
let d = C.document;
C.Cal =
C.Cal ||
function () {
let cal = C.Cal;
let ar = arguments;
if (!cal.loaded) {
cal.ns = {};
cal.q = cal.q || [];
d.head.appendChild(d.createElement("script")).src = A;
cal.loaded = true;
}
if (ar[0] === L) {
const api = function () {
p(api, arguments);
};
const namespace = ar[1];
api.q = api.q || [];
typeof namespace === "string" ? (cal.ns[namespace] = api) && p(api, ar) : p(cal, ar);
return;
}
p(cal, ar);
};
})(window, "https://cal.com/embed.js", "init");
Cal("init")
</script>
So I figured it out by myself, that I was trying to paste this script in +page.svelte file. To make it work You need to put it in the head tag in the app.html file.

NodeJS x-ray web-scraper:multiple urls in a loop callback

im using x-ray, which is great but lack of tutorial. anyway, I use an array of urls named urls. In the loop ,each url fetched and return result through callback. in the callback function i need to know what was the url which was parsed. How can i know which url is returning if the callback returns only err and results? (is it really an x-ray question or js)
xrayRamiLevy = function(){
var index = 0;
for (index; index < urls.length; index++){
x(urls[index].url, '.product_item',
[{
title : '.prodDescDiv h3',
description : '.prodBrand',
imageUrl : '.image_icons_zone .image img#src',
onclick : '.image_icons_zone .image a #onclick',
}]
)
(function(err, results){
for (var i = 0; i < results.length; i++){
var s = results[i].onclick.substr(0, results[i].onclick.lastIndexOf("'"));
s = s.slice(s.lastIndexOf("'") + 1);
results[i].catalogueNumber = s;
delete results[i].onclick;
if (results[i].description !== undefined && results[i].description.length > 0)
s = results[i].description.replace(/\s+/g, ' ').trim();
results[i].description = s;
if (urls[index].category !== undefined && urls[index].category.length > 0)
results[i].categoriesIds = urls[index].category;
if (urls[index].subcategory !== undefined && urls[index].subcategory.length > 0)
results[i].subcategoriesIds = urls[index].subcategory;
}
fs.writeFile("./results.json", JSON.stringify(results, null, '\t'));
});
}
}
See example of getting the url using JS closure. Note how the URL from the array is available in the fn callback.
var Xray = require('x-ray');
var util = require('util');
var x = Xray();
var sitesToHandle = ['https://dribbble.com?x=1', 'https://dribbble.com?x=2'];
sitesToHandle.forEach((urlToHandle) => {
x(urlToHandle, 'li.group', [{
title: '.dribbble-img strong',
image: '.dribbble-img [data-src]#data-src',
}]).(function (err, results) {
console.log(`let's now handle the result of ${urlToHandle}, the results are ${util.inspect(results)}`);
});
});
p.s. side note, when handling the returned errors, you might take a look at an error handling guide that I just wrote here
I didn't fully get your example, HOWEVER:
urls.forEach(function(url, index){
//whatever you need to do to prep your call to x
var callback = x(url, '.product_item', ...);
callback(wrappedCallback(url));
}
function wrappedCallback(url) {
return function(err, results){
// url is defined here
}
};

Plupload filters to allow all but a few extensions

Pupload lets you specify which file types can be uploaded, but I want to do the opposite: Allow all filetypes except a certain subset. Is this possible?
Someone posted a solution on Plupload's Github. You have to use the addFileFilter method.
plupload.addFileFilter('excluded_extensions', function(filter, file, cb){
var permitted = true;
var exts = filter[0].extensions.split(',');
//We have no excluded extensions, function presented default exclusion string, so allow anything
if(exts.length === 1 && exts[0] === "-")
permitted = true;
else
{
for(var i = 0; i < exts.length; i++)
{
var fileArray = file.name.split('.');
var extension = fileArray[fileArray.length - 1];
if(exts[i].toUpperCase() === extension.toUpperCase())
{
this.trigger('Error', {
code: plupload.FILE_EXTENSION_ERROR,
message: plupload.translate('File extension error.'),
file: file
});
permitted = false;
cb(false);
return;
}
}
}
if(permitted)
cb(true);
});
Source

Javascript Rewrite Config File

I have a config.js file which I believe is JSON which is called when the application first starts:
var config={};
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
]
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
]
To pull / push data I just use the following:
// Read
var curPrice = config.price[0].primary;
// Write
config.price[0].primary = "98.24";
How do I go about exporting the config file with the new value so that it will load next time the application is opened? I can use the file system object to write the file, I just don't understand how I would export everything (and preferably keep the same format).
I originally thought about reading the whole config file into a variable, cycling through to find the required block, id, and key and replacing the value, then writing the whole thing back, but I can't seem to figure out how to replace that specific value only.
Any help would be greatly appreciated
Edit Apologies, I forgot to mention that this application is completely offline and uses local directories
Solution
I stumbled across a few solutions to different issues which, when combined, gave me the perfect solution. First we cycle the Javascript object, building an array of the detail and then converting the array to a string:
vMethod.convertToText = function(obj) {
var string = [];
var output = '';
var count= 0;
var countTotal = 0;
if (typeof(obj) == "object" && (obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("{");
for (prop in obj) {
countTotal++;
}
for (prop in obj) {
if(count==countTotal - 1) {
string.push(prop, ": ", vMethod.convertToText(obj[prop]),'}\r\n');
} else {
string.push(prop, ": ", vMethod.convertToText(obj[prop]), ",");
}
count++;
};
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("[\r\n")
for (prop in obj) {
countTotal++;
}
for(prop in obj) {
if(count==countTotal - 1) {
string.push(vMethod.convertToText(obj[prop]),'];\r\n');
} else {
string.push(vMethod.convertToText(obj[prop]), ",");
}
count++;
}
} else if (typeof(obj) == "function") {
string.push(obj.toString())
} else {
string.push(JSON.stringify(obj))
}
output = string.join("").toString();
//output = output.slice(1, -1);
return output;
}
Then we clean the array (neccessary for me to remove excess characters)
vMethod.cleanConfigText = function() {
var outputText = vMethod.convertToText(config);
outputText = outputText.slice(1, -1);
outputText = 'var config = {};\r\n'+outputText;
outputText = outputText.replace('user:','config.user =');
outputText = outputText.replace(',price:','config.price =');
outputText = outputText.slice(0, -2);
outputText = outputText.replace(/"/g, "'")
return outputText;
}
Finally a function to export the object into my config.js file:
vMethod.writeToConfig = function() {
vObject.fileSystem = new ActiveXObject('Scripting.FileSystemObject');
vObject.fileSystemFile = vObject.fileSystem.CreateTextFile('source\\js\\config.js',true);
vObject.fileSystemFile.Write(vMethod.cleanConfigText());
vObject.fileSystemFile.Close();
delete vObject.fileSystemFile;
delete vObject.fileSystem;
}
So when I want to export a change in the config, I just call:
vMethod.writeToConfig();
The only difference in the file format is that the commas appear at the start of a trailing line rather than the end of a preceding line but I can live with that!
Edit Turns out I'm anally retentive and the commas were bugging me
Added these to the clean up function and now the config is identical to before but without the indent
outputText = outputText.replace(/[\n\r]/g, '_');
outputText = outputText.replace(/__,/g, ',\r\n');
outputText = outputText.replace(/__/g, '\r\n');
Thank you to those that looked at the question and tried to help, very much appreciated.
Edit
DO NOT READ THE SOLUTION ABOVE, IT IS IN THE WRONG PLACE AND THERFORE IS NOT A VALID ANSWER. YOU'VE BEEN WARNED.
You can use a very popular npm package: https://www.npmjs.com/package/jsonfile . There are many but I've choosen this one.
Usually config stuff should be in json or .env files.
Now, all you have to do is use jsonfile's API to read/write JSON and parse (the package does the serialization/deserialization) it at the beginning when the application starts.
Example:
var jsonfile = require('jsonfile');
var util = require('util');
var config = null;
var file = './config.json';
// Reading
jsonfile.readFile(file, function(err, obj) {
config = obj;
});
// Writing
// Edit your config blah blah
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
];
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
];
jsonfile.writeFile(file, config, function (err) {
if(err) return err;
console.log('Config saved to file!');
});

javascript show the source of page the that runs the script

I have a firefox extension, and I would like to know how can I see witch file my script is running on.
I'm using window.location.href but in my case is not so useful.
Because I want to know what kind of file, for example, i just want my script be run on html files.
How can I do this? some ideas?
You can throw an Error, catch it and inspect the callstack.
var frames = [];
try {
throw new Error("debug");
} catch (exception) {
if (exception.stack && typeof exception.stack === "string") {
var lines = exception.stack.split("\n");
for (var i = 0; i < lines.length; i += 1) {
var frame = lines[i].match(new RegExp("^(.*)#(.*):(.*)$"));
frames.push({
"function": frame[1] || "anonymous",
"line": frame[3],
"file": frame[2]
});
}
}
}
console.log(frames);
fixed:
window.addEventListener('load', function () {
if (document.doctype) {
if (document.doctype.name == 'html') {
easy :)
thank you anyway for your help

Categories