Categories
Express JavaScript Nodejs

Tracking Response Time of Express App Responses

To gauge the performance of our apps, we need to measure the response time of our API.

To do this with our Express app, we can use the response-time package.

Installation

response-time is available as a Node package. We can install it by running:

npm install response-time

Then we can import it by writing:

const responseTime = require('response-time');

responseTime([options])

We can set various options by passing an object into the optional options parameter.

It’ll create a middleware that adds a X-Response-Time header to responses.

The options object takes the following properties:

digits

The digits property is a fixed number of digits to include in the output, which is always in milliseconds. The default is 3.

header

The name of the header to be set. It defaults to X-Response-Time.

suffix

The suffix property is a boolean property to indicate if units of measure should be added to the output. The default value is true.

responseTime(fn)

The function creates a middleware that records the response time of a request and makes it available to our own function fn. fn has the signature (req, res, time) where time is a number in milliseconds.

Examples

Simple Example

We can use the responseTime package without any options or function passed in:

const express = require('express');  
const bodyParser = require('body-parser');  
const responseTime = require('response-time')  
const app = express();  
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(responseTime());app.get('/', (req, res) => {  
  res.send('foo');  
});
app.listen(3000);

Then we get a X-Response-Time response header with a value like 0.587ms.

We can check the response header on an HTTP client like Postman.

Passing in Options

We can change the options for the header returned with the response. For example, we can write the following to change the number of digits sent:

const express = require('express');  
const bodyParser = require('body-parser');  
const responseTime = require('response-time')  
const app = express();  
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(responseTime({  
  digits: 5  
}))
app.get('/', (req, res) => {  
  req.id = 1;  
  res.send('foo');  
});
app.listen(3000);

Then we get a X-Response-Time response header with a value like 0.71987ms.

Passing in Our Own Function

We can pass a function into the responseTime function as follows:

const express = require('express');  
const bodyParser = require('body-parser');  
const responseTime = require('response-time')  
const app = express();  
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(responseTime((req, res, time) => {  
  console.log(`${req.method} ${req.url} ${time}`);  
}))
app.get('/', (req, res) => {  
  req.id = 1;  
  res.send('foo');  
});
app.listen(3000);

Then we get something like:

GET / 2.9935419999999997

from the console.log.

It’s useful if we want to manipulate the response time data or log it ourselves.

Conclusion

We can get the response time in the response header of a request with the response-time package.

It has a responseTime function which returns a middleware that we can use with the use method of express or express.Router() .

The function can either take an options object and or a function with the req, res, and time parameters to get the request, response, and response time respectively.

Categories
JavaScript Vue

Introduction to Vue.js Templates

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at how to create and use templates to display data and handle events.

How it Works

Vue templates let us bind data to the DOM.

Vue compiles the template into Virtual DOM render functions. It can figure out the minimal number of components to re-render and minimize DOM manipulation when data changes.

Interpolations

The most basic form of data binding is text interpolation with double curly braces.

For example, we can write:

<p>{{foo}}</p>

To show the value of foo from a Vue instance or component.

The code above will be updated when foo updates.

We can keep it from updating after the first render by using the v-once directive as follows:

<p v-once>{{foo}}</p>

Raw HTML

We can also put raw HTML into an element with the v-html directive.

This lets us add HTML elements and formatting into an element.

For example, if we have the following in src/index.js :

new Vue({  
  el: "#app",  
  data: {  
    rawHtml: "<b>bar</b>"  
  }  
});

and the following in index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>Hello</title>  
    <meta charset="UTF-8" />  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
  </head> <body>  
    <div id="app">  
      <p v-html="rawHtml"></p>  
    </div>  
    <script src="./src/index.js"></script>  
  </body>  
</html>

Then we get bar bolded displayed since the inner HTML of the p element is <b>bar</b> .

When we’re using this, we have to sanitize the HTML so that it won’t contain any code. This is to prevent cross-site scripting attacks since code will be run if there are any when we pass in a value to the v-html directive.

Attributes

We can set values of HTML element attributes dynamically with v-bind as follows.

In src/index.js , we write:

new Vue({  
  el: "#app",  
  data: {  
    isButtonDisabled: true  
  }  
});

Then when we write the following in index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>Hello</title>  
    <meta charset="UTF-8" />  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
  </head> <body>  
    <div id="app">  
      <button v-bind:disabled="isButtonDisabled">Button</button>  
    </div>  
    <script src="./src/index.js"></script>  
  </body>  
</html>

Then since we set the isButtonDisabled property to true , the button will be disabled. This also apply to any other truthy value.

On the other hand, if we set it to false , we see that the button is disabled. This also applies to other falsy values like null , undefined , 0 and empty string.

JavaScript Expressions

We can add any other JavaScript expressions between the curly braces.

For example, we can write:

{{ number + 10 }}  
{{ yes ? 'YES' : 'NO' }}  
{{ str.split('').reverse('').join('') }}

Also, we can write expressions as the value of the v-bind directive as follows:

<div v-bind:id="`div-${id}`"></div>

Statements will not run inside the curly braces. For example:

{{ let a = 1 }}

will give us an error. We’ll get the error ‘avoid using JavaScript keyword as the property name: “let”’ in the console.

We also can’t run conditional statements within curly braces:

{{ if (id) { return id } }}

We’ll get the error ‘avoid using JavaScript keyword as the property name: “if”’.

Directives

Directives are special attributes with the v- prefix. We can pass in a single JavaScript expression as the value.

v-for can accept more than one expression separated by ; .

For example, we can conditionally display content with v-if :

<p v-if="show">Hello</p>

If show is truthy, then we’ll see Hello . Otherwise, it won’t be shown.

Arguments

Some directive takes an argument, which is denoted by a colon after the directive name.

For example, we can set the href value of an a element by writing:

<a v-bind:href="'https://medium.com'">Medium </a>

The v-on directive also takes an argument. For example, we can handle the click event of an element by writing:

<a v-on:click="onClick"> Click Me </a>

Then the onClick method in our Vue instance or component will be run when we click on the a element.

Dynamic Arguments

Since Vue.js 2.6.0, we can use a JavaScript expression as an argument for a directive.

For example, we can use it as follows. In src/index.js , we write:

new Vue({  
  el: "#app",  
  data: {  
    click: `${"cl"}${"ick"}`  
  },  
  methods: {  
    onClick() {  
      alert("clicked");  
    }  
  }  
});

Then in index.html , we can use a dynamic argument as follows:

<!DOCTYPE html>  
<html>  
  <head>  
    <title>Hello</title>  
    <meta charset="UTF-8" />  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
  </head> <body>  
    <div id="app">  
      <a v-on:click="onClick"> Click Me </a>  
    </div>  
    <script src="./src/index.js"></script>  
  </body>  
</html>

This will reference the value of the click property of the data property in our Vue instance, and so we actually have v-on:click .

And therefore, when we click the a tag, we get an alert box with the clicked text displayed.

Dynamic argument expressions must evaluate to a string or null .

Spaces and quotes also aren’t valid inside the brackets.

Conclusion

We can create templates in various ways. The most basic is interpolation with the double curly brace syntax. We can put any JavaScript expression between the braces.

To set the values of attributes dynamically, we can use the v-bind directive. The value can be any JavaScript expression.

Some directives take an argument, which is the part of the directive name after the colon. Again the directive’s value can be any JavaScript expression in this case.

Dynamic arguments can be used since Vue 2.6.0. We can use it by putting an expression in square brackets.

Categories
JavaScript TypeScript

Multiple Inheritance with TypeScript Mixins

In JavaScript, there’s no easy way to inherit from multiple classes. We can make our own mixins to inherit from multiple objects. This is made easier in TypeScript by making mixins a standard. With TypeScript, we can make interfaces that extend multiple classes or interfaces. This way, we can reuse multiple partial classes to create a new child class. We do this with mixins and copy over the properties to a new class that derive members from parent classes with our own function.

To define a interfaces that inherit from multiple classes in TypeScript, we create an interface that extends multiple classes or interfaces. Each of these classes or interfaces is called a mixin. We can mix and match them to create a combined interface to have whatever properties that we want. For example, we can write something like the following code:

class Animal {  
    species: string;  
    constructor(species: string) {  
        this.species = species  
    }  
}

class Person {  
    name: string;  
    constructor(name: string) {  
        this.name = name  
    }  
}

interface Employee extends Person, Animal {  
    employeeCode: string;  
}

let employee: Employee = {  
    species: 'human',  
    name: 'Joe',  
    employeeCode: '123'  
}

In the code above, we made an Employee interface which inherits all the members from the Animal and Person classes and we incorporated the employeeCode member into the Employee interface. This lets us create an Employee object with the species , name , and employeeCode properties.

We can only use the extends keyword with multiple classes or interfaces if we use the keyword in the interfaces. It won’t work if we use it in a class. For example, if we write:

class Animal {  
    species: string;  
    constructor(species: string) {  
        this.species = species  
    }  
}

class Person {  
    name: string;  
    constructor(name: string) {  
        this.name = name  
    }  
}

class Employee extends Person, Animal {  
    employeeCode: string;  
}

let employee: Employee = {  
    species: 'human',  
    name: 'Joe',  
    employeeCode: '123'  
}

Then we get the error message:

Classes can only extend a single class.(1174)

We can also inherit from interfaces, along with classes in an interface like we do in the code below:

class Animal {  
    species: string;  
    constructor(species: string) {  
        this.species = species  
    }  
}

class Person {  
    name: string;  
    constructor(name: string) {  
        this.name = name  
    }  
}

interface Job {  
    title: string;  
}

interface Employee extends Person, Animal, Job {  
    employeeCode: string;  
}

let employee: Employee = {  
    species: 'human',  
    name: 'Joe',  
    employeeCode: '123',  
    title: 'laborer'  
}

As we can see, interfaces are very flexible, we can inherit from different interfaces and classes whatever way we want, unlike classes. Each of our classes is called a mixin.

If we have overlapping properties in our mixins, then they’ll be combined together with declaration merging operations done by TypeScript. For example, if we have 2 classes with the some overlapping members like we have in the code below as long as the overlapping members are identical:

class Animal {  
    species: string;  
    id: number = 0;  
    constructor(species: string) {  
        this.species = species  
    }  
}

class Person {  
    name: string;  
    id: number = 0;  
    constructor(name: string) {  
        this.name = name  
    }  
}

interface Job {  
    title: string;  
}

interface Employee extends Person, Animal, Job {      
    employeeCode: string;  
}

let employee: Employee = {  
    id: 1,  
    species: 'human',  
    name: 'Joe',  
    employeeCode: '123',  
    title: 'laborer'  
}

As we can see, we have an id member in both the Person and Animal interfaces and they’re both of the number type. Overlapping members with the same name and type are allowed for multiple inheritance. However, overlapping members with the same name but different types aren’t allowed. For example, if we have:

class Animal {  
    species: string;  
    id: string = '';  
    constructor(species: string) {  
        this.species = species  
    }  
}

class Person {  
    name: string;  
    id: number = 0;  
    constructor(name: string) {  
        this.name = name  
    }  
}

interface Job {  
    title: string;  
}

interface Employee extends Person, Animal, Job {      
    employeeCode: string;  
}

let employee: Employee = {  
    id: 1,  
    species: 'human',  
    name: 'Joe',  
    employeeCode: '123',  
    title: 'laborer'  
}

Then we get the error message:

Interface 'Employee' cannot simultaneously extend types 'Person' and 'Animal'.Named property 'id' of types 'Person' and 'Animal' are not identical.(2320)

since we id in the Animal class is a string , but id in the Person class is a number.

Copying Implementation Parent Classes to the Derived Class

To copy the mixin methods into a new class. We can write the following function to copy the methods from the parent class into a new class. The function has to loop through the base classes and get the content inside the classes and then define new properties in the class derived from the parent classes and then set them one by one in the new class. This is works because classes are just syntactic sugar for constructor objects that are in JavaScript since the early days.

We can write the following function to achieve what we want:

function applyMixins(derivedConstructor: any, baseConstructors: any[]) {  
    baseConstructors.forEach(baseConstructor => {  
      Object.getOwnPropertyNames(baseConstructor.prototype)  
      .forEach(name => {  
        Object.defineProperty(derivedConstructor.prototype,   
           name,  
           Object.  
             getOwnPropertyDescriptor(  
               baseConstructor.prototype,   
               name  
             )  
           );  
        });  
    });  
}

The applyMixin does exactly what we described above. Now we just have to call it with the child class that inherits the parent classes as the first argument and then an array with the parent classes as the second argument. We call it as in the following code:

applyMixins(Employee, [Person, Animal])

Then given that we have the following classes defined:

class Animal {  
    species: string;  
    id: number = 0;  
    constructor(species: string) {  
        this.species = species  
    }  
    eat(){}  
}

class Person {  
    name: string;  
    id: number = 0;  
    constructor(name: string) {  
        this.name = name  
    }  
    speak(){}  
}

interface Employee extends Person, Animal {      
    employeeCode: string;  
}

class Employee {      
}

We should get that the prototype of Employee having the eat and speak methods. We can call eat directly on a Employee object like the following code:

let employee: Employee = new Employee();  
employee.eat();

We can define our mixins with our class notation to let us do multiple inheritance with TypeScript. Then we define an interface that specifies which mixins we inherit from. Once we did that, we copy over the members that are in the parent classes to the child class’ prototype. Then we have all the properties of the parent classes accessible from the child class.

Categories
JavaScript Rxjs

More Useful Rxjs Creation Operators

Rxjs is a library for doing reactive programming. Creation operators are useful for generating data from various data sources to be subscribed to by Observers.

In this article, we’ll look at more creation operators from Rxjs, like functions that create Observables from event handlers, functions that generate Observables that emit numbers, and functions that let us conditionally subscribe to Observables.

fromEvent

The fromEvent function creates an Observable that emits event objects of the type that we specified as it happens to the event target.

It takes up to 4 arguments. The first argument is the event target. which is required. It can be a DOM event target, Node.js event emitter, jQuery like event target, NodeList, or HTMLCollection to attach event handlers to.

The second argument is the event name that’s being emitted by the event target.

The 3rd argument is an optional argument with some options.

The last argument is an optional result selector function.

Every time the Observable is subscribed to, the event handler function will be registered to the event target on the given event type.

When the event fires, the event object will emitted by the Observable.

The event targets are checked by duck typing. We can safely use fromEvent on the object on the object if it exposes the following methods:

  • DOM event target if it has the addEventLister and removeEventListener methods
  • Node.js event emitter if it has the addListener and removeListener methods
  • jQuery style objects if it has the on and off methods
  • DOM NodeLists or HtmlCollection if they have a list of DOM nodes returned by methods like document.querySelectorAll or the childNodes property of a DOM node.

We can use fromEvent as follows:

import { fromEvent } from "rxjs";
const clicks = fromEvent(window, "click");  
clicks.subscribe(x => console.log(x));

The code above watches for clicks on the document object. We should see MouseEvent objects logged when we click anywhere on the browser tab.

fromEventPattern

This is similar to fromEvent , except that we pass in handler functions for adding event listeners and removing event listeners.

It takes 3 arguments. The first 2 are the add and remove handlers respectively. The remove handler is optional. The last argument is an optional result selector function for manipulating emitted values.

For example, we can use it to detect the clicks on a div with ID app as follows:

import { fromEventPattern } from "rxjs";
const app = document.querySelector("#app");

function addClickHandler(handler) {  
  app.addEventListener("click", handler);  
}

function removeClickHandler(handler) {  
  app.removeEventListener("click", handler);  
}

const clicks = fromEventPattern(addClickHandler, removeClickHandler);  
clicks.subscribe(x => console.log(x));

We should see MouseEvent objects logged when we click anywhere on a div with the ID app .

generate

The generate function creates an Observable with a stream of values by passing in the initial state, a function with the condition for the ending the emitting of values, a function for iterating through the values, result selector function for selecting the emitted results, and a scheduler object for changing the timing for emitting the values.

Only the initial state is required. For example, we can create an Observable that emits the values 0 to 9 by writing:

import { generate } from "rxjs";
const generated = generate(0, x => x < 10, x => x + 1);  
generated.subscribe(  
  value => console.log(value),  
  err => {}  
);

The first argument of the generate function call has the first value to emit or the initial state. The second has the ending condition, which is less than 10. The last argument has the function that indicates how to move on and emit the next item and move towards the ending condition in the second argument.

interval

interval creates an Observable that emits sequential numbers in a specified interval of time.

It takes 2 optional arguments. The first is the number of milliseconds or the time unit determined by the scheduler’s clock. The default is 0.

The second argument is the scheduler to use, which defaults to async .

For example:

import { interval } from "rxjs";
const numbers = interval(1000);

creates an Observable that emits a new value every second.

of

This creates an Observable out of its arguments.

It takes an infinite number of arguments.

For example, we can use it as follows:

import { of } from "rxjs";
of(1, 2, 3).subscribe(  
  val => console.log(val),  
  err => console.log(err),  
  () => console.log("end")  
);

range

We can use range to create an Observable that emits a sequence of numbers within the specified range.

It takes 3 optional arguments, which are the start, which defaults to 0. The number of integers to generate, which defaults to undefined and the scheduler to use, which defaults to undefined .

For example, we can use it to create an Observable which emits number 1 to 20 as follows:

import { range } from "rxjs";
const numbers = range(1, 20);  
numbers.subscribe(x => console.log(x));

throwError

Creates an Observable that only emits an error notification.

It takes up to 2 arguments. The first is the error to emit. The second is an optional scheduler argument to let us choose the scheduler. It defaults to undefined .

We can use it as follows:

import { throwError } from "rxjs";
const numbers = throwError("error");  
numbers.subscribe(() => {}, err => console.log(err));

We subscribed to the error notification in the second argument.

timer

timer creates an Observable that starts emitting values after a specified time and emit ever-increasing number after a specified interval thereafter.

The first argument is the time that the Observable starts emitting, which defaults to 0. The number is in milliseconds.

The second argument is the period of emitting values which defaults to undefined . The number is in milliseconds.

The last argument is the scheduler to use, which defaults to undefined .

For example, we can create an Observable to emit values after 2 seconds, then every second thereafter by writing:

import { timer } from "rxjs";
const numbers = timer(2000, 1000);  
numbers.subscribe(x => console.log(x));

iif

Let us create an Observable that decides which Observable will be subscribed to at subscribe time.

It takes up to 3 arguments. The first is the condition for which Observable to be chosen. The 2nd and 3rd arguments are the Observable that are chosen when the condition is true and false respectively.

For example, we can use it as follows:

import { iif, of } from "rxjs";
let wantFoo;  
const fooBar = iif(() => wantFoo, of("foo"), of("bar"));
wantFoo = true;  
fooBar.subscribe(val => console.log(val));
wantFoo = false;
fooBar.subscribe(val => console.log(val));

In the code above, if wantFoo is true , when of('foo') is subscribed. Otherwise, of('bar') is subscribed.

We can create Observables that handle DOM or Node.js events with the fromEvent creation operator.

of operator lets us create Observables from any list of objects.

throw only throws an error and does nothing else.

generate , interval , and range let us create Observables that emit number ranges.

timer lets us create timed Observables and iif lets us create conditional Observables.

Categories
Flow JavaScript

JavaScript Type Checking with Flow — Type Casting

Flow is a type checker made by Facebook for checking JavaScript data types. It has many built-in data types we can use to annotate the types of variables and function parameters.

In this article, we’ll look at how to cast values from one type to another.

Syntax

To value to a given type, we can use the following syntax:

(value: Type)

It can be used in variables, objects, or arrays. In variable assignments, it can be used as follows:

let foo = (value: Type);

With objects, we can cast the values of properties by writing:

let obj = { prop: (value: Type) };

Also, we can cast array entries by writing:

let arr = ([(value: Type), (value: Type)]: Array<Type>);

We can also cast expressions into a type. For example, we can write:

(1 + 1: number);

to cast numbers.

Type Assertions

We can only cast types when they make sense. For example, if we have:

let x = 1;

Then we can write:

(x: 1);

or:

(x: number);

since x is a number with value 1 . Casting to a type that isn’t the type of the value will fail. So casting the variable x to s string by writing:

(x: string)

will give an error since x is a number.

Type Casting

We can cast a value to a broader type than the original type of a variable. For example, if we have a number variable:

let x = 1;

Then we can either cast x to the 1 literal type or the number type as follows:

(x: 1);   
(x: number);

When we assign a variable to a new variable, we can also cast it to the same broad type:

let y = (x: number);

But casting it to a narrower type will fail, so if we write:

(y: 1);

we would get an error since y is expected to be a number with an indeterminate value.

Type Casting Through any

We can cast anything to any , which then let us cast it to anything else.

For example, if we want to cast a number into a string, we can see that we can’t do it directly from the examples above since we can’t cast anything to an unrelated type.

However, we can bypass that by first casting to any , then we can cast it to any type we want.

So we can write:

let x = 1;  
(x: 1);   
(x: number);  
let y = ((x: any): string);  
(y: string);

This isn’t recommended, but it may be convenient for some situations where we need to cast something from one type to an unrelated type.

Type Assertions

We can set the type of an object by casting the type of the object when we operate on it in a function. For example, if we have a function that clones an object, we can write:

function foo(obj) {  
  const cloneObj = {...(obj: { [key: string]: mixed })};  
  return cloneObj;  
}

Then when we call it, Flow is smart enough to determine the type of the properties:

let cloneObj = foo({  
  a: 1,  
  b: true,  
  c: 'three'  
})  
(cloneObj.a: 1);  
(cloneObj.b: true);  
(cloneObj.c: 'three');

This is more useful than putting the type in the parameter:

function foo(obj: { [key: string]: mixed }) {  
  const cloneObj = {...obj};  
  return cloneObj;  
}

Since Flow won’t know the structure of cloneObj this way.

We can also use generics with the $Shape keyword to assert the type of the obj parameter as follows:

function foo<T: { [key: string]: mixed }>(obj: T): $Shape<T> {  
  const cloneObj = {...obj};  
  return cloneObj;    
}

The code<T: { [key: string]: mixed }> will let Flow know that the obj parameter accepts an object.

With Flow, we can cast types to relevant types given the object’s value by using the : and the type identifier after it.

Also, we can cast something to an unrelated type by first casting it to any .

Finally, to make Flow be aware that a variable or parameter is a dynamic object, we can use the <T: { [key: string]: mixed }> and (obj: T) signature to make sure that the parameter is a dynamic object.

Then we set $Shape<T> as the return type to enforce that type of the object returned by the function is a dynamic object.