Access Object.prototype.<method_name> method - javascript

I am working on a nodeJS based project where I am using node-zendesk package. This library provides functions to extract list of articles. But the method is in form of Object.prototype.list, I have no idea how to access this method.
node-zendesk package is inside node_modules.
The method I need to access is at node-zendesk/lib/client/helpcenter/articles.js
var util = require('util'),
Client = require('../client').Client
var Articles = exports.Articles = function(options) {
this.jsonAPINames = ['articles', 'article'];
this.sideLoadMap = [{
field: 'author_id',
name: 'user',
dataset: 'users'
},
{
field: 'section_id',
name: 'section',
dataset: 'sections'
},
{
field: 'category_id',
name: 'category',
dataset: 'categories'
}
];
Client.call(this, options);
};
util.inherits(Articles, Client);
Articles.prototype.list = function(cb) {
this.requestAll('GET', ['articles'], cb); //all
};
I need to access Articles.prototype.list. What I have tried is:
var zendesk = require('node-zendesk');
var client = zendesk.createClient({
username: < my_username > ,
token: < my_token > ,
remoteUri: < my_remoteUri > ,
helpcenter: true
});
client.articles.list((err, req, result) => {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(result)); //gets the first page
});
The error is something like this:
{ Error: Zendesk Error (404): Item not found
> at checkRequestResponse (/<project_path>/node_modules/node-zendesk/lib/client/client.js:259:13)
at requestCallback (/<project_path>/node_modules/node-zendesk/lib/client/client.js:274:3)
at Request._callback (/<project_path>/node_modules/node-zendesk/lib/client/client.js:111:5)
at Request.self.callback (/<project_path>/node_modules/request/request.js:185:22)
at Request.emit (events.js:189:13)
at Request.EventEmitter.emit (domain.js:441:20)
at Request.<anonymous> (/<project_path>/node_modules/request/request.js:1161:10)
at Request.emit (events.js:189:13)
at Request.EventEmitter.emit (domain.js:441:20)
at IncomingMessage.<anonymous> (/<project_path>/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:277:13)
at IncomingMessage.emit (events.js:194:15)
at IncomingMessage.EventEmitter.emit (domain.js:441:20)
at endReadableNT (_stream_readable.js:1103:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Help me to access Articles.prototype.list method.

It seems you're accessing the articles' list method correctly. You're probably just getting a network error due to the 404 Item Not Found.

Related

NodeJS discord-rpc application not found

I am trying to setup Discord RPC. For it, I registered a new application and copied the client ID.
Then I am using this code:
const RPC = require("discord-rpc");
const discordClient = new RPC.Client({ transport: "ipc" });
let defaultActivity;
(async () => {
discordClient.on("ready", async () => {
console.log('Authed for user', discordClient.user);
console.log(discordClient.application.name);
console.log(discordClient.user.username);
defaultActivity = {
details: `${discordClient.user.username}`,
state: "Test",
largeImageKey: "test",
largeImageText: "Kirka Client",
smallImageText: `${discordClient.user.username}#${discordClient.user.discriminator}`,
}
discordClient.setActivity(defaultActivity);
});
await discordClient.login({clientId: "871730144836976650"}).catch(console.error)
})();
But this gives me the following error:
Authed for user { id: '771601176155783198',
username: 'AwesomeSam',
discriminator: '7985',
avatar: '93d3fd4fb9fd0921830d69e07a248036',
bot: false,
flags: 176,
premium_type: 1 }
(node:6664) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of null
at RPCClient.discordClient.on (D:\kirkaclient\src\features\discordRPC.js:9:47)
at RPCClient.emit (events.js:198:13)
at RPCClient.login (D:\kirkaclient\node_modules\discord-rpc\src\client.js:139:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
Well, it is as it says.
Cannot read property 'name' of null
It seems that the property "discordClient.application" in line 9 is null, so it could not read a "name" value of null.
I'm not into discord-rpc, I do prefer discord.js, so I can't come up with a solution for this.
You should try debugging it with console.log(discordClient)

Spotify API - JSON returns undefined, but I can still console.log() it

I'm trying to use Spotify's Web Player API to access the value 'device_id'. According to the docs, the server-side API call I make should return a 'json payload that contains device objects' such as below:
This is my API call:
app.get('/c+party', (req,res)=>{
const access_token = req.query.access_token;
var device_id;
var options = {
url: 'https://api.spotify.com/v1/me/player/devices',
headers: {
'Authorization': 'Bearer '+ access_token,
'Content-Type':'application/json'
},
json:true
};
request.get(options, (err,response,body) => {
const device_id = body.devices[0].id;
res.json(device_id);
});
});
It should return:
{
"devices" : [ {
"id" : "5fbb3ba6aa454b5534c4ba43a8c7e8e45a63ad0e",
"is_active" : false,
"is_private_session": true,
"is_restricted" : false,
"name" : "My fridge",
"type" : "Computer",
"volume_percent" : 100
} ]
}
edit, here's the error:
const device_id = body.devices[0].id;
^
TypeError: Cannot read property 'id' of undefined
at Request._callback (C:\code\music-room\src\server.js:69:43)
at Request.self.callback (C:\code\music-room\node_modules\request\request.js:185:22)
at Request.emit (events.js:223:5)
at Request.<anonymous> (C:\code\music-room\node_modules\request\request.js:1154:10)
at Request.emit (events.js:223:5)
at IncomingMessage.<anonymous> (C:\code\music-room\node_modules\request\request.js:1076:12)
at Object.onceWrapper (events.js:312:28)
at IncomingMessage.emit (events.js:228:7)
at endReadableNT (_stream_readable.js:1185:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
I can console.log(body) to see the desired output, but I can't actually access the value I want. When my code runs, I get an error that body.devices is undefined. Any help with a fix? I'm brand new with express.js - is my routing messing this up?
Another edit: I tried res.json(body)... my server is responding with an empty 'devices' array of objects.
You are actually sending an empty response back from your API. That's what res.end() does. I am not entirely sure what is the content of the Spotify API response, but if you can see the correct JSON value in the body variable, you can use res.json(...) instead of res.end() like so:
request.get(options, (err,response,body) => {
// Assuming that the body variable contains the correct data
const device_id = body.devices[0].id;
res.json(device_id);
});

Cannot read property 'castForQuery' of undefined at castArrayFilters in Node.js

I am using arrayFilters as option in findOneAndUpdate (in mongoose) to update value of name and isRecursive fields in TimetableModel.
The fields are updating successfully in MongoDb but also I am getting the exception, which is being added at the end of this query.
What am I supposed to do to eliminate this exception?
Following are the details of my work:
Versions: "mongodb": "^3.1.13",
"mongoose": "^5.4.9",
this is the Schema:
const timetableSchema = new Schema({
individualId: {
type: Schema.Types.ObjectId,
required: true
},
date: {
type: Number,
required: false
},
time: []});
this is the logic:
TimetableModel.findOneAndUpdate({
individualId: req.query.individualId,
date: req.query.date,
}, {
'time.$[i].name': req.query.name,
'time.$[i].isRecursive': req.query.isRecursive,
}, {
arrayFilters: [{
'i.timeSlot': req.query.timeSlot
}],
}, function (err, result) {
if (result) {
resolve(result);
} else if (err) {
reject(err);
}
}).catch((err) => {
reject(err);
})
and this is the exception
"TypeError: Cannot read property 'castForQuery' of undefined
at castArrayFilters (/Users/user/Desktop/Projects/ParentsPlus/ParentsPlusRepo/parents-plus-back-end/node_modules/mongoose/lib/helpers/update/castArrayFilters.js:59:37)
at _castArrayFilters (/Users/user/Desktop/Projects/ParentsPlus/ParentsPlusRepo/parents-plus-back-end/node_modules/mongoose/lib/query.js:1739:5)
at model.Query.Query._findAndModify (/Users/user/Desktop/Projects/ParentsPlus/ParentsPlusRepo/parents-plus-back-end/node_modules/mongoose/lib/query.js:3205:3)
at model.Query. (/Users/user/Desktop/Projects/ParentsPlus/ParentsPlusRepo/parents-plus-back-end/node_modules/mongoose/lib/query.js:2830:8)
at model.Query._wrappedThunk [as _findOneAndUpdate] (/Users/user/Desktop/Projects/ParentsPlus/ParentsPlusRepo/parents-plus-back-end/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/Users/user/Desktop/Projects/ParentsPlus/ParentsPlusRepo/parents-plus-back-end/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)"
I think there is a bug since version 5.4.4 or maybe another previous version. It was reported here. For the moment I solved it by downloading the mongoose version to 5.3.15.

serverless framework with json parsing error

I use serverless framework with javascript.
my code is:
import { App } from '../lib/App';
export const hello = (event, context, cb) => {
context.callbackWaitsForEmptyEventLoop = false;
// This resolved promise would be be in the application library code in a real-world application and provide the results
App.handleFirst(event) // eslint-disable-line promise/catch-or-return
.then(result => ({
statusCode: 200,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(result)
}))
.asCallback(cb);
return;};
inside App.js
import BbPromise from 'bluebird';
const THE_MESSAGE = 'Hello from the webpack 4 sample';
export class App {
static handleFirst(event) {
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event
};
console.info(myDemoResult);
return BbPromise.resolve(myDemoResult);
}
I use fellow command to deploy it.
set SLS_DEBUG=*
severless deploy
my error is:
Syntax Error -------------------------------------------
Unexpected token A in JSON at position 0
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
Stack Trace --------------------------------------------
SyntaxError: Unexpected token A in JSON at position 0
SyntaxError: Unexpected token A in JSON at position 0
at JSON.parse (<anonymous>)
at BbPromise.try (F:\workspace\svlecma\node_modules\serverless-webpack\lib\packagers\npm.js:61:47)
at tryCatcher (F:\workspace\svlecma\node_modules\bluebird\js\release\util.js:16:23)
at Function.Promise.attempt.Promise.try (F:\workspace\svlecma\node_modules\bluebird\js\release\method.js:39:29)
at Utils.spawnProcess.catch.then.then.depJson (F:\workspace\svlecma\node_modules\serverless-webpack\lib\packagers\npm.js:61:35)
at tryCatcher (F:\workspace\svlecma\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:512:31)
at Promise._settlePromise (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:569:18)
at Promise._settlePromise0 (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:614:10)
at Promise._settlePromises (F:\workspace\svlecma\node_modules\bluebird\js\release\promise.js:694:18)
at _drainQueueStep (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:138:12)
at _drainQueue (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:131:9)
at Async._drainQueues (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (F:\workspace\svlecma\node_modules\bluebird\js\release\async.js:17:14)
From previous event:
at PluginManager.invoke (C:\Users\sheng\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:390:22)
at PluginManager.spawn (C:\Users\sheng\AppData\Roaming\npm\node_modules\serverless\lib\classes\PluginManager.js:408:17)
at ServerlessWebpack.BbPromise.bind.then.then.then (F:\workspace\svlecma\node_modules\serverless-webpack\index.js:102:51)
at runCallback (timers.js:694:18)
at tryOnImmediate (timers.js:665:5)
at processImmediate (timers.js:647:5)
at process.topLevelDomainCallback (domain.js:121:23)
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Issues: forum.serverless.com
Your Environment Information -----------------------------
OS: win32
Node Version: 10.10.0
Serverless Version: 1.31.0
my serverless.yml is here:
https://gist.github.com/thinksource/9fd0c8728df2195b7110b3be04aec2ae
why json first element error? how Can I see the json string?
After seeing your serverless.yml file, I believe that the issue may well be in the webpack.config.js file. It may be worth trying changing your custom section, and putting quotes around: 'webpack.config.js'. Like:
custom:
webpack:
webpackConfig: 'webpack.config.js'
includeModules: true
I think that the issue is in your App.js class here:
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event
};
You have a invalid JSON structure; where the object event is being passed, it is not being given a key/name. You probably want something like:
const myDemoResult = {
message: App.THE_MESSAGE,
from: 'First lambda ',
event: event
};
Also your constant THE_MESSAGE is not inside your App class. You should move it inside the App classes {..} like this:
export class App {
static get THE_MESSAGE() { return 'Hello from the webpack 4 sample'; }
...

Undefined not a function -- Meteor Smart Package

Recently, I've been trying to work on a smart package for a project I'm working on, and I'm having a problem.
The following code lives inside server/methods.js:
Meteor.startup(function() {
Meteor.methods({
// ISBN Lookup for AWS
isbnAWS: function(isbn) {
OperationHelper = apac.OperationHelper;
isbn = isbn.replace(/-/g,"");
console.log("Looking up ISBN: " + isbn);
cachedBook = BookCache.findOne({"isbn": isbn});
// If the book isn't in cache, use apac to get information into cache.
if (!cachedBook) {
// Instantiate the OH object for APAC.
OpHelper = new OperationHelper({
awsId: AWS_KEY_ID,
awsSecret: AWS_SECRET_KEY,
assocId: AWS_ASSOC_ID
});
// Use OH to query AWS, synchronously.
result = OpHelper.executeSync({
SearchIndex: 'Books',
ResponseGroup: 'Medium,Images',
IdType: 'ISBN',
ItemId: isbn
});
console.log(result);
} else {
console.log("Using cache for ISBN: " + isbn);
}
}
});
});
This method is being called by an event handler in a project template, as such:
"click #isbn-btn": function() {
// Store the current ISBN in Session, for reactivity.
theISBN = $("#isbn").val().trim().replace(/-/g, "");
Session.set("aws-isbn", theISBN);
// Make a call to our Meteor.method, which will contact AWS, and give us
// a result.
Meteor.call("isbnAWS", theISBN, function(err, res) {
if (err)
console.log("Error: " + err);
else
console.log("Success!");
});
}
OperationHelper is part of the package I have written, which contains this code, inside the package's lib/meteor-apac.js:
if (!Meteor.isClient) {
apac = Npm.require("apac-czbaker");
OperationHelper = apac.OperationHelper;
function makeSyncMethod(method){
var wrapped=Meteor._wrapAsync(method);
var syncMethod=function(){
return wrapped.apply(this,arguments);
};
return syncMethod;
}
OperationHelper.prototype.executeSync = makeSyncMethod(OperationHelper.prototype.execute);
}
And this is my package.js, where the apac object is clearly exported for use in my project:
Package.describe({
summary: "Access to the Amazon Product Advertising API, using the NodeJS 'apac' module.",
version: "0.0.4",
git: "https://github.com/czbaker/meteor-apac.git",
name: "czbaker:apac"
});
Npm.depends({
"apac-czbaker": "1.0.0"
});
Package.onUse(function(api) {
api.versionsFrom('METEOR#0.9.0.1');
api.use('underscore', 'server');
api.addFiles('lib/meteor-apac.js');
api.export('apac');
});
For some reason, I get the following output when I try to use the executeSync() function that I attempt to add using my package:
I20140831-15:16:56.651(-4)? Looking up ISBN:
W20140831-15:16:56.826(-4)? (STDERR)
W20140831-15:16:56.826(-4)? (STDERR) events.js:72
W20140831-15:16:56.827(-4)? (STDERR) throw er; // Unhandled 'error' event
W20140831-15:16:56.827(-4)? (STDERR) ^
W20140831-15:16:56.831(-4)? (STDERR) TypeError: undefined is not a function
W20140831-15:16:56.831(-4)? (STDERR) at /home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/lib/OperationHelper.js:85:17
W20140831-15:16:56.832(-4)? (STDERR) at Parser.<anonymous> (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:384:20)
W20140831-15:16:56.832(-4)? (STDERR) at Parser.emit (events.js:95:17)
W20140831-15:16:56.832(-4)? (STDERR) at Object.onclosetag (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:348:26)
W20140831-15:16:56.832(-4)? (STDERR) at emit (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:615:33)
W20140831-15:16:56.833(-4)? (STDERR) at emitNode (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:620:3)
W20140831-15:16:56.833(-4)? (STDERR) at closeTag (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:861:5)
W20140831-15:16:56.834(-4)? (STDERR) at Object.write (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/node_modules/sax/lib/sax.js:1294:29)
W20140831-15:16:56.834(-4)? (STDERR) at Parser.exports.Parser.Parser.parseString (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:403:31)
W20140831-15:16:56.834(-4)? (STDERR) at Parser.parseString (/home/misutowolf/projects/meteor-apac/.build.czbaker:apac/npm/node_modules/apac-czbaker/node_modules/xml2js/lib/xml2js.js:6:61)
=> Exited with code: 8
=> Your application is crashing. Waiting for file change.
From what I gather, it seems like it's trying to say that executeSync isn't a function, but...it clearly is. I'm very confused. I have no idea what I'm doing wrong here. Any thoughts would be greatly appreciated.
OperationHelper.prototype.execute takes 3 arguments function(operation, params, callback)
Meteor._wrapAsync just tacks on an extra argument as a callback
You only provide 1 argument to OpHelper.executeSync
The net result is the "automatic" callback provided by Meteor._wrapAsync is being passed as the second paarameter params rather than as the 3rd parameter "callback".
Change your server/method.js to provide an empty params to the function, and you should be fine. eg:
result = OpHelper.executeSync({
SearchIndex: 'Books',
ResponseGroup: 'Medium,Images',
IdType: 'ISBN',
ItemId: isbn
}, {});

Categories

Resources