Be well coding/In Immersive
6/19 / server , RESTFUL API
be well
2019. 6. 19. 19:53
Toy 11번 문제.
배열에서 특정 타겟 탐색 with 시간복잡도.
ㄴ 시간복잡도를 가장 적게 해결하는 게 목표인 듯했다. 어떤 답이 효율적일지 모르겠지만 메소드를 사용한 내 코드도
TIme Complexity는 똑같이 잡아먹을 것 같다.
var rotatedArraySearch = function (rotated, target) {
// Your code here:
};
let result = [];
if(!rotated.includes(target)){
return null;
}
return rotated.indexOf(target)
}
onst fs = require('fs');
const fileName = __dirname + '/chat-log.json';
let chatLog = fs.readFileSync(fileName, 'utf8');
let parsedChatLog = JSON.parse(chatLog);
let messages = {
results : []
};
const requestHandler = function(request, response) {
const statusCode = 200;
const headers = defaultCorsHeaders;
headers['Content-Type'] = 'text/plain';
let body = [];
request.on('data',(chunk)=>{
body.push(chunk);
})
request.on('end',()=>{
if(request.method==='OPTIONS'){
response.writeHead(statusCode, headers);
response.end()
}
if(request.method==='GET'&&request.url==='/classes/messages'){
response.writeHead(statusCode, headers);
response.end(JSON.stringify(parsedChatLog))
}
if(request.method==='POST'&&request.url==='/classes/messages'){
response.writeHead(201, headers);
parsedChatLog.results.push(JSON.parse(body));
response.end(JSON.stringify(parsedChatLog))
fs.writeFileSync(fileName,JSON.stringify(parsedChatLog),'utf8')
}
else {
response.writeHead(404, headers);
response.end()
}
})
};
평소에 맨날 뒤쳐지다가 오늘은 운이 좋아서 advanced 까지 하나는 달성..
앞전에 했던 것 처럼 request 와 response 를 인자로 받는 서버에서 if 문을 통해 요청을 구분하고 요청에 따른 응답을 주었다.
OPTION 의 경우 접속 코드가 200일 경우 허용 . 응답으로 주는 값은 없다.
GET 의 경우 접속코드도 200이고 응답으로 쌓여있는 data 를 넘겨주었다.
POST 의 경우 요청으로 들어온 data 를 서버 data 저장하는 객체에 같이 저장해주었다.
* 클라이언트 - JSON - 서버 - JSON - 클라이언트
JSON 형식으로 data 를 넘겨줘야했다. 중간에 기존 data 가 저장된 객체에 넣어줄 때는 parse 를 통해 JSON 형식을 풀어서 추가해주었다.
+ fs File System 으로 간단한 write 와 read 를 사용해보았다.