Monday, June 29, 2020

how to test JWT token with CURL in command line?

after we implement api to load the JWT with basic authentication via login form that requried user to provide email and password in order to access the api with JWT authorization.

it is very to easy to test the logic by executing the following command line in CMD/cmder

curl -d "email=test@email.com&password=test1234" http://localhost:3000/api/login

the output is below indicating that the JWT token is generated with provided login information.

λ curl -d "email=test@email.com&password=test1234" http://localhost:3000/api/login
{"success":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiNW
VmYTA5ZWEzMGE2ZTAwYzIwMmJhNjhiIiwiZXhwIjoxNTkzNTQ0NDM4NzE2L
CJpYXQiOjE1OTM0NTgwMzh9.IHTlnRuOg_AlppmraGMY8xibrGNAoGGSMA3yGx_2DmI"}

how to use environment variable in Node.js and Express Server development?

it is very convenient to use environment variable during the web development with express server and Node.js

here is the steps to configure the environment variable in the  project.

1. add a .env file to the project folder.

2. install the dotenv package
    npm i dotenv -S

3. add dotnet library to the file that will load the environment variable. in my case it is from a controller

dotenv = require('dotenv');
dotenv.config();

4. add required variables to the .env file

#test token
TOKEN=recipeT0k3n

# API
API_TOKEN=recipeAPIT0k3n

5. load the environment variable, it must be the same file in the step 3

const token=process.env.TOKEN || "recipeT0k3n",

or you can define it as global variable in the index.js or main.js with the following snippet of code

dotenv = require('dotenv');
dotenv.config();
export const token=process.env.TOKEN || "recipeT0k3n",


Sunday, June 21, 2020

Handy npm commands

1. use npm init to generate a package.json file for the application

2. use npm install --save flag to mark the package as an application dependency.

for example when i ran npm install express --save, the process will automatically add express to the
dependencies section.

use npm install --save-dev to install the library for the development of an application only

{
  "name""first_express_project",
  "version""1.0.0",
  "description""first web project build with express",
  "main""main.js",
  "scripts": {
    "test""echo \"Error: no test specified\" && exit 1"
  },
  "author""Dan Deng",
  "license""ISC",
  "dependencies": {
    "express""^4.17.1"
  }
}

3.  run npm docs library name to access the library documentation.

for example npm docs express will launch the default web browser to http://expressjs.com.

4. npm i nodemon -g to install the node monitor package to force restart the application. after any change to the project.
use the following configuration to setup nodemon to run the application

 "scripts": {
    "start":"nodemon main.js",
    "test""echo \"Error: no test specified\" && exit 1"
  },

then run npm start to launch the application.

λ npm start

> first_express_project@1.0.0 start C:\code\Node\first_express_project
> nodemon main.js

[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node main.js`
The express server has started and is listening on port number : 3000








Tuesday, June 16, 2020

how to implement a simple typesafe assertion library in Typescript?

we can assert typesafe to ensure that parameters with specific type in typescript.

here i will demostrate a simple function to ensure that input parameters are the same type

type is={
    <T>(aTb:T):boolean
}

let isSame:is=<T>(
    first:T,
    second:T
)=>{
    return first==second;
}

function print(b:boolean){
    console.log(b);
}

print(isSame("string","anotherString"));
print(isSame(true,false));
print(isSame(4242));
print(isSame(10'foo'));

src/index.ts:73:18 - error TS2345: Argument of type '"foo"' is not assignable to parameter of type 'number'.

73 print(isSame(10, 'foo'));
                    ~~~~~


Found 1 error.




we can easily get the catch the error in compile time. that is the magic of typesafe in typescript, the compiler enforce the type-safe check in the compile time. 



Monday, June 15, 2020

Types in TypeScript

1. Object vs object

Object represents alll types in typescript include all primitive type and non-primitive type.

primitivie type has the following types:
  • boolean
  • number
  • biginit
  • string
  • symbol
  • null :means absence of a value
  • undefined : variable that has not been defined.
in contrast object represent non-primitive type.

we can define a object with property, optional property and index signature.

let exampleO :{
      p1: string,
      p2?: number //optional property
     [p3: string]: string //index singatue [key:T] : U to indicate all keys of T(T should be number and string only) must have values of type U
}

Typescript use index signature to add more keys to the object.

2. Array vs Tuples

both types use square bracket []

let a: string[] //declare a string array

let b: [string] //a tuple

let c: [string, string, number] // a tuple with three elements

3. use const enum to prevent the unsafe access

enum Color {
     Red,
     White,
    Green
}
we should rewrite it with const enum for a safer subset of enum behavior, since CONST ENUMS doesn't let you do reverse looks up. However number value enums still will allow all numbers assign to enums, we can avoid this issue with string-value enums

const enum Color {
     Red,
     White,
    Green
}