7. Node 가계부 만들기 [ 유저 기능 (회원 가입) Service코드 작성 ] - 4

2022. 5. 28. 18:21프로젝트/가계부 - 제작 JavaScript

전송 포멧, 에러포멧 설명 https://crispypotato.tistory.com/211

사용 함수 설명 https://crispypotato.tistory.com/214

사용 repository 설명 : https://crispypotato.tistory.com/215

 

1. 아이디 찾기 /user/:id [ GET ]

설명

- 아이디 찾는 값을 params에서 가져오고

- users.repository.js IdFind()에 해당 유저가 존재 하는지 함수에 넣어서 확인한다.

- IdFind() 함수는 async라서 await를 사용해야한다.

 

결과

id가 존재 하지 않을 때는 * Send() 함수 [ 만들었던 전송포멧 ] 에 넣어 전송한다.

id가 존재 할 때는 409 에러를 발생시킨다.

//users.service.js

const httpError = require('http-errors')
const { IdFind } = require('./users.repository')
const { Send } = require('../../lib/lib')

const CheckUserId = async (req, res, next) => {
  try {
    const { id } = req.params
    const check = await IdFind(id)
    if (!check) {
      return Send(res, true)
    } else {
      throw httpError(409)
    }
  } catch (E) {
    next(E)
  }
}

 

2. 회원가입 /user/signup [ POST ]

설명

- body에서 id와 pwd 값을 가져온다.

- 아이디가 있는지 유효성 검사 [ IdFind() ]를 진행한다.

- 필수 함수로 salt값 생성 함수를 이용하여 salt값을 받는다

- 비밀번호를 hash값으로 만들기 위해 salt값과 비빌번호를 넣어 hash값을 가져온다

- 전달 받은 id와, 생성한 salt, password (hash값)을 회원가입 repository UserCreate함수에 넣어 생성한다.

 

결과

id가 존재 하지 않을 때는 아이디를 생성하고 * Send() 함수 [ 만들었던 전송포멧 ] 에 넣어 전송한다.

id가 존재 할 때는 409 에러를 발생시킨다.

//users.service.js

const httpError = require('http-errors')
const { IdFind, UserCreate } = require('./users.repository')
const { Send } = require('../../lib/lib')
const { Password, CreateSalt } = require('../../lib/lib')

const CreateUser = async (req, res, next) => {
  try {
    const { id, pwd } = req.body
    const userCheck = await IdFind(id)
    if (!userCheck) {
      const salt = CreateSalt()
      const password = Password({ pwd, salt })
      const result = await UserCreate({ id, password, salt })
      if (result) {
        return Send(res, '')
      } else {
        throw httpError(500)
      }
    } else {
      throw httpError(409)
    }
  } catch (E) {
    next(E)
  }
}

 

3. 최종 users.service.js

const httpError = require('http-errors')
const { IdFind, UserCreate } = require('./users.repository')
const { Send } = require('../../lib/lib')
const { Password, CreateSalt } = require('../../lib/lib')

const CheckUserId = async (req, res, next) => {
  try {
    const { id } = req.params
    const check = await IdFind(id)
    if (!check) {
      return Send(res, true)
    } else {
      throw httpError(409)
    }
  } catch (E) {
    next(E)
  }
}

const CreateUser = async (req, res, next) => {
  try {
    const { id, pwd } = req.body
    const userCheck = await IdFind(id)
    if (!userCheck) {
      const salt = CreateSalt()
      const password = Password({ pwd, salt })
      const result = await UserCreate({ id, password, salt })
      if (result) {
        return Send(res, '')
      } else {
        throw httpError(500)
      }
    } else {
      throw httpError(409)
    }
  } catch (E) {
    next(E)
  }
}

module.exports = { CheckUserId, CreateUser }
728x90
반응형