2018년에 작성한 노트를 옮겨 놓은 페이지입니다.
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
app.get('/rooms', (req, res, next) => {
resn.send(req.query.roomId);
});
/users?occupation=gamer # Fetch a list of gamer user
app.post('/rooms', (req, res, next) => {
resn.send(req.body.roomId);
});
test('handle checkin without mandatory field should throw error', () => {
function unfit(){ //테스트 대상을 감싸는 wrapper를 만든다
handleCheckin(nonValid);
}
return expect(unfit).toThrow('Bad Request'); //해당 wrapper를 expect하고 에러메시지 비교. 에러오브젝트 따로 require하지 않아도 됨
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);
});
});
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: 비동기 함수에서 성공과 실패 분리
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 for Designing a Pragmatic RESTful API