Can't subscribe to publication in Meteor - coffeescript

I have an app with a collection, publication and subscription as follows:
collections/Cities.coffee:
#Cities = new Meteor.SmartCollection('cities')
server/publications.coffee:
Meteor.publish "userCities", -> Cities.find { userId: #userId }
client/subscriptions.coffee:
Meteor.subscribe "cities",
onReady: -> console.log 'subscription a success'
onError: (err) -> console.log 'subscription a failure', err
The subscription seems to fail, the error mentions Internal server error [500]
There is also an error when the Meteor server starts:
Exception from sub DrWAY95DFAEkjBHrY TypeError: Object function (name) { ...
} has no method '_compileSelector'
No idea where this is going wrong. I have reset the server.

As pointed out by Marco in the comments, Meteor.smartCollection is retired. Switching to regular collections solved the issue.

Related

Mongo connection occasionally makes the lambda function timeout

I have been using MLab MongoDB and mongoose library to create a db connection inside a serverless (Lambda) handler. It works smoothly on local machine. But sometimes it doesn't work after deployment.The request returns an Internal server error. The weird thing is sometimes it works. But If I remove the database connection code, the handler works. The serverless log just says Process exited before completing request. No real errors so no idea what to do.
The db connection looks like this:
handler.js
// Connect to database
mongoose.connect(process.env.DATABASE_URL, {
useMongoClient: false
}).then((ee) => {
console.log('------------------------invoke db ', ee);
})
.catch(err => console.error('-----------error db ', err));
No error in here too. Any idea what's happening?
When you get Process exited before completing request, it means that the node process has crashed before Lambda was able to call callback. If you go to Cloudwatch logs, there would be an error and stack trace of what happened.
You should connect to the MongoDB instance inside your handler and before you call callback(), disconnect first.
It would be like this...
exports.handler = (event, context, callback) => {
let response;
return mongoose.connect(process.env.DATABASE_URL, {
useMongoClient: false
}).then((ee) => {
// prepare your response
response = { hello: 'world' }
}).then(() => {
mongoose.disconnect()
}).then(() => {
// Success
callback(null, response)
}).catch((err) => {
console.error(err);
callback(err);
})
};
Here is an article explaining with details how lambda work with node and an example of how to implement DB connection.
Differently of #dashmug suggested, you should NOT disconnect your DB since connecting every time will decrease your performance.

Sending request from hubot http listener callback, "TypeError: Cannot read property 'on' of undefined"

I've been having issues trying to get my hubot instance to perform an http request while in a callback from a http listener. My guess is that it is in the middle of a req/res cycle and unable to complete a different request. Usually the robot object has the http method that allows for sending one, but I keep getting "TypeError: Cannot read property 'on' of undefined" In other hubot examples I've seen online, they refer to the use of the response object, but that is only the case inside of a chat listener and indeed when I attempt to use the response object it throws an error, "TypeError: res.http is not a function". Any help is much appreciated. Thanks!
robot.router.post '/gitlab-incoming', (req, res) ->
data = {
"request_type": req.body.object_kind,
"status": req.body.object_attributes.state,
"project_name": req.body.object_attributes.source.name,
"branch_name": req.body.object_attributes.source_branch,
"job_name": 'review_stop',
"team_name": process.env.GITLAB_TEAM_NAME,
"gitlab_ci_token": process.env.GITLAB_CI_TOKEN,
"action": 'play',
"project_id": "#{process.env.GITLAB_TEAM_NAME}%2F#{req.body.object_attributes.source.name}"
}
if data['status'] == 'merged'
robot.http("https://gitlab.com/api/v4/projects/#{data['project_id']}/jobs")
.header('Accept', 'application/json')
.header('PRIVATE-TOKEN', data['gitlab_ci_token'])
.get() (err, http_res, body) ->
if err
res.send 'Sorry. Unable to fetch the list of jobs from Gitlab'
job_found = false
job_id = undefined

Auth0 custom database mongodb, signup script is returning SandboxTimeoutError

I'm trying to use my own mongo database which is created in mlab in auth0 for user management. Here is the template they provided.
function create (user, callback) {
mongo('mongodb://user:pass#mymongoserver.com/my-db', function (db) {
var users = db.collection('users');
users.findOne({ email: user.email }, function (err, withSameMail) {
if (err) return callback(err);
if (withSameMail) return callback(new Error('the user already exists'));
bcrypt.hashSync(user.password, 10, function (err, hash) {
if (err) { return callback(err); }
user.password = hash;
users.insert(user, function (err, inserted) {
if (err) return callback(err);
callback(null);
});
});
});
});
}
After changing connection URI, I tried to "create" a user by providing email and password with the script. I see the following error:
[SandboxTimeoutError] Script execution did not complete within 20 seconds. Are you calling the callback function?
I followed the Debug Script they provided. Here is the log:
$ wt logs -p "myservice-eu-logs"
[12:35:27.137Z] INFO wt: connected to streaming logs (container=myservice)
[12:35:29.993Z] INFO wt: new webtask request 1478435731301.992259
[12:35:30.047Z] INFO wt: { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
[12:35:30.047Z] INFO wt: js-bson: Failed to load c++ bson extension, using pure JS version
[12:36:05.080Z] INFO wt: finished webtask request 1478435731301.992259 with HTTP 500 in 35096ms
Any suggestions?
Actually, bcrypt.hashSync is a synchronous method, so the callback function is never called and the script times out.
Either use:
var hashedPwd = bcrypt.hashSync(user.password);
or
bcrypt.hash(user.password,10,function(....);

How do I get a Slack message's id/timestamp from a Hubot script?

There doesn't seem to be a timestamp property and the id property is undefined. Here is the hubot's plugin script code:
module.exports = (robot) ->
robot.hear /\bclocks?\b/i, (msg) ->
msg.http("https://slack.com/api/reactions.add")
.query({
token: process.env.SLACK_API_TOKEN
name: "bomb"
timestamp: msg.message.timestamp # This property doesn't exist
})
.post() (err, res, body) ->
console.log(body)
return
The response that I get back from the Slack API is:
{"ok":false,"error":"bad_timestamp"}
When I log msg.message it looks like this:
{ user:
{ id: 'abc123',
name: 'travis',
room: 'test-bots',
reply_to: 'zyx987' },
text: 'clock',
id: undefined,
done: false,
room: 'test-bots' }
How can I get a timestamp or id for the message that triggered the listener?
I heard back from Slack's team and there is a newer property called rawMessage that you have access to when up upgrade to the newer API. Here's the steps I went through to get it working:
Upgrade nodejs & hubot (this may be optional, but our versions were very out of date)
Upgrade the slack-adapter and follow their instructions to connect to the newer API https://github.com/slackhq/hubot-slack#upgrading-from-earlier-versions-of-hubot
You should now get access to the newer properties from your scripts.
Here's the code that worked for me after upgrading:
https://gist.github.com/dieseltravis/253eb1c6fea97f116ab0
module.exports = (robot) ->
robot.hear /\bclocks?\b/i, (msg) ->
queryData = {
token: process.env.HUBOT_SLACK_TOKEN
name: "bomb"
channel: msg.message.rawMessage.channel # required with timestamp, uses rawMessage to find this
timestamp: msg.message.id # this id is no longer undefined
}
if (queryData.timestamp?)
msg.http("https://slack.com/api/reactions.add")
.query(queryData)
.post() (err, res, body) ->
#TODO: error handling
return

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.