I am new in node.js.I downloaded and executed a project from GitHub from this link. Here on this link there is live demo of this app. It is running rdf search using wikidata. This is the function that I found for the search of keyword from wikidata written in file public/scripts/controllers/main.js.
function search () {
//TODO: fix when null;
if (vm.searchInput != vm.lastSearch) {
var input = vm.searchInput;
vm.lastSearch = input;
vm.searchWait = true;
vm.noResults = false;
//$http.get('https://www.wikidata.org/w/api.php?action=wbsearchentities&format=json&language=en&limit=20&uselang=en&type=item&continue=0&search='+input).then(
$http({
method: 'GET',
url: 'https://www.wikidata.org/w/api.php',
params: {
action: 'wbsearchentities',
format: 'json',
language: 'en',
uselang: 'en',
type: 'item',
continue: '0',
limit: '20',
search: input,
origin: '*',
}
}).then(
function onSuccess (response) {
onSearch(response.data.search);
},
function onError (response) { onSearchErr(); console.log('Error: ' + response.data); }
);
//request.execQuery(query.search(input), onSearch, onSearchErr);
}
vm.searchActive = true;
}
I have changed the above function for DBpedia but it not search the keyword from DBpedia
function search2 () {
//TODO: fix when null;
if (vm.searchInput != vm.lastSearch) {
var input = vm.searchInput;
vm.lastSearch = input;
vm.searchWait = true;
vm.noResults = false;
//$http.get('https://www.wikidata.org/w/api.php?action=wbsearchentities&format=json&language=en&limit=20&uselang=en&type=item&continue=0&search='+input).then(
$http({
method: 'GET',
url: 'http://dbpedia.org/sparql',
params: {
action: 'wbsearchentities',
format: 'json',
language: 'en',
uselang: 'en',
type: 'item',
continue: '0',
limit: '20',
search: input,
origin: '*',
}
}).then(
function onSuccess (response) {
onSearch(response.data.search);
},
function onError (response) { onSearchErr(); console.log('Error: ' + response.data); }
);
//request.execQuery(query.search(input), onSearch, onSearchErr);
}
vm.searchActive = true;
}
how I can change this above function for search in DBpedia?Please help
Related
I'm trying to integrate Paytm's Payment gateway [Custom Checkout]. However, while UPI Integration, after sending the request i'm getting Invalid payment mode response code on the callback url.
As suggested in documentation,
First i'm calling the Initiate Transaction API for token.
initialise(order, res, next) {
const paytmParams = {};
paytmParams.body = {
requestType: 'Payment',
mid: paytm.mid,
websiteName: paytm.website,
orderId: order.orderId,
callbackUrl: paytm.callbackUrl,
txnAmount: {
value: order.amount,
currency: 'INR',
},
userInfo: {
custId: order.custId,
},
};
const paytmChecksum = PaytmChecksum.generateSignature(paytmParams.body, paytm.merchantKey);
paytmChecksum.then(function (checksum) {
paytmParams.head = {
signature: checksum,
};
const post_data = JSON.stringify(paytmParams);
const options = {
hostname: paytm.host,
port: 443,
path: `/theia/api/v1/initiateTransaction?mid=${paytm.mid}&orderId=${order.orderId}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length,
},
};
let response = '';
const post_req = https.request(options, function (post_res) {
post_res.on('data', function (chunk) {
response += chunk;
});
post_res.on('end', function () {
const result = JSON.parse(response);
if (result.body.resultInfo.resultStatus === 'S') {
res.status(200).json({ token: result.body.txnToken, orderId: order.orderId });
} else {
next(new ApiError(httpStatus.EXPECTATION_FAILED, result.body.resultInfo.resultMsg));
}
});
});
post_req.write(post_data);
post_req.end();
});
}
After this i'm taking the user's vpa and validating that via Validate VPA API.
validateUpi(data, res, next) {
const paytmParams = {};
paytmParams.body = {
vpa: data.upiId,
};
paytmParams.head = {
tokenType: 'TXN_TOKEN',
token: data.token,
};
const post_data = JSON.stringify(paytmParams);
const options = {
hostname: paytm.host,
port: 443,
path: `/theia/api/v1/vpa/validate?mid=${paytm.mid}&orderId=${data.orderId}`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length,
},
};
let response = '';
const post_req = https.request(options, function (post_res) {
post_res.on('data', function (chunk) {
response += chunk;
});
post_res.on('end', function () {
const result = JSON.parse(response);
if (result.body.resultInfo.resultStatus === 'S') {
res.status(200).json({
action: `https://${paytm.host}/theia/api/v1/processTransaction?mid=${paytm.mid}&orderId=${data.orderId}`,
params: {
mid: paytm.mid,
orderId: data.orderId,
txnToken: data.token,
paymentMode: 'UPI',
payerAccount: data.upiId,
},
});
} else {
next(new ApiError(httpStatus.EXPECTATION_FAILED, result.body.resultInfo.resultMsg));
}
});
});
post_req.write(post_data);
post_req.end();
}
After the successfull response, i'm returning the action URL and the params to the front end to create the form and post it in front end.
const res = await paymentAPI.validateUpiId(body);
paymentHelpers.createFormAndSubmit(res.action, res.params, 'redirect');
export const createFormAndSubmit = (url: string, data: any, type = "") => {
const form = document.createElement("form");
form.method = "POST";
form.action = url;
form.type = type;
Object.keys(data).forEach((key) => {
const input = document.createElement("input");
input.type = "text";
input.name = key;
input.value = data[key];
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
};
But after this form is being submitted, i'm getting redirected to callbackUrl with error message
http://localhost:3000/callback/paytm?retryAllowed=false&errorMessage=Invalid%20payment%20mode&errorCode=317
class FetchTenant {
constructor (){
this.Config = this._getConfig();
this.Token = this._getToken();
this.TenantMap = new Map();
}
async getTenantId(Id){
if(!this.TenantMap[Id]){
const serviceid = await this._getInfo(Id, false);
this.TenantMap[Id] = serviceid;
}
return this.TenantMap[Id];
}
_getConfig() {
return get_env_from_local({ name: 'env_1' });
}
async _getToken() {
const options = {
method: 'POST',
uri: `${this.Config.url}`,
json: true,
resolveWithFullResponse: false,
transform2xxOnly: true,
transform: body => body.access_token,
auth: {
username: this.Config.clientid,
password: this.Config.clientsecret
},
form: {
grant_type: 'client_credentials'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
return request(options)
.catch(err => {
logger.error('Could not get Token', err.statusCode, err.message);
return null;
});
}
async _getInfo(Id, newtoken) {
if(newtoken){
this.accessToken = await this._getToken();
if(this.accessToken == null){
logger.error(`fetching token failed`);
return null;
}
}
const options = {
method: 'GET',
uri: `${this.Config.url}/xyz/${Id}`,
json: true,
resolveWithFullResponse: false,
transform2xxOnly: true,
transform: body => body.tenantId,
auth: {
bearer: this.accessToken
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
return request(options)
.catch(err => {
if(err.statusCode != 401) {
logger.error(`Could not get tenant id`, err.statusCode, err.message);
return null;
}
else {
return this._getServiceInstanceInfo(Id, true);
}
});
}
}
module.exports = FetchTenant;
this is the class that i have created.
how to write a unit test for this class using sinon (stub and mock),i have to test only the public functions and the only public function here is getTenantId(Id) where in all the other private functions have a http request which can give either a valid response or an error.
is there any way to test the public function by mocking all the other private functions. i want to pre-define the data which will be returned by each private function and the primary data they fetch from env and use to send the request.
You can use nock (https://www.npmjs.com/package/nock) to mock all your http calls and test the public function you would normally do.
First, please understand that I am new to nodejs, and in fact javascript so temper your response accordingly as I might not be familiar with the concepts that seem very obvious to you.
Is it possible (and if yes, please point me in the right direction) to parse and use the response body from a request.get call in a new request?
For example:
var eventDetails;
function getLatestEvent() {
var options = {
url: 'http://localhost:4000/events/get/latest',
json: true,
headers: {
'User-Agent': 'request'
}
};
return new Promise(function(resolve, reject) {
request.get(options, function(err, resp, body) {
if (err) {
reject(err);
} else {
resolve(body);
console.log(body);
}
})
})
}
function resolveLatestEvent() {
var eventsPromise = getLatestEvent();
eventsPromise.then(function(result) {
eventDetails = result;
// Here I would like to make a new POST request using parts of
// the JSON response from the GET request above
// How can I parse and use the response body in the request,
// assuming the request looks something like below
// Send POST request
const config = { headers: { 'Content-Type': 'application/json' } };
request.post({
url: 'http://localhost:3000/events/notify',
headers: {},
data: {
title: '',
team: '',
day: '',
creator: '',
description: '',
ticket: ''
}
}, config);
// log result
console.log(eventDetails);
}, function(err) {
console.log(err);
})
}
console.log('Fetching latest event data and making new POST request');
resolveLatestEvent();
Example response body from the GET request:
[ { title: 'test title',
team: 'TEST',
description: 'asd asd asdf sdafsda',
ticket: 'ABC-12345',
day: 'Today at 10pm',
creator: 'user_name' } ] }
As the body is a JavaScript Object you could reference it with a . or with a key ['content'].
So you gonna get the return and use like:
eventsPromise[0].title
or
eventsPromise[0]['title']
As the response is inside an array you should reference the the position you want or just iterate to get to all the positions.
The correct solution from my code example above is as follows:
function resolveLatestEvent() {
var eventsPromise = getLatestEvent();
eventsPromise.then(function(result) {
eventDetails = result;
const config = { headers: { 'Content-Type': 'application/json' } };
axios({
method: 'post',
url: 'http://localhost:3000/events/notify',
headers: {},
data: {
title: eventDetails[0].title,
team: eventDetails[0].team,
day: eventDetails[0].day,
creator: eventDetails[0].creator,
description: eventDetails[0].description,
jira: eventDetails[0].ticket
}
}, config);
// Log out what we get for debugging
//console.log('here are the eventDetails', eventDetails)
}, function(err) {
console.log(err);
})
}
I am developing a chatbot on the Facebook Messenger Platform using Node.js. This is my functioning code for setting up a text response:
const fbReq = request.defaults({
uri: 'https://graph.facebook.com/me/messages',
method: 'POST',
json: true,
qs: {
access_token: Config.FB_PAGE_TOKEN
},
headers: {
'Content-Type': 'application/json'
},
});
const fbMessage = (recipientId, msg, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
text: msg,
},
},
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
I am also able to set up an image response this way. However, when I try to make the response a button template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template), no response is received. No error is thrown either.
const fbInfo = (recipientId, cb) => {
const opts = {
form: {
recipient: {
id: recipientId,
},
message: {
attachment:{
type:"template",
text:"Check out our website",
payload:{
template_type:"button",
buttons:[
{
type:"web_url",
url:"https://some.website.com",
title:"Website"
}
]
}
}
}
}
};
fbReq(opts, (err, resp, data) => {
if (cb) {
cb(err || data.error && data.error.message, data);
}
});
};
Instead of form you should use json.
take a look at the code which I have written on glitch
should be something like:
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: <TOKEN> },
method: 'POST',
json: messageData}, ...)
I'm currently building a node implementation of the new Box View API and I'm getting a 202 everytime I upload a document and retrieve a session. However, if I do a curl call, I dont get a 202. Is there anyone else experiencing this issue?
Here is my Ember Implementation:
export default Ember.View.extend({
document: null,
documentID: null,
session: null,
sessionID: null,
getDocument: function() {
var self = this;
return Ember.$.ajax({
url: 'http://localhost:3000/doc',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ "docURL": this.textField.value })
}).then(function(response){
self.set('document', response);
self.set('documentID', response.document_id);
});
},
getSession: function() {
var self = this;
return Ember.$.ajax({
url: 'http://localhost:3000/sess/',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ "docID": this.get('documentID') })
}).
then(function(response) {
self.set('session', response);
self.set('sessionID', response.session_id);
});
}.observes('documentID'),
actions: {
upload: function() {
this.getDocument();
}
}
});
Here is my node implementation:
var https = require('https');
var requestCount = 0;
exports.doc = function(req, res) {
var docURL = req.body.docURL;
var httpReq;
var opts = {
hostname: 'view-api.box.com',
path: '/1/documents',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Token <my token>' }
};
res.header('Access-Control-Allow-Origin', '*');
httpReq = https.request(opts, function(preq, pres) {
var output = '';
preq.on('data', function(chunk) {
output += chunk;
});
preq.on('end', function() {
output = JSON.parse(output);
output.document_id = output.id;
delete output.id;
res.json(output);
});
});
httpReq.write(JSON.stringify({ "url": docURL }));
httpReq.end();
};
exports.sess = getSession;
function getSession(req, res) {
var docID = req.body.docID;
var httpReq;
var opts = {
hostname: 'view-api.box.com',
path: '/1/sessions',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Token <my token>' }
};
res.header('Access-Control-Allow-Origin', '*');
httpReq = https.request(opts, function(preq, pres) {
var output = '';
if(preq.statusCode === 202) {
setTimeout(function() {
console.log('Retrying Request :: Count(' + requestCount + ')');
if (requestCount >= 3) {
res.json({ 'error': "Retry Again.", 'time': preq.headers['retry-after'] });
return;
}
getSession(req, res);
requestCount += 1;
}, 2000);
return;
}
preq.on('data', function(chunk) {
output += chunk;
});
preq.on('end', function() {
console.log('Successful Request!');
requestCount = 0;
output = JSON.parse(output);
output.session_id = output.id;
delete output.id;
res.json(output);
});
});
httpReq.write(JSON.stringify({ "document_id": docID, "duration": 60 }));
httpReq.end();
}
But now I'm getting this error. Is there a UI that can help me remove the uploaded documents?
{
"message": "You have exceeded your document upload rate-limit.",
"type": "error",
"request_id": "49f8b480b304496987b8cf21f5850c90"
}
You have the correct approach with retry-after for sessions.
The rate limiting you're seeing is actually due to the 2-document rate limit in place for the View API beta. See the FAQ for more info.
You can use webhooks to be notified when your documents finish converting (allowing you to upload another), so you don't have to poll the /documents endpoint for status.