Friday, February 1, 2019

install node modules globally in debian 9

Installing node modules globally in debian 9 The unix way, your user need to be part of staff group

educacion@family:~/src/docker17_puppeteer$ fgrep educacion /etc/group
staff:x:50:educacion
ssh:x:113:educacion
educacion:x:1000:

Now you have clean access to /usr/local, because you are part of staff group, it's the unix way ( try to not use sudo, not been part of sudo )

educacion@family:~/src/docker17_puppeteer$ npm set prefix /usr/local

educacion@family:~/src/docker17_puppeteer$ npm install -g jshint
/usr/local/bin/jshint -> /usr/local/lib/node_modules/jshint/bin/jshint
+ jshint@2.9.7

install vs code debian

Install visual code in debian


root@family:/home/educacion/src/docker17_puppeteer# apt install software-properties-common apt-transport-https

root@family:/home/educacion/src/docker17_puppeteer# wget -q https://packages.microsoft.com/keys/microsoft.asc -O- | apt-key add -


root@family:/home/educacion/src/docker17_puppeteer# add-apt-repository "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main"


root@family:/home/educacion/src/docker17_puppeteer# apt update


root@family:/home/educacion/src/docker17_puppeteer# apt install code

install nodejs in debian

Installing nodejs in debian 9


root@family:/home/educacion/src/docker17_puppeteer# curl -sL https://deb.nodesource.com/setup_11.x -o nodesource_setup.sh


root@family:/home/educacion/src/docker17_puppeteer# chmod +x nodesource_setup.sh 

root@family:/home/educacion/src/docker17_puppeteer# ./nodesource_setup.sh 

root@family:/home/educacion/src/docker17_puppeteer# apt install -y nodejs

root@family:/home/educacion/src/docker17_puppeteer# node --version
v11.9.0

Monday, January 21, 2019

react redux one source file sample all components january 2019

Trying to simplify One File Source Code Explanation of React Redux.

This is the minimal example i have seen.

>React Redux, 'there is nothing new under the sun', i had an interview, i didn't know react redux at the time, i clearly sed that. So i Solved an exercise without react redux. I just write down vanilla javascript ES6, class, view, model, controller, html css. So, when the interview finished, i started searching, reading blogs, three days later.. here you have, react redux, it's not so complex. So Developers, 'there is nothing new under the sun', if you manage design patterns have a day with this, and there is it running. )

https://github.com/maximilianou/docker15_react_redux_onefile https://www.linkedin.com/pulse/developer-you-only-need-three-days-learn-react-redux-usich/?published=t
( This could help in a realtime interview, clone, cut and paste, npm install, and do the react redux exercise, 

showing that you manage the concepts, fast, clear.. or not so.

Changing this code, 

Adding inputs in the form, or adding another form (jsx, React.Component), "connecting it with the redux store" 

Changing the view, or adding another views (jsx, React.Component) "connecting it with the redux store", 

Making more actions, will help you show faster your understanding of react redux.

Show how to make many differents redux stores, 
for a partition of your busness data layer in this presentation layer.

- Later you talk about Hierarchy of the filesystem, were you will write down your .js files ('like unix man hier') when you have many business logic accions. 

/actions/

/constants/

/reducers/

/components/

)

---

I run the environment with, editor vscode, docker-compose just to use it.
And we can change the code, and see changes on runtime.
code . 

docker-compose up

```javascript

// index.js, react redux, onefile flatting explanation.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import { Provider, connect } from "react-redux";
import './App.css';
import uuidv1 from "uuid";
import { createStore } from 'redux'; 
//// Route (business logic) actions, with tipified constant Names.
//// To change de state of the Global store App
const ADD_ARTICLE = "ADD_ARTICLE";
const initialState = {
  articles: []
};
const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_ARTICLE:
      return { ...state, articles: [ ...state.articles, action.payload ] };    
    default:
      return state;
  }
};
//// Create an "Input Form React Component", connected with redux store state.
//// Write down the html view of this component.
//// Write down the handlers in javascript methods, for dom events. 
//// Connect the dom events handlers in the html view.
//// Dispatch de state of the Component, to the redux (global) store.
const store = createStore(rootReducer);
const addArticle = article => ({
  type: ADD_ARTICLE,
  payload: article
});
const mapDispatchToProps = dispatch => {
  return {
    addArticle: article => dispatch(addArticle(article))
  };
};
class ConnectedForm extends React.Component {
  constructor() {
    super();
    this.state = {
      title: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({ [event.target.id]: event.target.value });
  }
  handleSubmit(event) {
    event.preventDefault();
    const { title } = this.state;
    const id = uuidv1();
    this.props.addArticle({ title, id });
    this.setState({ title: "" });
  }
  render() {
    const { title } = this.state;
    return (
      < form onSubmit={this.handleSubmit} >
        < div className="" >
          < label htmlFor="title">Title< /label >
          < input
            type="text"
            className=""
            id="title"
            value={title}
            onChange={this.handleChange}
          / >
        < /div >
        < button type="submit" className="" >
          SAVE
        < /button >
      < /form >
    );
  }
}
const Form = connect(null, mapDispatchToProps)(ConnectedForm);
//// Create a Function with de html view in jsx from react, 
//// And connect the state properties to the redux store
//// Like an observer/observable, from general design patterns.
const mapStateToProps = state => {
  return { articles: state.articles };
};
const ConnectedList = ({ articles }) => (
  < ul className="" >
    {articles.map(el => (
      < li className="" key={el.id} >
        {el.title}
      < /li >
    ))}
  < /ul >
);
const List = connect(mapStateToProps)(ConnectedList);
//// Create de view in jsx, width html and React Component of the Application
const App = () => (
  < div className="App" >
    < div className="App-header" >
      < h2 >Add a new article< /h2 >
      < Form / >
    < /div >
    < div className="" >
      < h2 >Articles< /h2 >
      < List / >
    < /div >
  < /div >
);
//// Making the action of rendering the final DOM in html, in 'index.html'->'div#app'
//// we have to connect the Global Redux store of the Rreact App, 
////       with the Provider react-redux Component
ReactDOM.render(
  < Provider store={store} >
    < App / >
  < /Provider >,
  document.querySelector("#app")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

```

https://bitbucket.org/maximilianou/docker15_react_redux_onefile/

https://github.com/maximilianou/docker15_react_redux_onefile

REFERENCE: https://dev.to/valentinogagliardi/react-redux-tutorial-for-beginners-learning-redux-in-2018-13hj

Thursday, January 17, 2019

javascript react docker initial development environment

REFERENCE: https://mherman.org/blog/dockerizing-a-react-app/

1. This recipe really run well, so. Installing scaffolding tools from react script over npm.

educacion@educacion:~/src/docker13react$ npm install create-react-app

2. Creating a default app, ( scaffolding ) frontend in this case.

educacion@educacion:~/src/docker13react$ npx create-react-app frontend

3. Looking what files were created.

educacion@educacion:~/src/docker13react$ cd frontend/
educacion@educacion:~/src/docker13react/frontend$ ls
Dockerfile  node_modules  package.json  public  README.md  src  yarn.lock

4. Create the docker file, from the tutorial reference.

educacion@educacion:~/src/docker13react/frontend$ cat Dockerfile 
# base image
FROM node
# set working directory
RUN mkdir /usr/src/app
WORKDIR /usr/src/app
# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH
# install and cache app dependencies
COPY package.json /usr/src/app/package.json
RUN npm install --silent
RUN npm install react-scripts@1.1.1 -g --silent
# start app
CMD ["npm", "start"]

5. There are some files that can be excluded from de docker image.

educacion@educacion:~/src/docker13react/frontend$ cat .dockerignore 
node_modules

6. Building the docker image for initial react development.

educacion@educacion:~/src/docker13react/frontend$ docker build -t react-docker .

7. Running the docker image in port 3000, exported and binded with the localhost port.

educacion@educacion:~/src/docker13react/frontend$ docker run -it -v ${PWD}:/usr/src/app -v /usr/src/app/node_modules -p 3000:3000 --rm react-docker

http://localhost:3000/ 

8. Using docker compose.

educacion@educacion:~/src/docker13react_initial/frontend$ cat docker-compose.yml 
version: '3.5'
services:
  react-docker:
    container_name: react-docker 
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - '.:/usr/src/app'
      - '/usr/src/app/node_modules'
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=development

9. Running docker compose

educacion@educacion:~/src/docker13react/frontend$ docker-compose up

10. Ckecking if it is running (manually).

http://localhost:3000/ 

11. Running the visual code editor, for runtime development.

educacion@educacion:~/src/docker13react$ ls
frontend  node_modules  package.json  package-lock.json

educacion@educacion:~/src/docker13react$ code .

12. And now!, It's running OK, pushing to the repository, on bitbucket.org with mercurial.

educacion@educacion:~/src$ hg clone https://bitbucket.org/maximilianou/docker13react_initial

educacion@educacion:~/src/docker13react_initial$ cp -R ../docker13react/* .

13. Adding new files to the repository

educacion@educacion:~/src/docker13react_initial$ hg add .

educacion@educacion:~/src/docker13react_initial$ hg commit -u maximilianou@gmail.com -m 'initial react docker development environment'

14. Updating the repository, with push.

educacion@educacion:~/src/docker13react_initial$ hg push

Monday, December 31, 2018

mocha test hapi rest api oop javascript

1. At first, Verify the status of our code, or clone it.

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ hg status

2. This is our package.json


educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ cat package.json 
{
  "name": "rest_echo_hapi",
  "version": "1.0.0",
  "description": "This README would normally document whatever steps are necessary to get your application up and running.",
  "main": "server/index.js",
  "scripts": {
    "start": "node server/index.js",
    "test": "mocha --recursive ./test/**.js"
  },
  "keywords": [],
  "author": "maximilianou@gmail.com",
  "license": "MIT",
  "dependencies": {
    "hapi": "^17.8.1",
    "isemail": "^3.2.0",
    "mocha": "^5.2.0",
    "node-fetch": "^2.3.0"
  }
}

3. I'll try to run the test program, widthout the libraries installed

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ npm test

> rest_echo_hapi@1.0.0 test /home/educacion/src/resthapi/v3/rest_echo_hapi
> mocha --recursive ./test/**.js

sh: 1: mocha: not found
npm ERR! Test failed.  See above for more details.

4. Now i'm installing manualy, with npm, mocha the test suite, and node-fetch to have most standard fetch library updated. I'm sure this fetch is going to be part of our nodejs api. Standards are the most important thing a developer must be confident with.

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ npm install mocha node-fetch


5. And, now, we are running the test, and the OK result, baby steps, it's really the minimal code size.

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ npm test
> rest_echo_hapi@1.0.0 test /home/educacion/src/resthapi/v3/rest_echo_hapi
> mocha --recursive ./test/**.js
  routes :: server
    method http GET /
      ✓ should return text (43ms)
    method http POST /
      ✓ should return text
    metodo http PUT /
      ✓ should return text
    metodo http DELETE /
      ✓ should return text
  4 passing (67ms)

6. Here we have our test code, plain, one line assert focus, just to run our baby steps. Testing GET POST PUT DELETE minimal, hardcodeing configuration like 127.0.0.1 and others. But having a structure of describe() one scenario, describe() each case, it check one value item in each case. Here we have the assert.ok() and the RegExp() from the standard node api, following our Standard way of programming, having our code clean from temporal dependencies in libraries that will may change, but we expect some standards to be done. ( This kind of temporal dependencies problems happended to some project where i was working some time ago, when the browsers doesn't support JSON parse and stringify, so i start using, from our Master Programmer, our Master Key Programmer, Doublas Crockford, his version of the standard, so we don't have to worry about the future, because he does!, https://github.com/douglascrockford/JSON-js, some time later i don't have to change my older code, because his library was thought with the stantard in mind, so JSON.parse() JSON.stringify() was all done native in the browser one day, now. )

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ cat test/server_index_test.js 
const assert = require('assert');
const fetch = require('node-fetch');
describe('routes :: server', () => {
  describe('method http GET /', () => {
    it('should return text', (done) => {
      const thevalue = "Mafalda";
      fetch( 'http://127.0.0.1:3002/'+thevalue
      ).then( res => res.text() 
      ).then(
        (body) => {
          assert.ok( new RegExp(thevalue+"$").test(
            JSON.parse(body)) , ":::Data Error!!!");
          done();
        }
      ).catch(done);
      });
    });      
  describe('method http POST /', () => {
    it('should return text', (done) => {
      const thevalue = "Larguirucho";
      fetch(
        'http://127.0.0.1:3002/msg', {
          method: 'POST',
          body:    JSON.stringify(thevalue),
          headers: { 'Content-Type': 'application/json' },
      }        
      ).then( res => res.text() 
      ).then(
        (body) => {
          assert.ok( new RegExp(thevalue+"$").test(
            JSON.parse(body)) , ":::Data Error!!!");
          done();
        }
      ).catch(done);
    });
  });
  describe('metodo http PUT /', () => {
    it('should return text', (done) => {
      const thevalue = "Profesor Neurus";
      fetch(
        'http://127.0.0.1:3002/msg', {
          method: 'PUT',
          body:    JSON.stringify(thevalue),
          headers: { 'Content-Type': 'application/json' },
      }        
      ).then( res => res.text() 
      ).then(
        (body) => {
          assert.ok( new RegExp(thevalue+"$").test(
            JSON.parse(body)) , ":::Data Error!!!");
          done();
        }
      ).catch(done);
    });
  });  
  describe('metodo http DELETE /', () => {
    it('should return text', (done) => {
      const thevalue = "Pedrito";
      fetch( 'http://127.0.0.1:3002/'+thevalue
      ).then( res => res.text() 
      ).then(
        (body) => {
          assert.ok( new RegExp(thevalue+"$").test(
            JSON.parse(body)) , ":::Data Error!!!");
          done();
        }
      ).catch(done);
    });
  });
});

7. Here we have our server REST API with JSON body request and JSON body response. Body or parameter depending on POST PUT, GET DELETE, in case.

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ cat server/index.js 
const Hapi = require('hapi');
class EchoServerHapi{
    constructor(args){
        this.server = Hapi.server(args);
    }
    async init(){
        try {
          await this.routing();
          await this.server.start();
          console.log(`Here we have the echo Server Hapi running:: ${this.server.info.uri}`);
        } catch (error) {
          console.log('Error while trying to run echo Server Hapi:: ' + error.message);
        }
    }
    async routing(){
        this.server.route({
            method: 'GET',
            path: '/',
            handler: (request, h) => {
                return JSON.stringify('Hello, Javascript Developer');
            }
        });        
        this.server.route({
            method: 'GET',
            path: '/{name}',
            handler: (request, h) => {
                return JSON.stringify('Hello, ' + encodeURIComponent(request.params.name) );
            }
        });
        this.server.route({
            method: 'POST',
            path: '/msg',
            handler: (request, h) => {
                return JSON.stringify(request.payload);
            }
        });
        this.server.route({
            method: 'PUT',
            path: '/msg',
            handler: (request, h) => {
                return JSON.stringify(request.payload);
            }
        });
        this.server.route({
            method: 'DELETE',
            path: '/{name}',
            handler: (request, h) => {
                return JSON.stringify( 'Bye, ' + encodeURIComponent(request.params.name) );
            }
        });
    }
}
const firstEchoServer = new EchoServerHapi({
  port: 3002,
  host: '0.0.0.0',
  app: {}
});
firstEchoServer.init();

8. Our Dockerfile is just to have the posibility to change code when we are running our development environment API REST.

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ cat Dockerfile 
FROM node
WORKDIR /code
RUN npm set prefix /usr/local && npm install -g nodemon
COPY package.json /code/package.json
RUN npm set prefix /usr/local && npm install && npm ls
RUN mv /code/node_modules /node_modules
COPY . /code
#EXPOSE 3000  # expose but no publish, except useing docker -P
CMD ["npm", "start"]

9. And, containers compose in docker-compose.yml, to have running the services

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ cat docker-compose.yml 
version: "2"
services:
  web:
    build: .
    command: nodemon -L --inspect=0.0.0.0:5858
    volumes:
      - .:/code
    ports:
      - "3002:3002"
      - "5858:5858"

10. Once it's running OK, upload to the repository, to our bitbucket mercurial.

educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ hg commit -u maximilianou@gmail.com -m 'testing mocha, first steps '
educacion@educacion:~/src/resthapi/v3/rest_echo_hapi$ hg push


Wednesday, December 26, 2018

docker rest api hapijs nodejs vscode realtime development


1. The javascript echo parameter server hapi 

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ cat server/index.js 
const Hapi = require('hapi');
class EchoServerHapi{
    constructor(args){
        this.server = Hapi.server(args);
    }
    async init(){
        try {
          await this.routing();
          await this.server.start();
          console.log(`Here we have the echo Server Hapi running:: ${this.server.info.uri}`);
        } catch (error) {
          console.log('Error while trying to run echo Server Hapi:: ' + error.message);
        }
    }
    async routing(){
        this.server.route({
            method: 'GET',
            path: '/',
            handler: (request, h) => {
                return 'Hello, Javascript Developer! ! !\n';
            }
        });        
        this.server.route({
            method: 'GET',
            path: '/{name}',
            handler: (request, h) => {
                return 'Hello, ' + encodeURIComponent(request.params.name) + '!\n';
            }
        });
        this.server.route({
            method: 'POST',
            path: '/msg',
            handler: (request, h) => {
                return "POSTing:: "+JSON.stringify(request.payload) + '\n';
            }
        });
        this.server.route({
            method: 'PUT',
            path: '/msg',
            handler: (request, h) => {
                return "PUTing:: "+JSON.stringify(request.payload) + '\n';
            }
        });
        this.server.route({
            method: 'DELETE',
            path: '/{name}',
            handler: (request, h) => {
                return 'Bye, ' + encodeURIComponent(request.params.name) + '!\n';
            }
        });
    }
}
/* LOOK THIS COMMENT, NO localhost, just 0.0.0.0 */
/*const firstEchoServer = new EchoServerHapi({
    port: 3001,
    host: 'localhost',
    app: {}
  });*/
  const firstEchoServer = new EchoServerHapi({
    port: 3001,
    host: '0.0.0.0',
    app: {}
  });
firstEchoServer.init();

2. The node package.json done with npm

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ cat package.json 
{
  "name": "rest_echo_hapi",
  "version": "1.0.0",
  "description": "This README would normally document whatever steps are necessary to get your application up and running.",
  "main": "server/index.js",
  "scripts": {
    "start": "node server/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "maximilianou@gmail.com",
  "license": "MIT",
  "dependencies": {
    "hapi": "^17.8.1",
    "isemail": "^3.2.0"
  }
}

3. The Dockerfile to run and modify the javascript program

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ cat Dockerfile 
FROM node
WORKDIR /code
RUN npm set prefix /usr/local && npm install -g nodemon
COPY package.json /code/package.json
RUN npm set prefix /usr/local && npm install && npm ls
RUN mv /code/node_modules /node_modules
COPY . /code
#EXPOSE 3000  # expose but no publish, except useing docker -P
CMD ["npm", "start"]

4. The docker compose to run the composition of service docker having volume shared path

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ cat docker-compose.yml 
version: "2"
services:
  web:
    build: .
    command: nodemon -L --inspect=0.0.0.0:5858
    volumes:
      - .:/code
    ports:
      - "3001:3001"
      - "5858:5858"

5. Starting from command line with npm, from package.json

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ npm start
> rest_echo_hapi@1.0.0 start /home/educacion/src/resthapi/v2/rest_echo_hapi
> node server/index.js
Here we have the echo Server Hapi running:: http://0.0.0.0:3001

6. Starting from docker compose

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ docker-compose up
Starting restechohapi_web_1
Attaching to restechohapi_web_1
web_1  | [nodemon] 1.18.7
web_1  | [nodemon] to restart at any time, enter `rs`
web_1  | [nodemon] watching: *.*
web_1  | [nodemon] starting `node --inspect=0.0.0.0:5858 server/index.js`
web_1  | Debugger listening on ws://0.0.0.0:5858/e6293311-3e2c-4f77-af38-d087a52d30c3
web_1  | For help, see: https://nodejs.org/en/docs/inspector
web_1  | Here we have the echo Server Hapi running:: http://0.0.0.0:3001

7. Checking GET, POST, PUT and DELETE echoing the parameter in each case.

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl http://0.0.0.0:3001
Hello, Javascript Developer! ! !
educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl http://127.0.0.1:3001
Hello, Javascript Developer! ! !
educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl http://localhost:3001
Hello, Javascript Developer! ! !

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl http://localhost:3001/Hijitus
Hello, Hijitus!

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl --request DELETE http://localhost:3001/Larguirucho
Bye, Larguirucho!

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl --header "Content-Type: application/json" --request POST --data '{"name":"Pucho"}' http://localhost:3001/msg
POSTing:: {"name":"Pucho"}

educacion@educacion:~/src/resthapi/v2/rest_echo_hapi$ curl --header "Content-Type: application/json" --request PUT --data '{"name":"Profesor Neurus"}' http://localhost:3001/msg
PUTing:: {"name":"Profesor Neurus"}