Wednesday, December 9, 2020

Typescript - nodejs 2020 december

api/safeFetch.ts

  • Code:

maximilianou@instrument:~/projects/weekly20$ cat api/safeFetch.ts 


import * as TE from "fp-ts/lib/TaskEither";
import * as E from "fp-ts/lib/Either";
const fetch = require('node-fetch');

type User = {

};

export const safeFetch = (
  url: string,
  errMessage: string
): TE.TaskEither> => 
     TE.tryCatch(
       () => fetch(url).then( res => res.json()),
       () => new Error(errMessage)
     );

safeFetch(
  "https://jsonplaceholder.typicode.com/users",
  "failed to fetch users"
)().then(E.fold(console.error, console.log));

  • Run code, over command line:

maximilianou@instrument:~/projects/weekly20/api$ ./node_modules/.bin/ts-node safeFetch.ts

Tuesday, December 1, 2020

Public Learning: Work in progress

Work in progress

https://github.com/maximilianou/weekly20/

Typescript

React

Docker

docker-compose

nginx - loadbalancer - localmachine

planning to learn Github Action

planning to learn AWS

Wednesday, October 14, 2020

This way i take variable inside dockerfile, from the file in my machine, and from environment in aws

Makefile

vm:
	docker-compose --env-file .env.development up --build	
docker-compose.yaml
    build: # specify the directory of the Dockerfile
      context: .
      dockerfile: Dockerfile.dev
      args:
        - NPM_TOKEN_PARAM
        - NPM_MAIL_PARAM
        - NPM_USER_PARAM
    env_file: 
      - .env.development
. env.development
NPM_USER_PARAM=max...
NPM_TOKEN_PARAM=fe...
NPM_MAIL_PARAM=max..
Dockerfile.dev
ARG NPM_USER_PARAM
ARG NPM_TOKEN_PARAM
ARG NPM_MAIL_PARAM
ENV NPM_USER=$NPM_USER_PARAM
ENV NPM_TOKEN=$NPM_TOKEN_PARAM
ENV NPM_MAIL=$NPM_MAIL_PARAM
COPY .npmrc ./ 
RUN npm install npm-cli-login
RUN  ./node_modules/.bin/npm-cli-login -r https://npm.pkg.github.com -s @... -u ${NPM_USER} -p ${NPM_TOKEN}  -e ${NPM_MAIL}

Wednesday, March 6, 2019

React using state and props, Shopping Cart MVC 2019

React using state and props, Shopping Cart MVC 2019

I mean, the simplest example learning how to use the React state, and React props

( Clearly here i'm not using Redux, this is the next step, just to be clear )

React state of the App

React props of each React.Component Instance

So we can have list of products, and a shopping cart (list of items of products), adding and removing items.

The point is to learn how to pass action control over components, changing from state to new states on action events from components, to the Root App, and showing the change in the other affected Component.

https://codesandbox.io/s/v0l1knv1yl

https://github.com/maximilianou/react_2019_state_props_shoppingcart_mvc/

https://gitlab.com/maximilianou/react_2019_state_props_shoppingcart_mvc

https://bitbucket.org/maximilianou/react_2019_state_props_shoppingcart_mvc


import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const ProductsList = props => {
  const { products, adding } = props;
  return (
    < section>
      < h2>List of Products< /h2>
      {products.map(product => (
        < article key={"product_" + product.id}>
          < h4>{product.name}< /h4>
          < span>{product.price}< /span>
          < button onClick={adding} value={JSON.stringify(product)}>
            +
          < /button>
        < /article>
      ))}
    < /section>
  );
};
const ItemsList = props => {
  const { items, removing } = props;
  return (
    < section>
      {items.map(item => (
        < article key={"item_" + item.product.id}>
          < h4>{item.product.name}< /h4>
          < span>{item.product.price}< /span>
          < span>{item.quantity}< /span>
          < span>{item.quantity * item.product.price}< /span>
          < button onClick={removing} value={JSON.stringify(item)}>
            -
          < /button>
        < /article>
      ))}
    < /section>
  );
};
class ShoppingCart extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      < section>
        < h2>Shopping Cart< /h2>
        < ItemsList items={this.props.items} removing={this.props.removing} />
      < /section>
    );
  }
}
class App extends React.Component {
  state = {
    products: [
      { id: 20, name: "Limonade", price: 200 },
      { id: 21, name: "Green Tea", price: 150 },
      { id: 22, name: "Chocolate Milk", price: 350 }
    ],
    items: []
  };
  constructor(props) {
    super(props);
    this.adding = this.adding.bind(this);
    this.removing = this.removing.bind(this);
  }
  adding = evt => {
    const product = JSON.parse(evt.target.value);
    let item = this.state.items.find(ite => ite.product.id === product.id);
    if (item === null || item === undefined) {
      item = {};
      item.product = product;
    }
    if (item.quantity === undefined) {
      item.quantity = 1;
      this.setState({ items: [...this.state.items, item] });
    } else {
      item.quantity += 1; // mm.. here i'm changing the original object. mmm...
      this.setState({ items: [...this.state.items] });
    }
  };
  removing = evt => {
    const item_p = JSON.parse(evt.target.value);
    const item = this.state.items.find(
      ite => ite.product.id === item_p.product.id
    );
    if (item.quantity === 1) {
      const listItems = this.state.items.filter(
        ite => ite.product.id !== item.product.id
      );
      this.setState({
        items: listItems
      });
    } else {
      item.quantity -= 1; // mmm.. here i'm changing the original object. mmm...
      this.setState({ items: [...this.state.items] });
    }
  };
  render() {
    return (
      < div className="App">
        < ProductsList products={this.state.products} adding={this.adding} />
        < ShoppingCart items={this.state.items} removing={this.removing} />
      < /div>
    );
  }
}

const rootElement = document.querySelector("#root");
ReactDOM.render(<  App />, rootElement);

Friday, February 1, 2019

running test sample puppeteer docker compose debian 9

Here we have a simple sample, to run puppeteer and check OK or NOT browsing uno site.

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


educacion@family:~/src/docker17_puppeteer/frontest$ docker-compose up


educacion@family:~/src/docker17_puppeteer/frontest/test$ cat index.spec.js 
const assert    = require('assert');
const puppeteer = require('puppeteer');
describe("Browsing with puppeteer:", ()=> {
  describe("Geting one page", ()=>{
    it("Check OK:",  async ()=> {
        const browser = await puppeteer.launch({
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox'
            ]
        });    
        const page = await browser.newPage();
        await page.goto('https://bitbucket.org/maximilianou/'); //, {waitUntil: 'networkidle2'});    
        let textResponse = await page.evaluate(() => {
          //Maximiliano Usich
          let elemCheck = document.querySelector('a[href="/maximilianou/"]');
          return elemCheck.innerHTML;
        });
        assert( textResponse === 'Maximiliano Usich', "[OK] Content Found" );
        browser.close();
    });
    it("Check Not Found:", async ()=> {
        const browser = await puppeteer.launch({
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox'
            ]
        });    
        const page = await browser.newPage();
        await page.goto('https://bitbucket.org/maximilianou/UPS!!');// , {waitUntil: 'networkidle2'});    
        let textResponse = await page.evaluate(() => {
          //Maximiliano Usich
          let elemCheck = document.querySelector('a[href="/maximilianou/"]');
          return elemCheck;
        });
        assert( textResponse === null, "[OK] Content Not Found" );
        browser.close();
        
      });
  });
});



educacion@family:~/src/docker17_puppeteer/frontest$ cat Dockerfile 
FROM alekzonder/puppeteer
# set working directory
#RUN mkdir /app
WORKDIR /app
# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH
# install and cache app dependencies
COPY package.json /app/package.json
COPY test /app/test
RUN npm install
# start app
CMD ["npm", "run", "test"]


educacion@family:~/src/docker17_puppeteer/frontest$ cat docker-compose.yml 
version: '3.5'
services:
  docker-test-puppeteer:
    container_name: docker-test-puppeteer
    build:
      context: .
      dockerfile: Dockerfile
    volumes:
      - '.:/app'
      - '/app/node_modules'
    ports:
      - '3333:3333'
    environment:
      - NODE_ENV=development

ERROR: when an error like this happen

docker-test-puppeteer    |   1) Browsing with puppeteer:
docker-test-puppeteer    |        Geting one page
docker-test-puppeteer    |          Check OK::
docker-test-puppeteer    |      Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/app/test/index.spec.js)

The site did NOT responde on time ( 10000 milis). We have configured this in package.json

educacion@family:~/src/docker17_puppeteer/frontest$ cat package.json 
{
  "name": "frontest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "node_modules/mocha/bin/mocha --timeout 10000  test/index.spec.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mocha": "^5.2.0"
  }
}

This is the way of code, set the timeout in the it().timeout(0), because mocha take 2 seconds.

const assert    = require('assert');
const puppeteer = require('puppeteer');
describe("Browsing with puppeteer:", ()=> {
  describe("Geting one page", ()=>{
    it("Check OK:",  async ()=> {
        const browser = await puppeteer.launch({
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox'
            ]
        });    
        const page = await browser.newPage();
        await page.goto('https://bitbucket.org/maximilianou/', {waitUntil: 'domcontentloaded'}); //, {waitUntil: 'networkidle2'});    
        let textResponse = await page.evaluate(() => {
          //Maximiliano Usich
          let elemCheck = document.querySelector('a[href="/maximilianou/"]');
          return elemCheck.innerHTML;
        });
        assert( textResponse === 'Maximiliano Usich', "[OK] Content Found" );
        browser.close();
    }).timeout(0);;
    it("Check Not Found:", async ()=> {
        const browser = await puppeteer.launch({
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox'
            ]
        });    
        const page = await browser.newPage();
        await page.goto('https://bitbucket.org/maximilianou/UPS!!', {waitUntil: 'domcontentloaded'});// , {waitUntil: 'networkidle2'});    
        let textResponse = await page.evaluate(() => {
          //Maximiliano Usich
          let elemCheck = document.querySelector('a[href="/maximilianou/"]');
          return elemCheck;
        });
        assert( textResponse === null, "[OK] Content Not Found" );
        browser.close();
        
      }).timeout(0);;
  });
});

install docker compose in debian 9

Installing docker-compose in debian 9

root@family:/home/educacion/src/docker17_puppeteer/frontest# curl -L https://github.com/docker/compose/releases/download/1.23.2/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose


root@family:/home/educacion/src/docker17_puppeteer/frontest# chmod +x /usr/local/bin/docker-compose


root@family:/home/educacion/src/docker17_puppeteer/frontest# docker-compose --version
docker-compose version 1.23.2, build 1110ad01