본문 바로가기

IT diary

Medium API를 사용하여 내 사이트로 글 가져오기

서론

Medium은  온라인 출판 플랫폼으로 시작하였다.

어려운 말을 붙일 필요 없이 그냥 블로그의 일종이라고 생각하면 편할 것같다. 

 

오늘은 이런 Medium의 특정 유저의 글을 올라올때마다 자동으로 반영하여 글을 가져와 내 사이트에 보여줄 수 있는

JS 코드에 대해 알아보고자 한다. 

 

본문에 들어가기에 앞서 본 글의 내용은 아래 사이트를 참고 하였다.

https://medium.com/@Jason_Matthew/display-medium-articles-on-your-site-d772b3b05779

 

Display Medium articles on your site.

For a while now I have been trying understand how I can best use medium and my own personal site together in harmony. Today I think I found…

medium.com

 

우선 완성본을 보자.

 

 

css를 적용하지 않아서 보기 불편한 페이지이긴 하나, 확실히 medium의 글을 가져온것이다. 

우리가 보는 medium의 페이지는 아래 링크이다.

 

https://medium.com/@WillOremus

 

Will Oremus – Medium

Read writing from Will Oremus on Medium. Senior Writer, OneZero, at Medium. Every day, Will Oremus and thousands of other voices read, write, and share important stories on Medium.

medium.com

이 사이트를 들어가보고 위의 캡쳐화면을 비교해보면 성공적으로 API를 사용한 것을 알 수 있다. 

 

본론

 

1. 소스코드

 

우선 html 코드를 작성한다.

 

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<head>
</head>
 
<body>
<div class="jsonContent" id="jsonContent" name="jsonContent">
</div>
 
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</body>
</html>
cs

 

해당 코드의 <div>부분에 medium의 컨텐츠들이 삽입되게 된다. 아래코드에 앞으로 id가 jsonContent인 div에 삽입할 것이므로 id 작성에 주의하길 바란다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<script type="text/javascript">
function getFormatDate(date){ 
var strArray = date.split('-');
strArray[2]=strArray[2].substring(0,2);
return strArray[0+ '.' + strArray[1+ '.'+strArray[2] ;
}
 
$(function () {
var $content = $('#jsonContent');
var data = {
rss_url: 'https://medium.com/feed/@WillOremus'
};
$.get('https://api.rss2json.com/v1/api.json', data, function (response) {
if (response.status == 'ok') {
//var output = '';
var output = '<h1>' + response.feed.title + '</h1>';
$.each(response.items, function (k, item) {
var visibleSm;
if(k < 3){
visibleSm = '';
else {
visibleSm = ' visible-sm';
}
output += '<div class="col-sm-6 col-md-4' + visibleSm + '">';
output += '<div class="blog-post"><header>';
 
//output += '<h4 class="date">' + item.pubDate + "</h4>";
output += '<h4 class="date">' + getFormatDate(item.pubDate)+"</h4>";
 
var tagIndex = item.description.indexOf('<img'); // Find where the img tag starts
var srcIndex = item.description.substring(tagIndex).indexOf('src='+ tagIndex; // Find where the src attribute starts
var srcStart = srcIndex + 5// Find where the actual image URL starts; 5 for the length of 'src="'
var srcEnd = item.description.substring(srcStart).indexOf('"'+ srcStart; // Find where the URL ends
var src = item.description.substring(srcStart, srcEnd); // Extract just the URL
 
output += '<div class="blog-element"><img class="img-responsive" src="' + src + '" width="360px" height="240px"></div></header>';
output += '<div class="blog-content"><h4><a href="'+ item.link + '">' + item.title + '</a></h4>';
output += '<div class="post-meta"><span>By ' + item.author + '</span></div>';
 
var yourString = item.description.replace(/<img[^>]*>/g,"");
var maxLength = 120 // maximum number of characters to extract
 
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
 
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
 
output += '<p>' + trimmedString + '...</p>';
output += '</div></div></div>';
 
return k < 5;
});
$content.html(output);
}
});
});
</script>
cs

다음으론 javascript부분을 작성한다.

위의 html코드에서 jquery를 삽입한 부분 아래에 위 코드를 작성한다.

 

2. 세부 설명

 

1
var $content = $('#jsonContent');
cs

 

이 js 변수의 값이 아까 설정한 div의 id 값이다. 혹시라도 다른 id로 div를 작성했다면 이 #jsonContnet 부분을 변경해라.

 

1
2
3
var data = {
rss_url: 'https://medium.com/feed/@WillOremus'
};
cs

 

data변수는 내가 가져올 medium 주소를 의미한다. @WillOremus 부분을 내가 원하는 페이지이름으로 변경하면 된다. 

여기서 중요한 점은 그냥 medium주소가 아니라 feed를 가져와야한다는 점이다.

 

1
2
3
4
var output = '<h1>' + response.feed.title + '</h1>';
 
output += '<div class="col-sm-6 col-md-4' + visibleSm + '">';
output += '<div class="blog-post"><header>';
cs

 

output 변수는 앞으로 jsonContent영역에 표기될 태그, 내용들을 담는다. 

태그는 ''으로 묶어줘야 제대로 동작한다. 원하는 class tag가 있다면 ''으로 묶어서 문자열 연결을 해준다.

 

1
return k < 5;
cs

 

return  부분의 k는 가져올 글의 개수를 의미하는 변수이다. 따라서 5보다 작은 경우인 현재엔 6개의 글을 가져온다.

k를 이용해서 가져온글에 번호를 붙일 수도 있다.

 

 

결론

 

코드를 똑같이 따라치고 세부 설명에 나와있는대로 변수값을 변경하면 아마 원하는 결과가 제대로 나올것이다.

그대로 사용하기엔 css가 없어서 부족한 부분이 있다. 값을 잘 가져오는 것에 의미를 가지고자한다.

이 글을 보게될 다른 분들은 css를 열심히 만들어서 예쁜 페이지를 만들길 바란다.

 

오타나 문의할 점은 댓글로 부탁드린다.