Javascript & Rest APIs notes

Ryu·2022년 5월 3일
0

2018-archive

목록 보기
2/2

2018년에 작성한 노트를 옮겨 놓은 페이지입니다.

Request URL and Body

Path Parameter (req.params)

  • URI에서 마치 web address인 것처럼 존재.

  • /rooms/201 : 여러개의 rooms 중에서 201호 하나.

    app.get('/rooms/:roomId', (req, res, next) => {
        resn.send(req.params.roomId);
    });
  • Best practice: Use Path Variable when you want to identify a resource

    /users/123  # Fetch a user who has id 123
  • Side effects: No need extra endpoint for CRUD

    /users [GET] # Fetch a list of users
    
    /users [POST] # Create new user
    
    /users/123 [PUT] # Update user
    
    /users/123 [DELETE] # remove user

Query Parameter (req.query)

  • URI에서 ?와 함께 등장.
  • /rooms?roomId=201
    app.get('/rooms', (req, res, next) => {
        resn.send(req.query.roomId);
    });
  • 쿼리는 URI의 맨 마지막에. 그러므로 Path처럼 logical depth를 표현하기 부적절할 수 있다.
  • Best practice: Use Query Variable when you want to sort for filter items
    /users?occupation=gamer  # Fetch a list of gamer user
  • "I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters."

Body

  • Form 데이터를 submit 하는 경우
  • Body에 roomId=201
    app.post('/rooms', (req, res, next) => {
        resn.send(req.body.roomId);
    });
  • Body parser 필요
  • Best practice: Use Request Body when the data gets too long (414 URI Too long)

Test

테스트 대상이 에러를 던질 경우

test('handle checkin without mandatory field should throw error', () => {
  function unfit(){  //테스트 대상을 감싸는 wrapper를 만든다
    handleCheckin(nonValid);
  }
  return expect(unfit).toThrow('Bad Request'); //해당 wrapper를 expect하고 에러메시지 비교. 에러오브젝트 따로 require하지 않아도 됨 

테스트 대상이 Promise를 뱉는 경우

resolves/rejects 를 사용하는 (편한) 방법과, then/catch를 사용하는 방법이 있다.
어느 경우든 반드시 BE SURE TO RETURN PROMISE

test('handleEvent without message should reject false', () => {
  return expect(handleEvent()).rejects.toBe(false); //테스트할 함수를 expect하고 resolves 혹은 rejects 검사
});

test('recordSwitch should call proper functions', () => {
  return handleEvent(fiasData)  //expect를 여러가지 할 경우에 사용. 꼭 return하기
    .then(result => {  //positive case일 때 then, negative case일 때 catch만 작성
      expect(result).toBe(true);
      expect(handleCheckin).toHaveBeenCalledWith(parsedData);
    });
});

테스트 대상이 try/catch인 경우

Test도 try/catch 구문을 따른다.

function handleFias(data) {
  try {
    const result = parseFias(data);  // throw1
    if (isSupported(result.recordId) && isValid(result)) {  //throw2 && throw3
      return result;
    }
  } catch (err) {
    debug(err.message);
    return false;
  }
}


test('when fields are missing', () => {
  try {
    expect(handleFias(testData);  // parseFias/isSupported/isValid에서 throw되는 데이터 테스트
  } catch (e) {
    expect(e).toBe('/^validationError/i');  // catch안에서 expect 가능
  }
});

Promise

Promise: 비동기 함수에서 성공과 실패 분리

콜백 함수: 에러 처리 힘들다

try {
  setTimeout(() => { throw 'Error!'; }, 1000);
} catch (e) {
  console.log('에러를 캐치하지 못한다..');
  console.log(e);
}

프로미스 생성, 실행

// 생성
const promise1 = function (param) {
	return new Promise( function(resolve, reject){
		if(param){
			resolve("hello");
		}
		else{
			reject("wolrd");
		}
	});
}
// 실행
promise1(true)
	.then( res => {console.log(res)})
    .catch( err => {console.log(err)});

프로미스 에러 처리 (초록: 성공, 빨강: 에러)

asyncThing1()
	.then(function() { return asyncThing();})
	.then(function() { return asyncThing3();})
    .catch(function(err) { return asyncRecovery1();})
 
    .then(function() { return asyncThing4();}, function(err) { return asyncRecovery2(); })
    .catch(function(err) { console.log("Don't worry about it");})
 
    .then(function() { console.log("All done!");});

여러 개 기다릴수도

Promise.all([promise1, promise2])
	.then( val => { console.log(val); });

Best practices

Best Practices for Designing a Pragmatic RESTful API

RESTful API Designing guidelines — The best practices

RESTful API Design. Best Practices in a Nutshell.

0개의 댓글