Wednesday, April 5, 2017

Dynamic dropdown list in reactJs

type="vertical"
control="select"
id="number-of-devices"
label="Number of devices"
required={true}
value={this.state.devices}
onChange={e => this.setState({devices: e.target.value})}
options={this.getDevices()}
/>

getDevices() {
let i = 0;
let devices = [];
while (i <= this.props.pay.number_of_devices) {
   devices.push({label: i, value: i})
   i++;
}
return devices;
}

Sunday, January 8, 2017

Starting with Webpack

INSTALLING WEBPACK

You need to have node.js installed.
$ npm install webpack -g
This makes the webpack command available.

SETUP THE COMPILATION

Start with a empty directory.
Create these files:

add entry.js

document.write("It works.");

add index.html

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script type="text/javascript" src="bundle.js" charset="utf-8"></script>
    </body>
</html>
Then run the following:
$ webpack ./entry.js bundle.js
It will compile your file and create a bundle file.
If successful it displays something like this:
Version: webpack 1.14.0
Time: 12ms
    Asset     Size  Chunks             Chunk Names
bundle.js  1.42 kB       0  [emitted]  main
chunk    {0} bundle.js (main) 28 bytes [rendered]
    [0] ./tutorials/getting-started/setup-compilation/entry.js 28 bytes {0} [built]
Open index.html in your browser. It should display It works.

SECOND FILE
Next, we will move some code into an extra file.

add content.js

module.exports = "It works from content.js.";

update entry.js

- document.write("It works.");
+ document.write(require("./content.js"));
And recompile with:
$ webpack ./entry.js bundle.js
Update your browser window and you should see the text It works from content.js..
webpack will analyze your entry file for dependencies to other files. These files (called modules) are included in your bundle.js too. webpack will give each module a unique id and save all modules accessible by id in the bundle.js file. Only the entry module is executed on startup. A small runtime provides the require function and executes the dependencies when required.

THE FIRST LOADER

We want to add a CSS file to our application.
webpack can only handle JavaScript natively, so we need the css-loader to process CSS files. We also need the style-loader to apply the styles in the CSS file.
Run npm install css-loader style-loader to install the loaders. (They need to be installed locally, without -g) This will create a node_modules folder for you, in which the loaders will live.
Let’s use them:

add style.css

body {
    background: yellow;
}

update entry.js

+ require("!style!css!./style.css");
document.write(require("./content.js"));
Recompile and update your browser to see your application with yellow background.
By prefixing loaders to a module request, the module went through a loader pipeline. These loaders transform the file content in specific ways. After these transformations are applied, the result is a JavaScript module.

BINDING LOADERS

We don’t want to write such long requires require("!style!css!./style.css");.
We can bind file extensions to loaders so we just need to write: require("./style.css")

update entry.js

- require("!style!css!./style.css");
+ require("./style.css");
document.write(require("./content.js"));
Run the compilation with:
webpack ./entry.js bundle.js --module-bind 'css=style!css'
Some environments may require double quotes: –module-bind “css=style!css”
You should see the same result:
A CONFIG FILE
We want to move the config options into a config file:

add webpack.config.js

module.exports = {
    entry: "./entry.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" }
        ]
    }
};
Now we can just run:
webpack
to compile:
Version: webpack 1.14.0
Time: 163ms
    Asset     Size  Chunks             Chunk Names
bundle.js  10.7 kB       0  [emitted]  main
chunk    {0} bundle.js (main) 8.85 kB [rendered]
    [0] ./tutorials/getting-started/config-file/entry.js 64 bytes {0} [built]
    [1] ./tutorials/getting-started/config-file/style.css 943 bytes {0} [built]
    [2] ../~/css-loader!./tutorials/getting-started/config-file/style.css 197 bytes {0} [built]
    [3] ../~/css-loader/lib/css-base.js 1.51 kB {0} [built]
    [4] ../~/style-loader/addStyles.js 6.09 kB {0} [built]
    [5] ./tutorials/getting-started/config-file/content.js 45 bytes {0} [built]
The webpack command-line will try to load the file webpack.config.js in the current directory.

A PRETTIER OUTPUT

If the project grows the compilation may take a bit longer. So we want to display some kind of progress bar. And we want colors…
We can achieve this with
webpack --progress --colors

WATCH MODE

We don’t want to manually recompile after every change…
webpack --progress --colors --watch
Webpack can cache unchanged modules and output files between compilations.
When using watch mode, webpack installs file watchers to all files, which were used in the compilation process. If any change is detected, it’ll run the compilation again. When caching is enabled, webpack keeps each module in memory and will reuse it if it isn’t changed.

DEVELOPMENT SERVER

The development server is even better.
npm install webpack-dev-server -g
webpack-dev-server --progress --colors
This binds a small express server on localhost:8080 which serves your static assets as well as the bundle (compiled automatically). It automatically updates the browser page when a bundle is recompiled (SockJS). Open http://localhost:8080/webpack-dev-server/bundle in your browser.

The dev server uses webpack’s watch mode. It also prevents webpack from emitting the resulting files to disk. Instead it keeps and serves the resulting files from memory.

Main article is here: http://webpack.github.io/docs/tutorials/getting-started/ 

Webpack - module bundler

Webpack কি?
 Webpack হচ্ছে একটা module bundler. যার কাজ হচ্ছে আলাদা-আলাদা এক্সটেনশান এর Module এবং তার সব ধরনের dependency গুলোকে নেয় এবং তা ইন্টারপ্রেট করে একটা Single asset আকারে রুপান্তর করে যা Browser এর পড়ার জন্যে সুবিধাজনক।



Webpack ইউজ করার সুবিধা কি?
  • Initial loading এর জন্যে webpack অনেক কম সময় নেয়।
  • যে কোন ধরনের Static asset কেই module আকারে ইউজ করা যায়।
  • Third party library ইউজ করা যায়।
  • Module bundler এর প্রায় সব কিছুই নিজের মতো করে কাস্টমাইজ করে নেওয়া যায়।
  • জায়ান্ট প্রজেক্টের জন্যে সুবিধাজনক।




Webpack এর কয়েকটি উল্লেকযোগ্য বৈশিষ্টঃ
Code Splitting
Webpack এর dependency tree তে দিও ধরনের dependency আছে, আর তা হলো Synchronous এবং Asynchronous . Async dependency গুলো অনেকটা আলাদা আলাদা প্যাকেটের মতো কাজ করে, এবং যখন সবগুলো dependency Optomize হয়ে যায় তখন ওই প্রত্যেক্টা প্যাকেট একটা আলাদা ফাইল হিসাবে প্রসেস হয়।

Loaders
আমরা যদি শুধুমাত্র Webpack এর কথা চিন্তা করি তাহলে এক্তা শুধুমাত্র JS ফাইলই প্রসেস করতে পারে কিন্তু এতে Loader ব্যাবহারের সুবিধা থাকায় Loader অন্যান্য Resourse গুলোকেও Webpack এর মাধ্যমে JS Asset এ রুপান্তর করতে পারে।

Plugin system
Webpack এ প্লাগিন সিস্টেম enabled থাকায় এবং Webpack এর প্রায় সব ধরনের ইন্টারনাল ফিচার প্লাগিন আকারে থাকায় নিজ ইচ্ছা মতো যে কোন ফিচার কাস্টমাইজ করে নেওয়া যায় এমন কি নিজের যে কোন কাস্টমাইজ/নিউ ফিচার open source আকারে অন্যদের সাথে শেয়ারও করা যায় তাতে নিজের ভুলগুলো ধরা পড়ে এবং ফিচারটি আরো ব্যাবহার উপযোগী হয়।

মুল লেখাটি এখানেঃ http://webpack.github.io/docs/what-is-webpack.html

Friday, September 23, 2016

Express JS Routing In Detail

Express JS Routing In Detail

Routing refers to the definition of application end points (URIs) and how they respond to client requests. For an introduction to routing, see Basic routing.
The following code is an example of a very basic route.
var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world');
});

Route methods

A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.
// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage');
});
Express supports the following routing methods that correspond to HTTP methods: getpostputheaddeleteoptionstracecopylockmkcolmovepurgepropfindproppatchunlockreportmkactivitycheckoutmergem-searchnotifysubscribeunsubscribepatchsearch, and connect.
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ...
There is a special routing method, app.all(), which is not derived from any HTTP method. This method is used for loading middleware functions at a path for all request methods.
In the following example, the handler will be executed for requests to “/secret” whether you are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in the http module.
app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

Route paths

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
The characters ?+*, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.
Query strings are not part of the route path.
Here are some examples of route paths based on strings.
This route path will match requests to the root route, /.
app.get('/', function (req, res) {
  res.send('root');
});
This route path will match requests to /about.
app.get('/about', function (req, res) {
  res.send('about');
});
This route path will match requests to /random.text.
app.get('/random.text', function (req, res) {
  res.send('random.text');
});
Here are some examples of route paths based on string patterns.
This route path will match acd and abcd.
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});
This route path will match abcdabbcdabbbcd, and so on.
app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});
This route path will match abcdabxcdabRANDOMcdab123cd, and so on.
app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});
This route path will match /abe and /abcde.
app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});
Examples of route paths based on regular expressions:
This route path will match anything with an “a” in the route name.
app.get(/a/, function(req, res) {
  res.send('/a/');
});
This route path will match butterfly and dragonfly, but not butterflymandragonflyman, and so on.
app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

Route parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
app.get('/users/:userId/books/:bookId', function(req, res) {
  res.send(req.params);
});
Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters for useful purposes.
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }
Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }
The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).

Route handlers

You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
A single callback function can handle a route. For example:
app.get('/example/a', function (req, res) {
  res.send('Hello from A!');
});
More than one callback function can handle a route (make sure you specify the next object). For example:
app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});
An array of callback functions can handle a route. For example:
var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

var cb2 = function (req, res) {
  res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);
A combination of independent functions and arrays of functions can handle a route. For example:
var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});

Response methods

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
MethodDescription
res.download()Prompt a file to be downloaded.
res.end()End the response process.
res.json()Send a JSON response.
res.jsonp()Send a JSON response with JSONP support.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus()Set the response status code and send its string representation as the response body.

app.route()

You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.
Here is an example of chained route handlers that are defined by using app.route().
app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });

express.Router

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
Create a router file named birds.js in the app directory, with the following content:
var express = require('express');
var router = express.Router();

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;
Then, load the router module in the app:
var birds = require('./birds');
...
app.use('/birds', birds);
The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

Detail is here: