DAY09

yejichoi·2022년 11월 21일
0

CodeCamp

목록 보기
11/11
post-thumbnail

1. Algorithm Study

자연수 뒤집어 배열로 만들기
자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.

// Reference Code ( for )
function solution(n) {
    const answer = [];
    // 숫자 타입의 데이터를 문자열 타입으로 변환
    n = String(n);
    
    // 최초식 : n의 length 값이 5를 가지면, 최초식의 인덱스 값은 4부터 
    // 조건식 : 인덱스의 0번째 까지 ( 0번째를 포함 )
    for( let i = n.length - 1; i >= 0; i-- ) { //마지막부터 넣어주기
        answer.push( Number(n[i]) )
    }
    
    return answer;
}
//Reference Code ( for : reverse 사용 )
function solution(n) {
    const answer = [];
    // 숫자 타입의 데이터를 문자열 타입으로 변환
    n = String(n);

    for( let i = 0; i < n.length; i++ ) {
        answer.push( Number(n[i]) )
    }
		answer.reverse();
    
    return answer;
}
//Reference Code ( map ) 
function solution(n) {
    let answer = String(n)
                   .split("")
                   .reverse()
                   .map( el => {
                        return Number( el )
                   })
    return answer;
}

나누어 떨어지는 숫자 배열
array의 각 element 중 divisor로 나누어 떨어지는 값을 오름차순으로 정렬한 배열을 반환하는 함수, solution을 작성해주세요.
divisor로 나누어 떨어지는 element가 하나도 없다면 배열에 -1을 담아 반환하세요.

//Reference Code ( for )
function solution(arr, divisor) {
    const answer = [];
    
    for( let i = 0; i < arr.length; i++ ) {
        if( arr[i] % divisor === 0 ) {
            answer.push( arr[i] );
        }
    }
        
    return answer.length === 0 //element가 하나도 없다면 즉, 길이가 0
        ? [-1]
        : answer.sort( (a, b) => a - b )
}
//Reference Code ( filter )
function solution(arr, divisor) {
    const answer = arr.filter( num => {
        return num % divisor === 0
    })
    
    return answer.length === 0
        ? [-1]
        : answer.sort( (a, b) => a - b )
}

2. Backend Class

ODM

Model

// board.model.js

import mongoose from 'mongoose'

const BoardSchema = new mongoose.Schema({
    writer: String,
    title: String,
    contents: String
})

export const Board = mongoose.model("Board", BoardSchema)

model() 메소드를 사용하여 문자열과 schema를 전달하여 model을 생성
첫번째 인자는 해당 collection의 단수적 표현을 나타내는 문자열

GET 조회

// index.js

import { Board } from './models/board.model.js'

const app = express()
app.use(cors())
app.use(express.json())
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerJsdoc(options)));
app.get('/boards', async (req, res) => {
  // 1. 데이터를 조회하는 로직 => DB에 접속해서 데이터 꺼내오기
  // const result = [
  //   { number: 1, writer: "철수", title: "제목입니다~~", contents: "내용이에요@@@" },
  //   { number: 2, writer: "영희", title: "영희 제목입니다~~", contents: "영희 내용이에요@@@" },
  //   { number: 3, writer: "훈이", title: "훈이 제목입니다~~", contents: "훈이 내용이에요@@@" },
  // ]
  const result = await Board.find()

  // 2. 꺼내온 결과 응답 주기
  res.send(result)
})

find는 보통 모든 데이터를 조회할 때 사용되며, findOne 은 특정 데이터만 조회할 때 자주 사용

POST 데이터 등록

//index.js

app.post('/boards', async (req, res) => {
  console.log(req.body);

  // 1. 데이터를 등록하는 로직 => DB에 접속해서 데이터 저장하기
  const board = new Board({
    writer: req.body.writer,
    title: req.body.title,
    contents: req.body.contents,
  });
  await board.save();

  // 2. 저장 결과 응답 주기
  res.send('게시물 등록에 성공하였습니다!!');
});

Scraping

다른 사이트 정보를 한 번만 가져옴
=> 포스트맨, axios로 받아오기

The Open Graph protocol
페이스북에서 시작해서 유명해진 것으로,
아래의 정보들을 htmlhead 안에 meta 태그로 넣어줍니다.
og:title - The title of your object as it should appear within the graph, e.g., "The Rock".
og:type - The type of your object, e.g., "video.movie". Depending on the type you specify, other properties may also be required.
og:image - An image URL which should represent your object within the graph.
og:url - The canonical URL of your object that will be used as its permanent ID in the graph, e.g., "https://www.imdb.com/title/tt0117500/".

Crawling

스크래핑을 정기적으로 주기적으로 여러번하는 것

Cheerio

데이터를 뽑을 때 알고리즘을 만들어 뽑아내어 저장을 해줘야하는데, 이 과정을 쉽게끔 도와주는 라이브러리

// cheerio docs 를 참고 
// 3. 스크래핑 결과에서 OG(오픈그래프) 코드 골라내서 변수에 저장하기
  const $ = cheerio.load(result.data);
	// meta 태그들만 찾아서 가져오고, 각각 마다 돌면서 콜백 함수를 실행
  $("meta").each((_, el) => {
    if ($(el).attr("property")) {
      const key = $(el).attr("property").split(":")[1];
      const value = $(el).attr("content");
      console.log(key, value);
    }
  });

3. HW

0개의 댓글