백엔드

패스트캠퍼스 챌린지 15일차 - 이미지 리사이징 서버

꾸준이 2021. 9. 20. 23:45

0.공부인증

공부 시작 22 : 15

공부 종료 23 : 45

 

 

1. GItHub 관리 CLI 만들기

https://www.npmjs.com/package/commander

 

commander

the complete solution for node.js command-line programs

www.npmjs.com

를 활용하여, Node 환경에서 쉽게 Commander 를 작성할 수 있도록하고,

https://www.npmjs.com/package/octokit

 

octokit

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno

www.npmjs.com

를 통해서는 Github 환경을 조작할 수 있음.

- 레파지토리를 만들거나 이슈를 만드는 작업 등.

 

2. Commander로 CLI 뼈대 만들기

// 입력한 커맨더들을 노드 프로그램에서 확인할 수 있음.
console.log(process.argv)

커맨더의 기초 사용법

 

* 우선 ch 13 14 는 지금 단계에서는 제가 접할 단계는 아닌 것 같아서 스킵했습니다.

 

2. RDB는 무엇인가.

- 스키마(테이블)와 각종 제약 조건을 정하고 그에 맞게 데이터를 저장하는 것.

- 대부분의 경우 SQL로 상호 작용함. (다른 RDB라고 할지라도 어느 정도 비슷한 언어를 사용함.)

 

ORM - Object-relational Mapping

- 데이터베이스의 테이블을 객체의 형태로 매핑해서 다룸.

 

 

3. Postgres 사용하기

https://www.postgresql.org/download/

 

PostgreSQL: Downloads

Downloads PostgreSQL Downloads PostgreSQL is available for download as ready-to-use packages or installers for various platforms, as well as a source code archive if you want to build it yourself. Packages and Installers Select your operating system family

www.postgresql.org

데이터 베이스 생성하기

CREATE DATABASE fc21

데이터 베이스 유저 생성하기

CREATE USER myuser WITH ENCRYPTED PASSWORD "mypass";

특정 유저에게 특정 데이터베이스의 특정 권한주기

GRANT ALL PREVILEGES ON DATABASE fc21 TO myuser;

 

4. 노드를 통해서 Postgres 접근하기

https://node-postgres.com/

 

Welcome

node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, streaming results, C/C++ bindings, rich type parsing, and

node-postgres.com

 

노드JS에서 Postgres에 접근하는 방법

const { Client } = require('pg')


const main = async () =>{
    const client = new Client({
        user : 'myuser',
        password : 'mypass',
        database : 'fc21',
    })
    await client.connect()
    const res = await client.query('SELECT $1::text as message', ['Hello world!'])
    console.log(res.rows[0].message) // Hello world!
    await client.end()
}

main()

CLI 환경에서 데이터베이스에 접근하기

psql -U myuser -d fc21 -h localhost --password

데이터베이스에 테이블만들기

CREATE TABLE users(id SERIAL PRIMARY KEY, name VARCHAR NOT NULL);

생성된 테이블에 값을 넣기

INSERT INTO users (name) VALUES ('Cocos');

저장된 값 불러오기

SELECT * FROM users

위의 내용을 노드에서 실행하기

- commander 와 prompts 활용하기

const { Client } = require('pg')
const program = require('commander')
const prompts = require('prompts')

async function connect(){
    const client = new Client({
        user : 'myuser',
        password : 'mypass',
        database : 'fc21',
    })
    await client.connect()
    return client
}

program.command('list').action(async () => {
	const client = await connect()
    const query = `SELECT * FROM users`
    
    const result = await client.query(query)
    console.log(result)

    
    await client.end()
})

program.command('add').action(async () => {
	const client = await connect()
    const userName = await prompts({
    	type : "text",
		name : "userName",
        message : "Provide a user name to insert"
    })
    
    const query = `INSERT INTO users (name) VALUES ('${userName.userName}')`
    await client.query(query)
    
    await client.end()
})

program.command('remove').action(async () => {
	const client = await connect()
    const userName = await prompts({
    	type : "text",
		name : "userName",
        message : "Provide a user name to delete"
    })
    
    const query = `DELETE FROM users WHERE name = ('${userName.userName}')`
    await client.query(query)
    
    await client.end()
})

program.parseAsync()

하지만,

SQL 인젝션이 가능한 부분들이 있음.

    // 해당 지점에서 SQL 인젝션이 가능한 지점.
    // `' OR '' = '`  >> 이런 인풋이 들어오면, 모든 파일이 삭제됨
    const query = `INSERT INTO users (name) VALUES ('${userName.userName}')`
    await client.query(query)

 

위에서 언급한 부분들이 내가 자주 사용하는 라이브러리들이 아니라서 익숙하지가 않았음.

다만, RDB에 대해서 한번은 제대로 공부해야겠다고 생각했음.

 

다음 강의에서 Sequelize 를 활용해서 RDB를 관리하는 방법이 있음.

 

그리고 GraphQL를 배운다고 한다.

여튼 그것을 이번 연휴에 빨리 공부해야겠다.

 

 

 

 

환급 챌린지 (15/30)

 

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #한번에끝내는Node.js웹프로그래밍초격차패키지