coffee script method is not defined - coffeescript

i have coffee script class that defined a method named 'isOutdated', right it only output some text, i need to use this method in another method, but it always complained 'isOutdated is not defined', don't know why,
here is my code:
class A
...
isOutdated: (last, curr) ->
'hell..o'
run: (callback) ->
#store.findOne config, {name : 'a' }, {}, {}, (err, results) =>
return callback err, null if err
callback null, isOutdated 'last', 'curr'
and here is what it complaint:
[ReferenceError: isOutdated is not defined]

If you want to reference the isOutdated method then you need to say
callback null, #isOutdated 'last', 'curr'
# -------------^
Just isOutdated is looking for a local variable, not the method.

Related

sails helpers and machine spec

I upgrade sails to the #^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
var ob = await ails.helpers.testy('sayHello');
res.json({ob:ob});
helper
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: async function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
fn: async function (inputs, exits) {
^^^^^^^^
SyntaxError: Unexpected token function.......
and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed. Any chance the
source code is missing an "await"?
To assist you in hunting this down, here is a stack trace:
```
at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)
The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
sync: true, // Here is essential part
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
From the another side, you have a problem with async/await. The top most reason for this are
Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing

Result promise being processed before it executed on Ionic 2 Facebook login

I have an Ionic 2 application running the following code on an Angular 2 service:
signInWithFacebook(): firebase.Promise<any>
{
if (this.platform.is('cordova'))
{
console.log('Running on cordova...');
Facebook.login(['email', 'public_profile']).then(res =>
{
const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
console.log('credential value', facebookCredential);
var temp = firebase.auth().signInWithCredential(facebookCredential);
console.log('temp value: ', temp);
return temp;
});
}
else
{
return this.auth$.login({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup
});
}
}
Then on my login component page I call it like this, on a login button:
pubic doFacebookLogin(): void
{
var temp = this.userDataService.signInWithFacebook()
.then(() =>
{
console.log("Passed here! [1]");
this.onSignInSuccess();
console.log("Passed here! [2]");
});
}
My console logs the following when I click the button:
Running on cordova...
main.js:46695 TypeError: Cannot read property 'then' of undefined
at LoginPage.doFacebookLogin (main.js:50920).....
credential value Lf {accessToken: "xxxxxx", provider: "facebook.com"}
temp value: I {F: 0, ka: undefined, o: I, fa: null, Ma: null…}
The flow I'm expecting is this:
call to the doFacebookLogin() method
call to the service.signInWithFacebook() method
Console logs 'Running on cordova...'
step [1] waits for the return promisse of [2]
call to Facebook.login(['email', 'public_profile'])
when the login on [4] is concluded, it calls the firebase.auth().signInWithCredential() method, which returns a promise too
Console logs 'credential value' and 'temp value'
the result promise of [5] is then returned on the service.signInWithFacebook() function
the doFacebookLogin() function finally processes the promise returned on [6] and execute onSignInSuccess()
But from the console logs we can see that it's logging 'Running on cordova', then we get an exception on the .then call of the first funcion (so the facebook login result promise was not yet processed (so the return promise doesn't exist), and after this the facebook login is processed (and now it exists, but the other function already tried to process it, generating the exception).
What am I missing with these promises?
It looks like you are just missing a return.
return Facebook.login(....).then(...);

Saving a model using mongoose [duplicate]

I have this route defined, but any requests made to it get's stuck on 'pending' and runs forever.
When I log the code, I see 1 followed by 4, which means the code inside the find method never gets executed
# Calendar routes
router.get '/calendars', (req, res) ->
console.log '1'
Calendar.find (err, calendars) ->
console.log "2" + err
console.log "3" + calendars
res.send(err) if err
res.json(calendars)
return
console.log '4'
return
Model
mongoose = require("mongoose")
module.exports = mongoose.model("Calendar",
name: String
)
Any ideas on why this is?
Until you call mongoose.connect, your mongoose queries will simply be queued up.
Add code like this in your startup code to connect:
mongoose.connect('mongodb://localhost/test', function(err) {
if (err) {
console.error(err);
} else {
console.log('Connected');
}
});
In the connection string, replace test with the name of your database.

How can I wrap each API response into a standard reply object in SailsJS?

I'm new to Sails and I'm trying to figure out the best/proper method for returning a standard object for every API response.
The container our front-end requires is:
{
"success": true/false,
"session": true/false,
"errors": [],
"payload": []
}
Currently, I’m overwriting the blueprint actions in each controller like this example (which just seems so very, very wrong):
find : function( req, res ){
var id = req.param( 'id' );
Foo.findOne( { id : id } ).exec( function( err, aFoo ){
res.json(
AppSvc.jsonReply(
req,
[],
aFoo
), 200
);
});
}
And in AppSvc.js:
jsonReply : function( req, errors, data ){
return {
success : ( errors && errors.length ? false : true ),
session : ( req.session.authenticated === true ),
errors : ( errors && errors.length ? errors : [] ),
payload : ( data ? data : [] )
};
}
Additionally, I’ve had to modify each res.json() method for each default response (badRequest, notFound,etc). Again, this feels so wrong.
So, how do I properly funnel all API responses into a standard container?
Sails custom responses are great for this.
If you look at the blueprint code, you'll see that each one calls res.ok when it's done: https://github.com/balderdashy/sails/blob/master/lib/hooks/blueprints/actions/find.js#L63
You can add your own file - ok.js - to api/responses/ - which will override the default built in handler.
https://github.com/balderdashy/sails/blob/master/lib/hooks/responses/defaults/ok.js <- just copy and paste this to start, and adapt as you need.

Requirejs with mocha

RequireJS and mocha have some problem working together.
I figured this is because mocha does not wait for requireJS's asynchronous operations to finish and decides testing is done.
As a hot fix I wrapped requireJS 's loading calls in mocha's it() calls.
Somehow mocha knows when I add a callback, that it should wait for the asynchronous methods to finish.
But I'd like to know whether there is no other, more convenient setup than the one I'm using now. The current setup isn't really nice nor flexible.
This is my test.coffee script:
describe 'Ink', ->
describe '#constructor', ->
it 'should return an Ink instance', ( done ) ->
requirejs [ "build/ink/core/Ink" ], ->
# commence testing
a = new Ink( '<div></div>' )
assert.equal( new Ink instanceof Ink, false )
assert.equal( new Ink instanceof window.jQuery, true )
done()
describe 'Mixin', ->
f : ( Mixin ) ->
# test mixin
class A
constructor : ( #a ) ->
class m extends Mixin
constructor : () -> #mixin_prop = 42
increment : ( arg ) -> return arg + 1
class B extends A
Mixin.mixin( m, # )
b = new B()
return b
it 'should chain the constructor', ( done ) ->
requirejs [ "build/ink/core/Mixin" ], ( Mixin ) ->
b = f( Mixin )
assert.equal( b.mixin_prop, 42 )
done()
it 'should add the methods from the mixin to the new class', ( done ) ->
requirejs [ "build/ink/core/Mixin" ], ( Mixin ) ->
b = f( Mixin )
assert.equal( b.increment( 42 ), 42 )
done()
I initialize my modules in beforeEach, and use a callback to trigger async:
describe...
var Module
beforeEach(function(callback){
requirejs
Module = loadedFile
callback(); // suites will now run
})
I have a bootstrap here: https://github.com/clubajax/mocha-bootstrap
Mocha provides a done callback to the function you invoke with it, and it works nicely for this purpose. Here's an example of how I'm currently using it--note that I'm using require to load my test config as well, and obviously this is straight JS, not CoffeeScript, but it should obtain.
define([
'chai',
'SystemUnderTest'
], function(chai, SystemUnderTest) {
var expect = chai.expect;
describe('A functioning system', function() {
it('knows when to foo', function(done) {
sut = new SystemUnderTest();
expect(sut.foo()).to.be.ok;
done();
});
});
So mocha's support for async testing, which you might 'normally' use to test async services, can also be used to support testing of asynchronously loaded modules.
Mocha's async documentation
I haven't used requirejs in my tests, but I think the before function might help:
describe 'Mixin - ', ->
before (done) ->
console.log dateFormat(new Date(), "HH:MM:ss");
requirejs [ "build/ink/core/Ink" ], ->
# commence testing
a = new Ink( '<div></div>' )
assert.equal( new Ink instanceof Ink, false )
assert.equal( new Ink instanceof window.jQuery, true )
done()
beforeEach ->
....
describe ...