Today I Learend 8일차

유승완·2022년 5월 16일
0

Today I Learned

목록 보기
2/11
const http = require('http')

/**
 * @typedef Post
 * @property {string} id
 * @property {string} title
 * @property {string} content
 */

/** @type {Post[]} */
const posts = [
  {
    id: 'my_first_post',
    title: 'My first post',
    content: 'Hello!',
  },
  {
    id: 'my_second_post',
    title: 'My second post',
    content: 'Second post!',
  },
]

/**
 * Post
 *
 * GET / posts
 * GET /posts/:id
 * POST /posts
 */

const server = http.createServer((req, res) => {
  const POST_ID_REGEX = /^\/posts\/([a-zA-Z0-9-_]+)$/
  const postIdRegexResult =
    (req.url && POST_ID_REGEX.exec(req.url)) || undefined

  if (req.url === '/posts' && req.method === 'GET') {
    const result = {
      posts: posts.map((post) => ({
        id: post.id,
        title: post.title,
      })),
      totalCount: posts.length,
    }
    res.statusCode = 200
    res.setHeader('Content-Type', 'application/json; encoding=utf-8')
    res.end(JSON.stringify(result))
  } else if (postIdRegexResult && req.method === 'GET') {
    // GET /posts/:id
    const postId = postIdRegexResult[1]
    const post = posts.find((_post) => _post.id === postId)

    if (post) {
      res.statusCode = 200
      res.setHeader('Content-Type', 'application/json; encoding=utf-8')
      res.end(JSON.stringify(post))
    } else {
      res.statusCode = 404
      res.end('Post not found.')
    }
  } else if (req.url === '/posts' && req.method === 'POST') {
    req.setEncoding('utf-8')
    req.on('data', (data) => {
      /**
       * @typedef CreatePostBody
       * @property {string} title
       * @property {string} content
       * */

      /** @type {CreatePostBody} */
      const body = JSON.parse(data)
      console.log(body)
      posts.push({
        id: body.title.toLowerCase().replace(/\s/g, '_'),
        title: body.title,
        content: body.content,
      })
    })

    res.statusCode = 200
    res.end('Creating post')
  } else {
    res.statusCode = 404
    res.end('Not found.')
  }
})

const PORT = 4000

server.listen(PORT, () => {
  console.log(`The server is listening at port: ${PORT}`)
})

Node 입문, 강의듣고 이해하려 노력하면서 따라 코딩을 했는데 아직 많이 버겁다.
그래도 내용에 대해선 이해가 대부분 된거같은데, 문법들이나 Typescript을 활용해서 주석으로 타입 정의하는부분은 아주 낯설다.

오늘 알고리즘 공부하는 데 자바스크립트에서
String + Number = String 인 것은 알았었는데,
String * Number = Number 인 것은 처음알았다. 나름 요긴하게 쓸거같다.(알고리즘 푸는데 있어서는)

let, const, var
const 재선언,재할당 모두 불가
var 재선언,재할당 모두 가능
let 재선언 불가, 재할당 가능
대부분의 경우 const사용, 필요한경우에 한해 let사용, var는 쓰지 않는다!

profile
나를 위한 기록

0개의 댓글