Sitemap

Archive #1

10 min readMay 8, 2019

--

Learnings:

Typescript: developed by Microsoft an open source JavaScript language.

Used for WIN.Js and Angular.Js. help for lock the variables when in traditional JavaScript debug is difficult.

Used with GRUNT (task runner / complier) and gulp (automatically complier).

Works well for large projects and good for long term maintenance.

Typescript is used primarily with Node JS backend language.

Typescript files cannot be read by browsers so we need compliers.

Install typescript complier using node JS by npm (node package manager) => $ npm install — g typescript

Types are typical component of typescript.

Refer: http://www.typescriptlang.org/docs/handbook/basic-types.html

Vector: An array containing only elements of specified types

Enum is a type used to store built in variables accessible like keys with reference

Void returns nothing

Interfaces are blueprint of an object. To get the correct error position in the code while using objects.

Classes are supercharged blueprint of object. However, it is constructor with reusable components.
Refer: http://www.typescriptlang.org/docs/handbook/classes.html

Inheritance is way for objects or classes to gain access to the properties of classes that are possessed by other objects.

Modules are powerful way to share code with between files by using modules effectively you can keep your file size small and your dependencies clear.

In order to combine the two TS files and make it as single js file. In the cmd prompt window $ tsc fileame1.ts filename2.ts –out filename1.js (Note: here filename2 will be the one having module)

Integration of Typescript with Grunt:

GITHUB page you can view the number of issues and stars that library has. From that determine whether to use that or not.

GRUNT task runner: Download the TS plugin from grunt page,

In the terminal window,

$ npm init and give enter to all the default settings then $ npm install typescript — save

Now add grunt command line interface $ npm install grunt — save and $ npm install grunt-cli — save

And $ npm install grunt-ts — save

Create a file named as gruntfile.js

And use $ grunt to run the file

<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

let

var Variables in JavaScript are function scoped. This is different from many other languages (C# / Java etc.) where the variables are block scoped. If you bring a block scoped mindset to JavaScript, you would expect the following to print 123, instead it will print 456:

var foo = 123;

if (true) {

var foo = 456;

}

console.log(foo); // 456

This is because {does not create a new variable scope. The variable foo is the same inside the if block as it is outside the if block. This is a common source of errors in JavaScript programming. This is why Typescript (and ES6) introduces the let keyword to allow you to define variables with true block scope. That is if you use let instead of var you get a true unique element disconnected from what you might have defined outside the scope. The same example is demonstrated with let:

let foo = 123;

if (true) {

let foo = 456;

}

console.log(foo); // 123

Another place where let would save you from errors is loops.

var index = 0;

var array = [1, 2, 3];

for (let index = 0; index < array.length; index++) {

console.log(array[index]);

}

console.log(index); // 0

In all sincerity we find it better to use let whenever possible as it leads to lesser surprises for new and existing multi-lingual developers.

Reference: https://basarat.gitbooks.io/typescript/docs/let.html#

06/13/2018:

Type Inference: var n = 1;

Type Annotations: var n : Number = 1; explicitly mentioning a data type for a variable.

NaN — Not a Number

String Array:

Like usual JavaScript, in typescript also array index starts @ 0

Adding Reference of type definition files in Typescript:

By adding this you can use jQuery comments inside.

Use this link : http://definitelytyped.org/ — Repository by Boris Yanko — took a respected file from this site and add it to your project directory.

/// <reference path=”jquery/jquery.d.ts” />

Typescript function with required and optional input parameters:

Refer code plox.

Typescript function with Arrow functions:

Refer code plox.

OBJECTS:

Objects in typescript is comes in many forms classes, functions, interfaces, object literals and modules.

Using class:

Refer code; Folder Name: create a class

Implementation of class inheritance in typescript:

Implementing interfaces for multiple classes:

Refer code; Super used to call the base class also usage of data object helps to get the base class objects.

Modules:

Making the internal modules accessible for external usage:

Creating and accessing nested module:

ANGULAR JS 2 & TYPESCRIPT:

In Visual Studio 13 tools => Nuget Package manager; get the following library packages,

· Angular JS

· Angular JS Typescript definitely typed

Interface hasLocation { location : string; }

Function showLocation(obj: hasLocation){ alert(obj.hasLocation); }

Working with Node JS cmd prompt:

C: or D: = switch over between computer drives.

cd desktop/foldername = to get inside the folder.

node app.js = will launch the JS file.

Refer below link for all types of commands.

Reference link: https://www.thomas-krenn.com/en/wiki/Cmd_commands_under_Windows

Node JS:

· When you are working with Node JS everything is reference. For example, in below code, you are not making a copy of the first object “arjun” you are just getting reference to the object Arjun.

var arjun = {    favFood: "Laddu",    favMovie: "Inception"};var person = arjun;person.favFood = "Burger";console.log(arjun.favFood);

Two and three equal signs:

Two equal signs: used for whenever you want to compare values.

Three equal signs: used for whenever you want to compare types and values.

Keyword THIS refers to whatever thing/object calling it.

Prototyping:

Whenever you are importing module never include the dot JS (filename.JS)

Object factory is basically an object used to create another object — used to avoid sharing module.

Core Module: While require the core module don’t use the path.
Console.log(__dirname);

Console.log(__filename);

Creating a Basic Server:

var http = require("http");http.createServer(onRequest).listen(8888);console.log("server is running");

Highlighted term onRequest used to, call back or what code you want to run whenever user wants to connect to your server. Which will send them back with a web page or web file or info from our database.

Listen: server has to be listening for request with a port number (ex: 8888).

Status code in response write head: 200 — everything ok , 404 — error

Connect module:

Open terminal in IDE, npm install connect

Express framework in Node JS:

Easy and flexible framework, integrates with many templating engines and contains middleware framework.

HTML methods/verbs: GET, POST, PUT, DELETE.

There are various view-engines (basically HTML views) available for Noda JS.

Ex: Jade template and EJS (Embed JavaScript) where ejs is most commonly used by html users.

EJS:

<%= ‘your variable name comes here’ %> — — with equals variable name comes. Variable which is based from js file.

<% ‘plain JavaScript code’ %> — — without equal sign plain old JavaScript code comes.

Ex:

Get Nagarjun deepak’s stories in your inbox

Join Medium for free to get updates from this writer.

// print five times
<% for(var i = 0; i < 5; i++ ) { %>
<p> Hello </p>
<% } %>

JSON:

JSON is JavaScript Object Notation which is data storing and interchange. Just a combination of objects.

MongoDB:

It’s a no-sql database most commonly it is document database where data or records stored in document formats.

Create data folder and inside that folder named db where mongo going to save all the data.

Schema is collection of records based on this. Object contains the various properties of the records.

Mocha Testing: testing framework to perform tests within our app, test our connection with Database.

Note: inside package.json file change the test equals to ‘mocha’. Then proceed to testing the db.

Assert will result in Boolean.

Es6 default promise library:

Robo Mongo: gives the visual representation of our data in MongoDB.

https://robomongo.org

note: mongoose pluralize our model/collection because it assumes we are going to have more than one records.

Object ID is unique ID created by MongoDB to each record.

Find the various update operators and usage in the below link: https://docs.mongodb.com/manual/reference/operator/update/index.html#id1

Relational Database:

Books table and Authors table, in MongoDB collection format:

Author’s ID

- Name

- Age

- Books [Array]

o Book ID

§ Title

§ Pages

Object Format example:

{

Name: ‘Patrick’,

Age: 30,

Books: [

{title: ‘the name of the wind’, pages: 300},

{title: ‘wise man fear’, pages: 200},

]

}

Nesting with the sub documents:

Task Runners: Grunt or Gulp JS

Grunt JS:

It is a task runner. Which helps us to;

Performs repetitive tasks, prefix the CSS rules, compiling SASS files into CSS, minify the CSS and JS files also concatenating the files.

Angular 2 and above:

Frontend/Client side JavaScript framework which runs on web server. Powerful single page applications.

MEAN Stack: MongoDB which is no sql database, Express is a backend web framework and Angular and Node are JavaScript Runtimes.

Components: Sections of UI can be broken up into encapsulated components. Basic building block of UI. An Angular application is a tree of angular components.

Services: Classes that send data and functionality across the components. Ideal place for AJAX call and keep components lean.

In the new app folder created “e2e” names folder is for end to end testing.

App.module.ts = it’s a meeting place for everything in your app the services, components and modules.

Everything added into the NG module and components goes into the declarations, modules like http modules and forms modules goes into imports and services goes into the providers also bootstrap will part of main root component. So literally when you create anything you should bring it into this file.

App.component.specs.ts = it is meant for testing

App.component.ts = meant for Components

Creating a component:

Command line in node command prompt:

Ng g component components (which is folder name inside the app) / user (name of the new component you are going to create)

Fake Online REST API for Testing and Prototyping — https://jsonplaceholder.typicode.com/

NOTE: After including services we have to manually add our service into app.module file and it goes into providers and title head.

Also include the service into component file

Whenever you use service you have to inject it as dependency parameter which goes into constructor in the component.ts

Angular -2:

npm install –g angular-cli => angular cli in globally.

npm install –g typescript => Typescript in globally.

ng new name of the project => creates all source files for us.

ng serve => which will give the local server and port number.

https://material.angular.io => Materials for Angular

view encapsulation introduced by angular JS where it eliminates shadow DOM that an HTML element has its separate DOM behind the scenes.

<ng-content> used to render the component multiple times.

Data-binding methods:

1. String Interpolation: {{expression resolving to a string}}

2. Property Binding: it means sending data to the properties in your html code. There 3 kinds of property binding available.

<button [disabled]=” expression resolving to required value type”>

3. Event Binding: it means listen to events emitted from the elements from something. Also you can setup a method to execute.

<button (click)=” expression handling the event”>

4. Two-way Data Binding: which made angular popular. Which make bi-directional

<input [(ng-model)] =” bound model (e.g. object)”>

Custom bindings for Property and Event bindings:

Property bindings: @Input() propertyName: string;

Event bindings: @Output() eventName = new EventEmitter();

Also please note that input, output and event emitter is within the angular core module so, add that to your import inside angular core line in your code.

Directives: these are instructions which tell angular to do something. There are 2 types of directives which are

1. Attribute: interacts with the elements it’s on to change its properties — ex: ngClass.

2. Structural: changes the structure of the HTML code — ex: *ngIf.

Pipes “|”: used to change the output data. For example:

<span [ngStyle]=”{background: ninja.belt}”>{{ninja.belt | uppercase | slice: 1}} Belt</span>

It is an example of chaining a pipe events where uppercase first and slicing the output text ninja belt. you can also make custom pipes.

Services: ng g s file name,

Firebase and Fire store with Angular 2:

RXJS: Reactive Extension JavaScript.

Ng build –prod => move to PROD.

MEAN STACK:

JWT — JSON Web Tokens — token generations and authentications

CORS — Cross Origin Resource Sharing — to make request from frontend to backend.

ODM — Object Document Mapper — MongoDB

Npm install –g nodemon => which is used to restart our local host server.

Use POSTMAN — a google extension used to verify get and post request in the browser localhost itself. Where you can create the json file and verify the results.

[sudo] npm uninstall -g @angular/cli

npm cache clean

[sudo] npm install -g @angular/cli

Create component by, ng g c componentname

Flash message service issues: https://stackoverflow.com/questions/48139567/this-flashmessage-show-is-not-a-function

Note: Local storage only can store the values in string not as an object so always use stringify function in JSON.

Guard: ng generate guard [name]

CSRF attack on Cookie storage: cross-site request forgery

_____________________________________________________________________________

NODE JS & PASSPORT JS LOGIN System:

A step by step procedure to create a login authentication using NODE JS.

#1 create package.json file using node JS cli by NPM INIT by doing this give entry point as app.js, and Add below dependencies to your package file and run NPM INSTALL.

“dependencies”: {
“bcryptjs”: “*”,
“body-parser”: “*”,
“connect-flash”: “*”,
“cookie-parser”: “*”,
“express”: “*”,
“express-messages”: “*”,
“express-handlebars”: “*”,
“express-session”: “*”,
“express-validator”: “*”,
“mongodb”: “*”,
“mongoose”: “*”,
“passport”: “*”,
“passport-local”: “*”,
“passport-http”: “*”
},

#2 create app.js file in root level. And add the dependencies to the header of the JS file, also set routes

#3 set view engine and routes as below

const routes = require(‘./routes/index’);
const users = require(‘./routes/users’);

// Init the app
const app = express();

// View Engine
app.set(‘views’, path.join(__dirname, ‘views’)); => setting views folder as view model.
app.engine(‘handleBars’, exphbs({defaultLayout:’layout’})); => using handlebar express layout as layout format for our app.
app.set(‘view engine’, ‘handlebars’); => similarly letting handle bar as view engine.

#3 Adding Middleware (Body parser, Cookie Parser) which are just configuration files.

Error Formatter for middleware Express-Validator: https://github.com/VojtaStavik/GetBack2Work-Node/tree/master/node_modules/express-validator#middleware-options

#4

REACT JS

npm i –g create-react-app => it will create the modules inside App data in system’s C folder and now run.

ZERO-CONFIG Setup:

At first, create-react-app react-app => which will give us the development server (local host for hosting locally), web pack used for bundling the files, babel for compiling the JavaScript code.

To customize to our production environment run npm run eject.

NOTES:

npm start => starts the development server.

npm run build => bundles the app into static files for production.

npm test => starts test runner.

npm run eject => removes this tool and copies build dependencies, configuration files and scripts into app directory. If you do this, you can’t go back to zero configuration setup.

Start the app by typing below two commands:

cd react-app

npm start

--

--

Nagarjun deepak
Nagarjun deepak

Written by Nagarjun deepak

Web Development | Cinema | Comics