0%

GraphQL

  • more efficient
  • alternative to REST API
  • Not a Framework!
  • similar to router

REST

  • pattern, standard for APIs
  • interface that tells the external how to get the datas
  • have endpoints (e.g. ‘/messages’)
/teams/CH
send all the info

–> moduler
/teams/CH/info
/teams/CH/players
/teams/CH/matches

  • Query Language (Standard)

order also matches!

Implementation

  1. Schema
    • Types

id => unique
[]! => need [] type, you need to pass [] thing
team: Team! => team is related to type Team (Team: object)

  1. Resolvers
  • Scalar Types
    (Built-In)
  • Int
  • Float
  • String
  • Boolean
  • ID
    (Custom Scalar)
  • Date, Url, EmailAddress …
    id, name, age: primitive type
    team: object -> sub-doc. type => repeat the same process to find the type
  1. Queries & Mutations
    one single endpoint

-> perform queries

  • Sub-Selection
    pass the object to the type -> give the right interface of information of that object
  • have to ask the property of the object
  • Arguments

  • Variables

put “DEF” into $position var

      • fetching data - - -
        👇
      • change (mutate) data - - -
  • Mutations

  • another type of action like query that performs changes on the resources
  • diff is like GET - POST: doesn’t change anything in the server - change something in the server
    -> do st that doesn’t suppose to do, run semantic, perform changes by manipulating inside my DB
  1. create new data POST
  2. update existing data PUT
  3. delete existing data DELETE

name, position: response
1st: input type checking -> 2nd: actually executing the mutation

  • ID: created internally by the program
  • send the request to the root (4000-graphQL as the endpoint)
  • reliable, flexible
  • Execution
    search for syntax error

undefined height -> null, name ~ pass height ~ go inside team obj

  • Resolvers
    Schema: define, Resolver: interact => interplay to call server flexibly

get id:42 from upper example

  • obj : the previous resolved obj, parent element that has been previously resolved
  • args : the arguments object for the field in the query, include id .. all the args that we want to pass
  • context : shared object provided to every resolver, communicate and share information, later function can access to it (i.e. ctx in Koa)
  • info : extra information about the current query to mutate, etc.

Implementation

typeDefs: routers
resolvers: controllers

  • index.js

  • typeDefs.js

  • resolvers.js

not using obj => replace it with _
👇

  • resolvers.js

※ express / koa : REST API = apollo-server : gql

Web Components

Features

  1. Scoped
  2. Reusable
  3. Encapsulated

Made by 4 main technologies

  1. HTML Template
  2. Custom Elements
  3. Shadow DOM
  4. HTML Imports

Basic Web Components

  • Card Title
  • Component Title
1
2
3
4
5
<section class="card">
<div>
<h2>
<p>
</...>

👇

  1. reduce duplicated contents using…
    <product-card
    data-header=
    data-img=
    data-text=

  2. with JavaScript!

  • customElements : global variable
  • shadow, secret // outside world can’t get access to it
  • shadow DOM
    a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an HTML document in the case of web documents).
    ※ font-size => DON’T use px !!! USE rem

Progressive Web App (PWA)

  1. Reliable: download and work off-line
  • Service worker (downloads content-heavy web, use off-line)
  • Pre-caching
  1. Fast
  2. Engaging
  • No app store needed
  • Immersive full screen
  • Push Notifications
  • Chrome DevTools : Inspect -> LightHouse 이용!!

Advanced HTML - CSS

Everything is a BOX

Box-sizing

developer.mozilla.org/ko/docs/Web/CSS/box-sizing

  • border box : the way we calculate the box size is just a/c the content
    • { // * : everything
      box-sizing: border-box;
      }

Position

developer.mozilla.org/ko/docs/Web/CSS/position

CSS position 속성은 문서 상에 요소를 배치하는 방법을 지정합니다. top, right, bottom, left 속성이 요소를 배치할 최종 위치를 결정합니다.

  • position : static / relative / absolute / fixed
  • static: default
    요소를 일반적인 문서 흐름에 따라 배치합니다. top, right, bottom, left, z-index 속성이 아무런 영향도 주지 않습니다. 기본값입니다.

  • relative: have elements
    요소를 일반적인 문서 흐름에 따라 배치하고, 자기 자신을 기준으로 top, right, bottom, left의 값에 따라 오프셋을 적용합니다. 오프셋은 다른 요소에는 영향을 주지 않습니다. 따라서 페이지 레이아웃에서 요소가 차지하는 공간은 static일 때와 같습니다.

    • sticky:
      요소를 일반적인 문서 흐름에 따라 배치하고, 테이블 관련 요소를 포함해 가장 가까운, 스크롤 되는 조상과, 표 관련 요소를 포함한 컨테이닝 블록(가장 가까운 블록 레벨 조상) 을 기준으로 top, right, bottom, left의 값에 따라 오프셋을 적용합니다. 오프셋은 다른 요소에는 영향을 주지 않습니다.
      이 값은 항상 새로운 쌓임 맥락을 생성합니다. 끈끈한 요소는 “스크롤 동작”(overflow가 hidden, scroll, auto 혹은 overlay)이 존재하는 가장 가까운 조상에 달라붙으며, 사실 그 조상은 스크롤 불가하며 실제로 스크롤 가능한 조상이 따로 존재할 경우 “끈끈한” 동작을 보이지 않는 점에 주의하세요.
  • absolute: relative to its first position parent(e.g. body), not static, everything opposite to static
    not affected to the scrolling
    요소를 일반적인 문서 흐름에서 제거하고, 페이지 레이아웃에 공간도 배정하지 않습니다. 대신 가장 가까운 위치 지정 조상 요소에 대해 상대적으로 배치합니다. 단, 조상 중 위치 지정 요소가 없다면 초기 컨테이닝 블록을 기준으로 삼습니다. 최종 위치는 top, right, bottom, left 값이 지정합니다.

  • fixed: 스크롤을 하더라도 fixed된 top-left-right-bottom 위치에 고정
    요소를 일반적인 문서 흐름에서 제거하고, 페이지 레이아웃에 공간도 배정하지 않습니다. 대신 뷰포트의 초기 컨테이닝 블록을 기준으로 삼아 배치합니다. 단, 요소의 조상 중 하나가 transform, perspective, filter 속성 중 어느 하나라도 none이 아니라면 (CSS Transforms 명세 참조) 뷰포트 대신 그 조상을 컨테이닝 블록으로 삼습니다. (perspective와 filter의 경우 브라우저별로 결과가 다름에 유의) 최종 위치는 top, right, bottom, left 값이 지정합니다.

  • class => CSS, id => JavaScript

Display

  • display: block / inline / inline-block / dom / flex
  • block : vertical alignment, take as much as horizontal place they can
  • inline : take the CONTENT as horizontal alignment, ignore any width value
  • inline-block :
  1. Compared to ‘display: inline’, the major difference is that ‘display: inline-block’ allows to set a width and height on the element.
  2. Compared to display: block, the major difference is that display: inline-block does not add a line-break after the element, so the element can sit next to other elements.
  • dom : can check the dom (test) but not rendered inside the dom
  • flex (Flexbox) : This defines a flex container; inline or block depending on the given value. It enables a flex context for all its direct children.
    css-tricks.com/snippets/css/a-guide-to-flexbox/
    > start / center / space-between / space-around / space-evenly

developer.mozilla.org/en-US/docs/Web/CSS/justify-content

  • order : arbitrarily set the orders
    .box:first-child {
    order: 3
    }
    .box:last-child {
    order: 1
    }

Units

  • percentages / absolute
  • percentages
    • vw : Viewpoint Width
    • vh : Viewpoint Height
    • em : Relative to the font-size of the element (2em means 2 times the size of the current font)
    • rem : Relative to font-size of the root element
  • absolute
    • px : pixels
    • pt : 72pts = one inch

Z-index

control overlapping -> no need for static (which considers content layouts)

DIV num 따라 구조화 하고 -> DIV에 포함된 DIV의 z-index는 소수점으로 판단된다!
=> DIV
#1 : 5
#2: 2
#3: 4

  • #4: 4.6
  • #5: 4.1
  • #6: 4.3

Vendor Prefixes

  • webkit
    WebKit is a web browser engine used by browsers such as Safari and Chrome. You can make use of WebKit features such as animation, transform, transition, and more through the use of the -webkit prefix in your CSS

Transformations

Animations

@keyframes [name] {
}

Transition

:hover : not switch, interpolating

Responsive Web

Media queries

CSS Preprocessors

SASS

CSS with Super-power

LESS

CSSnext

CSS Frameworks

Bootstrap

Skeleton

Materialize

Bulma

Antd

NoSQL

Non-relational databases

  • don’t enforce a predeifend structure on data
  • main families are: document, key-value, and graph
  • offer a lot of flexibility, but less guarantees

Document Databases

  • document looks like JSON
  • don’t need constraints
  • id: automatically generated
  • each document can be represented as a row, BUT document is document inside the collection!
  • structured to store big data
  • mongoDB
  • faster than SQL

Key-Value Databases

key-value pair

  • faster than any other dbs
  • set as a pair and get right away
  • used for caching
  • Redis
    You can run atomic operations on these types, like appending to a string;incrementing the value in a hash; pushing an element to a list; computing set intersection, union and difference; or getting the member with highest ranking in a sorted set.

To achieve top performance, Redis works with an in-memory dataset. Depending on your use case, you can persist your data either by periodically dumping the dataset to disk or by appending each command to a disk-based log. You can also disable persistence if you just need a feature-rich, networked, in-memory cache.
Redis also supports asynchronous replication, with very fast non-blocking first synchronization, auto-reconnection with partial resynchronization on net split.

Graph Databases

  • arrow: who follows whom
  • similar to ASCII Art
  • graph structure: map, social network

Relational vs. Non-relational

Dimension Relational Non-relational
Schema Predefined Flexible
Scaling Vertical Horizontal
ACID Yes No guarantees

In database systems, ACID (Atomicity, Consistency, Isolation, Durability) refers to a standard set of properties that guarantee database transactions are processed reliably. ACID is especially concerned with how a database recovers from any failure that might occur while processing a transaction.

  • Non-relational => covers the relational databases’ constraints
    SQL: MySQL is a relational database management system (RDBMS) from the Oracle Corporation. Like other relational systems, MySQL stores data in tables and uses structured query language (SQL) for database access. When MySQL developers need to access data in an application, they merge data from multiple tables together in a process called a join. In MySQL, you predefine your database schema and set up rules to govern the relationships between fields in your tables.

NoSQL: MongoDB is a NoSQL database that stores data as JSON-like documents. Documents store related information together and use the MongoDB query language (MQL) for access. Fields can vary from document to document - there is no need to declare the structure of documents to the system, as documents are self-describing. Optionally, schema validation can be used to enforce data governance controls over each collection.

ORMS

Object Relational Mappings

Sequelize

model/user.js

not need to define model.js by ourselves

  • table not exists: create table/ exists: send the related table

models/task.js

connecting db with new Sequelize
.readditSync(__dirname) : return array of files in __dirname
// [index.js, task.js, user.js, .hide]
.filter(file => {
return (file.indexOf(‘.’) !== 0) && (file !== ‘index.js’) && (file.slice(-3) === ‘.js’);
// [task.js, user.js]
.forEach(file => {
const model = require(path.join(__dirname, file))
// create absolute path to the file
(sequelize, Sequelize.DataTypes);
// requiring models/task.js function
db[model.name] = model
// model: task / user
// each file will be the model object
db.sequelize = sequelize;
db.Sequelize = Sequelize;
// take the code and put it individually
// leave this code without changing anything in this file
module.exports = db
exports db with passing db

👇

index.js

  • set-up everything in the db perfectly and then connect to the client

router.js

not changed

controllers/user.js

models/user.js

models/task.js

— complete declare, now run —

models/index.js

mkcd [dir]
npm init -y
touch [index.js] [router.js]
npm i sequelize koa koa-router

create table

get the model : model/index.js, createStudent -> not view, create template with the data

get student by id, bodyparser -> router.post

* npm weekly downloads : >= 7M *

Database

  • piece of software, store and retrieve
  • similar to data.json()

Relational Databases

  • Primary Key
  • unique
  • ordered
  • can’t be null
  • Foreign Key
  • reference the primary key of other table

SQL

  • can use various types of tables
    e.g. B-tree …

SQL - Relations

  • One to many
  • Many to many
    Combine…
  • Many to one
  • one to Many
  • One to One

SQL - Queries

SELECT _ FROM _ WHERE _ : SELECT COL FROM TABLE WHERE CONDITION

  1. SELECT * FROM “Users”
  • *: everything
  1. SELECT “Email” FROM “Users” WHERE Id=7
  • Time Complexity
    approach table by index, not directly by primary key => O(n)
  • -> (because a primary key is ordered,) binary_search => O(logN)

SQL - Indexes

  1. SELECT “Email” FROM “Users” WHERE Email = “bill.gates@microsoft.com
  • Time Complexity
    approach table by checking each element => O(n)
  • -> set email as a primary key by adding a table and search in the original table using id as a reference key => O(2*logN)

SQL - Joins

Sharding and Replicating

Not good in developer stand, but for safety (backup)

  • Sharding : divide into half and put each one into different machines
  • Replicating : write the same data into different machines
    In case of sharding the data might be nicely distributed and hence the queries.
  • To “improve query” response on reading data, replication will help. You could write away to your primary and read from secondaries to distribute the queries. Also the primary then is relieved of the expensive reads, and can be busy with only writing.

In case of replicating existing shards, there will be more hosts to respond to a query request.

  • There is a some improvement with sharding if you choose a good shard key. Writing queries away ‘might’ be distributed if you do that correctly. The main reason for sharding is to “horizontally expand your database”. Working with big data, and not wanting to create/insert bigger and bigger disks … you can just create new servers next to it, as much as you want.

Async Patterns

  1. Callbacks

too complicated -> simplified in ES6

  1. Promises
    reduce too many handlings, make into clean code (sugar coding)

Promise -> invoke reject/ resolve as callbacks

then -> happen arg first and then ‘then’ method

  • resolve : when we find the answer
  • reject : st went wrong
  1. Async / Await
  • async === setTimeOut
  • await : pending promise/ valid answer from crypto.compare

☝️

callback functions are stacked
: first cb -> first wait + call the second stacked callback function
second cb -> second wait + third callback

✌️

nested callback functions
wait for set time and execute the next one

=> create new Promise and put setTimeOut in it, use resolve function

async
=> create asyn function, use await

print 1 time

  • async itself is just a normal function, but return the value as Promise

Koa

Search everything by ‘koa ~’

  • promise based -> always use ‘async’ !
  • app.use() : go to the next() middleware
  • express : req/res each send/receive info to/from the client
    koa : ctx controls everything, koa sends/receives the info all by itself, control everything related to the client

await next() -> call bodyParser -> call router -> call allowedMethods…
*** install packages needed !!

  • controller -> usually the end of the chain (next -> next -> … -> ctrl)
  • controller doesn’t send anything to the client (no res.send()) => app (koa obj) sends the info to the client after receiving everything from the chain of next & controller

response aliases : Not method!, just variables!

  • ctx.request.body -> approach the request of body

Pre-requisite

code . // vscode
npm init –y // npm initialise
touch index.js router.js controller.js // make files
npm i koa
@ npm i “koa pkg” // search!

index.js

middleware ( 1 -> 2 -> 3 ) -> router: doorman –> controller: manager)

  • app.use(router) : always the last, right before to the controller

set the middleware next(), which is the ‘router.routes()’ in this case

router.js

const Router = require(‘koa-router’)

controller.js

get the id as params.id

  • all the vars sent via the address are saved in the ctx.request.params!
    e.g. /:name/:id –> ctx.request.params.name, ctx.request.params.id

  • Linux ‘/‘ path

  • GET / POST
    adrian0220.tistory.com/209

Error Handling

try {// something that might go wrong} catch (e) {// handle error}

MVC

model: starting making logics from here
controller: conductor of orchestra, router
receive the request
the only part to communicate with the outside part
coming to the controller
sending from the controller
knowing who to call and packages the content, send it to the outside
view: html structure filled in template with no data
send the filled template back to the controller
.gitignore : files to be ignored when creating a repo

npm handle-bars
programmingsummaries.tistory.com/381

Back-end Frameworks

Back-end

executed on server

Front-end

executed on clinet (browser, mobile, tablet…)

Web server

software on the physical machine (hardware)

Node JS

  • server side javascript
    • interact with file (operating) systems
    • FIFO
    • time difference: 1sec ~ 28hours
  • non-blocking === asynchronous Input/Output
    • allows other operation on the other side
    • delegate to someone something and do other stuff => higher efficiency
    • multi-threads (JS: single-thread) : e.g. one looking for the answer / one doing help request
  • allows to use the same language on client and server

Npm

  • npm init
    • initialise the packages
  • package . json
    • list all dependencies
  • npm install / uninstall (–save-dev)
  • npm publish
    • create lib -> give authority as an open source
  • weekly download counts
  • last publish (updated) version

Async

Sync: fs 설정 시 다른 scope에서도 접근 가능하지만
Async: fs 안에서만 data 접근 가능, 밖 scope에서 접근 불가

HTTP

msg sending to client: “Hello World”

Modules

  • Node.js: common js Module
  • Module: object
  • require: read exports and take object’s properties in it, assign to the variable which is reading the require, follow the execution in the file
  • module.exports : what the file does/ passes

touch: create file
nodemon: watches the file, automatically restart (reload, update) the file

Networking

Protocol

  1. Data formats
    e.g. language
  2. Address formats
    e.g. location
  3. Routing
  4. Acknowledgements and Errors

IP addresses and ports

  • IPV4: 32 bits, 4 groups of 8 bits(0~256), 2^32 combinations
  • IPV6: 128 bits, 16 groups of 8 bits, 2^128 combinations
  • Port range: 0-65535 (first 1023 reserved)

e.g. IPV4- 192.168.0.4:3000
IPV6- [2001:0db8:85a3:0000:0000:8a2e:0370:7334]:3000

LAN and WAN

make connection
LAN: office, wifi
-> internal (private IP address) ->
WAN: extended envir

Data serialization and transport

breakdown the data into chunks, called packets
protocol controls which packet to deliver

URL

scheme://host[:prt]/path[?query#fragment] => key-value pairs
e.g. https://(ip)218.24.0.93:443 or (address)mydomain.com/recipes?unit=metric&ingredients=bananas

DNS

Domain Name System
receives queries, give corresponding address

HTTP(s)

Hyper-Tags Transfer Protocol

  • HTTPs -> safer
  • Request / Response
    • server can’t initiate request, only client can initiate
  • Stateless
    • protocol(http) doesn’t remember any information, server and client do

REST API & Methods

Representational State Transfer
http://server/entities(messages, topics, hosts, …)

  • indicated (pre-defined) methods to know what to do with entities
  • attached to the header of packets
  • GET
    • only the safe method, not changing anything
  • POST
  • PUT
  • DELETE
  • more…

important to receive good response to smoothly communicate —>

Status Codes

1xx: Hold on
2xx: Here you go
e.g. 201: created(posted) successfully
3xx: Go away
4xx: You fucked up (syntax / fulfilled)
e.g. 404: not found
5xx: I fucked up

en.wikipedia.org/wiki/List_of_HTTP_status_codes
List of HTTP status codes - Wikipedia
From Wikipedia, the free encyclopedia Jump to navigation Jump to search Response codes of the Hypertext Transfer Protocol This is a list of Hypertext Transfer Protocol (HTTP) response status codes. Status codes are issued by a server in response to a clien
en.wikipedia.org

Ajax

setting the origin (server) of the client
request: carrying around the data to send and receive
cb: callback -> assign function, passing the function to the API and api returns the data
e.g. cb = fcName

  • shouldn’t access the WAPI as it would be from a different origin
    but ok if we do it using a script —>
    • security check if it’s done indirectly

JSONP

update the scripts (.js)

callback the function and run the code: callback -> displayWeather func -> put data as an arg

CORS

Client Origin Resource Sharing
each server can decide whether to accept the JSON callback from client or not
give right (bypass the inability) to access third party APIs

  1. preflight request -> decide allow or not
  2. main request

WebSockets

WebRTC

Real Time Communication
WebRTC 는 웹 브라우저 간에 플러그인의 도움 없이 서로 통신할 수 있도록 설계된 API이다.
e.g. chatroulette

: Chatroulette is an online chatwebsite that pairs random users for webcam-based conversations. Visitors to the website begin an online chat (text, audio, and video) with another visitor. At any point, either user may leave the current chat by initiating another random connection.