How to use objects inside res() in Node.js? - node.js

When I tried giving like this, it says error
temaplateObj.name: obj.name,
^
SyntaxError: Unexpected token .
My code:
var temaplateObj = {};
res.render('modules/users/server/templates/getdeals', {
temaplateObj.name: obj.name,
temaplateObj.from: common.tokenInfo.name,
temaplateObj.appName: 'GAIPP',
temaplateObj.company: company,
temaplateObj.logo: logo,
temaplateObj.url:url
},
I am not sure how to assing values to an obj inside res({}). Can any one suggest help?

Just pass a valid object to res.render():
res.render('modules/users/server/templates/getdeals', {
name : obj.name,
from : common.tokenInfo.name,
appName : 'GAIPP',
company : company,
logo : logo,
url : url
});
There's no need for temaplateObj.
If you want to assign it to an object first, use this:
var templateObj = {
name : obj.name,
from : common.tokenInfo.name,
appName : 'GAIPP',
company : company,
logo : logo,
url : url
};
res.render('modules/users/server/templates/getdeals', templateObj);

Related

Extract Public Id From Cloudinary URL

I am using Cloudinary to host my media on the cloud for my NodeJS project.
To delete an image from the Clodinary Cloud, I need to pass a Public Id for that image, to the Cloudinary API.
I realised, Public ID is embedded into the url, how to I extract it out from the URL?
Because, I don't want to store my data in this format :
image : {
url : `http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png`,
publicId : `rsorl4rtziefw46fllvh`
}
Rather, I find it better to store it like this :
image : `http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png`
The solution to this problem is to implement a funciton which extracts the publicId for every URL passed in as argument.
Here's the function :
const getPublicId = (imageURL) => imageURL.split("/").pop().split(".")[0];
Edited after #loic-vdb 's suggestion
Explanation :
It splits the string in an array using "/" as seperator.
imageURL="http://res.cloudinary.com/cloud_name/image/upload/v1647610701/rsorl4rtziefw46fllvh.png";
becomes,
imageURL = [ 'http:',
'',
'res.cloudinary.com',
'cloud_name',
'image',
'upload',
'v1647610701',
'rsorl4rtziefw46fllvh.png' ]
Next, pop the array (returns the last element of the array)
imageURL = 'rsorl4rtziefw46fllvh.png';
Now, split this string into array using "." as seperator, we get :
imageURL = [ 'rsorl4rtziefw46fllvh', 'png' ]
Finally select the 0th element that is our PublicId return that
imageURL = 'rsorl4rtziefw46fllvh';
Based on the answer by a Cloudinary support team member
... the public_id contains all folders and the last part of the public_id is the filename.
Here is what I tried and worked
const path = require("path");
const getPublicId = (imageURL) => {
const [, publicIdWithExtensionName] = imageURL.split("upload/");
const extensionName = path.extname(publicIdWithExtensionName)
const publicId = publicIdWithExtensionName.replace(extensionName, "")
return publicId
};
especially for cases where you store your assets in folders

Chrome Extension: contextMenus.create: Invalid url pattern

Trying to make a very simple Chrome extension. If someone right clicks on a subreddit link, there is a context option to send it to redditp.com instead.
background.js
{
function redpts(info,tab) {
var url = info.linkUrl;
console.log("Link " + info.selectionText + " was clicked to be redditp'd.");
var urlp = url.replace(/reddit.com/i, "redditp.com");
chrome.tabs.create({ url: urlp });
}
chrome.contextMenus.create({
"title" : "RedditP That Shizz!",
"type" : "normal",
"contexts" : ["link"],
"targetUrlPatterns": ["*://*reddit.com/r*"],
"onclick" : redpts
});
}
The error chrome throws is that I have not pattern matched the subreddit URL properly, but I very much tried to follow the formatting instructions of the 'Match Patterns' google page.
Full Error: Unchecked runtime.lastError while running contextMenus.create: Invalid url pattern '*://*reddit.com/r*'
I am a bit cross-eyed trying to see my mistake. Thanks.
Edit: If I comment out the targetUrlPatterns, it works as expected.
Your url pattern should be
"*://*.reddit.com/r*
and you context menu for new chrome version look like be
chrome.contextMenus.create({
"id" : "someuniquerid",
"title" : "RedditP That Shizz!",
"type" : "normal",
"contexts" : ["link"],
"targetUrlPatterns": ["*://*.reddit.com/r*"]
});
chrome.contextMenus.onClicked.addListener(function(e){
if(e.menuItemId == 'someuniquerid') {
chrome.tabs.getSelected(function(tab){
// do you work here
});
}
});

Getting specific keys from dictionaries

I am developing an API service for my website. The website is about Recipes, where a user is supposed to register on his first visit, then log in. When he logs in he gets an access token, which he uses to do REST services on categories and recipes.
So coming to Recipes, he can give a title, ingredients, and directions. Example:
{
"title" : "api recipe",
"directions" : "Testing api recipe directions",
"ingredient1" : "postman",
"ingredient2" : "ing2",
"ingredient3" : "me",
"ingredient4" : "ingredient4",
"ingredient5" : "ingredient5"
}
Now, I am facing a problem when it comes to PUT method. I want to enable a user to edit a recipe giving only that which he wants to edit. Example:
{
"title" : "PUT"
}
Using PUT method, if a user provides an ingredient as such:
{
"ingredient2" : "Potatoes",
"ingredient5" : "stackexchange"
}
I would like to only change the ingredients that he provided me with and leave the rest the way it is.
Before coming to my question, when a user provides the above, I get a dictionary with the keys and values he/she has provided. My question is, how can I get all the ingredients he wants to edit plus their number?
my code:
data = request.get_json()
category = Category.query.filter_by(user_id=user_id).filter_by(id=category_id).first()
if not category:
return jsonify({'message' : 'category does not exists'})
category.edit_recipe(data, id=recipe_id)
return jsonify({'message' : 'Edited successfully'})
def edit_recipe(self, data, *args, **kwargs):
edit_this = None
if 'id' in kwargs:
edit_this = Recipe.query.filter_by(id=kwargs['id']).filter_by(category_id=self.id).first()
else:
edit_this = Recipe.query.filter_by(title=kwargs['prev_title']).filter_by(category_id=self.id).first()
"""TODO: Get ingredient from data followed by its number.
if data == {'title' = 'change title', 'ingredient2' = 'change ing 2', 'ingredient5' = 'change ing 5'}
then I want to get keys that start with ingredient followed by their number and its value
"""
if 'title' in data:
edit_this.title = data['title']
if 'directions' in data:
edit_this.directions = data['directions']
if 'filename' in data:
edit_this.filename = data['filename']
db.session.commit()
To get only the ingredients, the following below should
keyValue = {
"title" : "api recipe",
"directions" : "Testing api recipe directions",
"ingredient1" : "postman",
"ingredient2" : "ing2",
"ingredient3" : "me",
"ingredient4" : "ingredient4",
"ingredient5" : "ingredient5"
}
oldListOfKeys = keyValue.keys()
ingredientsList = filter(lambda x: x not in ["directions", "title"], oldListOfKeys)
newDict = {key: keyValue[key] for key in keyValue if key in ingredientsList}
print newDict # {'ingredient4': 'ingredient4', 'ingredient5': 'ingredient5', 'ingredient1': 'postman', 'ingredient2': 'ing2', 'ingredient3': 'me'}
(Am using this in a flask app with sqlAlchemy- hope it helps)
In your put method, first query of a specific recipe for example
recipe = Recipe.query.filter_by(recipe_id=id).first()
Then you can access the specific keys like this
data = request.get_json()
recipe.title = data['title']
recipe.directions = data['directions']
recipe.ingredient1 = data['ingredient1']
recipe.ingredient2 = data['ingredient2']

How to use dynamic variable name in nodejs

I need a dynamic variable in nodejs .
I use the allocine-api, and she return, a different object when I use it . For example :
allocine.api(type, {code: code}, function(error, result) {
if(error){
console.log('Error : '+ error);
return;
}
socket.emit("allocine_"+type ,result);
});
if type is "movie", result contain a movie object, but if type is "tvseries", result contain a tvseries object. So I need to take the variable "originalTitle" in "tvseries" or "movie" object, so I need to make this :
result.<type>.originalTitle
But, how to use the contain of "type" for this ?
I have try with the javascript method, and the use of "window['type']", but it's don't work in nodeJs .
as javascript objects elements can be accessed as an associative array ( cf mozilla js doc )
using myobject.myproperties is strictly equal to use myobject["myproperties"]
so if a var hold the properties name to read var myvar = "myproperties"; you could also use myobject[myvar]
so, concretely :
var o = {
tvseries : {
originalTitle : "hello world"
}
}, type = "tvseries";
console.log( o[type].originalTitle );
jsfiddle
also, if the result object get only one sub object, named by the type, you can get type name directly from it
var type = Object.keys( myobject )[0];
jsfiddle
or more simply :
var theTitle = myobject[ Object.keys( myobject )[0] ].originalTitle;
jsfiddle
var results = {};
results.a = {originalTitle: "One"};
var results2 = {b:{originalTitle: "Two"}};
console.log(results['a'].originalTitle); //now one
console.log(results2['b'].originalTitle); //now Two
With two ways of creating the object.
Try the fiddle:
http://jsfiddle.net/rmoskal/6rf0juq6/

Getting url for an attachment

I'm using CouchApp to build an easy web application that allows to upload and manage pictures. The actual image file is stored as attachment to the doc like show below.
{
"_id":"09fe82d75a26f9aa5e722d6b220180d2",
"_rev":"2-5797b822c83b9d41545139caa592f611",
"data":"some additional fields with info about the image",
"_attachments":
{
"foo.jpg":
{
"stub":true,
"content_type":"image/jpeg",
"length":23721
}
}
}
But for integrating the image in html i need the url to the attachment. How do i get this url?
I'm using evently and mustache for generating the web pages. Below is the data.js for reading the data:
function(data) {
return {
items : data.rows.map(function(r) {
return {
id : r.value._id,
rev : r.value._rev,
title : r.value.description,
url : "how am i supposed to do this?"
};
})
};
};
The URL to the attachment would be http://domain/database/09fe82d75a26f9aa5e722d6b220180d2/foo.jpg
If your filenames are dynamic, you would have to iterate the _attachments object and fetch the keys on your way - that's where your filename would be.
for(var filename in r.value._attachments){break;}
// ...
url : '<database>/' + r.value._id +'/'+filename;

Resources