Search This Blog

2019/11/22

use strict in javascript

"use strict" is introduced in ES5.By Default javascript ignore certain mistakes of coding.enabling strict mode help us prevent errors at time of coding only that cannot be caught otherwise.

one can write "use strict" at beginning of javascript file or at start of function definition as below

    function Add(a,b)
    {
     "use strict"
     return a+b;
    }


common mistakes that get caught with strict mode

1) polluting global namespace
    "use strict"
    function myFunc()
    {
        x=10;//variable x get defined in global namespace
    }

    myFunc()
    console.log(x);

    in function myFunc variable x is assigned value before defining it.so x get defined in global namespace so console.log after myFunc() print 10.

2) Unexpected eval or arguments in strict mode

    "use strict"
    var eval = 3.14;
    console.log(eval);

    var arguments = 3.14;
    console.log(arguments);

3) Delete of an unqualified identifier in strict mode

    "use strict";
    //Delete of an unqualified identifier in strict mode
    var obj={
        x:10,
        y:20
    }

    delete obj;

    console.log(JSON.stringify(obj));

4) readonly property

    "use strict";
    var obj ={
        x:10
    }

    Object.defineProperty(obj,"x",{writable:false});

    obj.x =20;

    console.log(obj.x);

    'obj' has property 'x' which is readonly so we cant assign value to it,by default javascript ignore assignment of value to such property.

5) promotion of this to global namespace

    "use strict";
    function myFunc() {
        console.log(this);
    }
    myFunc();

    if not in strict mode this get promoted to global scope  otherwise this becomes undefined.
     contrary to  normal function arrow function behavior is different for

let func = ()=>{
    console.log(this);
}

func();

print empty object i.e. {} without adding "use strict" .


6) undefined variable

    "use strict";
    x= 10
    console.log(x);

    variable x is assigned value before declaration.
7) function param duplication
    "use strict";
    function MyFunc (i1,i2,i3,i1)
    {
       console.log(i1);
    }

    MyFunc(10,20,30,40);

       parameter i1 is put twice in function defination , value of i1 40 override its
       initial value 10

8) reserved keyword
     "use strict";
      var package = 1500;


      here "package" is reserved keyword in javascript.   


2019/10/16

creating graphql api using express.js & postgressql



first we will create a table as follows

create table person(
id serial,
firstname character varying(50),
lastname character varying(50),
email character varying(150),
joined timestamp,
lastloggedin timestamp
)

add some records to newly created table

insert into person(firstname,lastname,email,joined,lastloggedin) values('sangram','desai','ssd1110@gmail.com',current_timestamp,current_timestamp)

insert into person(firstname,lastname,email,joined,lastloggedin) values('sagar','desai','ssd1778@gmail.com',current_timestamp,current_timestamp)


we need following packages in our project
pg-promise express graphql express-graphql dotenv

also we are using nodemon as developer dependency.


index.js

"use strict";
const graphql = require("graphql");
const express = require("express");
const expressGraphQl = require("express-graphql");
const { GraphQLSchema } = graphql;
const { query } = require("./schemas/queries");
const { mutation } = require("./schemas/mutations");

const schema = new GraphQLSchema({
query,
mutation
});

var app = express();
app.use('/', expressGraphQl({
schema: schema,
graphiql: true
})
);




app.listen(3000, () =>
console.log('GraphQL server running on localhost:3000')
);


.env file at root location contains

POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=playground
POSTGRES_USER=sangram
POSTGRES_PASSWORD=sangram


.gitingore file contains

node_modules/

create a folder called schemas in this folder create three files
mutation.js ,types.js & queries.js.



Mutation.js file contains

const graphql = require("graphql");
const db = require("../pgAdaptor").db;
const { GraphQLObjectType, GraphQLID, GraphQLString, GraphQLBoolean } = graphql;
const { PersonType } = require("./types");

const RootMutation = new GraphQLObjectType({
name: "RootMutationType",
type: "Mutation",
fields: {
addPerson: {
type: PersonType,
args: {
firstname: { type: GraphQLString },
lastname: { type: GraphQLString },
email: { type: GraphQLString }
},
resolve(parentValue, args) {
const query = `insert into person(firstname,lastname,email,joined,lastloggedin) VALUES ($1, $2, $3, current_timestamp,current_timestamp) RETURNING *`;
const values = [
args.firstname,
args.lastname,
args.email
];

return db
.one(query, values)
.then(res => res)
.catch(err => err);
}
},
editPerson: {
type: PersonType,
args: {
id:{type:GraphQLString},
firstname: { type: GraphQLString },
lastname: { type: GraphQLString },
email: { type: GraphQLString }
},
resolve(parentValue, args) {
const query = `Update person set firstname=$1,lastname=$2,email=$3 where id=$4 RETURNING *`;
const values = [
args.firstname,
args.lastname,
args.email,
args.id
];

return db
.any(query, values)
.then(res => {
console.log(JSON.stringify(res));
return res[0]
})
.catch(err => err);
}
},
deletePerson: {
type: PersonType,
args: {
id:{type:GraphQLString},
},
resolve(parentValue, args) {
const query = `Delete from person where id=$1 RETURNING *`;
const values = [
args.id
];

return db
.any(query, values)
.then(res => {
//console.log(JSON.stringify(res));
return res[0]
})
.catch(err => err);
}
}
}
});

exports.mutation = RootMutation;

types.js contains

const graphql = require("graphql");
const { GraphQLObjectType, GraphQLString } = graphql;

const PersonType = new GraphQLObjectType({
name: "Person",
type: "Query",
fields: {
id: { type: GraphQLString },
firstname: { type: GraphQLString },
lastname: { type: GraphQLString },
email: { type: GraphQLString },
joined: { type: GraphQLString },
lastloggedin: { type: GraphQLString }
}
});

exports.PersonType = PersonType;

queries.js contain

const { db } = require("../pgAdaptor");
const { GraphQLObjectType, GraphQLID,GraphQLList,GraphQLNonNull,GraphQLString,GraphQLDate } = require("graphql");
const { PersonType } = require("./types");

const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
type: "Query",
fields: {
person: {
type: PersonType,
args: { id: { type: GraphQLNonNull(GraphQLID) }},
resolve(parentValue, args) {
const query = `SELECT * FROM person WHERE id=$1`;
const values = [args.id];
return db
.one(query, values)
.then(res => res)
.catch(err => err);
}
},
persons: {
type: GraphQLList(PersonType),
args: {
email: { type: GraphQLString },
firstname: { type: GraphQLString },
lastname: { type: GraphQLString }
},
resolve(parentValue, args) {
let query = `SELECT * FROM person where 1=1 `;
let values=[];

if(args.email){
query = query + ` and email='` + args.email + `'`;
}

if(args.firstname){
query = query + ` and firstname='` + args.firstname + `'`;
}

if(args.lastname){
query = query + ` and lastname='` + args.lastname + `'`;
}

return db
.any(query, values)
.then(res => {
//console.log(JSON.stringify(res));
return res;
})
.catch(err => err);

}
},
}
});




exports.query = RootQuery;

in root location create pgAdapter.js

pgAdapter.js contains

require('dotenv').config()
const pgPromise = require('pg-promise');

const pgp = pgPromise({}); // Empty object means no additional config required

const config = {
host: process.env.POSTGRES_HOST,
port: process.env.POSTGRES_PORT,
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD
};

const db = pgp(config);


/*db.any('select * from person')
.then(res => {
console.log(res);
});
*/

exports.db = db;



start application using npm start.

On browser hit http://localhost:3000 graphiql interface will be shown.

Whole project can be viewed at https://gitlab.com/sangram.desai/graphql-express-postgres


Inside you can run following queries.

GraphQL Queries:

1) inserting record into table using grapql API

mutation {
addPerson(firstname: "sachin", lastname: "desai", email: "ssd2109@gmail.com") {
id
}
}
2) getting record whose id is 3
{
person (id:3){
firstname,
lastname,
email,
lastloggedin,
joined
}
}

3) get all records in table
{
persons{
firstname,
lastname,
email,
lastloggedin,
joined
}
}

4) editing record whose is is 4
mutation {
editPerson(firstname: "swapnil", lastname: "sardeshmukh", email: "ssd2109@gmail.com",id:"4") {
id,
lastname,
firstname,
email,
lastloggedin,
joined
}
}

5) deleteing record whose id is 4
mutation {
deletePerson(id:"4") {
id,
lastname,
firstname,
email,
lastloggedin,
joined
}
}

6) listing all records whose firstname is sangram ,email is ssd1110@gmail.com & lastname is desai.

{
persons(firstname:"sangram",email:"ssd1110@gmail.com",lastname:"desai"){
firstname,
lastname,
email,
lastloggedin,
joined
}
}

2019/10/02

Simple Node.js interview question

Find output of following code

1) var arr = [1,2,3]
console.log(arr)
output:
   [ 1, 2, 3 ]

2) var arr1={
    "a":1,
    "b":2,
    "c":3
}
console.log(arr1);
output:
{ a: 1, b: 2, c: 3 }

3) var func = function(a,b){
    return a+b;
}
console.log(func);
output:
[Function: func]
4) var obj ={
    add:function(a,b){
        return a+b
    },
    substract:function(a,b){
        return a-b;
    }
}
console.log(obj);
output:
{ add: [Function: add], substract: [Function: substract] }

5) for(a in arr1){
  console.log(a);
}
output:
a
b
c
6) for(a in arr){
    console.log(a);
  }
output:
0
1
2
7) for(a of arr){
   console.log(a);
}
output:
1
2
3
8) var c = 3 in arr
console.log(c);
output:
false
9) var fruits = ["Banana", "Orange", "Apple", "Mango"];
var n = fruits.includes("Mango");
console.log(n);
output:
true
10) var d ={
    add:function (y){
      var x=5;
      function add1(x,y){
          return x+y;
      }
      return add1;
    }
}
console.log(d);
output:
{ add: [Function: add] }

11) can we have func(a)(b) in javascript


function space(a) {
    let b = function (c) {
        return a+c;
    }
    return b;
}


var t = space(7)(6)
console.log(t);

output:13