Sunday, September 6, 2015

Don't marshal when you can cast

var loginDto = <Dto.LoginDto> {};
extend(loginDto, req.body); // marshal the req.body dictionary to strongly-typed object
console.log(loginDto.username);

The code above is inefficient, extending is an expensive process. The above could be simply rewritten as:

var loginDto = <Dto.LoginDto> req.body;
console.log(loginDto.username);


Imagine the nodejs code above if done with statically-typed framework such as ASP.NET MVC, the values from Request.Form (same as nodejs's req.body) need to be marshalled to DTO object every time a request is made, a bit inefficient.


You can make something efficient and be efficient (autocomplete support) when coding with TypeScript.

Thin Angular Controller

An example of caller of Authentication API:

App.Login.Controller.ts:
module App.Login {

    export class Controller {


        username:string;
        password:string;

        // Dependency-injected sweet alert, so it can be easily mocked
        constructor(public authApi:InhouseLib.AuthApi, public $http:ng.IHttpService, public $state:any,
                    public TheSweetAlert:SweetAlert.SweetAlertStatic,
                    public appWide:SharedState.AppWide) {
        }


        login():void {


            this.authApi.verify(this.username, this.password)
                .then(success => {
                    console.log(success.data.isValidUser);
                    this.appWide.isUploadVisible = true;
                    this.$http.defaults.headers["common"]["Authorization"] = success.data.theBasicAuthHeaderToUse;
                    this.$state.go('root.app.home');
                }, error => {
                    console.log(error.data.isValidUser);                    
                    this.appWide.isUploadVisible = false;
                    delete this.$http.defaults.headers["common"]["Authorization"];
                    this.TheSweetAlert("Oops...", "Not authorized", "error");                
                });

            }//login
            
        }//Controller
}


An example of Authentication API, AuthApi.ts:

///<reference path="../../typings/angularjs/angular.d.ts"/>
///<reference path="../../shared/dto/LoginDto.ts"/>
///<reference path="../../shared/dto/LoginResponseDto.ts"/>

module InhouseLib {

    export class AuthApi {

        constructor(public $http : ng.IHttpService) {

        }

        verify(username: string, password: string) : ng.IHttpPromise<Dto.LoginResponseDto> {

            var u = new Dto.LoginDto();
            u.username = username;
            u.password = password;


            return this.$http.post<Dto.LoginResponseDto>('/api/member/verify', u);

        }

    }

}


// Angular initialization code:
// mod.service('AuthApi', ['$http', InhouseLib.AuthApi]);



The problem with the caller(Login Controller) of the Authentication API is it does things that should not be of concern to it. One concern that should not be in the controller is the assigning and invalidating of Basic Authentication to angular's $http pipeline.


To improve that. The assigning and invalidating of Basic Authentication information to angular's $http pipeline should be done on AuthApi.ts. Following is an example. First, we must remove the code related to Basic Authentication away from the concerns of Login controller.

login():void {

    this.authApi.verify(this.username, this.password)
        .then(success => {
             console.log(success.isValidUser);
             this.appWide.isUploadVisible = true;
             this.$state.go('root.app.home');
        }, error => {
             console.log(error.isValidUser);                
             this.appWide.isUploadVisible = false;
             this.TheSweetAlert("Oops...", "Not authorized", "error");
        });


}


Then move that concern to AuthApi.ts:

verify(username: string, password: string) : ng.IPromise<Dto.LoginResponseDto> {

    var deferred = this.$q.defer();

    var u = new Dto.LoginDto();
    u.username = username;
    u.password = password;


    this.$http.post<Dto.LoginResponseDto>('/api/member/verify', u)
    .then(success => {

        this.$http.defaults.headers["common"]["Authorization"] = success.data.theBasicAuthHeaderToUse;

        // This goes to then's success callback parameter
        deferred.resolve(success.data);

    }, error => {

        delete this.$http.defaults.headers["common"]["Authorization"];

        // this goes to then's error callback parameter
        deferred.reject(error.data);

    });

    return deferred.promise;

}


If the caller code (Login Controller) has a need receive http status code returned by the server, return a promise of IHttpPromiseCallbackArg with an argument of the other information(Dto.LoginResponseDto) instead.

verify(username: string, password: string) :     
    ng.IPromise<ng.IHttpPromiseCallbackArg<Dto.LoginResponseDto>> 
{

    var deferred = this.$q.defer();

    var u = new Dto.LoginDto();
    u.username = username;
    u.password = password;


    this.$http.post<Dto.LoginResponseDto>('/api/member/verify', u)
        .then(success => {
            this.$http.defaults.headers["common"]["Authorization"] = success.data.theBasicAuthHeaderToUse;

            // This goes to then's success callback parameter
            deferred.resolve(success);

        }, error => {

            delete this.$http.defaults.headers["common"]["Authorization"];

            // this goes to then's error callback parameter
            deferred.reject(error);

        });

    return deferred.promise;

}


To access the other information(Dto.LoginResponseDto), access it via success.data and error.data. For the http status code, access it from success or error parameter, e.g., error.status.

login():void {


     this.authApi.verify(this.username, this.password)
         .then(success => {
             console.log(success.data.isValidUser);
             this.appWide.isUploadVisible = true;
             this.$state.go('root.app.home');
         }, error => {
             console.log(error.data.isValidUser);                
             this.appWide.isUploadVisible = false;
             this.TheSweetAlert(error.status.toString(), "Not authorized", "error");
         });

}

WebStorm Need Tight TypeScript Integration

Seriously.


Whereas Visual Studio Code coding assistance almost works flawlessly. For example Visual Studio Code shows on the tooltip the type of the parameter when hovering over the parameter:



..WebStorm has problem knowing the type:



Wishing there is TypeScriptStorm.

Thursday, September 3, 2015

Fast text search in PostgreSQL

This works in Postgres:


select * from location where location_id = any(array[1,6,8])

However, if you tried to match it against an array on another query, it won't work, even though the another query returns exactly one row only.

select * from location where location_id = any(select location_ids from province p where p.province_name = 'Metro Manila' limit 1)

Output:
ERROR:  operator does not exist: integer = integer[]
LINE 1: select * from location where location_id = any
                                                 ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.


To correct it, unnest the array:

select * from location where location_id = any(select unnest(location_ids) from province p where p.province_name = 'Metro Manila')

Might as well use IN:

select * from location where location_id in (select unnest(location_ids) from province p where p.province_name = 'Metro Manila')


There's a drawback on the queries above, it uses equal operator. In Postgres, indexers are bound to operator, and GIN, the indexing technology for indexing array, doesn’t support equal operator. See the detail here: http://stackoverflow.com/questions/4058731/can-postgresql-index-array-columns/29245753#29245753


So to optimize the query, use either of the following:


-- This query works same as the query at the bottom. The query at the bottom is more readable though.
-- The advantage of this query is if the province matches many rows, it would still work, say the province_name uses ILIKE operator.

select  *
from    location l
where   exists
        (
            select  p.location_ids
            from    province p
            where   p.province_name = 'Metro Manila'
                    and array[l.location_id] && p.location_ids
        );

The query uses overlap operator, &&. See the use of supported operators on arrays: http://www.postgresql.org/docs/9.1/static/functions-array.html

-- If province returns exactly one row, this is more readable than above
select   *
from     location l
where    array[l.location_id] && ( select location_ids p from province p where p.province_name = 'Metro Manila' );


Live code: http://sqlfiddle.com/#!15/6ac38/5


Happy Coding!

Monday, August 31, 2015

module.exports has lesser mental model when exporting a module

On my post about sharing TypeScript classes between client-side and server-side. I used exports rather than module.exports. However, as I later learned, it's better to use module.exports as it's the one being directly returned by the require function, module.exports is the real deal. If we uses module.exports rather than exports, we don't need to do this anymore:

class ExternalizedDomain {
    static Person : typeof Domain.Person = require('./shared/Domain/Person').DomainPerson;
    static Country : typeof Domain.Country = require('./shared/Domain/Country').DomainCountry;
}

And also the drawback of the idiom above is it is not compatible with proxyquire:

it("applies interest using stubbed calculator", () => {

 var calculatorStub : any = {};

 var financialCalculator : typeof Domain.FinancialCalculator = 
                  proxyquire('../shared/Domain/FinancialCalculator', { './Calculator': calculatorStub });

 var interestApplied = financialCalculator.applyInterest(200, 0.2);
 expect(interestApplied).toEqual(240);


 calculatorStub.multiply = (a,b) => 6;
 var interestAppliedFromStubbedCalculator = financialCalculator.applyInterest(100, 0.2);
 expect(interestAppliedFromStubbedCalculator).toEqual(6);
});


There's no way in proxyquire to specificy an specific property (e.g., .DomainPerson) of the object assigned to module.exports. To make the external module compatible with proxyquire, do as the following:


class ExternalizedDomain {
    static Person : typeof Domain.Person = require('./shared/Domain/Person');
    static Country : typeof Domain.Country = require('./shared/Domain/Country');
}


Then change the Person.ts and Country.ts to export things on module.exports:

Person.ts:
module Domain {
    export class Country {
        name : string;
    }
}

// Hack for converting internal module to external module
declare var exports: any;
if (typeof exports != 'undefined') {
    module.exports = Domain.Country;
}

Country.ts:
module Domain {
    export class Country {
        name : string;
    }
}


// Hack for converting internal module to external module
declare var exports: any;
if (typeof exports != 'undefined') {
    module.exports = Domain.Country;
}



Definition of Calculator.ts:
///<reference path="../../typings/node/node.d.ts"/>

var isNode = typeof exports !== 'undefined' && this.exports !== exports;


module Domain.Calculator {

    export function multiply(multiplicand: number, multiplier: number): number {

        return multiplicand * multiplier;
    }

    export function divide(dividend: number, divisor: number): number {

        return null;
    }
}



if (isNode) {
    module.exports = Domain.Calculator;
}


Definition of FinancialCalculator.ts:
/// <reference path="../../typings/node/node.d.ts"/>

///<reference path="Calculator.ts"/>


var isNode = typeof exports !== 'undefined' && this.exports !== exports;

var calculator : typeof Domain.Calculator = isNode ? require('./Calculator') : Domain.Calculator;


module Domain.FinancialCalculator {

    export function applyInterest(amount: number, percentInterest: number): number {

        return calculator.multiply(amount, 1 + percentInterest);
    }

}


if (isNode) {
    module.exports = Domain.FinancialCalculator;
}


On next post, I'll show the difference between TypeScript's classes and module when it comes to proxyquire.


Happy Coding!

TypeScript definition ambiguity woes. Which require function should go? RequireJS' or NodeJS'?

If you encountered this error:

Error:(49, 13) TS2403: Subsequent variable declarations must have the same type.  Variable 'require' must be of type 'Require', but here has type 'NodeRequire'.


It's better to remove RequireJS's require, as you can access the require functionality of RequireJS's through its syntax sugar a.k.a. simplified CommonJS wrapping.

RequireJS syntax sugar for require is done like this:
define(require => {
    var calculator : typeof SharedModel.Calculator = require('Calculator');
    var financialCalculator : typeof SharedModel.FinancialCalculator = require('FinancialCalculator');
});



On RequireJS's TypeScript definition, require.d.ts, comment or remove its require declaration:
// Ambient declarations for 'require' and 'define'
declare var requirejs: Require;
// declare var require: Require;
declare var define: RequireDefine;

Friday, August 28, 2015

Custom Basic Authentication and Authorization for Node Express

You have an existing REST API, and you wanted to protect it:

app.get('/api/something', (req: express.Request, res: express.Response, next: Function) => {
    res.json({message: 'Mensaje', description: 'Yeah!'});
});

The neatest way to protect your REST API is to make a function that returns a callback function for Basic Authentication so it can be chained on node express parameters, and the implementation detail can be hidden to user too. To wit, here's how it shall look like usage-wise:

import canBe = require('./CanBe');

app.get('/api/something', canBe.accessedBy(['guest']),  (req: express.Request, res: express.Response, next: Function) => {
    res.json({message: 'Mensaje', description: 'Yeah!'});
});


Most of the explanation of the use of bind shows its usefulness on the this object. The following code demonstrates another good use of bind function. What the called function accessedBy does is it returns the callback with a binded parameter (roles array parameter in the following example) by binding a leading parameter on the accessedByBind function; so when the callback function accessedByBind is called by node express, the roles parameter is passed to it too.


CanBe.ts:

/// <reference path="./typings/express/express.d.ts"/>

import express = require('express');

var basicAuth = require('basic-auth');


export function accessedBy(roles: string[]) : express.RequestHandler {
    return accessedByBind.bind(undefined, roles);
}


function accessedByBind(roles: string[], req: express.Request, res: express.Response, next: Function): express.RequestHandler {

    function unauthorized(res) : express.RequestHandler {
        res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return res.send(401);
    }


    function isUserInRole(userName:string): boolean {

        var userRole: string;

        if (userName == "foo") {
            userRole = 'guest';
        }
        else {
            userRole = '';
        }

        var isAllowed = false;

        for(var i = 0; i < roles.length; ++i) {
            if (roles[i] == userRole) {
                isAllowed = true;
                break;
            }
        }

        console.log("Is allowed " + isAllowed)

        return isAllowed;

    }


    // === accessedByBind starts here ===


    var user = basicAuth(req);

    if (!user || !user.name || !user.pass) {
        return unauthorized(res);
    }


    if (user.name === 'foo' && user.pass === 'bar') {

        var isAllowed = isUserInRole(user.name);

        console.log("Is allowed " + isAllowed);

        if (isAllowed)
            return next();
        else
            return unauthorized(res);

    } else {
        return unauthorized(res);
    }

}


Here's .bind in a nutshell:

Live Code http://jsfiddle.net/b33gukgv/

function list(a,b,c) { 
    console.log('a: ' + a);
    console.log('b: ' + b);
    console.log('c: ' + c);    
    console.log(arguments);
}

//  Create a function with a preset leading argument
var always = list.bind(undefined, "Omni", "Present");

list("of", "good", "things");

always("something", "there", "to");

always("remind", "me");


Output: