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
}, {});
Related
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.
I am trying to create a separate inventory file for Protractor Test where I can store all the reusable variable to be used by different test scrips. The sample Variable list is called Vars.js and the specs should import the variables from this file and consume those. However, this fails as shown below. Can this approach actually be used for storing reusable variables? Can I actually create a separate inventory file for protractor tests outside of conf.js?
Vars.js has the following content :
"use strict";
exports.config = {
function() {
global.loginMain = 'https://mytestsite.com/auth/login';
global.TestText = 'I am the test Text';
}
};
and the spec file is as follows:
require ('./Vars.js')
require('..\\waitAbsent.js')
require("../node_modules/jasmine-expect/index.js")
describe('Vairables Import Test', function() {
console.log(global.loginMain);
console.log(global.TestText);
browser.get(global.loginMain);
it('Text Validation', function(){
expect(browser.getCurrentUrl()).toEqual('https://mytestsite.com/auth/login')
})
});
The log
[10:55:29] I/local - Selenium standalone server started at http://192.168.1.187:51256/wd/hub
undefined
undefined
Started
(node:17800) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods
instead.
F
Failures:
1) Vairables Import Test encountered a declaration exception
Message:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
Stack:
TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type undefined
at Url.parse (url.js:152:11)
at urlParse (url.js:146:13)
at Url.resolve (url.js:661:29)
at Object.urlResolve [as resolve] (url.js:657:40)
at ProtractorBrowser.get (C:\FCPS_I\FCPS\node_modules\protractor\built\browser.js:653:17)
at Suite.<anonymous> (C:\FCPS_I\FCPS\TestBed_Scripts\TestBed.js:10:13)
at Object.<anonymous> (C:\FCPS_I\FCPS\TestBed_Scripts\TestBed.js:5:1)
1 spec, 1 failure
Update: a revised Vars.js where I used params as shown below also return the same failure.
"use strict";
exports.config = {
params: {
loginMain: 'https://dss-esy.insystechinc.com/auth/login',
TestText : 'I am the test Text',
}
};
The below approach should work for you.
conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['app.js'],
onPrepare: async() => {
global.globalVariables = require('./globalVariables');
}
};
app.js
describe('desribe the test', () => {
it('the it', async () => {
console.log(globalVariables.loginMain);
console.log(globalVariables.TestText);
})
})
globalVariables.js
module.exports = {
loginMain :'https://mytestsite.com/auth/login',
TestText : 'I am the test Text'
}
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'; }
...
I'm working on a meteor project and it's my first time with Meteor.
Everything was working fine until the moment I decided to do a "git init" into the directory I was working in, followed by a "git checkout -b gh-pages". So that I could post a repo and a live demo here to S.O. because I had a completely different question altogether.
After fiddling around with what used to be easy (creating gh-pages) that process no longer works for me, not sure if GitHub changed their process for creating pages, but for some reason it's not working for me, even after following these instructions: https://help.github.com/articles/creating-project-pages-manually/
After creating a another branch and attempting to push the code I have to a gh-pages i suddenly started getting these errors.
Sorry this is long:
=> Started proxy.
=> Started MongoDB.
W20141230-20:19:22.649(-5)? (STDERR)
W20141230-20:19:22.735(-5)? (STDERR) /Users/MARS/.meteor/packages/meteor-tool/.1.0.38.z83ibe++os.osx.x86_64+web.browser+web.cordova/meteor-tool-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:173
W20141230-20:19:22.735(-5)? (STDERR) throw(ex);
W20141230-20:19:22.735(-5)? (STDERR) ^
W20141230-20:19:22.735(-5)? (STDERR) Error: A method named '/players/insert' is already defined
W20141230-20:19:22.736(-5)? (STDERR) at packages/ddp/livedata_server.js:1444:1
W20141230-20:19:22.736(-5)? (STDERR) at Function._.each._.forEach (packages/underscore/underscore.js:113:1)
W20141230-20:19:22.736(-5)? (STDERR) at [object Object]._.extend.methods (packages/ddp/livedata_server.js:1442:1)
W20141230-20:19:22.736(-5)? (STDERR) at [object Object].Mongo.Collection._defineMutationMethods (packages/mongo/collection.js:886:1)
W20141230-20:19:22.736(-5)? (STDERR) at new Mongo.Collection (packages/mongo/collection.js:208:1)
W20141230-20:19:22.737(-5)? (STDERR) at app/leaderboard.js:1:50
W20141230-20:19:22.737(-5)? (STDERR) at app/leaderboard.js:80:3
W20141230-20:19:22.737(-5)? (STDERR) at /Users/MARS/Desktop/Sandbox/meteor/leaderboard/.meteor/local/build/programs/server/boot.js:175:10
W20141230-20:19:22.737(-5)? (STDERR) at Array.forEach (native)
W20141230-20:19:22.737(-5)? (STDERR) at Function._.each._.forEach (/Users/MARS/.meteor/packages/meteor-tool/.1.0.38.z83ibe++os.osx.x86_64+web.browser+web.cordova/meteor-tool-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
=> Exited with code: 8
It did this three times before ending with a "=> Your application is crashing. Waiting for file change."
Has anyone encountered this before, or can anyone explain why this might be happening?
Here is the only code I have so far:
PlayersList = new Mongo.Collection('players');
if(Meteor.isClient){
Template.leaderboard.helpers({
'player' : function(){
return PlayersList.find( {}, {sort: {score: -1, name: 1} });
},
'count' : function() {
return PlayersList.find().count();
},
'selectedClass' : function() {
var playerId = this._id;
var selectedPlayer = Session.get('selectedPlayer');
if(playerId === selectedPlayer) {
return "selected";
}
},
'showSelectedPlayer' : function() {
var selectedPlayer = Session.get('selectedPlayer');
return PlayersList.findOne(selectedPlayer);
}
});
Template.leaderboard.events({
'click .player' : function() {
var playerId = this._id;
Session.set('selectedPlayer', playerId);
},
'click .increment' : function() {
var selectedPlayer = Session.get('selectedPlayer');
PlayersList.update(selectedPlayer, {$inc: {score: 5} });
},
'click .decrement' : function() {
var selectedPlayer = Session.get('selectedPlayer');
PlayersList.update(selectedPlayer, {$inc: {score: -5} });
},
'click .remove' : function() {
var selectedPlayer = Session.get('selectedPlayer');
alert('Are you sure you want to delete this fool?');
PlayersList.remove(selectedPlayer);
}
});
Template.addPlayerForm.events({
'submit form' : function(event) {
event.preventDefault();
var playerNameVar = event.target.playerName.value;
var playerScoreVar = event.target.playerScore.value;
PlayersList.insert({
name: playerNameVar,
score: playerScoreVar
});
var formAddPlayer = document.getElementById('formAddPlayer');
formAddPlayer.reset();
}
});
}
if(Meteor.isServer){
}
Thanks.
I had an issue like this before. What fixed it for me was just running git clean -dfx
I don't really see anything wrong with your code that should throw that error. It may just be git being strange.
The error A method named '/xxx/insert' is already defined is a bit obscure, but it means you have this bit of code running on your server twice.
PlayersList = new Mongo.Collection('players');
Given that you have it once at the top of your file you should look for it elsewhere in your directory.
I'm not sure what git did specifically but the error is a result of a collection being defined twice so somewhere in the directory there must be a duplicate chunk of code.
everyone. I have a problem with my code and Meteor 0.9.4
Here is my code:
Server/publications.js
Meteor.publish('getUsers', function () {
var loggedInUser = Meteor.User();
if (Roles.userIsInRole(loggedInUser, ['admin'])) {
return Meteor.users.find({}, {fields: {
_id: 1,
emails: 1,
roles: 1
}});
}
this.stop();
return;
});
Lib/router.js
Router.map(function() {
this.route('dashboardUsers', {
layoutTemplate: 'dashboardLayout',
path: "/dashboard/users",
waitOn: function() {
return Meteor.subscribe('getUsers');
}
});
});
When I run meteor app, I have the following error:
=> App running at: http://localhost:3000/
I20141019-18:21:50.827(4)? Exception from sub 8CRiG3Jmdv4mohPhd TypeError: Object #<Object> has no method 'User'
I20141019-18:21:50.949(4)? at null._handler (app/server/publications.js:3:31)
I20141019-18:21:50.950(4)? at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
I20141019-18:21:50.950(4)? at _.extend._runHandler (packages/ddp/livedata_server.js:943)
I20141019-18:21:50.950(4)? at _.extend._startSubscription (packages/ddp/livedata_server.js:769)
I20141019-18:21:50.951(4)? at _.extend.protocol_handlers.sub (packages/ddp/livedata_server.js:582)
I20141019-18:21:50.951(4)? at packages/ddp/livedata_server.js:546
If you have a look at the docs for Meteor.user, you'll see it works everywhere except publish functions. You need to do:
var loggedInUser = Meteor.users.findOne(this.userId);
The error your getting is because of the upper-case 'u' in Meteor.User it should be Meteor.user.
However, as David Weldon pointed out you'll need to use Meteor.users.findOne(this.userId) inside of publish functions.
For anyone else running into the error Object #<Object> has no method 'user' when trying to access Meteor.user() be sure you have the accounts-base package.