using request-promise to querystring in JSON - node.js

I have a big API I want to query for userId and receive its details.
var options = {
uri: 'http://www.theapi.net/0862710324bo0',
method : 'GET',
useQuerystring: true,
qs: {
"must": [
{ "match": { "data.clients.id": req.params.userId }},
]
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
console.log(options.qs.must)
rp(options)
.then(function (repos) {
console.log(repos.clients.name);
res.status(200).json({
data:repos.clients[0].name
})
})...
This code returns:
[
{
match: { 'data.clients.id': 'b2d445-2160-4va7-ref-4edf860bd' }
}
]
undefined (because I didn't specify the object array index)
{
"data": "Sergio"
}
What I need:
{
"id":"ec9c1c4d-ab1a-41b2-bc1a-520b889cdeb9",
"name":"Sergio",
"email":"sergio#jorge.com",
},

I believe adding a "bool" tag would help you out.
var options = {
uri: 'http://www.theapi.net/0862710324bo0',
method : 'GET',
useQuerystring: true,
qs: {
"bool": { // Tag added
"must": [
{ "match": { "data.clients.id": req.params.userId }},
]
}
}
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
console.log(options.qs.must)
rp(options)
.then(function (repos) {
console.log(repos.clients.name);
res.status(200).json({
data:repos.clients[0].name
})
})
Beware - Untested code!

for (const [key, value] of Object.entries(repos.clients)) {
if (req.params.userId === repos.clients[key].id) {
return res.status(200).json({
data:repos.clients[key]
})
}
}

Related

null response when calling lambda

My lambda function is returning a null response and I'm not sure why. When I change 'res.body' to 'res.statusCode' I get the status code 200 as expected. I've checked the logs of my api call and see that there are no issues with the details I am passing (also confirmed using a curl command. Any ideas?
const https = require('https');
function getRequest() {
const options = {
host: 'vehimgd36c3.execute-api.ap-southeast-2.amazonaws.com',
path: '/callinglink',
method: 'GET',
headers: {
'link': 'https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html'
}
}
return new Promise(function(resolve, reject) {
https.get(options, (res) => {
resolve(res.body)
}).on('error', (e) => {
reject(Error(e))
})
})
}
exports.GetReturnMessage = async (event) => {
try {
const result = await getRequest();
console.log(result)
return {
"sessionState": {
"dialogAction": {
"type": "Close"
},
"intent": {
"confirmationState": "Confirmed",
"name": "FinalResponse",
"state": "InProgress",
},
},
"messages": [
{
"contentType": "CustomPayload",
"content": result
},
]
};
} catch (error) {
console.log('Error is: ️', error);
return {
statusCode: 400,
body: error.message,
};
}
};
If you check how to use lambda and apigateway. apigateway expects the lamba function to return a response with the structure Read here
var response = {
"statusCode": 200,
"body": "{\n \"TotalCodeSize\": 104330022,\n \"FunctionCount\": 26\n}"
}
in that case you could try returning your object as follows:
exports.GetReturnMessage = async (event) => {
try {
const result = await getRequest();
console.log(result)
const response = {
"sessionState": {
"dialogAction": {
"type": "Close"
},
"intent": {
"confirmationState": "Confirmed",
"name": "FinalResponse",
"state": "InProgress",
},
},
"messages": [
{
"contentType": "CustomPayload",
"content": result
},
]
};
return {
"statusCode": 200,
"body": JSON.stringify(response)
}
} catch (error) {
console.log('Error is: ️', error);
return {
statusCode: 400,
body: error.message,
};
}
}

chrome.webRequest.onBeforeSendHeaders.addListener() manifest_version:3

want an example chrome.webRequest.onBeforeSendHeaders.addListener() in [manifest_version:3],to change requestHeaders
chrome.webRequest.onBeforeSendHeaders.addListener(
(details) => {
return { requestHeaders: details.requestHeaders };
},
{ urls: ["<all_urls>"] },
["blocking", "requestHeaders", "extraHeaders"]);

Spotify: Create Playlist

Extending https://github.com/spotify/web-api-auth-examples - the code in the authorization_code folder.
It logs out access_token okay, but then hangs at the post request:
app.get('/createPlaylist', function(req, res) {
console.log('access_token=' + access_token)
request.post(
'https://api.spotify.com/v1/users/' + user_id + '/playlists',
{
headers: {
'Authorization' : access_token,
'Content-Type': 'application/json'
},
json: {
"collaborative": false,
"description": null,
// "external_urls": {
// "spotify": "http://open.spotify.com/user/thelinmichael/playlist/7d2D2S200NyUE5KYs80PwO"
// },
// "followers": {
// "href": null,
// "total": 0
// },
// "href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO",
// "id": "7d2D2S200NyUE5KYs80PwO",
"href": null,
"id": null,
"images": [],
"name": "A Generated Playlist",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/1150816110"
},
"href": "https://api.spotify.com/v1/users/1150816110",
"id": "1150816110",
"type": "user",
"uri": "spotify:user:1150816110"
},
"public": true,
// "snapshot_id": "s0o3TSuYnRLl2jch+oA4OEbKwq/fNxhGBkSPnvhZdmWjNV0q3uCAWuGIhEx8SHIx",
"tracks": {
"href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO/tracks",
// "href": "https://api.spotify.com/v1/users/kb8mc65qdvz4lz0gdk0i4ztp3/playlist/46RFjEgbskxglR8rVsu38x/tracks",
"items": [],
"limit": 100,
"next": null,
"offset": 0,
"previous": null,
"total": 0
},
"type": "playlist",
// "uri": "spotify:user:thelinmichael:playlist:7d2D2S200NyUE5KYs80PwO"
}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
});
Any idea what is wrong?
'It looks like your post is mostly code; please add some more details.'
What details StackOverflow? I just wanna know why the POST request hangs.
Modified my code to Kevin's specs ... can't believe I misread output for input ... but it still hangs ... node version v12.14.1
app.get('/createPlaylist', function (req, res) {
console.log('access_token=' + access_token)
request.post(
'https://api.spotify.com/v1/users/' + user_id + '/playlists',
{
headers: {
'Authorization': access_token,
'Content-Type': 'application/json'
},
json: {
name: 'A generated playlist',
public: true,
collaborative: false,
description: 'Generated at ' + Date.now(),
}
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
}
);
});
Comparing your code to the documentation, it looks like the code is sending the JSON output as the input in the example.
To create a playlist, there are only 4 body parameters:
name - string - required
public - boolean - optional
collaborative - boolean - optional
description - string - optional.
I don't know where all the other information is coming from but the API could be hanging up on all of it.
Also be sure you have the right scopes involved with permission to create a playlist for a user.
The request would look trimmed down:
request.post(
'https://api.spotify.com/v1/users/' + user_id + '/playlists',
{
headers: {
'Authorization' : access_token,
'Content-Type': 'application/json'
},
json: {
name: 'A generated playlist',
public: true,
description: 'A playlist generated by JS'
}
}
...

Returning responses from got (requests) to an object for callback

I am using got module to make POST requests to get data.
I am wanting to synchronously call 3 APIs, get the response objects, then callback. I am having trouble getting returning the response to callback object. It is returning {} instead of the actual response. I would also like to make all of these calls synchronously so that the requests are occurring simultaneously to save time.
const got = require('got');
exports.handler = (event, context, callback) => {
async function getDATA1() {
return await got.post('https://url.com/serviceapi/1/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":1,
}
}
}).json();
}
async function getDATA2() {
return await got.post('https://url.com/serviceapi/2/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":2,
"color":"blue",
}
}
}).json();
}
async function getDATA3() {
return await got.post('https://url.com/serviceapi/3/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":3,
"size":"large",
}
}
}).json();
}
callback(null,{
"DATA1": getDATA1(),
"DATA2": getDATA2(),
"DATA3": getDATA3(),
});
};
The response I am getting is
{
"DATA1": {},
"DATA2": {},
"DATA3": {}
}
The response I am expected/ want is something like this
{
"DATA1": {
"available_f":"Y"
},
"DATA2": {
"available_f":"N"
},
"DATA3": {
"available_f":"Y"
},
}
Those async functions will need to be awaited so you would need to do something like this that will wait till all of the requests have resolved and then you can gather the results and return them through the callback.
const got = require('got');
exports.handler = (event, context, callback) => {
async function getDATA1() {
return await got.post('https://url.com/serviceapi/1/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 1,
}
}
}).json();
}
async function getDATA2() {
return await got.post('https://url.com/serviceapi/2/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 2,
"color": "blue",
}
}
}).json();
}
async function getDATA3() {
return await got.post('https://url.com/serviceapi/3/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 3,
"size": "large",
}
}
}).json();
}
Promise.all([getDATA1, getDATA2, getDATA3]).then(values => {
return callback(null, {
DATA1: values[0],
DATA2: values[1],
DATA3: values[2]
})
}).catch(err => {
return callback(err);
});
};

Cannot assign to read only property '_id'

get Error Cannot assign to read only property '_id' when insert data in mongodb using node js
Cannot assign to read only property '_id' of
{"Diagnosis":"vvvvv",
"Treatment":[{
"name":"treatment1",
"SubTreatment":[{
"name":"subtreatment1",
"SubTreatment2" : [{
"name":"subtreatmentexp1",
"$$hashKey":"object:27","Name":"vvvvv"
}],
"$$hashKey":"object:22","Name":"vvvvv"
}],
"$$hashKey":"object:12",
"Name":"vvvvv"
}
]}
please help me to solve this error
my code is
app.post('/post', function (req, res) {
var diagnosis;
var obj = req.headers['data'];
var temp = JSON.parse(obj)
console.log("Received body data:");
console.log(obj);
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
insertDocument(temp, db, function () {
db.close();
});
});
var insertDocument = function (obj, db, callback) {
try {
console.log(obj);
db.collection('diagnosis').remove();
db.collection('diagnosis').insertOne(obj, function (err, result) {
assert.equal(err, null);
console.log("Inserted a document into the Diagnosis collection.");
callback();
});
res.send("Inserted a document into the Diagnosis collection.");
} catch (err) {
console.log(err);
}
};
})
my function to call API is
$scope.post = function () {
var diagnosis = $scope.Treatments;
var httpRequest = $http({
method: 'POST',
url: '/post',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'data': JSON.stringify($scope.Treatments)
},
}).success(function (data, status) {
});
};
Treatments array....
$scope.Treatments =
{
Diagnosis: '',
Treatment: [
{
name: 'treatment1',
SubTreatment: [
{
name: 'subtreatment1',
SubTreatment2: [{ name: 'subtreatmentexp1' }]
}
],
}
]
};
Generated JSON to insert data is
{
"Diagnosis": "sss",
"Treatment": [
{
"name": "treatment1",
"SubTreatment": [
{
"name": "subtreatment1",
"SubTreatment2": [
{
"name": "subtreatmentexp1",
"$$hashKey": "object:27",
"Name": "sss"
}
],
"$$hashKey": "object:22",
"Name": "sss"
}
],
"$$hashKey": "object:12",
"Name": "sss"
}
]
}

Resources