CODALIEN

Codalien Blog

This is where we spread the light of knowledge.

JavaScript - Stringify Object to formatted JSON

There are numerous cases where we need to convert our objects to JSON using JSON.stringify and there are also several cases where we need to have the output JSON to be formatted for easy readability.

For the above mentioned purpose JSON.stringify(...) function has support to format the output if required. It takes special arguments for this purpose.

JSON.stringify Signature

> JSON.stringify(value[, replacer[, space]])

Here we will use the space argument ot control formatting. By defaut the value is null, though if you specify a value it will set the space accordingly. Possible values are:

  1. Number: If you provide a number (say n) in space argument then it will indent the formatted JSON with n spaces. Hence you will recieve a formatted JSON with indentation of n spaces.

| JSON | javascript |

Hapijs - Adding Routes in HapiJs

In this blog we will learn how to Adding routes in hapi.

Steps.
  • Define the path.
  • Define the method.
  • Define the handler.

| nodeJS | hapijs |

Hapijs - Built in methods

Hapi has some built in logging methods, as well as some limited capability for viewing these logs.

There are two nearly identical logging methods,

  • server.log,
  • request.log. > They both accept up to three parameters. They are, in order, tags, data, and timestamp.

| nodeJS | hapijs |

HandlerBars

let's see an example. ``` <div class="xyz"> <h1>{{title}}</h1> <div class="body"> {{#noop}}{{body}}{{/noop}} </div>

| nodeJS | HandlerBars |

HandlerBars

installlation
  • run the following command.

    npm install --save handlebars

  • include the package, require('handlebars');
  • builds are located in the node_modules/handlebars/dist/ directory.

| nodeJS | HandlerBars |

Hapijs - Plugins

  • hapi has dozens of plugin system. like ,

Authentication, Documentation, Localization/Internationalization, Logging/Metrics, Messaging, Security, Session, Templating, Utility, Validation....

  • you can write your own plugin.
  • plugins are objects with a register function, and has a signature function (server, options, next).
  • register function has an attributes object.
  • this object provides some additional information about the plugin, such as name and version.

| nodeJS | hapijs | plugins |

Hapijs - views

There are two ways for rendering a view

  • by using reply.view() interface,
  • or by using view handler.

- reply.view()

``` server.route({ method: 'GET',

| nodeJS | hapijs |

Hapijs - Serving static files

  • Using hapi plugin called inert we use the additional handlers.

>First you need to install and add inert as a dependency to your project:

npm install --save inert

reply.file()

| nodeJS | hapijs |

Hapijs - validation with joi

  • you perform validation by using the module joi.
  • By default, no validation will be performed.

let's see a example: ``` server.route({

| nodeJS | hapijs | joi |

Collections in Meteor

A collection is a special data structure that takes care of storing your data in the permanent, server-side MongoDB database, and then synchronising it with each connected user’s browser in real-time. The automatic synchronisation of data between client and server id provided by a key piece of technology called, the Meteor Collection.

Since we want our posts to be permanent and shared between users, so we'll start by creating a collection named Posts and store them in it.

Posts = new Mongo.Collection('posts');

lib/collections/posts.js

| meteor | collections |

Creating First App in Meteor

I have explained how to install Meteor on your System in my previous blog. This blog will explain how to create first App in Meteor following these simple steps.

Step 1.

We use Meteor's command line tool meteor:

```sh

| meteor | tutorial | nodeJS |

Creating a Meteor Package

To create your own Meteor package, you need to have a Meteor Developer account. . You can go claim yours at meteor.com, but there’s a good chance you already did so when you signed up for the book.

We’ll use the username tmeasday in this chapter – you can substitute your own in for it.

First we need to create some structure for our package to reside in. We can use the meteor create --package tmeasday:errors packages/tmeasday:errors/ command to do so. Note that Meteor has created a folder named packages/tmeasday:errors/, with some files inside. We’ll start by editing package.js , the file that informs Meteor of how the package should be used, and which objects or functions it needs to export.

| meteor | meteor-package | tutorial | nodeJS |

Allow and Deny in Meteor for Security

Meteor’s security system allows us to control database modification without having to define Methods every time we want to make changes.

We didn’t really need to create new Methods for updating and deleting data in database. We just needed to check if the user had permission to do these actions, and this was made easy by allow and deny callbacks. Using these callbacks lets us be more declarative about database modifications, and say what kind of updates can be used.

Multiple callbacks

We can define as many allow callbacks as required. We just need at least one of them to return true for the given change that is happening. So when (database).insert is called in a browser (no matter if it’s from our app’s client-side code or from the console), the server will in turn call whatever allowed- insert checks it can until it finds one that returns true. If it does not find any, it will not allow the insert, and will return a 403 error to the client.

Similarly, we can define one or more deny callbacks. If any of those callbacks return true, the change will be cancelled and a 403 will be returned. The logic of this means that for a successful insert, one or more allow insert callback as well as every deny insert callback will be executed.

| meteor | add-security | nodeJS |

File Structure in Meteor App

The four basic types of directories that must be defined inside any Meteor App are /client,/sever, /public and /lib. These directories are special and when it comes to coding, Meteor has few rules:

  • Code inside /server directory only runs on server.
  • Code inside /client directory only runs on client.
  • Everything else runs on both client and server.
  • Static assests (like fonts, images etc.) goes into /public directory.

| meteor | meteor-package | nodeJS |

Hapijs - Installing HapiJs

In this blog we will learn how to install hapi and how to create server in hapi.

Installing hapi.

In this section we will learn how to install hapi.

| nodeJS | hapijs |

Meteor's Autopublish Package

If you create Meteor project from scratch(i.e using meteor create), it will automatically have the autopublish package enabled.

The goal of autopublish package is to make it very easy to start coding with Meteor, and it does this by automatically mirroring all the data from server to client, thus taking care of publications and subscriptions for you.

Suppose you have a collection called 'posts' on the server. Thenautopublish will automatically send every post that it finds in the Mongo posts collection into a collection called 'posts' on the client (assuming there is one).

| meteor | autopublish | meteor-package | nodeJS |

How to install Meteor on your System

Meteor's install process is relatively simple and you can run it in less than five minutes. To begin with , if you're using Mac OS or Linux you can install Meteor by running this command in Terminal Window.

curl https://install.meteor.com | sh

If you are running Windows , download exe file from below link.

https://install.meteor.com/windows

| meteor | tutorial | nodeJS |

Meteor Publication and Subscription

In 2011, when Meteor was not around ,When u hit a site build on Rails, The client(i.e your browser) sends a request to your app, which lives on the server. The app finds out which data the client need , which could be of any size. Once the right data has been selected, the app then translate into human-readable HTML (or JSON in case of API).

Finally, the App takes the HTML code and sends it to the client's browser. The app's job is done here.

The Meteor Way

The feature that makes Meteor different from others is while Rails App only lives on Server, Meteor App lives both on Server and Client. Simply put, Meteor takes part of your database and copy it to client. This has two implications: Firstly, instead of sending HTML code to the client, a Meteor app will send raw data and let the client deal with it. Secondly, you'll be able to access and even modify that data instataneously without having to wait for round-trip to the server(latency compensation).

| meteor | publication-subscription | nodeJS |

Naming Routes using Iron Router in Meteor

By default, Iron Router will look for a template with the same name as the route name. In fact, it will even infer the name from the path you provide.

You may be wondering why we even need to name our routes in the first place. Naming routes lets us use a few Iron Router features that make it easier to build links inside our app. The most useful one is the {{pathFor}} Spacebars helper, which returns the URL path component of any route.

so instead of specifying a static / URL, we can also use the Spacebars helper.The end result will be the same, but this gives us more flexibility since the helper will always output the right URL even if we later change the route’s path in the router.

Example:

| meteor | iron-router | nodeJS | tutorial |

Packages in Meteor

Talking about packages in regard of Meteor is different from other languages. Meteor uses five basic types of packages.

  • Meteor platform packages : The Meteor core itself is split into different Meteor packages. They are included in every Meteor App and you do not need to explicitly add these.
  • Regular Meteor packages : These are also known as "isopacks" or isomorphic packages and they work both on client and server. First-party packages such as accounts-ui or appcache are developed by Meteor core team comes bundled with Meteor.
  • Third-party packages : These are the isopacks developed by other users and uploaded on Meteor's package server. You can browse them on Atmosphere or with meteor search command.
  • Local packages : These are the custom packages you create yourself and place them in /packages directory.
  • NPM packages (Node.js Packaged Modules) : These are Node.js packages. They do not work different with Meteor but these can be used by previous types of packages.

| meteor | meteor-package | nodeJS |

Routing in Meteor

While creating a website we need our pages to be accessible via permalink , a URL of the form http://myapp.com/posts/xyz. This means we’ll need some kind of routing to look at what’s inside the browser’s URL bar and display the right content accordingly.

Iron Router is a routing package that was conceived specifically for Meteor apps. Not only does it help routing, but it also take care of filters and even manages subscriptions.

First, let’s install the package from Atmosphere:

```sh

| meteor | iron-router | nodeJS |

The Session in Meteor

Meteor is a reactive framework. What this means is that as data changes, things in your application change without you having to explicitly do anything. The current state of the user’s application is completely contained in the URL that they are looking at (and the database). But in many cases, you’ll need to store some ephemeral state that is only relevant to the current user’s version of the application (for example, whether an element is shown or hidden). The Session is a convenient way to do this.

The Session is a global reactive data store. It’s global in the sense of a global singleton object: there’s one session, and it’s accessible everywhere. Global variables are usually seen as a bad thing, but in this case the session can be used as a central communication bus for different parts of the application.The Session is a global reactive data store. It’s global in the sense of a global singleton object: there’s one session, and it’s accessible everywhere. Global variables are usually seen as a bad thing, but in this case the session can be used as a central communication bus for different parts of the application.

The Session is available anywhere on the client as the Session object. To set a session value, you can call:

```sh

| meteor | meteor-session | nodeJS |

Why Meteor's account-ui-bootstrap-3 {{loginButtons}} not displaying

Sometimes this happens when you include both accounts-ui and accounts-ui-bootstrap-3 packages in your App. The standard package accounts-ui classes tends to overrides the CSS classes of bootstrap-3 styled accounts-ui. Just remove the standard package from your App by typing the following command in terminal:

meteor remover accounts-ui

And you will see you {{loginButtons}} get appear in the browser.

This may also happen when you include both bootstrap and bootstrap-3 packages in your App which may break the CSS. So by removing bootstrap everything works fine.

| meteor | meteor-package | tutorial | nodeJS |

HandleBars

let's see an example. ``` <div class="xyz"> <h1>{{title}}</h1> <div class="body"> {{#noop}}{{body}}{{/noop}} </div>

| nodeJS | HandleBars |

HandleBars

installlation
  • run the following command.

    npm install --save handlebars

  • include the package, require('handlebars');
  • builds are located in the node_modules/handlebars/dist/ directory.

| nodeJS | HandleBars |