Monthly Archives: September 2017

Node.js Weekly Update - September 15

By Tamas Kadlecsik

Node.js Weekly Update - September 15

Below you can find RisingStack‘s collection of the most important Node.js updates, projects & tutorials from this week:

Re-thinking the Node.js ecosystem for modern JavaScript

We need to rebuild most of the software infrastructure in the Node.js Ecosystem.

In order to move forward, we’re going to have to stop using a lot of the software infrastructure we rely on today but first we need solid alternatives.

What’s new in Node.js 8.5?

With the recent release of Node.js 8.5, three very exciting new features landed in the Node.js core.

In the short blogpost, you are going to learn about them:

  • ECMAScript Modules in Node.js!
  • Performance Hooks
  • File copy with the core fs module

Using ES modules natively in Node.js

Starting with version 8.5.0, Node.js supports ES modules natively, behind a command line option. Most of the credit for this new functionality goes to Bradley Farias.

This blog post explains the details.

How To Combine a NodeJS Back End with a ReactJS Front End App

This blogpost shows how you can build the front and back end of a website using NodeJS for the back end.

Node.js Weekly Update - September 15

We’ll use node to create endpoints, and set up a database in JSON format. Then, we’ll create a front end application using React that will post to the database, and also fetch data from it.

Understanding & Measuring HTTP Timings with Node.js

Understanding and measuring HTTP timings helps us to discover performance bottlenecks in client to server or server to server communication.

Node.js Weekly Update - September 15

This article explains timings in an HTTP request and shows how to measure them in Node.js.

Building a crude Node.js from scratch

Node is powered by the JavaScript engine used in Google Chrome, called V81. This post is going to guide you through two steps:

  • making a “Hello World” example in V8
  • making a crude Node runtime with support for 3 statements: console.log, console.error and quit for quitting the process

Securing Node.js RESTful APIs with JSON Web Tokens

Have you ever wondered how authentication works? What’s behind all the complexity and abstractions. Actually, nothing special. It’s a way of encrypting a value, in turn creating a unique token that users use as an identifier. This token verifies your identity. It can authenticate who you are, and authorize various resources you have access to. If you by any chance don’t know any of these keywords, be patient, I’ll explain everything below.

This will be a step by step tutorial of how to add token based authentication to an existing REST API. The authentication strategy in question is JWT (JSON Web Token). If that doesn’t tell you much, it’s fine. It was just as strange for me when I first heard the term.

ES2017’s async/await is the best thing to ever happen to JavaScript

Async await is part of the ES2017 standard, in node since version 7 and all current browsers.

  • await – is a way to await until a promise has returned a value (resolved). Error handling is plain old JavaScript: if something breaks (ie, a promise rejects), an Error is thrown. On the next line, you can just use the value like any other. No more .then().
  • async – a thing you add to the function containing the await keyword. Technically it starts a special context, practically it’s a thing you need to add.

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we read that Node.js 6.11.3 (LTS) & Yarn 1.0 got released & about Fastify, a speedy Node.js Web Framework.

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Sublime Text 3 Out of Beta! Main Features and More

By Eniola Lucas Fakeye

Sublime 3.0 user interface

Sublime text 3 has been in the beta phase for sometime now but yesterday (13th September, 2017), Sublime HQ, the creators of Sublime text editor annouced in a blog post, the release of Sublime 3.0.

Sublime 3.0 is in a class of its own compared to previous releases of Sublime Text. It has:

  • A brand new user interface with a modern look
  • A new logo
  • Is significantly faster than Sublime 2,

It is light and feels light, startup is faster too, it has a new syntax hightlighting engine, the list of all the features is quite long. However, if you care to take a look, you can find it here.

In this article let’s look through the most important features of Sublime 3.0.

Main Features

  1. New Icon
    The new Sublime text icon

  2. Refreshed UI theme, including full high Dot Per Inch support
  3. Added new color schemes namely Breakers, Mariana and Sixteen.


Mariana.


Breakers


Sixteen.

  1. Added color scheme and theme switchers with live preview via the command palette.
  2. Significant improvements to C#, Java, Python and R syntax highlighting.
  3. Improved auto indent rules for HTML and PHP.
  4. Fixed empty panes on startup when hot_exit was set to false.
  5. Improved font selection on all platforms, allowing selection of different weights by name.
  6. Fix multi-cursor pasting when clipboard contains one or more full lines.
  7. Various regex handling improvements in the Find panel.
  8. Various bugs with the syntax highlighting engine have been resolved.

More: Platform specific improvements and changes

Mac

  1. Improved default web browser detection.
  2. Handle layout changes due to macOS Sierra tabs.

Linux

  1. Update X11 selection on clipboard every time selection changes.
  2. Improved MOD3 modifier key handling

Windows

  1. Fix ctrl+` shortcut for UK (ISO) keyboards
  2. Improved font selection logic.
  3. Font rendering defaults to DirectWrite unless using Consolas or Courier New.
  4. The subl executable on OS X and plugin_host.exe on Windows are now signed.
  5. Improved file change detection robustness.

Conclusion.

Obviously, a lot of work has been done to make Sublime text great again by addressing and eliminating pain points. However, them team has refused to rest on its oars as work has started already on version 3.1. I will recommend Sublime 3.0 to developers using low end machines as it is very light compared to most editors and IDEs out there.

Source:: scotch.io

Processing Incoming Request Data in Flask

By Anthony Herbert

In any web app, you’ll have to process incoming request data from users. Flask, like any other web framework, allows you to access the request data easily.

In this tutorial, we’ll go through how to process incoming data for the most common use cases. The forms of incoming data we’ll cover are: query strings, form data, and JSON objects. To demonstrate these cases, we’ll build a simple example app with three routes that accept either query string data, form data, or JSON data.

The Request Object

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things. Although all the information the request object holds can be useful, in this article, we’ll only focus on the data that is normally directly supplied by the caller of our endpoint.

To gain access to the request object in Flask, you simply import it from the Flask library.

from flask import request

You then have the ability to use it in any of your view functions.

Once we get to the section on query strings, you’ll get to see the request object in action.

The Example App

To demonstrate the different ways of using request, we’ll start with a simple Flask app. Even though the example app uses a simple organization layout for the view functions and routes, what you learn in this tutorial can be applied to any method of organizing your views like class-based views, blueprints, or an extension like Flask-Via.

To get started, first we need to install Flask.

pip install Flask

Then, we can start with the following code.

#app.py

from flask import Flask, request #import main Flask class and request object

app = Flask(__name__) #create the Flask app

@app.route('/query-example')
def query_example():
    return 'Todo...'

@app.route('/form-example')
def form_example():
    return 'Todo...'

@app.route('/json-example')
def json_example():
    return 'Todo...'

if __name__ == '__main__':
    app.run(debug=True, port=5000) #run app in debug mode on port 5000

Start the app with:

python app.py

The code supplied sets up three routes with a message telling us ‘Todo…’. The app will start on port 5000, so you can view each route in your browser with the following links:

http://127.0.0.1:5000/query-example (or localhost:5000/query-example)
http://127.0.0.1:5000/form-example (or localhost:5000/form-example)
http://127.0.0.1:5000/json-example (or localhost:5000/json-example)

For each of the three routes, you’ll see the same thing:

Query Arguments

URL arguments that you add to a query string are the simpliest way to pass data to a web app, so let’s start with them.

A query string looks like the following:

example.com?arg1=value1&arg2=value2

The query string begins after the question mark (?) and has two key-value pairs separated by an ampersand (&). For each pair, the key is followed by an equals sign (=) and then the value. Even if you’ve never heard of a query string until now, you have definitely seen them all over the web.

So in that example, the app receives:

arg1 : value1
arg2 : value2

Query strings are useful for passing data that doesn’t require the user to take action. You could generate a query string somewhere in your app and append it a URL so when a user makes a request, the data is automatically passed for them. A query string can also be generated by forms that have GET as the method.

To create our own query string on the query-example route, we’ll start with this simple one:

http://127.0.0.1:5000/query-example?language=Python

If you run the app and navigate to that URL, you’ll see that nothing has changed. That’s only because we haven’t handled the query arguments yet.

To do so, we’ll need to read in the language key by using either request.args.get('language') or request.args['language'].

By calling request.args.get('language'), our application will continue to run if the language key doesn’t exist in the URL. In that case, the result of the method will be None. If we use request.args['language'], the app will return a 400 error if language key doesn’t exist in the URL. For query strings, I recommend using request.args.get() because of how easy it is for the user to modify the URL. If they remove one of the keys, request.args.get() will prevent the app from failing.

Let’s read the language key and display it as output. Modify with query-example route the following code.

@app.route('/query-example')
def query_example():
    language = request.args.get('language') #if key doesn't exist, returns None

    return '''<h1>The language value is: {}</h1>'''.format(language)

Then run the app and navigate to the URL.

As you can see, the argument from the URL gets assigned to the language variable and then gets returned to the browser. In a real app, you’d probably want to do something with the data other than simply return it.

To add more query string parameters, we just append ampersands and the new key-value pairs to the end of the URL. So an additional pair would look like this:

http://127.0.0.1:5000/query-example?language=Python&framework=Flask

With the new pair being:

framework : Flask

And if you want more, continue adding ampersands and key-value pairs. Here’s an example:

http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=Scotch

To gain access to those values, we still use either request.args.get() or request.args[]. Let’s use both to demonstrate what happens when there’s a missing key. We’ll assign the value of the results to variables and then display them.

@app.route('/query-example')
def query_example():
    language = request.args.get('language') #if key doesn't exist, returns None
    framework = request.args['framework'] #if key doesn't exist, returns a 400, bad request error
    website = request.args.get('website')

    return '''<h1>The language value is: {}</h1>
              <h1>The framework value is: {}</h1>
              <h1>The website value is: {}'''.format(language, framework, website)

When you run that, you should see:

If you remove the language from the URL, then you’ll see that the value ends up as None.

If you remove the framework key, you get an error.

Now that you undertand query strings, let’s move on to the next type of incoming data.

Form Data

Next we have form data. Form data comes from a form that has been sent as a POST request to a route. So instead of seeing the data in the URL (except for cases when the form is submitted with a GET request), the form data will be passed to the app behind the scenes. Even though you can’t easily see the form data that gets passed, your app can still read it.

To demonstrate this, modify the form-example route to accept both GET and POST requests and to return a simple form.

@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
    return '''<form method="POST">
                  Language: <input type="text" name="language"><br>
                  Framework: <input type="text" name="framework"><br>
                  <input type="submit" value="Submit"><br>
              </form>'''

Running the app results in this:

The most important thing to know about this form is that it performs a POST request to the same route that generated the form. The keys that we’ll read in our app all come from the “name” attributes on our form inputs. In our case, language and framework are the names of the inputs, so we’ll have access to those in our app.

Inside the view function, we need to check if the request method is GET or POST. If it’s GET, we simply display the form we have. If it’s POST, then we want to process the incoming data.

To do that, let’s add a simple if statement that checks for a POST request. If the request method isn’t POST, then we know it’s GET, because our route only allows those two types of requests. For GET requests, the form will be generated.

@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
    if request.method == 'POST': #this block is only entered when the form is submitted
        return 'Submitted form.'

    return '''<form method="POST">
                  Language: <input type="text" name="language"><br>
                  Framework: <input type="text" name="framework"><br>
                  <input type="submit" value="Submit"><br>
              </form>'''

Inside of the block, we’ll read the incoming values with request.args.get('language') and request.form['framework']. Remember that if we have more inputs, then we can read additional data.

Add the additional code to the form-example route.

@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
    if request.method == 'POST':  #this block is only entered when the form is submitted
        language = request.form.get('language')
        framework = request.form['framework']

        return '''<h1>The language value is: {}</h1>
                  <h1>The framework value is: {}</h1>'''.format(language, framework)

    return '''<form method="POST">
                  Language: <input type="text" name="language"><br>
                  Framework: <input type="text" name="framework"><br>
                  <input type="submit" value="Submit"><br>
              </form>'''

Try running the app and submitting the form.

Similiar to the query string example before, we can use request.form.get() instead of referencing the key directly with request.form[]. request.form.get() returns None instead of causing a 400 error when the key isn’t found.

As you can see, handling submitted form data is just as easy as handling query string arguments.

JSON Data

Finally, we have JSON data. Like form data, it’s not so easy to see. JSON data is normally constructed by a process that calls our route. An example JSON object looks like this:

{
    "language" : "Python",
    "framework" : "Flask",
    "website" : "Scotch",
    "version_info" : {
        "python" : 3.4,
        "flask" : 0.12
    },
    "examples" : ["query", "form", "json"],
    "boolean_test" : true
}

As you can see with JSON, you can pass much more complicated data that you could with query strings or form data. In the example, you see nested JSON objects and an array of items. With Flask, reading all of these values is straightforward.

First, to send a JSON object, we’ll need a program capable of sending custom requests to URLs. For this, we can use an app called Postman.

Before we use Postman though, change the method on the route to accept only POST requests.

@app.route('/json-example', methods=['POST']) #GET requests will be blocked
def json_example():
    return 'Todo...'

Then in Postman, let’s do a little set up to enable sending POST requests.

In Postman, add the URL and change the type to POST. On the body tab, change to raw and select JSON (application/json) from the drop down. All this is done so Postman can send JSON data properly and so your Flask app will understand that it’s receiving JSON.

From there, you can copy the example into the text input. It should look like this:

To test, just send the request and you should get ‘Todo…’ as the response because we haven’t modified our function yet.

To read the data, first you must understand how Flask translates JSON data into Python data structures.

Anything that is an object gets converted to a Python dict. {"key" : "value"} in JSON corresponds to somedict['key'], which returns a value in Python.

An array in JSON gets converted to a list in Python. Since the syntax is the same, here’s an example list: [1,2,3,4,5]

Then the values inside of quotes in the JSON object become strings in Python. true and false become True and False in Python. Finally, numbers without quotes around them become numbers in Python.

Now let’s get on to reading the incoming JSON data.

First, let’s assign everything from the JSON object into a variable using request.get_json().

req_data = request.get_json()

request.get_json() converts the JSON object into Python data for us. Let’s assign the incoming request data to variables and return them by making the following changes to our json-example route.

@app.route('/json-example', methods=['POST']) #GET requests will be blocked
def json_example():
    req_data = request.get_json()

    language = req_data['language']
    framework = req_data['framework']
    python_version = req_data['version_info']['python'] #two keys are needed because of the nested object
    example = req_data['examples'][0] #an index is needed because of the array
    boolean_test = req_data['boolean_test']

    return '''
           The language value is: {}
           The framework value is: {}
           The Python version is: {}
           The item at index 0 in the example list is: {}
           The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)

If we run our app and submit the same request using Postman, we will get this:

Note how you access elements that aren’t at the top level. ['version']['python'] is used because you are entering a nested object. And ['examples'][0] is used to access the 0th index in the examples array.

If the JSON object sent with the request doesn’t have a key that is accessed in your view function, then the request will fail. If you don’t want it to fail when a key doesn’t exist, you’ll have to check if the key exists before trying to access it. Here’s an example:

language = None
if 'language' in req_data:
    language = req_data['language']

Conclusion

You should now understand how to use the request object in Flask to get the most common forms of input data. To recap, we covered:

  • Query Strings
  • Form Data
  • JSON Data

With this knowledge, you’ll have no problem with any data that users throw at your app!

Learn More

If you like this tutorial and want to learn more about Flask from me, check out my free Intro to Flask video course at my site Pretty Printed, which takes you from knowing nothing about Flask to building a guestbook app. If that course isn’t at your level, then I have other courses on my site that may interest you as well.

Source:: scotch.io

Handling Route Parameters in Angular v2+

By Chris Sevilleja

The Angular router is a very powerful tool that allows us to do all the routing things needed. The router allows us to:

One of the most common tasks when using the router is to create routes with parameters. For instance, here on Scotch, we have user profile links: https://scotch.io/@chris. The chris part of that is a dynamic route parameter.

The Two Ways to Grab Route Parameters

The router provides a couple different ways to grab route parameters. We’ll explore both of these and talk about the benefits and cons of each:

  • The Snapshot Way: The router provides us with a snapshot of the current route
  • The Observable/Stream Way: Since Angular employs Observables heavily, the router also returns an Observable that we can listen to.

We’ll talk more on both of these options soon.

Creating Routes with Parameters

Let’s get the simple stuff out of the way. We’ll create a route that has a route parameter.

// app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'users/:username',
    component: UserComponent
  }
];

Note: This is a piece of code out of the AppRoutingModule that the Angular CLI creates by default when you run ng new my-app --routing.

The way that we create a route parameter is with the colon syntax. Here we have a route with :username as the route parameter.

Linking to Routes with Parameters

We’ll need to create routes to both of these sections. Here’s the various ways we can link to the home page. The Angular router provides us with the RouterLink directive. All of the following achieve the same effect.

<!-- basic routerLink -->
<a routerLink="/">Home</a>

<!-- using the property binding with a string -->
<a [routerLink]="'/'">Home</a>

<!-- using the directive with a full array passed in -->
<a [routerLink]="['/']">Home</a>

Since this route doesn’t have any parameters, you can go ahead and use the first option. You can use the second option if you like having the bracket property binding so it’s easy to read as an Angular directive. The third option will be useful when we have route parameters.

Linking to the Profile Page with Route Parameters

Here’s the ways we can link to the user profiles. In this scenario, we have a variable called username in the corresponding component class.

<a [routerLink]="['/users', username]">{{ username }} Profile</a>

Now that we have our links, we can go look at how we could grab these route parameters in a UserComponent.

Grabbing Route Parameters (The Snapshot Way)

Let’s see how we can use the snapshot way to grab route parameters. The Angular Router provides an ActivatedRoute that we can inject into our classes. This will be the main tool we’ll use to grab route parameters.

Let’s see the basic setup for the UserComponent.

// user.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user',
  template: `<h1>This is {{ username }}'s profile!</h1>`
})
export class UserComponent implements OnInit {
  username: string;

  // inject the activatated route
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // this is where we'll grab data
  }

}

We’ll inject the ActivatedRoute into this component via the constructor. Next we’ll use the ActivatedRoute to grab the username route parameter in ngOnInit()

ngOnInit() {
  // this is where we'll grab data
  // grab using the snapshot method
  this.username = this.route.snapshot.params.username;
}

This will be enough to grab the username! Let’s look at the next way we can grab route parameters and why we would want to use the second method instead of the snapshot method.

Angular Route Performance

Angular works hard to keep application performance as fast as possible. One of the ways Angular does this is by reusing components as often as possible. Angular doesn’t have to destroy and recreate multiple times, it will just switch out the data.

Angular reuses components to improve performance.

A scenario where the snapshot method wouldn’t work is when we are on one profile and click a link to second profile. The snapshot method only runs one time when the component is initiated. The component wouldn’t update if we travelled from (/users/chris) to another profile (/users/nick).

If you are sure that you won’t be using the same component over and over, you can use the snapshot method. Otherwise, we’ll look to the observable way to

Grabbing Route Parameters (The Observable Way)

Observables by their nature are a stream of events. This means that when we go from one profile (/users/chris) to another profile (/users/nick), the Observable will pass along the new data as it changes.

Angular v4+ router provides us with ParamMap which is an Observable we can use. Here’s the syntax to use it instead of the snapshot method:

ngOnInit() {
  // subscribe to the parameters observable
  this.route.paramMap.subscribe(params => {
    console.log(params.get('username'));
    this.username = params.get('username');
  });
}

Now whenever we click to a new profile, you’ll see the console.log() updating to show the username from the route.

Note: The Angular router will handle unsubscribing from ParamMap on its own.

Angular v2

The paramMap is one of the newer additions. If you’re working with Angular v2 instead of v4+, you can grab route parameters with params instead of paramMap.

ngOnInit() {
  // subscribe to the parameters observable
  this.route.params.subscribe(params => {
    console.log(params.username);
    this.username = params.username;
  });
}

With just a few more lines of code, this component will listen for route changes now and always update the username based on the route.

Conclusion

The Angular router makes it easy to work with route parameters. Remember to weigh your options when deciding between the snapshot vs the Observable way. Usually it’s best to lean towards the Observable way just to avoid any issues you may run into in the future if you run into a scenario where you reuse a component.

Source:: scotch.io

Build a License Plate Recognition Service In 31 Lines of Code

By Prosper Otemuyiwa

A few days ago, when prowling around the internet, I came across a very interesting article, How I replicated an $86 million project in 57 lines of code. The use of open source technology was greatly emphasized in the license plate recognition. The article’s author also insisted on implementing an on-device image processing platform, which would require installing image processing software on every device.

Reading this, a few thoughts came to mind:

  1. Open source technology is great, but it also has its downsides. For instance, a bug in the open source software means every device that has the software running could be hacked easily and instantly. Remember the Heartbleed bug?
  2. Fixing and updating the software installed on these devices would be a massive pain. They would have to be upgraded individually.
  3. I can definitely build a similar system using alternative technology because I am a software engineer.

I use Cloudinary for any project that relates to image, audio and video uploads, as well as filtering and transformations in production for virtually every software project I code. And guess what? I quickly skimmed through Cloudinary’s documentation to see if there was a way I could easily extract text from images. Unsurprisingly, I found a hidden gem, and I’ll show you how to use it as we build our license plate recognition system in 31 lines of code

Wait, what’s Cloudinary, anyway?

Cloudinary is a cloud-based solution for image and video management, including server or client-side upload, a huge range of on-the-fly image and video manipulation options, including face detection, quick content delivery network (CDN) delivery, and powerful asset management options.

Cloudinary enables web and mobile developers to address all of their media management needs with simple bits of code in their favorite programming languages or frameworks, freeing them to focus primarily on their own product’s value proposition.

Step 1: Create a Cloudinary Account

Sign up for a free Cloudinary account.

Once you are signed up, you will be redirected to the dashboard where you can get your credentials.

Take note of your Cloud name, API Key and API Secret

Step 2: Set Up A Node Server

Initialize a package.json file:

 npm init

Install the following modules:

 npm install express connect-multiparty cloudinary cors body-parser --save

express: We need this module for our API routes
connect-multiparty: Needed for parsing http requests with content-type multipart/form-data
cloudinary: Node SDK for Cloudinary
body-parser: Needed for attaching the request body on express’s req object
cors: Needed for enabling CORS

Step 3: Activate OCR Text Detection and Extraction Add-on

Go to the dashboard add-ons section. Click on OCR Text Detection and Extraction Add-on and select the Free Plan.

Note: You can change to other plans as your usage increases.

Step 4: Set Up License Plate Character Recognition

Create a server.js file in your root directory. Require the dependencies we installed:

const express = require('express');
const app = express();
const multipart = require('connect-multiparty');
const cloudinary = require('cloudinary');
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

const multipartMiddleware = multipart();

Next, configure Cloudinary:

cloudinary.config({
    cloud_name: 'xxxxxxxx',
    api_key: 'xxxxxxxx',
    api_secret: 'xxxxxxx'
});

Replace xxxxxx with the real values from your dashboard.

Add the route for uploading. Let’s make the route /upload.

app.post('/upload', multipartMiddleware, function(req, res) {
  cloudinary.v2.uploader.upload(req.files.image.path,
    {
      ocr: "adv_ocr"
    }, function(error, result) {
        if( result.info.ocr.adv_ocr.status === "complete" ) {
          res.json(result); // result.info.ocr.adv_ocr.data[0].textAnnotations[0].description (more specific)
        }
    });
});

Once a user makes a POST request to the /upload route, the route grabs the image file from the HTTP request, uploads to Cloudinary, sends to Google Vision. The OCR Add-on is powered by the Google Vision API and it integrates seamlessly with Cloudinary’s upload and manipulation functionality.

A JSON response is quickly sent back, with the characters of the license plate in the image that was recently uploaded.
Let’s quickly test this functionality with Postman.

Make sure your server is running:

nodemon server.js

Uploaded this car image

I sent the image as a POST request to the http://localhost:3333/upload route.

Results from Uploaded Car image

Boom! It extracted the plate number from the image: LMIO OHH.

A comprehensive JSON response is returned. The ocr node of the response includes the following:

  • The name of the OCR engine used by the add-on (adv_ocr)
  • The status of the OCR operation
  • The detected language of the text
  • The outer bounding rectangle containing all of the detected text
  • A description listing the entirety of the detected text content, with a newline character (n) separating groups of text
  • For multi-page files (e.g. PDFs), a node indicating the containing page
  • The bounding rectangle of each individual detected text element and the description (text content) of that individual element

Multi-page PDF files? Yes, you can extract text from PDF files using Cloudinary’s OCR add-on.

One More Gem

You can blur, pixelate or overlay other images on all detected text with simple transformation parameters. You also can use the add-on to ensure that important text isn’t cut off when you crop your images.

cloudinary.image("image.jpg", {transformation: [
  {width: 1520, height: 1440, gravity: "west", x: 50, crop: "crop"},
  {effect: "pixelate_region:15", gravity: "ocr_text"}
  ]})

Check out the documentation for more gems on using the OCR add-on

Conclusion

The advantage of using Cloudinary’s cloud-based system for building services, like the one we showed here with 31 lines of code, is that you can perform a string of operations other than just detecting and extracting text.

You can leverage a full-blown suite of Image transformation features in your applications and services.

Source:: scotch.io

Lazy Loading in Angular v2+

By Chris Sevilleja

Application performance is an important part of web development. We always want our users to have the quickest and most performant experience when they visit our apps.

Lazy loading is one of the features we can add to our app to improve performance. What exactly is lazy loading?

Lazy loading is the act of only loading parts of our app when they are needed.

The benefits are:

  • Keep the initial payload small
  • Smaller payloads lead to faster download speeds
  • Lower resource costs especially on mobile networks
  • If a user doesn’t visit a section of our app, they won’t ever download those resources

The Angular router provides a simple and easy way to add lazy loading to our application. Let’s take a look at how we can add it.

Overview and Setup

Lazy loading in Angular requires us to format our application a certain way. All the assets that you want to be lazy loaded should be added to its own module.

For instance, if we wanted to lazy load our entire dashboard/ section, we would need to have all those assets/components in their own DashboardModule.

Rules for lazy loading:

  • Move components and assets into their own module
  • DO NOT load the module in the main AppModule
  • Lazy loading will be setup in the main routing file

TLDR: Adding Lazy Loading

Once you have a module you want to lazy load to (let’s say a DashboardModule), we can add it to our writing file.

Here is the route to use for a DashboardModule:

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: 'app/dashboard/dashboard.module#DashboardModule',
  }
];

We’re using the loadChildren parameter to pass a string that points to our module. Make sure you reference from the root src/ folder. Notice we started the string at app/.

The dashboard module will most likely have its own routes. We add the path: dashboard here in the main router and the child router will be set to path: ''.

Now when you visit your dashboard section, you

Building a Lazy Loaded App

Let’s build a quick lazy loaded app to see exactly how this would work. We’ll be using the Angular CLI. You don’t need to using the CLI. Just make sure you have a module and route to it using loadChildren.

We’ll create an app with a dashboard section. This dashboard section will be lazy loaded. Not all users will visit the dashboard.

Here’s the overview of our app:

  • Home route | ” | HomeComponent
  • Dashboard section | ‘dashboard’ | DashboardHomeComponent

We’ll use the CLI to create the entire app with routing:

# create the app
ng new lazyload-app --routing

# create the home component
ng g component home

# create the dashboard module
ng g module dashboard --routing

# create the dashboard home page
ng g component dashboard/dashboard-home

We now have a clean app setup:

The cool thing about creating a component with the CLI is that the CLI will automatically register the component in its respective module. We don’t have to go write the import and add it to the declarations array.

Setup Dashboard Routes

We have our new dashboard module with a new dashboard-routing.module.ts file. This is where we’ll define routes. Any routes defined here will be lazy loaded!

Let’s update our dashboard-routing.module.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardHomeComponent } from './dashboard-home/dashboard-home.component';

const routes: Routes = [
  {
    path: '',
    component: DashboardHomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule { }

We added path: '' because we’ll define the dashboard route in the main router.

Setup Main Lazy Loaded Route

Let’s update the main router now to point our dashboard section to this new DashboardModule. We’ll also be setting up lazy loading!

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'dashboard',
    loadChildren: 'app/dashboard/dashboard.module#DashboardModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The loadChildren parameter is how we tell Angular to lazy load that section. Remember that we don’t have to load the DashboardModule into the main AppModule.

Testing Our App

Now this is all looking good. How do we actually test to see if lazy loading is working? Let’s do one last thing before we can test.

Creating a Dashboard Link

To test lazy loading, we’ll need a link that points to the dashboard. We need a way to get to our new section we just created.

Open up app.component.html and add the following to the top:

<a routerLink="/dashboard">Dashboard</a>

Starting the App

Now we can start up our app and find out if lazy loading is working.

ng serve --open

Open up dev tools and go to the Network -> JS tab.

As soon as you click the Dashboard link, you’ll see the dashboard module get loaded!

Conclusion

Just by adding all our code to a module and adding the loadChildren parameter, the Angular router makes it easy to lazy load sections of our application.

Source:: scotch.io

Protecting Angular v2+ Routes with CanActivate/CanActivateChild Guards

By Chris Sevilleja

Protecting routes is something that has to happen in any app with authentication. There will be sections of your applications that you don’t want certain users to get to.

We’ll be looking at a simple example of how to use Angular router guards to protect an area of our site. While this will be a simple example that you can reference back to, we’ll look at more advanced setups in future articles.

In this tutorial, we’ll look at how we can use Angular guards to:

  • Protect an entire section (route)
  • Protect just a part of the app (child routes)

TLDR: How to Create and Use An Angular Guard

The overall process for protecting Angular routes:

  • Create a guard service: ng g guard auth
  • Create canActivate() or canActivateChild() methods
  • Use the guard when defining routes

To create a guard using the Angular CLI, use:

ng g guard auth

This will create an auth.guard.ts

Here is the generated file:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthGuard implements CanActivate {

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      return true;
  }

}

Now we can add in an AuthService that we may have:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

// import the auth service here
// import { AuthService } from '../core/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  // add the service we need
  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      // handle any redirects if a user isn't authenticated
      if (!this.auth.isLoggedIn) {
        // redirect the user
        this.router.navigate(['/login']);
        return false;
      }

      return true;
  }

}

In the canActivate() method, we can do any checks we need to check if a user has access. Return a boolean true/false. Also, this is where you can handle routing users away from a route if they don’t have access.

Import this new class into a module so your app knows how to grab it. Then you can use this when defining routes:

// import the newly created AuthGuard

const routes: Routes = [
  {
    path: 'account',
    canActivate: [AuthGuard]
  }
];

This will protect the /account route! That’s the quick overview on how to use the guards. Let’s go a bit more in depth.

The Angular Router Guards

The Angular router ships with a feature called guards. These provide us with ways to control the flow of our application. We can stop a user from visitng certain routes, stop a user from leaving routes, and more.

We’ll only be talking about CanActivate/CanActivateChild in this tutorial, but be aware that these are the available guards:

  • CanActivate: Check if a user has access
  • CanActivateChild: Check if a user has access to any of the child routes
  • CanDeactivate: Can a user leave a page? For example, they haven’t finished editing a post
  • Resolve: Grab data before the route is instantiated
  • Lazy loading feature modules.
  • CanLoad: Check to see if we can load the routes assets

Creating a Sample App

Our sample app will be a very simple one. We’ll use the [Angular CLI]() to create a new Angular app. We’ll also create a brand new account and dashboard sections. The requirements:

  • Only logged in users can visit the /account section
  • Only admins can access the /dashboard section
  • Only super admins can visit the /dashboard/super-duper section

Let’s get started!

Using the CLI to Create an App

Once you have the CLI installed, create a new app with routing and a home page component using:

ng new angular-guard-app --routing

This will generate a new app for us with routing configured. Check out our src/ folder:

We can open up our app now using:

ng serve --open

Creating a Main Route

We’ll need a home page route so that we can have a default path configured. Create a home component with:

ng g component home

The CLI will automatically add this new component to our app.module.ts. All we have to do is set it in our app-routing.module.ts:

// app-routing.module.ts 

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now when you visit your app, you should see home works in tiny text at the very bottom. This is where the is located.

Next we’ll move onto our app sections.

Creating Our App Sections

We’ll need an account section and also a dashboard section. While we could create these as components, we’ll be creating them as modules.

Here’s the modules and components we’ll want.

|- dashboard.module.ts
    |- dashboard-home.component.ts
    |- super-duper.component.ts
|- account.module.ts
    |- account-home.component.ts

Since these are sections of our app that a user might not always visit, we may want to lazy-load these sections. By lazy loading, the assets for these sections will only be loaded when a user visits that section.

# create the account module and main component
ng g module account --routing
ng g component account/account-home

# create the dashboard module and main component
ng g module dashboard --routing
ng g component dashboard/dashboard-home

# create the dashboard child route for super admins
ng g component dashboard/super-duper

These commands will get us two new modules and a new component.

Now we can setup the routing for each of these modules.

Routing the Child Modules

Each module created will have its own routing file (dashboard-routing.module.ts and account-routing.module.ts).

We’ll set up the routing in each of these child routing files. The auth guards will be used when we define the routes in these modules. The reason we attach guards here and not in the main app-router.module.ts is because we’ll be lazy-loading them and we’ll have more control in the child routing files.

Let’s setup the routes now:

// account-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AccountHomeComponent } from './account-home/account-home.component';

const routes: Routes = [
  {
    path: '',
    component: AccountHomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AccountRoutingModule { }
// dashboard-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardHomeComponent } from './dashboard-home/dashboard-home.component';
import { SuperDuperComponent } from './super-duper/super-duper.component';

const routes: Routes = [
  {
    path: '',
    component: DashboardHomeComponent,
    children: [
      {
        path: 'super-duper',
        component: SuperDuperComponent
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DashboardRoutingModule { }

Now we can add these to the main app-routing.module.ts. We’ll use the syntax for lazy-loading by using the loadChildren parameter.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'account',
    loadChildren: 'app/account/account.module#AccountModule'
  },
  {
    path: 'dashboard',
    loadChildren: 'app/dashboard/dashboard.module#DashboardModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Notice that we don’t import the AccountModule or DashboardModule. We also don’t import these into the main AppModule; if we did import it there, then it would no longer be lazy-loaded.

Since we defined the path as dashboard and account in the main app-routing.module.ts, we’ll define the top level route as '' in the child routes.

Now that we have our routes ready, we can work on the auth service and guards!

Authentication Service

We’ll create a generic authentication service that won’t hook into anything. We’ll return a boolean for true to show a user is logged in. In your application, you would hook this into a service like a backend API to check auth status.

We’ll use the CLI to create this service. I’m going to drop this right into the main app/ folder but it would be good practice to create services and guards inside a CoreModule or its own AuthModule.

ng g service auth/auth

We’ll add a method to check for isLoggedIn and isSuperAdmin. We’ll just fill these in with a boolean but you’ll need to make sure to add the logic for your own apps. It wouldn’t be great security if your AuthService always returned true!

import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

  constructor() { }

  get isLoggedIn() {
    return true;
  }

  get isSuperAdmin() {
    return true;
  }

}

Note We’re using the get keyword here to treat these as properties. That way we can access these functions as:

// with the get keyword we can do this
const isLoggedIn = this.auth.isLoggedIn;

// without it, we have to treat it was a method
const isLoggedIn = this.auth.isLoggedIn();

Our service is ready to be used in our guards!

Authentication Guard

We’ll need a guard to check if a user is logged in or not. We’ll create it in the auth/guards folder that we’ll create now with the CLI:

ng g guard auth/guards/auth

Here’s the new guard in all its glory:

// app/auth/guards/auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return true;
  }
}

We’ll inject the AuthService and bring in the Router so that we can:

  • check if a user is logged in
  • redirect them if not logged in
// app/auth/guards/auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    // redirect and return false
    if (!this.auth.isLoggedIn) {
      this.router.navigate(['']);
      return false;
    }

    return true;
  }
}

Easy cheese! Let’s make an admin guard now for our dashboard super-duper section.

Super Admin Guard

ng g guard auth/guards/admin
// app/auth/guards/admin.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    // redirect and return false
    if (!this.auth.isSuperAdmin) {
      this.router.navigate(['']);
      return false;
    }

    return true;
  }
}

With our service and guards ready to use, we’ll need to register them with our application’s AppModules. While the CLI automatically registers components, it doesn’t do the same for services.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AuthService } from './auth/auth.service';
import { AuthGuard } from './auth/guards/auth.guard';
import { AdminGuard } from './auth/guards/admin.guard';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    AuthService,
    AuthGuard,
    AdminGuard
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

All good! Now we can finally apply these to our routes. Open up the child routes and let’s use our new guards.

Applying to Our Routes

In the account routing, we’ll use the main AuthGuard. Here are the relevant lines:

// account-routing.module.ts
...

import { AuthGuard } from '../auth/guards/auth.guard';

const routes: Routes = [
  {
    path: '',
    component: AccountHomeComponent,
    canActivate: [AuthGuard]
  }
];

...

Let’s test this out! Visit http://localhost:4200/account in your browser. You should be able to see at the very bottom account-home works!

Testing the Auth

We need to make sure that our user actually gets redirected to the home page if they aren’t authenticated. Go back into the AuthService and change the isLoggedIn() method to return false.

get isLoggedIn() {
  return false;
}

Now when we visit http://localhost:4200/account, we’ll be redirected to the home page!

How does this work?

When we define the route and its guard, Angular will look inside the guard and look for the corresponding method. For instance, we defined this line:

{
  path: '',
  component: AccountHomeComponent,
  canActivate: [AuthGuard]
}

Angular will look inside the AuthGuard file and match the canActivate method.

CanActivateChild

We could do the same exact thing for our dashboard section, but let’s switch it up. We’ll use canActivateChild instead of the main canActivate. Remember we defined child routes inside the dashboard-routing.module.ts.

Let’s update our admin guard to also implement the canActivateChild method.

// dashboard-routing.module.ts

import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../auth.service';

@Injectable()
export class AdminGuard implements CanActivate, CanActivateChild {

  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    // redirect and return false
    if (!this.auth.isLoggedIn) {
      this.router.navigate(['']);
      return false;
    }

    return true;
  }

  canActivateChild(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    // redirect and return false
    if (!this.auth.isLoggedIn) {
      this.router.navigate(['']);
      return false;
    }

    return true;
  }
}

Then we can apply this to our dashboard routes:

// dashboard-routing.module.ts
...

import { AdminGuard } from '../auth/guards/admin.guard';

const routes: Routes = [
  {
    path: '',
    component: DashboardHomeComponent,
    canActivateChild: [AdminGuard],
    children: [
      {
        path: 'super-duper',
        component: SuperDuperComponent
      }
    ]
  }
];

...

One thing to note is that since these are child routes, we’ll need to add a new to the dashboard-home.component.html:

<p>
  dashboard-home works!
</p>

<router-outlet></router-outlet>

Now our guard works! We can go into AuthService and change the isAdmin() method to check.

The reason you would use CanActivateChild over CanActivate is that you can limit the nested router-outlet. Notice we can still see the dashboard-home.component but not anything in its own nested routes.

Conclusion

Angular CanActivate and CanActivateChild guards provide a clean and defined way to “guard” certain routes. We’ve only taken a look at two of the guards, but all of them are worth looking into! They are a solid way to manage the flow of users throughout your app.

Source:: scotch.io

How to Create Filters in Vue.js with Examples

By Rachid Laasri

Similar to AngularJS, Vue.js has its way of transforming data and applying filters to it, but you must keep in mind that filters don’t transform the original data, they only change the output and return a filtered version of it. Filters can be useful in a lot of different situations like keeping your API responses as clean as possible and handling the formatting of your data on your frontend. They can also be efficient in cases where you want to avoid repetition and concatenation by encapsulating all that logic behind reusable code blocks.

I hope this small introduction got you excited to learn more about Filters. How you can create and use them and couple more things you will discover going through the article. HERE WE GO!

Vue.js Default Filters

If this isn’t your first time reading about Vue.js filters then you know that the older versions shipped with built-in filters, but they got removed from Vue 2.0 and this is Evan You ‘s (the creator of Vue.js)’ reasoning behind that:

Built-in filters can be useful, but they lack the flexibility of pure JavaScript. When a built-in function doesn’t suit your needs, you either end up re-implementing something similar (and shipping both in your final code, where the built-in becomes useless, dead code) or have to wait for Vue to update them and release a new version.

With that in mind, be careful reading or watching old tutorials. Here is a full list of the old default filters in case you want to learn more about them: Filters – vue.js.

Spoiler Alert: We will be reproducing few of them in the examples below

Defining and Using Filters

With Vue, you can register your filters in two different ways: Globally and Locally. The former gives you access to your filter across all your components, unlike the latter which only allows you to use your filter inside the component it was defined in.

Filters are simple JavaScript functions, they take the value to be transformed as the first parameter, but you can also pass in as many other arguments as you will need to return the formatted version of that value.

Global Filters

Here is what a Global filter looks like:

// In this example, we will register a global filter
// which will add the dollar sign in front of the price:

// DECLARATION
Vue.filter('toUSD', function (value) {
    return `$${value}`;
});

// USAGE
<div id="app">
  <span>{{ 351.99 | toUSD }}</span>
</div>

PS: The filter definition must always be above the main Vue instance, or you will get a “Failed to resolve filter: toUSD” error.

// DECLARATION
Vue.filter('toUSD', function (value) {
    return `$${value}`;
});

new Vue({
    el: '#app',

     data: {
        price: 351.99
    }
});

// USAGE
<div id="app">
  <span>{{ price | toUSD }}</span>
</div>

See it in action

Local Filters

Local filters are registered to a Vue component scope. The following illustrates how they are created:

// In this example, we are creating a filter 
// That turns the string you give it to upper-case.

// DECLARATION
new Vue({
    el: '#app',

    data: {
        name: 'scotch.io'
    },

    filters: {
       // Filter definitions
        Upper(value) {
            return value.toUpperCase();
        }
    }
});

// USAGE
<div id="app">
  <span>{{ name | Upper }}</span>
</div>

See it in action

As you can see in the example above, Local Filters are stored within the Vue component as functions inside the “filters” property. You can register as many as you want:

...
    filters: {
        Upper(value) {
              return value.toUpperCase();
        },
        Lower(value) {
            return value. toLowerCase();
        },
    }
....

Additional Arguments

As we mentioned in the introduction of this article, Filters can take as many arguments as you need:


// DECLARATION
Vue.filter('readMore', function (text, length, suffix) {
    return text.substring(0, length) + suffix;
});

new Vue({
    el: '#app',

    data: {
        text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non ab modi repellendus labore facere, fugiat ipsam quae accusantium commodi voluptas nesciunt dolor similique ipsum accusamus earum eligendi suscipit laborum quod.'
    }
});

// USAGE
<div id="app">
  <span>{{ text | readMore(10, '...') }}</span>
</div>

In this example, we created a filter with the name “readMore” which will limit the length of a string to a given number of characters and will also append a suffix of your choice to it. Vue.js passes the value to be filtered as the first param text and length, suffix as the second and third parameter.

See it in action: Edit fiddle – JSFiddle

Chaining Filters

One of my favorite things about Filters is the ability to chain them using the pipe ( | ) symbol and run a single value through a series of transformers. Let’s use the example of price value again; we want to limit it to two numbers after a comma and add the dollar sign to it.

Although we can achieve this using one single filter we might also want to use toUSD filter on its own. Separating and chaining filters, in this case, is the way to go:

Vue.filter('toFixed', function (price, limit) {
    return price.toFixed(limit);
});

Vue.filter('toUSD', function (price) {
    return `$${price}`;
});

new Vue({
    el: '#app',

    data: {
        price: 435.333
    }
});
<div id="app">
  <span>{{ price | toFixed(2) | toUSD }}</span>
</div>

Check it out in action

Examples

If you made it to this part of the article, congratulations! That was everything you needed to know about Vue.js filters, but it is always a good idea to go through few examples:

  • Convert a JavaScript value to a JSON string:
Vue.filter('json', function (value) {
    return JSON.stringify(value);
});

new Vue({
    el: '#app',

    data: {
        user: {
            username: 'johndoe',
            email: 'john@example.com',
            countryCode: 'U.K.'
        }
    }
});
<div id="app">
  <span>{{ user | json }}</span>
</div>

Edit fiddle – JSFiddle

  • Extracting a list of property values from an array of objects:
Vue.filter('pluck', function (objects, key) {
    return objects.map(function(object) { 
        return object[key];
    });
});

new Vue({
    el: '#app',

    data: {
        users: [
        {
            "id": 4,
            "first_name": "Eve",
            "last_name": "Holt"
        },
        {
            "id": 5,
            "first_name": "Charles",
            "last_name": "Morris"
        },
        {
            "id": 6,
            "first_name": "Tracey",
            "last_name": "Ramos"
        }
        ]
    }
});
<div id="app">
  <span>{{ users | pluck('last_name') }}</span>
</div>

Edit fiddle – JSFiddle

  • Return the element at the given index:
Vue.filter('at', function (value, index) {
    return value[index];
});

new Vue({
    el: '#app',

    data: {
        videos: ['Zi_XLOBDo_Y', 'sOnqjkJTMaA', 'sOnqjkJTMaA']
    }
});
<div id="app">
  <span>{{ videos | at(1) }}</span>
</div>

Edit fiddle – JSFiddle

  • Return the minimum value in a given list:
Vue.filter('min', function (values) {
    return Math.min(...values);
});

new Vue({
    el: '#app',

    data: {
        ages: [23, 19, 45, 12, 32]
    }
});
<div id="app">
  <span>{{ ages | min }}</span>
</div>

Edit fiddle – JSFiddle

  • Shuffle a list of elements:
Vue.filter('shuffle', function (values) {
    for (var i = values.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = values[i];
        values[i] = values[j];
        values[j] = temp;
    }
    return values;
});

new Vue({
    el: '#app',

    data: {
        cards: ['Lahire', 'Judith', 'Lancelot', 'Alexandre']
    }
});
<div id="app">
  <span>{{ cards | shuffle }}</span>
</div>

Edit fiddle – JSFiddle

  • Return the first element of an array:
Vue.filter('first', function (values) {
    if(Array.isArray(values)) {
        return values[0];
    }
    return values;
});

new Vue({
    el: '#app',

    data: {
        consoles: ['PlayStation', 'Nintendo DS', 'Xbox', 'Atari']
    }
});
<div id="app">
  <span>{{ consoles | first }}</span>
</div>

Edit fiddle – JSFiddle

  • Return the last element of an array:
Vue.filter('last', function (values) {
    if(Array.isArray(values)) {
        return values[values.length - 1];
    }
    return values;
});

new Vue({
    el: '#app',

    data: {
        consoles: ['PlayStation', 'Nintendo DS', 'Xbox', 'Atari']
    }
});
<div id="app">
  <span>{{ consoles | last }}</span>
</div>

Edit fiddle – JSFiddle

  • Return a copy of the array without the given elements:
Vue.filter('without', function (values, exclude) {
    return values.filter(function(element) {
        return !exclude.includes(element);
    });
});

new Vue({
    el: '#app',

    data: {
        unpaidInvoices: ['#1001', '#1002', '#1003', '#1004']
    }
});
<div id="app">
  <span>{{ unpaidInvoices | without('#1003') }}</span>
</div>

Edit fiddle – JSFiddle

  • Remove duplicated elements in an array:
Vue.filter('unique', function (values, unique) {
    return values.filter(function(element, index, self) {
        return index == self.indexOf(element);
    });
});

new Vue({
    el: '#app',

    data: {
        recentViewedPosts: [13, 43, 23, 13, 43, 3, 98, 42, 65]
    }
});
<div id="app">
  <span>{{ recentViewedPosts | unique }}</span>
</div>

Edit fiddle – JSFiddle

  • Prepend text to a string:
Vue.filter('prepend', function (string, prepend) {
    return `${string}${prepend}`;
});

new Vue({
    el: '#app',

    data: {
        greeting: 'Hello'
    }
});
<div id="app">
  <span>{{ greeting | prepend(' World!') }}</span>
</div>

Edit fiddle – JSFiddle

  • Repeat a string n times:
Vue.filter('repeat', function (string, times) {
    return string.repeat(times);
});

new Vue({
    el: '#app',

    data: {
        greeting: 'Hello'
    }
});
<div id="app">
  <span>{{ greeting | repeat(3) }}</span>
</div>

Edit fiddle – JSFiddle

If you are interested in these filters and you want to use them in your project GitHub – wy-ei/vue-filter: A collection of Vue.js filter. offers a set of a very useful Vue.js filters including the ones above. Head over there to see how you can install and use them.

Conclusion

I hope you learned something from this post and you now know how to create and use filters and most importantly you can now refactor your code and clean it a bit with filters.

Stay tuned for more Vue.js tutorials and see you soon!

Source:: scotch.io