Meteor – Accounts

Meteor – Accounts ”; Previous Next This package allows complete user authentication functionality. You can add it by running the following code in the command prompt window. C:UsersusernameDesktopmeteorApp>meteor add accounts-password Authentication Example This example will show basic authentication. We will create register, login, and home templates. If there is a currentUser (if the user is successfully registered or logged in), the home template will be shown. If there is no currentUser, the register and login templates will be visible. meteorApp.html <head> <title>meteorApp</title> </head> <body> {{#if currentUser}} {{> home}} {{else}} {{> register}} {{> login}} {{/if}} </body> <template name = “register”> <h2>REGISTER:</h2> <form> <input type = “email” name = “registerEmail”><br> <input type = “password” name = “registerPassword”><br> <input type = “submit” value = “Register”><br> </form> </template> <template name = “login”> <h2>LOGIN:</h2> <form> <input type = “email” name = “loginEmail”><br> <input type = “password” name=”loginPassword”><br> <input type = “submit” value = “Login”><br> </form> </template> <template name = “home”> <p>You”re logged in.</p> <button class = “logout”>Logout</button> </template> First, we need to create a register event. This function will read register inputs, create a new user, and store it to the database. The second event is login. This time the function will read inputs from the login template, log in the user if the email and password are valid or return an error if they aren”t. And finally the logout event will be used for logging out the user, once the button is clicked. meteorApp.js if (Meteor.isClient) { Template.register.events({ ”submit form”: function(event) { event.preventDefault(); var registerData = { email: event.target.registerEmail.value, password: event.target.registerPassword.value } Accounts.createUser(registerData, function(error) { if (Meteor.user()) { console.log(Meteor.userId()); } else { console.log(“ERROR: ” + error.reason); } }); } }); Template.login.events({ ”submit form”: function(event) { event.preventDefault(); var myEmail = event.target.loginEmail.value; var myPassword = event.target.loginPassword.value; Meteor.loginWithPassword(myEmail, myPassword, function(error) { if (Meteor.user()) { console.log(Meteor.userId()); } else { console.log(“ERROR: ” + error.reason); } }); } }); Template.home.events({ ”click .logout”: function(event) { event.preventDefault(); Meteor.logout(function(error) { if(error) { console.log(“ERROR: ” + error.reason); } }); } }); } Once the app starts, we will get the following page. On entering the email and password in the register form, we can register and login the new user. We will see that the console logs the users id and the home template is rendered. The login event will check the database and log in the user, if the email and password are correct. If not, the console will log an error. If the user clicks the LOGOUT button, the app will log the user out and show the register and login templates. Print Page Previous Next Advertisements ”;

Meteor – Methods

Meteor – Methods ”; Previous Next Meteor methods are functions that are written on the server side, but can be called from the client side. On the server side, we will create two simple methods. The first one will add 5 to our argument, while the second one will add 10. Using Methods meteorApp.js if(Meteor.isServer) { Meteor.methods({ method1: function (arg) { var result = arg + 5; return result; }, method2: function (arg) { var result = arg + 10; return result; } }); } if(Meteor.isClient) { var aaa = ”aaa” Meteor.call(”method1”, aaa, function (error, result) { if (error) { console.log(error); else { console.log(”Method 1 result is: ” + result); } } ); Meteor.call(”method2”, 5, function (error, result) { if (error) { console.log(error); } else { console.log(”Method 2 result is: ” + result); } }); } Once we start the app, we will see the calculated values in console. Handling Errors For handling errors, you can use the Meteor.Error method. The following example shows how to handle error for users that aren”t logged in. if(Meteor.isServer) { Meteor.methods({ method1: function (param) { if (! this.userId) { throw new Meteor.Error(“logged-out”, “The user must be logged in to post a comment.”); } return result; } }); } if(Meteor.isClient) { Meteor.call(”method1”, 1, function (error, result) { if (error && error.error === “logged-out”) { console.log(“errorMessage:”, “Please log in to post a comment.”); } else { console.log(”Method 1 result is: ” + result); }}); } The console will show our customized error message. Print Page Previous Next Advertisements ”;

Meteor – Best Practices

Meteor – Best Practices ”; Previous Next We already covered some of the best practices of Meteor development in the previous chapters. Following are some of the best practices to be kept in mind while using Meteor. Directory Structure There are no strict rules about the directory structure in Meteor apps. For more info on guidelines, check out Meteor – Structure chapter. Use Methods You should always use Meteor – Methodswhen working with sensitive data instead of calling insert, update, and remove directly from the client. Data Management Protect your data using Publish and Subscribe methods. If you want your data to be available to all clients, you can use null as the publication name instead. Publishing small chunks of data will also improve the performance of the app. Validate Data You should validate all data that will be stored inside collection. One of the best options is collection2 package. This package makes it easy to set the server and client side validation. Minimize Session The session variables are global variables and using globals is against the JavaScript best practices. Router There are two most popular options for Meteor routing. For smaller apps, there is Iron Router. It is automatically rerun once the data changes. For larger apps, there is Flow Router. This router gives you more freedom to optimize re-rendering of the templates at the cost of a little more boilerplate code. Packages Always check if the package is updated regularly before you choose to use it inside your app. Print Page Previous Next Advertisements ”;

Meteor – ToDo App

Meteor – ToDo App ”; Previous Next In this chapter, we will learn how to create a simple todo app. Step1 – Create an App Open the command prompt and run the following command − C:UsersusernameDesktop>meteor create todo-app To see the app, you need to run the app with the meteor command and go to http://localhost:3000 C:UsersusernameDesktoptodo-app>meteor Step2 – Create Folders and Files Instead of default file structure, we will refactor it. Let”s create a client folder, where we will create todo-app.html, todo-app.css and todo-app.js. C:UsersusernameDesktoptodo-app>mkdir client C:UsersusernameDesktoptodo-appclient>touch todo-app.html C:UsersusernameDesktoptodo-appclient>touch todo-app.js We will also create a server folder with server.js inside. C:UsersusernameDesktoptodo-app>mkdir server C:UsersusernameDesktoptodo-appserver>touch server.js Finally, let”s create collections folder with task-collection.js file inside. C:UsersusernameDesktoptodo-app>mkdir server C:UsersusernameDesktoptodo-appcollections>touch task-collection.js You can see the app structure on the following image − Step 3 – client/todo-app.html Our first development step is to create HTML for the app. We need an input field where we can add new tasks. The tasks will be in the form of a list with delete and check functionality. We will also have functionalities for showing or hiding completed tasks. <head> <title>Todo App</title> </head> <body> <h1>Todo List ({{incompleteCount}})</h1> <label class = “hide-completed”> <input type = “checkbox” checked = “{{hideCompleted}}” /> Hide Completed Tasks </label> <form class = “new-task”> <input type = “text” name = “text” placeholder = “Add new tasks” /> </form> <ul> {{#each tasks}} {{> task}} {{/each}} </ul> </body> <template name = “task”> <li class = “{{#if checked}}checked{{/if}}”> <button class = “delete”>x</button> <input type = “checkbox” checked = “{{checked}}” class = “toggle-checked” /> <span>{{username}} – {{text}}</span> </li> </template> Step 4 – collections/task-collection.js This is the place where we will just create a new MongoDB Collection, so we can use it on both the server and the client side. Tasks = new Mongo.Collection(“tasks”); Step 5 – server/server.js We will define methods for our app on the server side. These methods will be called from the client. In this file, we will also publish the database query. // Publishing tasks from the server… Meteor.publish(“tasks”, function () { return Tasks.find({}); }); // Methods for handling MongoDb Tasks collection data… Meteor.methods({ addTask: function (text) { Tasks.insert({ text: text, createdAt: new Date(), }); }, deleteTask: function (taskId) { var task = Tasks.findOne(taskId); Tasks.remove(taskId); }, setChecked: function (taskId, setChecked) { var task = Tasks.findOne(taskId); Tasks.update(taskId, { $set: { checked: setChecked} }); } }); Step 6 – client/todo-app.js This is the main client JavaScript file. This file can also be refactored but we will write all client side code here. First, we subscribe to the task collection that is published on the server. Then, we create helpers to be able to handle the app logic, and finally, we define the events that will call the methods from the server. // Subscribing to the published tasks Meteor.subscribe(“tasks”); // Show/Hide functionality Template.body.helpers({ tasks: function () { if (Session.get(“hideCompleted”)) { // If hide completed is checked, filter tasks return Tasks.find({checked: {$ne: true}}, {sort: {createdAt: -1}}); } else { // Otherwise, return all of the tasks return Tasks.find({}, {sort: {createdAt: -1}}); } }, hideCompleted: function () { return Session.get(“hideCompleted”); }, incompleteCount: function () { return Tasks.find({checked: {$ne: true}}).count(); } }); // Events for creating new tasks and Show/Hide functionality. // Calling methods from the server Template.body.events({ “submit .new-task”: function (event) { event.preventDefault(); var text = event.target.text.value; Meteor.call(“addTask”, text); event.target.text.value = “”; }, “change .hide-completed input”: function (event) { Session.set(“hideCompleted”, event.target.checked); } }); // Events for Deleting and Check/Uncheck functionality Template.task.events({ “click .toggle-checked”: function () { // Set the checked property to the opposite of its current value Meteor.call(“setChecked”, this._id, ! this.checked); }, “click .delete”: function () { Meteor.call(“deleteTask”, this._id); } }); Step 7 – Deploy After we are done with the development, we can deploy the app from the command prompt window. The deployment name of our app will be my-first-todo-app. C:UsersusernameDesktoptodo-app>meteor deploy my-first-todo-app We can open the http://my-first-todo-app.meteor.com/ to start using our app. Print Page Previous Next Advertisements ”;

Meteor – Blaze

Meteor – Blaze ”; Previous Next Blaze is a Meteor package for building live reactive templates. Render Method This method is used for rendering templates into the DOM. First, we will create myNewTemplate that will be rendered. We will also add myContainer, which will be used as a parent element, so the render method knows where to render our template. meteorApp.html <head> <title>meteorApp</title> </head> <body> <div id = “myContainer”> </div> </body> <template name = “myNewTemplate”> <p>Text from my new template…</p> </template> Next, we will create a render function that will take two arguments. The first one is a template that will be rendered and the second one is a parent element that we mentioned above. meteorApp.js Meteor.startup(function () { if(Meteor.isClient) { var myNewTemplate = Template.myNewTemplate; var myContainer = document.getElementById(”myContainer”); Blaze.render(myNewTemplate, myContainer); } }); Render with Data If you need to pass some data reactively, you can use renderWithData method. The HTML will be exactly the same as in the previous example. meteorApp.html <head> <title>meteorApp</title> </head> <body> <div id = “myContainer”> </div> </body> <template name = “myNewTemplate”> <p>Text from my new template…</p> </template> We can add our data as a second argument in Meteor.renderWithData method. The other two arguments are the same as in the previous example. In this example, our data is a function that will log some text. meteorApp.js Meteor.startup(function () { if(Meteor.isClient) { var myNewTemplate = Template.myNewTemplate; var myData = function() { console.log(”Log from the data object…”) } var myContainer = document.getElementById(”myContainer”); Blaze.renderWithData(myNewTemplate, myData, myContainer); } }); Remove Method We can add remove method. meteorApp.html <head> <title>meteorApp</title> </head> <body> <div id = “myContainer”> </div> </body> <template name = “myNewTemplate”> <p>Text from my new template…</p> </template> In this example, we are rendering the template that will be removed after three seconds. Notice the Blaze.Remove method that we are using to remove the template. meteorApp.js Meteor.startup(function () { if(Meteor.isClient) { var myNewTemplate = Template.myNewTemplate; var myContainer = document.getElementById(”myContainer”); var myRenderedTemplate = Blaze.render(myNewTemplate, myContainer); Meteor.setTimeout(function() { Blaze.remove(myRenderedTemplate); }, 3000); } }); The following table shows the other methods that can be used. Sr.No. Method & Details 1 Blaze.getData([elementOrView]) Used for retrieving data from the rendering element. 2 Blaze.toHTML(templateOrView) Used for rendering templates or views to the string. 3 Blaze.toHTMLWithData(templateOrView, data) Used for rendering templates or views to the string with additional data. 4 new Blaze.View([name], renderFunction) Used for creating a new Blaze reactive part of the DOM. 5 Blaze.currentView Used for getting the current view. 6 Blaze.getView([element]) Used for getting the current view. 7 Blaze.With(data, contentFunc) Used for constructing a view that renders some content with context. 8 Blaze.If(conditionFunc, contentFunc, [elseFunc]) Used for constructing a view that renders some conditional content. 9 Blaze.Unless(conditionFunc, contentFunc, [elseFunc]) Used for constructing a view that renders some conditional content (inverted Blaze.if). 10 Blaze.Each(argFunc, contentFunc, [elseFunc]) Used for constructing a view that renders contentFunct for every item. 11 new Blaze.Template([viewName], renderFunction) Used for constructing a new Blaze view with name and content. 12 Blaze.isTemplate(value) Used for returning true, if the value is a template object. Print Page Previous Next Advertisements ”;

Meteor – Events

Meteor – Events ”; Previous Next In this chapter, we will learn how to use tag, class and id as an event selector. Working with events is pretty straightforward. Let”s create three elements in the HTML template. The first one is p, the second one is myClass class and the last one is myId id. meteorApp.html <head> <title>meteorApp</title> </head> <body> <div> {{> myTemplate}} </div> </body> <template name = “myTemplate”> <p>PARAGRAPH…</p> <button class = “myClass”>CLASS</button> <button id = “myId”>ID</button> </template> In our JavaScript file, we are setting three events for three elements that we created above. You can see that we are just adding p, .myClass and #myId after the click event. These are the selectors we mentioned above. meteorApp.js if (Meteor.isClient) { Template.myTemplate.events({ ”click p”: function() { console.log(“The PARAGRAPH is clicked…”); }, ”click .myClass”: function() { console.log(“The CLASS is clicked…”); }, ”click #myId”: function() { console.log(“The ID is clicked…”); }, }); } To test this, we can first click on PARAGRAPH, then the CLASS button and finally the ID button. We will get the following console log. We can use all the other JavaScript events – click, dbclick, contextmenu, mousedown, mouseup, mouseover, mouseout, mousemove – following the example above. Print Page Previous Next Advertisements ”;

Meteor – Packages

Meteor – Packages ”; Previous Next Meteor offers thousands of community packages that you can use while developing your app. Adding Packages You can check the official Meteor package server here. Just search for the package you need and add it in the command prompt window. If, for example, you want to add http package to your app, you can do it by running the following code − C:UsersusernameDesktopmeteorApp>meteor add http Removing Packages A similar principle can be used to remove packages − C:UsersusernameDesktopmeteorApp>meteor remove http Updating Packages You can update the package running the following code − C:UsersusernameDesktopmeteorApp>meteor update http Checking Current Packages You can also check what packages your current application is using. C:UsersusernameDesktopmeteorApp>meteor list Package Maintenance If a package has : in the name, it means that it is a community package, while the ones without the prefix are maintained by the Meteor Development group. Adding Meteor Development Group Package C:UsersusernameDesktopmeteorApp>meteor add http Adding Community Package C:UsersusernameDesktopmeteorApp>meteor add cfs:http-methods Print Page Previous Next Advertisements ”;

Meteor – Assets

Meteor – Assets ”; Previous Next Static server assets are located in a private subfolder inside the app. In the following example, we will learn how to use data from a simple JSON file. Step 1 – Create Files and Folders Let”s create a private folder and my-json.json file inside that folder. We will do this using the following command in the command prompt window, however, you can also create it manually. C:UsersusernameDesktopmeteorApp>mkdir private C:UsersusernameDesktopmeteorAppprivate>touch my-json.json Step 2 – Get Text To be able to read data from our file, we will use Asssets.getText method. Note, this can only be done from the server side. Since we are using JSON, we need to parse it. if (Meteor.isServer) { var myFile = JSON.parse(Assets.getText(”my-json.json”)); console.log(myFile.data.text) } Following will be the output in the command prompt window. Step 3 – Create EJSON File We will create this file inside the private folder. This file will contain binary data “myBinary”: {“$binary”: “c3VyZS4=”} C:UsersusernameDesktopmeteorAppprivate>touch my-ejson.ejson Step 4 – Get Binary To read EJSON files, we can use the Assets.getBinary method. if (Meteor.isServer) { var myFile = Assets.getBinary(”my-ejson.ejson”); console.log(EJSON.stringify(myFile)); } The command prompt will log EJSON value. Print Page Previous Next Advertisements ”;

Meteor – EJSON

Meteor – EJSON ”; Previous Next EJSON is an extension of JSON syntax that supports Date and Binary types. Install EJSON To install EJSON package, we need to add it from the command prompt window. C:UsersusernameDesktopmeteorApp>meteor add ejson Date Example We can deserialize the date using the parse method. if (Meteor.isClient) { var myEjsonDate = ”{“$date”: 1455029631493}”; var myDate = EJSON.parse(myEjsonDate); console.log(myDate); } The console will log the correct date value. Binary Example The same can be applied to binary types. if (Meteor.isClient) { var myEjsonBinary = ”{“$binary”: “c3VyZS4=”}”; var myBinary = EJSON.parse(myEjsonBinary); console.log(myBinary); } You can see that the console is logging new deserialized value. Stringify We can serialize an object using the stringify method. This is the reversed process from the example above. if (Meteor.isClient) { var myObject = { myDate : new Date(), myBinary : new Uint8Array([115, 117, 114, 101, 46]) } var myEjosnData = EJSON.stringify(myObject); console.log(myEjosnData); } We can see our new values in the console. Sr.No. Method & Details 1 EJSON.parse(string) Used for parsing a string into EJSON value. 2 EJSON.stringify(value) Used for serializing a value to the string. 3 EJSON.fromJSONValue(value) Used for deserializing an EJSON value from JSON. 4 EJSON.toJSONValue(value) Used for serializing an EJSON value into JSON. 5 EJSON.equals(value1, value2) Used for comparing if two values are equal. 6 EJSON.clone(value) Used for returning a deep copy of the value. 7 EJSON.newBinary Used for assigning a binary data that EJSON can serialize. 8 EJSON.isBinary(x) Used for checking if the value is a binary data. 9 EJSON.addType(name, factory) Used for creating a custom EJSON type. 10 customType.typeName() Used for returning a name of the custom type. 11 customType.toJSONValue() Used for serializing custom types. 12 customType.clone() Used for returning a deep copy of the custom type. 13 customType.equals(otherValue) Used for comparison between the custom type value and other value. Print Page Previous Next Advertisements ”;

Meteor – Security

Meteor – Security ”; Previous Next In this chapter, we will learn how to secure our app and what should be taken into consideration while developing an app. Autopublish and Autosecure Autopublish is a package that automatically publishes all data from the database to the client. This is a convenience that should be disabled when in production. It can be disabled from the command prompt. C:UsersusernameDesktopmeteorApp>meteor remove autopublish You can publish some data to the client by using Meteor.publish() and Meteor.subscribe() methods that we will cover in the Publish and Subscribe chapter. Insecure is a package that allows MongoDB commands to be written in developer’s console, so that every user of the app is able to access the database. The package can be removed by running the following command in the command prompt. C:UsersusernameDesktopmeteorApp>meteor remove insecure Good practice is to remove both of the packages as soon as you start developing your app, so you don”t have to change and update your code later. Use Server Side Methods You should always create your methods on the server. You can do it by using the Meteor.methods() on the server and Meteor.call() on the client. We will learn more about this in the Methods chapter. Additional Security If you want to add additional layers of security to your app, you should consider using some other Meteor packages such as − Browser Policy can be used to control the external resources that should be loaded to your app. Check package can be used to check the user input types before they are processed. Audit Arguments Check is a package that will ensure all parameters are correctly checked before processed. If you missed some parameters, this package will inform you. Mylar packages can add some additional layers of security. You can check them out if you need that kind of protection. Print Page Previous Next Advertisements ”;