Ben
Ben

Reputation: 5087

Why doesn't calling this server method work in Meteor?

I have a file called authServices.coffee in the server/server directory of my Meteor project. It has the following function definition, followed by a Meteor.methods call:

 isAuthorized = () ->
    # note that at this point there is ever to be but one authorized user
    authorized = Assets.getText('authorizedUsers').trim()
    this.userId.trim() is authorized

This does not work--that is, calling Meteor.call 'getKey' returns undefined

Meteor.methods(
    isAuthorized : isAuthorized
    getKey : () -> 
    if isAuthorized()
        Assets.getText('Key')
)

but if I inline the isAuthorized within the above getKey, it returns true (given the correct input)

I'm guessing this is a function of how this behaves for these objects, but can't quite get a handle on it.

Upvotes: 0

Views: 221

Answers (2)

David Weldon
David Weldon

Reputation: 64312

The function isAuthorized, and the method getKey have different contexts. The easiest solution is just to implement getKey like so:

getKey: ->
  if Meteor.call 'isAuthorized'
    Assets.getText 'Key'

Alternatively you could manually use call or apply to pass this, or you could pass @userId as a parameter to the isAuthorized function.

Style point: when using CS, you don't need the empty parens when your function takes no arguments.

Upvotes: 1

Christian Fritz
Christian Fritz

Reputation: 21364

Would this be an option?

isAuthorized = (userId) ->
    # note that at this point there is ever to be but one authorized user
    authorized = Assets.getText('authorizedUsers').trim()
    userId.trim() is authorized

Meteor.methods(
    isAuthorized : () -> 
        isAuthorized(this.userId)
    getKey : () -> 
        if isAuthorized(this.userId)
            Assets.getText('Key')
)

Upvotes: 0

Related Questions