Showing posts with label question&answer. Show all posts
Showing posts with label question&answer. Show all posts
- QUESTION -

Let's say there is a running mongodb server for a GUI client (by wxPython) for a while. If we are gonna play with meteor with this mongodb server, how to do that?
- ANSWER -

Use the environment variable MONGO_URL. Something like:
export MONGO_URL=mongodb://localhost:27017/your_db
Replace your_db with meteor or whatever db you want to use.

- QUESTION -

Can a Meteor template be packaged up and deployed as a PhoneGap application?

- ANSWER -

Yes, this is possible, but not by packaging the meteor app on the phone. You have to point phonegap to your meteor server instead (you will still be able to use the API for accessing functionality on the device). Here are the instructions:
That's it. Compile and run the app.
A couple of time savers:
  • You can start setting up your meteor directory by copying the www/ directory contents into your meteor server root directory. Make sure to copy the javascript files under the client/ directory so that they get loaded before the main meteor js file.
  • Run app.initialize(window) from your main meteor js file, if the window parameter is not passed, the app will crash.
  • Don't try to set up the meteor server under the www/ directory in Xcode. You won't be able to deploy to a device because the .meteor subdirectory contains symbolic links to your node modules.
- QUESTION -

I have a new meteor project. I'm guessing the .meteor dir has a combination of configuration files (needed) and temporary files (not needed).
So what's in your .gitignore?
- ANSWER -
The only directory you want excluded from version control is .meteor/local.
Meteor automatically creates the right .gitignore in the .meteor directory, though -- you shouldn't need to do anything.

- QUESTION -

I just notice Firefox console outputs the following error for every single .js/.coffee file in my project (even the packages).
-file- is being assigned a //# sourceMappingURL, but already has one
Chrome's console doesn't show anything. I tried deleting all the .map files and clearing Firefox's cache but I'm still getting the errors.

- ANSWER -

It's a warning (not an error) and it is a bug (https://bugzilla.mozilla.org/show_bug.cgi?id=1020846)
This warning/error also applies to other libs (angular, backbone, etc.)

- QUESTION -

I don't see how to do test driven development in meteor.
I don't see it mentioned anywhere in documentation or FAQ. I don't see any examples or anything like that.
I see that some packages are using Tinytest.
I would need response from developers, what is roadmap regarding this. Something along the lines of:
  • possible, no documentation, figure it out yourself
  • meteor is not built in a way that you can make testable apps
  • this is planned feature
  • etc
- ANSWER -

UpdateVelocity is Meteor's official testing solution as of 0.8.1.

Not much has been written about automated testing with Meteor at this time. I expect the Meteor community to evolve testing best-practices before establishing anything in the official documentation. After all, Meteor reached 0.5 this week, and things are still changing rapidly.
The good news: you can use Node.js testing tools with Meteor.
For my Meteor project, I run my unit tests with Mocha using Chai for assertions. If you don't need Chai's full feature set, I recommend using should.js instead. I only have unit tests at the moment, though you can write integration tests with Mocha as well.
Be sure to place your tests in the "tests" folder so that Meteor does not attempt to execute your tests.
Mocha supports CoffeeScript, my choice of scripting language for Meteor projects. Here's asample Cakefile with tasks for running your Mocha tests. If you are using JS with Meteor, feel free to adapt the commands for a Makefile.
Your Meteor models will need a slight bit of modification to expose themselves to Mocha, and this requires some knowledge of how Node.js works. Think of each Node.js file as being executed within its own scope. Meteor automatically exposes objects in different files to one another, but ordinary Node applications—like Mocha—do not do this. To make our models testable by Mocha,export each Meteor model with the following CoffeeScript pattern:
# Export our class to Node.js when running
# other modules, e.g. our Mocha tests
#
# Place this at the bottom of our Model.coffee
# file after our Model class has been defined.
exports.Model = Model unless Meteor?
...and at the top of your Mocha test, import the model you wish to test:
# Need to use Coffeescript's destructuring to reference
# the object bound in the returned scope
# http://coffeescript.org/#destructuring
{Model} = require '../path/to/model'
With that, you can start writing and running unit tests with your Meteor project!

- QUESTION -
Imagine the following case:
  • 1,000 clients are connected to a Meteor page displaying the content of the "Somestuff" collection.
  • "Somestuff" is a collection holding 1,000 items.
  • Someone inserts a new item into the "Somestuff" collection
What will happen:
  • All Meteor.Collections on clients will be updated i.e. the insertion forwarded to all of them (which means one insertion message sent to 1,000 clients)
What is the cost in term of CPU for the server to determine which client needs to be updated?
Is it accurate that only the inserted value will be forwarded to the clients, and not the whole list?
How does this work in real life? Are there any benchmarks or experiments of such scale available?

- ANSWER-

The short answer is that only new data gets sent down the wire. Here's how it works.
There are three important parts of the Meteor server that manage subscriptions: the publish function, which defines the logic for what data the subscription provides; the Mongo driver, which watches the database for changes; and the merge box, which combines all of a client's active subscriptions and sends them out over the network to the client.

Publish functions

Each time a Meteor client subscribes to a collection, the server runs a publish function. The publish function's job is to figure out the set of documents that its client should have and send each document property into the merge box. It runs once for each new subscribing client. You can put any JavaScript you want in the publish function, such as arbitrarily complex access control using this.userId. The publish function sends data into the merge box by calling this.addedthis.changed and this.removed. See the full publish documentation for more details.
Most publish functions don't have to muck around with the low-level addedchanged and removed API, though. If a publish function returns a Mongo cursor, the Meteor server automatically connects the output of the Mongo driver (insertupdate, and removed callbacks) to the input of the merge box (this.addedthis.changed and this.removed). It's pretty neat that you can do all the permission checks up front in a publish function and then directly connect the database driver to the merge box without any user code in the way. And when autopublish is turned on, even this little bit is hidden: the server automatically sets up a query for all documents in each collection and pushes them into the merge box.
On the other hand, you aren't limited to publishing database queries. For example, you can write a publish function that reads a GPS position from a device inside a Meteor.setInterval, or polls a legacy REST API from another web service. In those cases, you'd emit changes to the merge box by calling the low-level addedchanged and removed DDP API.

The Mongo driver

The Mongo driver's job is to watch the Mongo database for changes to live queries. These queries run continuously and return updates as the results change by calling addedremoved, and changed callbacks.
Mongo is not a real time database. So the driver polls. It keeps an in-memory copy of the last query result for each active live query. On each polling cycle, it compares the new result with the previous saved result, computing the minimum set of addedremoved, and changed events that describe the difference. If multiple callers register callbacks for the same live query, the driver only watches one copy of the query, calling each registered callback with the same result.
Each time the server updates a collection, the driver recalculates each live query on that collection (Future versions of Meteor will expose a scaling API for limiting which live queries recalculate on update.) The driver also polls each live query on a 10 second timer to catch out-of-band database updates that bypassed the Meteor server.

The merge box

The job of the merge box is to combine the results (addedchanged and removed calls) of all of a client's active publish functions into a single data stream. There is one merge box for each connected client. It holds a complete copy of the client's minimongo cache.
In your example with just a single subscription, the merge box is essentially a pass-through. But a more complex app can have multiple subscriptions which might overlap. If two subscriptions both set the same attribute on the same document, the merge box decides which value takes priority and only sends that to the client. We haven't exposed the API for setting subscription priority yet. For now, priority is determined by the order the client subscribes to data sets. The first subscription a client makes has the highest priority, the second subscription is next highest, and so on.
Because the merge box holds the client's state, it can send the minimum amount of data to keep each client up to date, no matter what a publish function feeds it.

What happens on an update

So now we've set the stage for your scenario.
We have 1,000 connected clients. Each is subscribed to the same live Mongo query (Somestuff.find({})). Since the query is the same for each client, the driver is only running one live query. There are 1,000 active merge boxes. And each client's publish function registered an addedchanged, and removed on that live query that feeds into one of the merge boxes. Nothing else is connected to the merge boxes.
First the Mongo driver. When one of the clients inserts a new document into Somestuff, it triggers a recomputation. The Mongo driver reruns the query for all documents in Somestuff, compares the result to the previous result in memory, finds that there is one new document, and calls each of the 1,000 registered insert callbacks.
Next, the publish functions. There's very little happening here: each of the 1,000 insert callbacks pushes data into the merge box by calling added.
Finally, each merge box checks these new attributes against its in-memory copy of its client's cache. In each case, it finds that the values aren't yet on the client and don't shadow an existing value. So the merge box emits a DDP DATA message on the SockJS connection to its client and updates its server-side in-memory copy.
Total CPU cost is the cost to diff one Mongo query, plus the cost of 1,000 merge boxes checking their clients' state and constructing a new DDP message payload. The only data that flows over the wire is a single JSON object sent to each of the 1,000 clients, corresponding to the new document in the database, plus one RPC message to the server from the client that made the original insert.

Optimizations

Here's what we definitely have planned.
  • More efficient Mongo driver. We optimized the driver in 0.5.1 to only run a single observer per distinct query.
  • Not every DB change should trigger a recomputation of a query. We can make some automated improvements, but the best approach is an API that lets the developer specify which queries need to rerun. For example, it's obvious to a developer that inserting a message into one chatroom should not invalidate a live query for the messages in a second room.
  • The Mongo driver, publish function, and merge box don't need to run in the same process, or even on the same machine. Some applications run complex live queries and need more CPU to watch the database. Others have only a few distinct queries (imagine a blog engine), but possibly many connected clients -- these need more CPU for merge boxes. Separating these components will let us scale each piece independently.
  • Many databases support triggers that fire when a row is updated and provide the old and new rows. With that feature, a database driver could register a trigger instead of polling for changes.
- QUESTION -

We all know that Meteor offers the miniMongo driver which seamlessly allows the client to access the persistent layer (MongoDB).
If any client can access the persistent API how does one secure his application?
What are the security mechanisms that Meteor provides and in what context should they be used?

- ANSWER-

When you create a app using meteor command, by default the app includes the following packages:
  • AUTOPUBLISH
  • INSECURE
Together, these mimic the effect of each client having full read/write access to the server's database. These are useful prototyping tools (development purposes only), but typically not appropriate for production applications. When you're ready for production release, just remove these packages.
To add more, Meteor supports Facebook / Twitter / and Much More packages to handle authentication, and the coolest is the Accounts-UI package

- QUESTION -

I came across meteor.js and while it seems exciting, I want to know how it works. I mean conventional web-apps work like this: You have scripts on server which take data from database and add that dynamically to web-pages and the user submitted data gets added to databases through some other scrips.
But how do these things work in meteorJS? How are different parts or meteorJS related to each other?

- ANSWER -

Meteor is a framework that elegantly updates html in realtime.
The beauty of Meteor is that you only need to create the templates and the data models. The rest of the usual boilerplate code is hidden away. You don't need to write all the sync-ing code.
The key pieces of Meteor could be built yourself using these pieces:
  • It provides templating that updates automatically when your data models do. This is normally done using Backbone.jsEmber.jsKnockout.js, or another tool.
  • The client/server messaging is done via websockets using something like socks.js orsocket.io.
  • The client side connection to mongodb is really cool. It replicates the mongo-server driver into the client. Unfortunately, last I checked, they were still working on securing this database connection.
  • The latency compensation is simply updating the client-side model first, then sending the update to the server-server.
There may be other neat pieces to that you can find on the Meteor.JS site, or on Github

- QUESTION -

In all the examples (leaderboard, wordplay, etc.) they have one single HTML template file. Is there some large open source Meteor project with many different HTML template files we can use as a best practice example? Doesn't seem practical to put everything a large app needs all in one template file.

- ANSWER -

As in the unofficial meteor faq, I think it pretty much explains how to structure a large app:
Where should I put my files?
The example apps in meteor are very simple, and don’t provide much insight. Here’s my current thinking on the best way to do it: (any suggestions/improvements are very welcome!)

lib/                    # <- any common code for client/server. 
lib/environment.js      # <- general configuration
lib/methods.js          # <- Meteor.method definitions
lib/external            # <- common code from someone else
## Note that js files in lib folders are loaded before other js files.

collections/                 # <- definitions of collections and methods on them (could be models/)

client/lib              # <- client specific libraries (also loaded first)
client/lib/environment.js   # <- configuration of any client side packages
client/lib/helpers      # <- any helpers (handlebars or otherwise) that are used often in view files

client/application.js   # <- subscriptions, basic Meteor.startup code.
client/index.html       # <- toplevel html
client/index.js         # <- and its JS
client/views/<page>.html  # <- the templates specific to a single page
client/views/<page>.js    # <- and the JS to hook it up
client/views/<type>/    # <- if you find you have a lot of views of the same object type

server/publications.js  # <- Meteor.publish definitions
server/lib/environment.js   # <- configuration of server side packages
For larger applications, discrete functionality can be broken up into sub-directories which are themselves organized using the same pattern. The idea here is that eventually module of functionality could be factored out into a separate smart package, and ideally, shared around.
feature-foo/               # <- all functionality related to feature 'foo'
feature-foo/lib/           # <- common code
feature-foo/models/        # <- model definitions
feature-foo/client/        # <- files only sent to the client
feature-foo/server/        # <- files only available on the server
Find out more: Unofficial Meteor FAQ
- QUESTION -

Learning Ember.js / Backbone.js has been on my to-do list for a while. Now that Meteor is out, I am just wondering if anyone with experience of Meteor, Ember.js and Backbone.js can summarize the key differences and pros and cons of these three JavaScript frameworks for a person without any experience for any of them.
Specifically, I would like to know which tasks each framework is more suitable for, and why the others aren't.
Edit: now that I read a little bit more on Meteor, it seems to be more similar to Knockout.js rather than Backbone.js. So any comparison with Knockout.js is welcome too.
- ANSWER -

There is a nice run down/comparison of various MVx JS frameworks herehttp://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/ it's followed by a good discussion in the comments too. I think I've seen Gordon (who wrote it) on here so maybe you'll get a reply from him.
I'd say if you are looking to learn this style of application development then on the one hand, the wealth of open source backbone examples around could be good for you. But on the other hand, although new, the Ember package is actually more complete IMO than backbone.
Both give you the ability to implement things in a variety of ways which can be confusing, but Ember provides more of the code that you would have to write yourself in backbone as standard which for me personally is more important for rapid prototyping than the wealth of backbone examples available.
There are more mature plugings for data persistence for backbone, but there is a great community buzz around Ember and lots of contrib libraries are making great progress. I've been pleasantly surprised with how quick I (and others) have had quality responses for a relatively new framework here on Stack Overflow.
When you say meteor we are talking about totally other stuff. If you wanted to do more with code re-use on both client and server side then take a look the recently open sourced yahoo mojitohttps://github.com/yahoo/mojito running on node.js - I've been messing around with it over the last week, and If you become familiar with backbone/ember or any of the others its a snap to get to grips with.
I should also say I have Knockout.js in use on some production systems but have never used it for a fully fledged 'application'. I've got it hooked up to a mongo interface for drilling down into and pageing logs stored in mongo. I really like it, but I wouldn't feel comfortable building anything too big in it.
Well, that's a bit of a ramble - isn't it :)
Quite happy to talk more about it with anyone who is interested. I've used a number of these frameworks in anger/production (including things not listed in the 'top 10' article) and people at work are sick of hearing me talk about JS i think :-D

- QUESTION -
In my Meteor app, I have an array of objects with the following structure
[{ type: "oldValue" }]
When I run
testArray[0].type = 'test'
console.log(testArray[0].type)
'test' is correctly printed in the console. However, when I run
testArray[0].type[1] = 'd'
console.log(testArray[0].type)
'test' is printed in the console instead of 'tdst'. The second letter wasn't changed to a d.
How can I change individual characters within a string?

- ANSWER -

As @Pointy pointed out, strings are immutable. If you want to change certain characters, you can work with an array of characters:
var myString = 'hello there!'
myString = myString.split('')
myString[1] = 'a'
myString = myString.join('')
console.log(myString)     // 'hallo there!'
However, per your comment, you probably want to iterate through the string once, since constantly splitting and joining the string might be slow:
function replaceCharacters (str, chars, conversionFunction) {
    var charBuff = []
    for (var i = 0; i < str.length; i++) {
        if (chars.indexOf(str[i])) {
            charBuff.push(conversionFunction(str[i]))
        } else {
            charBuff.push(str[i])
        }
    }
    return charBuff.join('')
}
examples:
console.log(replaceCharacters('hello', 'al', function (myChar) { return 'Z' }))
// logs 'heZZo'
// you can pass an array or a string as the second parameter
// since `.indexOf` works on both strings and arrays
and if you're working with es6:
function replaceCharacters (str, chars, conversionFunc) {
    return [...str].reduce((p, c) => {
        p.push(chars.indexOf(c) === -1 ? c : conversionFunc(c))
        return p
    }, []).join('')
}

- QUESTION -

I need to build a form that a user can select one out of a few choices, then the next set of choices show up, then the user select one out of those choises, and so on.
Should I build this using JavaScript of jQuery, or using a meteor form package?
I'm an intermediate JS/jQuery user and a meteor beginner.
- ANSWER -

It will require some learning but I recommend: https://github.com/aldeed/meteor-autoform/
It's great package and it has a lot of support and lots of add-ons you should check it out.
- QUESTION -

I don't see how to do test driven development in meteor.
I don't see it mentioned anywhere in documentation or FAQ. I don't see any examples or anything like that.
I see that some packages are using Tinytest.
I would need response from developers, what is roadmap regarding this. Something along the lines of:
  • possible, no documentation, figure it out yourself
  • meteor is not built in a way that you can make testable apps
  • this is planned feature
  • etc

- ANSWER -

UpdateVelocity is Meteor's official testing solution as of 0.8.1.

Not much has been written about automated testing with Meteor at this time. I expect the Meteor community to evolve testing best-practices before establishing anything in the official documentation. After all, Meteor reached 0.5 this week, and things are still changing rapidly.
The good news: you can use Node.js testing tools with Meteor.
For my Meteor project, I run my unit tests with Mocha using Chai for assertions. If you don't need Chai's full feature set, I recommend using should.js instead. I only have unit tests at the moment, though you can write integration tests with Mocha as well.
Be sure to place your tests in the "tests" folder so that Meteor does not attempt to execute your tests.
Mocha supports CoffeeScript, my choice of scripting language for Meteor projects. Here's asample Cakefile with tasks for running your Mocha tests. If you are using JS with Meteor, feel free to adapt the commands for a Makefile.
Your Meteor models will need a slight bit of modification to expose themselves to Mocha, and this requires some knowledge of how Node.js works. Think of each Node.js file as being executed within its own scope. Meteor automatically exposes objects in different files to one another, but ordinary Node applications—like Mocha—do not do this. To make our models testable by Mocha,export each Meteor model with the following CoffeeScript pattern:
# Export our class to Node.js when running
# other modules, e.g. our Mocha tests
#
# Place this at the bottom of our Model.coffee
# file after our Model class has been defined.
exports.Model = Model unless Meteor?
...and at the top of your Mocha test, import the model you wish to test:
# Need to use Coffeescript's destructuring to reference
# the object bound in the returned scope
# http://coffeescript.org/#destructuring
{Model} = require '../path/to/model'
With that, you can start writing and running unit tests with your Meteor project!

Powered by Blogger.