How to access multiple models from a controller - node.js

I have a Locations model and a Recorders model. I want to be able to pass all of the data for both data sets to my view model. How can I access them though because I think they're not in scope since I'm getting undefined errors because I'm calling 'all'
https://gist.github.com/3998302
var Main = function () {
this.index = function (req, resp, params) {
var self = this;
var data = {};
geddy.model.Locations.all(function(err, locations) {
data.locations = locations;
geddy.model.Recorders.all(function(err, recorders) {
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
};
};
exports.Main = Main;
Error snippet:
timers.js:103
if (!process.listeners('uncaughtException').length) throw e;
^
TypeError: Cannot call method 'all' of undefined
at index (G:\code\PeopleTracker\app\controllers\main.js:23:24)
at controller.BaseController._handleAction.callback (C:\Users\Chris\AppData\Roaming\npm\node_modules\geddy\lib\base_
controller.js:387:22)

So it looks like you're initializing the data variable to 'undefined'. Try data = {} instead. If that doesn't fix it, I'll do some troubleshooting with you.
EDIT
If that doesn't do it for you, try installing geddy again:
npm uninstall -g geddy && npm install -g geddy
If that doesn't do it, make sure that your DB is actually running, make sure that the models are defined (try geddy console to check your models), and make sure that you're on the latest stable version of node.

Very late to the party, but I believe you can just call
geddy.model.Locations.all(function(err, locations) {
geddy.model.Recorders.all(function(err, recorders) {
var data = {};
data.locations = locations;
data.recorders = recorders;
self.respond({params: params, data: data}, {
format: 'html'
, template: 'app/views/locations/index'
}
});
}););
You could also have the respond say
self.respond({params: params, locations: locations, recorders: recorders});
but if you want all of that data available from the data literal you need it defined in the lowest scope callback. The callbacks can read above their scope but they cannot write above it.

Related

When exporting a module like this, what happens?

I was looking up some database connection Google searches when I saw something that exported an instance of a module as such
const foo = () => {
// Do stuff
};
...
module.exports = foo();
I don't know what this is called but how does nodejs treat exporting a function invocation vs an object or the function itself (without calling it)?
Thank you
The foo function only gets called once no matter how many times you require the module.
This is very simplified explanation of what is happening behind the scenes in Node.js
// cache for modules
var modules = {};
// very simplified require function
function require(name) {
// check cache
if (modules[name])
// so if it has already been required it returns the cached result
return modules[name].module.exports;
// it will resolve path to the required module
// and loads the file content
// not showing here
var obj = { module: { exports: {}}};
// node will wrap the code in a function similar to bellow
function module(module, exports){
const foo = () => {
// Do stuff
};
...
module.exports = foo();
};
module(obj.module, obj.module.exports);
// and now cache it
modules[name] = obj;
return obj.module.exports;
}

Undefined property when unit testing my discord.js bot (the test itself is passed, but it is followed by an error)

I am trying to set up unit testing for my discord.js bot, but when running npm test in the terminal, while the test is being passed, still gives an error.
This is an image of the test being passed followed by the error:
https://i.imgur.com/m2EOuxc.png
I need to fix this error in testing, while still having the bot being able to function.
I have tried to completely remove the line referenced in the error (and the lines that had something to do with that specific line)
jsfiles.forEach((f, i) => {
let props = require(`./cmds/${f}`)
bot.commands.set(props.help.name, props)
})
Removing this resolved the testing issue, but resulted in the bot not functioning correctly (it did not load the commands; meaning, the bot couldn't be interacted with), which is not the goal here.
I've also checked, that each of the files in the folder cmds ends with
module.exports.help = {
name: '<name of the command I use for each command>'
}
This is the part of my bot.js file that contains the problem.
// Loads the commands for the bot:
fs.readdir('./cmds/', (err, files) => {
if (err) console.error(err)
let jsfiles = files.filter(f => f.split('.').pop() === 'js')
if (jsfiles.length <= 0) {
console.log('No commands to load!')
return
}
if (testingSettings) {
console.log(`Loading ${jsfiles.length} commands!`)
}
// This is the problem referenced above:
// ----------------------------------------------------------------------
jsfiles.forEach((f, i) => {
let props = require(`./cmds/${f}`)
bot.commands.set(props.help.name, props)
})
// ----------------------------------------------------------------------
})
This is all of my code in the bot.test.js file
const {
// Functions
checkingTesting,
// Variables
testingSettings,
} = require('./bot')
test('checking to see if testing-mode is on', () => {
expect(checkingTesting(testingSettings, 'token')).toBe(process.env['token']);
});
If it is needed. This is the function, variable and exporting method that is used to connect bot.js to bot.test.js:
Variable (in bot.js file)
const testingSettings = false
Function (in bot.js file)
function checkingTesting (testingSettings, name) {
if (testingSettings) {
return testSettings[name]
} else if (!testingSettings) {
return process.env[name]
}
}
Exporting (in bot.js file)
module.exports = {
// Exporting functions
checkingTesting: checkingTesting,
// Exporting variables
testingSettings: testingSettings,
}
props.help is undefined. The required file's exported obj is either empty, doesn't have help, or some other unforeseen event.
A good practice is to always check whether an object key exist prior using it.
if (props && props.help) {
bot.commands.set(props.help.name, props)
} else {
//throw or handle error here
}
In your command file, it seems like there is no help property of module.exports. When you try to read help.name, it throws your error because help is undefined.
Check to make sure that you're declaring module.exports.help in every command file.

Defining modules in UI5

I am trying to keep my code separated in modules. When I defined my first module I extended sap.ui.base.Object and it worked. My question is: Is it a must to extend sap.ui.base.Object when defining my own module? According to the API documentation I tried following example:
sap.ui.define([], function() {
// create a new class
var SomeClass = function();
// add methods to its prototype
SomeClass.prototype.foo = function() {
return "Foo";
}
// return the class as module value
return SomeClass;
});
I required this module inside my Component.js as dependency like this:
sap.ui.define([
"path/to/SomeClass"
], function (SomeClass) {
"use strict";
//var test = new SomeClass();
I always receive a syntax error:
failed to load '[...]/Component.js' from ./Component.js: Error: failed to load '[...]/module/SomeClass.js' from ./module/Service.js: SyntaxError: Unexpected token ;
Does anyone have an idea why this happens? Thanks!
We group code in modules like this for example:
jQuery.sap.declare("our.namespace.iscool.util.Navigation");
our.namespace.iscool.util.Navigation = {
to: function (pageId, context) {
// code here
}
// etc.
}
and call the function of the module like this in a controller
jQuery.sap.require("our.namespace.iscool.util.Navigation");
sap.ui.controller("our.namespace.iscool.Detail", {
// somewhere in this file comes this
handleNavButtonPress: function (evt) {
our.namespace.iscool.util.Navigation.navBackToMaster(
evt.getSource().getBindingContext()
);
},
}
Stupid mistake - missing curly brackets in the docs.
var someclass = function() {} ;

Dynamic require in Nodejs

I'm requiring a library in NodeJS which has a self-invoking function, that results an error because it looks for an object which is not initialized at that moment .
I want to dynamically require this library when that object is initialized.
Is there any way to dynamically require/ load a library ?
This is the part of library required :
https://github.com/sakren/node-google-maps/blob/develop/lib/Google.js#L5
Actually I want to require when the window object is present (client-side rendering).
So something like this :
'use strict';
var React = require('react');
var Map = require('./map.jsx');
var Common = require('../common/common');
var MapStatic = require('./map-static.jsx');
exports.type = function() {
return 'map';
};
exports.jsx = function(data) {
if (Common.isServerSide()) {
return (<MapStatic data={data}/>);
} else {
return (
<Map data={data}/>
);
}
};
exports.transform = require('./map-transform.js');
The reason the code looks weired is that I'm using react.
In nodeJS require can be used anywhere at anytime whithout much limitations AFAIK.
Which error is thrown once you require at runtime ?
In your else branch.
Try the following.
requires = {}
function getter(key) {
if(!requires[key]){
requires[key] = require(key)
}
return requires[key]
}

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

Resources