JavaScript: Understanding Prototype and Class methods

So, in JavaScript, first of all, its an object oriented programming but without classes (till ES5), now with ES6 we have classes officially in JavaScript

But still the old behaviour of the language is forwarded with newer version

In Javascript creating an object is possible via its functions( new [Func]()), function is a first class (can be passed as an argument), function is a high order function(can be received as an argument), function it self acts a constructor( new func() )

take a look at below code

  
  function User(name, passwd) {
    this.name = name;
    this.passwd = passwd;
    this.methodname = "User"
  }

  u1 = new User("User1", "Password")
  u2 = new User("User2", "Password")

  console.log(u1)
  console.log(u2)

  User.prototype.method1 = function () {
    console.log("This is method1");
  }
  u1.method1()

  User.method2 = function() {
    console.log("this is method2");
  }
  User.method2()

  

explanation is as follows

  • We have defined a function called `User`
  • Created two objects from that function( Yes, in JS you can do that, function will now work a constrctor
  • Now if you look at console.log output u1 and u2 objects will contain the data, which are passed as argument to function
  • till now all good, then here comes interesting part, `prototype`, using prototype keyword, you are defining a new function called `method1`
  • this method1 function created after creating object u1, u2, but still because its a prototype method where JS will update its reference automatically to all existing objects, u1 and u2 objects can access that method
  • So, how's that happening ?, if you look u1 object structure, in console.log, you will a reference to User.prototype,so when ever a new method added to User.prototype, automatically its available for u1 object via path
  • But then we have defined a method called method2(), and this is defined at class level, so only the User function/constuctor can access that but not the objects like u1, u2
  • the reason isnt like its defined after you have created objects, the reason is its just not under the scope for objects, its under the scope of construtor only.
  • You can use this trick in Javascript, that if you have a method and you dont want that method to be available to your object, then create the method like method2

There is so much to say about prototype and class methods, but I believe this simple read might be helpful

Hope it helps

Thank you.

GoLang: How To work with JSON Data and Nested structs

GoLang: How To work with JSON Data and Nested structs

Hello Everyone,

I spent sometime today to craft this code, so this article slowly walk you through how to build a nested struct, how to load data into it, then converting it into JSON, writing to a file, reading from a file and append new data etc.

I was learning GoLang and found needed something like this. Hope it helps.

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type Schema struct {
	Users map[string]User
	Posts map[string]Post
}

type User struct {
	Username string `json:"username"`
	Email    string `json:"email"`
}
type Post struct {
	Heading     string `json:"post_heading"`
	Description string `json:"description"`
}

func main() {
	u1 := User{
		Username: "rajag",
		Email:    "rajag@example.com",
	}

	p1 := Post{
		Heading:     "Post 1 heading",
		Description: "Post 1 description",
	}

	fmt.Println(u1)
	fmt.Println(p1)

	schema := Schema{
		Users: make(map[string]User),
		Posts: make(map[string]Post),
	}

	schema.Users[u1.Username] = u1
	schema.Posts[p1.Heading] = p1

	fmt.Println(schema)

	// Now convert the data into JSON and print

	data, err := json.Marshal(schema)
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Printf("%s", string(data))

	// Append data to exist JSON

	u2 := User{
		Username: "user2",
		Email:    "user2@example.com",
	}

	p2 := Post{
		Heading:     "Post 2 heading",
		Description: "Post 2 description",
	}

	schema.Users[u2.Username] = u2
	schema.Posts[p2.Heading] = p2

	data, err = json.Marshal(schema)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%s\n", data)

	// Assume like you have to do unmarshal to append
	// create empty schema to store the data
	schema2 := Schema{
		Users: make(map[string]User),
		Posts: make(map[string]Post),
	}
	// then unmarshal by saying to store there, go principle share the memory
	err = json.Unmarshal(data, &schema2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Read from schema 2 >>>>>> ", schema2)

	u3 := User{
		Username: "user3",
		Email:    "user3@example.com",
	}

	p3 := Post{
		Heading:     "Post 3 heading",
		Description: "Post 3 description",
	}

	schema2.Users[u3.Username] = u3
	schema2.Posts[p3.Heading] = p3

	data, err = json.Marshal(schema2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("data from schema 2 >>>>>>> %s\n ", data)

	// Write JSON to file
	fileName := "./my.json"

	err = os.WriteFile(fileName, data, 0755)
	if err != nil {
		fmt.Println(err)
	}

	//Read JSON from file
	schema3 := Schema{
		Users: make(map[string]User),
		Posts: make(map[string]Post),
	}

	dataFromFile, err := os.ReadFile(fileName)
	if err != nil {
		fmt.Println(err)
	}

	err = json.Unmarshal(dataFromFile, &schema3)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("schema3 >>>>> ", schema3)

	// append data to structure
	u4 := User{
		Username: "user4",
		Email:    "user4@example.com",
	}

	p4 := Post{
		Heading:     "Post 4 heading",
		Description: "Post 4 description",
	}

	schema3.Users[u4.Username] = u4
	schema3.Posts[p4.Heading] = p4

	data, err = json.Marshal(schema3)
	if err != nil {
		fmt.Println(err)
	}

	// new data appended

	fmt.Printf("Schema4 >>>>> data %s\n", data)

	// now save changes to file
	os.WriteFile(fileName, data, 0755)
}

PostgreSQL: How To - Installation , Create User , DB and manage permissions

PostgreSQL: How To - Installation , Create User , DB and manage permissions

Installation

sudo apt install postgresql postgresql-contrib
  • Start the DB
    • you will have instruction printed in the output
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    pg_ctlcluster 12 main start

Ver Cluster Port Status Owner    Data directory              Log file
12  main    5432 down   postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log
update-alternatives: using /usr/share/postgresql/12/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmast
er.1.gz (postmaster.1.gz) in auto mode
invoke-rc.d: could not determine current runlevel
invoke-rc.d: policy-rc.d denied execution of start.

We are interested in pg_ctlcluster 12 main start line.

Creating User Account

  • login into DB
root@7204604adf5f:/# sudo -u postgres psql
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.
  • create DB and user from psql console
postgres=# create database mydb;
create user myuser with encrypted password 'mypass';
grant all privileges on database mydb to myuser;
CREATE DATABASE
CREATE ROLE
GRANT
postgres=# exit
  • create user and DB from OS console( contrib package provides these utils)
root@7204604adf5f:/# sudo -u postgres createuser user01
root@7204604adf5f:/# sudo -u postgres createdb db01

### Now drop to psql shell and give necessary permissions
root@7204604adf5f:/# sudo -u postgres psql
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

postgres=# alter user user01 with encrypted password 'Password#222';
grant all privileges on database db01 to user01;
ALTER ROLE
GRANT
postgres=# exit

Now lets verify login

root@7204604adf5f:/# psql -h localhost -U user01 -d db01
Password for user user01: 
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

db01=> exit
root@7204604adf5f:/# 

User Management file ( Work in Progress )

So the users we created and provided as default with installation are based here, /etc/postgresql/12/main/pg_hba.conf postgres support 3rd Party/external identify management systems.
Follow reference links for more information.

depending upon the OS, this file located at different location, but postgres can help identify this file location

admin@7204604adf5f:~$ psql -t -P format=unaligned -c 'SHOW hba_file;'
/etc/postgresql/12/main/pg_hba.conf
admin@7204604adf5f:~$ psql
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

admin=# SHOW hba_file;
              hba_file               
-------------------------------------
 /etc/postgresql/12/main/pg_hba.conf
(1 row)

PostgreSQL: How To - Installation , Create User , DB and manage permissions

PostgreSQL: How To - Installation , Create User , DB and manage permissions

Installation

sudo apt install postgresql postgresql-contrib
  • Start the DB
    • you will have instruction printed in the output
performing post-bootstrap initialization ... ok
syncing data to disk ... ok

Success. You can now start the database server using:

    pg_ctlcluster 12 main start

Ver Cluster Port Status Owner    Data directory              Log file
12  main    5432 down   postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log
update-alternatives: using /usr/share/postgresql/12/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmast
er.1.gz (postmaster.1.gz) in auto mode
invoke-rc.d: could not determine current runlevel
invoke-rc.d: policy-rc.d denied execution of start.

We are interested in pg_ctlcluster 12 main start line.

Creating User Account

  • login into DB
root@7204604adf5f:/# sudo -u postgres psql
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.
  • create DB and user from psql console
postgres=# create database mydb;
create user myuser with encrypted password 'mypass';
grant all privileges on database mydb to myuser;
CREATE DATABASE
CREATE ROLE
GRANT
postgres=# exit
  • create user and DB from OS console( contrib package provides these utils)
root@7204604adf5f:/# sudo -u postgres createuser user01
root@7204604adf5f:/# sudo -u postgres createdb db01

### Now drop to psql shell and give necessary permissions
root@7204604adf5f:/# sudo -u postgres psql
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

postgres=# alter user user01 with encrypted password 'Password#222';
grant all privileges on database db01 to user01;
ALTER ROLE
GRANT
postgres=# exit

Now lets verify login

root@7204604adf5f:/# psql -h localhost -U user01 -d db01
Password for user user01: 
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

db01=> exit
root@7204604adf5f:/# 

User Management file ( Work in Progress )

So the users we created and provided as default with installation are based here, /etc/postgresql/12/main/pg_hba.conf postgres support 3rd Party/external identify management systems.
Follow reference links for more information.

depending upon the OS, this file located at different location, but postgres can help identify this file location

admin@7204604adf5f:~$ psql -t -P format=unaligned -c 'SHOW hba_file;'
/etc/postgresql/12/main/pg_hba.conf
admin@7204604adf5f:~$ psql
psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1))
Type "help" for help.

admin=# SHOW hba_file;
              hba_file               
-------------------------------------
 /etc/postgresql/12/main/pg_hba.conf
(1 row)