Thursday, July 22, 2021

Elasticsearch multiple indexes

Just another post of how to do multiple indexes search.


 

 



Wednesday, July 21, 2021

Postman to query Elasticsearch

To query elasticsearch result, that is use GET method with JSON data. Generally in REST API, we don't have body data in the GET method.

 



Tuesday, July 20, 2021

Upload React to AWS S3

Direct upload to AWS S3.

  • Create s3 bucket
  • Use Upload UI to upload the whole build folder.


  • In the Properties, scroll down to the bottom and the static web site hosting. Enable it. Amazon will assign a http subdomain.

  • Go to AWS cloudfront to create a new distribute.



  • Check New distribution.

     




Monday, July 19, 2021

Where is URL for AWS serverless function?

To find the serverless function URL, it's in the API Gateway.



Isomorphic Application

What is Isomorphic Application?

Firstable, what is Isomorphic?
To be simple, that is to have the same result from different approaches.

In this case, we may easy to understand what is Isomorphic Application.
That could be an application with same results from different approaches.
One particular case for the web page is a web page generated from both client side and server side.

In the old days, server side technology to be used to generate a web page. That just has a lot of payload, like full HTML syntax, JS, and CSS. Search engine can understand that if content is all embedded inside HTML markup.

For the modern single page application (SPA), a big huge chunk of JS is loaded ahead of data. This is the way to minimum to payload and improve the user experience.

There are few of Isomorphic applications. The most popular for these days is React w/Next.


 

In Next, the first request page will be generated from the server side. In this case, search engine can understand page semantics. For the rest of clicking/action, the client side js is used in order to take advantage SPA. If any page refresh, once again the server rendering is triggered.



 




Sunday, July 18, 2021

VSCode react shortcut

Install React code snippets extension to VSCode.

rcc->  == class component skeleton
rsc->  == stateless component skeleton
rsf->  == stateless named function skeleton

React render props with typescript

Apply static type to props with typescript.


import React from 'react';
import './App.css';

interface SectionProps {
  titlestring;
  render(): React.ReactNode;
}

const RenderPropsComponentReact.FC<SectionProps> = (props=> {
  return (
    <section>
      <h2>{props.title}</h2>
      {props.render()}
    </section>
  )
}

const SampleRenderProps1React.FC = () => {
  return (
    <RenderPropsComponent
      title="First Component"
      render = {()=> {
        return (
          <p>
            My first description
          </p>
        )
      }}
    />
  )
}

const SampleRenderProps2React.FC = () => {
  return (
    <RenderPropsComponent
      title="Second Component"
      render = {()=> {
        return (
          <p>
            Another description
          </p>
        )
      }}
    />
  )
}

const AppReact.FC = () => {
  return (
    <div className="app">
      <h1>Render Props Example</h1>
      <SampleRenderProps1 />
      <SampleRenderProps2 />
    </div>
  );
}

export default App


Result:



Saturday, July 17, 2021

React-admin with typeORM

1. React-admin missing X-total-count issue.
Need to fix it from server side response header in order to meet react-admin requirement.

To fix it, add extra response header: Category.tsx

 // GET ALL
  @Get('')
  public async getAll() {
    //return getCategory();
    let objs = await getCategory();
    if (Array.isArray(objs)) {
      let total = objs.length;
      // react-admin
      this.setHeader('Access-Control-Expose-Headers''X-Total-Count')
      this.setHeader('X-Total-Count'total+"")
    }
    return objs;
  }

 

2. Unable to update data if primary id also submit from data. typeORM only take ID from URL parameter, not from data.

[1] GET /api/categories?_end=10&_order=ASC&_sort=id&_start=0 200 1.591 ms - 390
[1] Caught Validation Error for /api/categories/undefined: { categoryId: { message: 'invalid float number', value: 'undefined' } }
[1] GET /api/categories/undefined 422 0.702 ms - 176

To fix it, tailor the submission data: category.router.ts

export const CategoryEdit = (props:any=>{
    //typeORM doesn't like to have id in the submission data again.
    const transform = (data:any=> {
        const {id, ...newData} = data;
        return newData;
    };
    return (
        <Edit title="Edit Category" {...props} transform={transform}>
            <SimpleForm>
                <TextInput source="name" />
            </SimpleForm>
        </Edit>
    )
};




Sunday, July 11, 2021

Leetcode 125. valid palindrome

Solution 1. Just parse string into character array. Then, use another loop to compare the character with head to middle and tail to middle.

var isPalindrome = function(s) {

    // parse string into valid character array
    let tmp = [];
    s.split("").forEach(c=>{
        c = c.toLowerCase();
        if (c>="a" && c<="z") {
            tmp.push(c);
        } else if (c>="0" && c<="9") {
            tmp.push(c);
        }
    });

    // compare characters from head to middle and tail to middle
    let len = tmp.length;
    let [i,j] = [0,len-1];
    while (i < j) {
        if (tmp[i]!==tmp[j]) {
            return false;
        }
        i++;
        j--;
    }

    return true;
};


Solution 2. Optimize it. Only one while loop with one head index and the other tail index. That's the way to stand out.

var isPalindrome = function(s) {

    function getChar(c) {
        let ret = "";
        c = c.toLowerCase();
        if ( 
            (c >= "0" && c <= "9") ||
            (c >= "a" && c <= "z")
        ) {
            return c;
        }
        return ret;
    }

    let len =s.length;
    let [headIdxtailIdx] = [0len-1];
    let headChar="";
    let tailChar="";
    while (headIdx < tailIdx) {

        //a character from head, return blank charater if not valid
        if (headChar.length===0) {
            headChar = getChar(s[headIdx]);
        }
        //a character from tail
        if (tailChar.length===0) {
            tailChar = getChar(s[tailIdx]);
        }

        //check if both head chacter and tail character valid
        //then check they are equal
        if (
            headChar.length===1 &&
            tailChar.length===1
        ) {
            if (headChar===tailChar) {
                headChar = "";
                tailChar = "";
                headIdx++;
                tailIdx--;
            } else {
                return false;
            }
        } else {
            // if not a valid character, move to next index
            if (headChar.length===0) {
                headIdx++;
            }
            if (tailChar.length===0) {
                tailIdx--;
            }
        }
    }

    return true;
};

Friday, July 09, 2021

The link in gitbook

 When I put my bookstore project in gitbook, there were few links actually pointing back to my github project. I just curious how the markdown parser work in gitbook.


Today, I finally realize that gitbook take a link as same site reference only if this link in the left side menu. That's it need to be in SUMMARY.md.


Sunday, July 04, 2021

GraphQL Mutation Input

Without input type

  type Mutation {
    createCategory(name:String!):Category
    updateCategory(id:ID, name:String!):Category
    deleteCategory(id:ID):String

    createPublisher(name:String!):Publisher
    updatePublisher(id:ID, name:String!):Publisher
    deletePublisher(id:ID):String

    createAuthor(name:String!):Author
    updateAuthor(id:ID, firstName:String, lastName:String):Author
    deleteAuthor(id:ID):String

    createBook(title:String!, categoryId:String, publisherId:String, authorId:String):Book
    updateBook(id:ID, title:String!, categoryId:String, publisherId:String, authorId:String):Book
    deleteBook(id:ID):String
  }



With input type

  input CategoryInput {
    name:String!
  }
  input PublisherInput {
    name:String!
  }
  input AuthorInput {
    firstName:String
    lastName:String
  }
  input BookInput {
    title:String!
    categoryId:String
    publisherId:String
    authorId:String
  }
  type Mutation {
    createCategory(input:CategoryInput):Category
    updateCategory(id:ID, input:CategoryInput):Category
    deleteCategory(id:ID):String

    createPublisher(input:PubliserInput):Publisher
    updatePublisher(id:ID, input:PubliserInput):Publisher
    deletePublisher(id:ID):String

    createAuthor(input:AuthorInput):Author
    updateAuthor(id:ID, input:AuthorInput):Author
    deleteAuthor(id:ID):String
    
    createBook(input:BookInput):Book
    updateBook(id:ID, input:BookInput):Book
    deleteBook(id:ID):String
  }  



Correct the input foreign Key as type Int. They are categoryId, publisherId, authorId in BookInput.

 

  input BookInput {
    title:String!
    categoryId:Int
    publisherId:Int
    authorId:Int
  }

 



Friday, July 02, 2021

Flat list

arr = [[1,2,3],[4,5,6],[7,8,9]]

In javascript:

let flatList = arr.flat()


In python, my trick is walrus operator:

flat_list = []
[flat_list:=flat_list+sub for sub in arr]

 




Check if a value in two diminsion array

arr = [[1,2,3],[4,5,6],[7,8,9]] 

 For javascript: 

var result = 1 in arr.flat(); 

For python: 

var result = any(1 in sub for sub in arr);

Website thumbnail in my linkedin profile

 Just checked in linkedin profile today. And found my website thumbnail missing again.


Then double checked my gatsby source. That's fine.

I use linkedin link inspector: https://www.linkedin.com/post-inspector/inspect/
to check my website again : https://www.linkedin.com/post-inspector/inspect/https:%2F%2Fccapeng.github.io
I did get some warning, but my profile thumbnail shown again.