11const axios = require ( 'axios' ) ;
2- const { PostQuery } = require ( './query' ) ;
2+ const { join } = require ( 'path' ) ;
3+ const fs = require ( 'fs' ) . promises ;
4+
5+ const { PostsQuery, PostQuery } = require ( './query' ) ;
36
47class Crawler {
58 constructor ( username ) {
69 this . username = username ;
10+
711 this . __grahpqlURL = 'https://v2.velog.io/graphql' ;
812 }
913
1014 async parse ( ) {
1115 const posts = await this . getPosts ( ) ;
16+
17+ posts . map ( async ( postInfo , i ) => {
18+ const post = await this . getPost ( postInfo . url_slug ) ;
19+
20+ await this . writePost ( post ) ;
21+ console . log ( `✅ " ${ post . title } " 백업 (${ i + 1 } /${ posts . length } )` ) ;
22+ } ) ;
23+
1224 }
1325
1426 async getPosts ( ) {
@@ -27,18 +39,46 @@ class Crawler {
2739 }
2840
2941 try {
30- response = await axios . post ( this . __grahpqlURL , PostQuery ( this . username ) ) ;
42+ response = await axios . post ( this . __grahpqlURL , PostsQuery ( this . username ) ) ;
3143 } catch ( e ) {
32- console . error ( `⚠️ 벨로그에서 글을 가져오는데 실패했습니다. \n error = ${ e } ` ) ;
44+ console . error ( `⚠️ 벨로그에서 글 목록을 가져오는데 실패했습니다. \n error = ${ e } ` ) ;
3345 process . exit ( 1 ) ;
3446 }
3547
3648 const posts = response . data . data . posts ;
3749
3850 console . log ( `✅ ${ this . username } 님의 모든 글(${ posts . length } 개) 을 가져옴` ) ;
3951
40- return response . data ;
52+ return posts ;
4153 }
54+
55+ async getPost ( url_slug ) {
56+ let response ;
57+
58+ try {
59+ response = await axios . post ( this . __grahpqlURL , PostQuery ( this . username , url_slug ) ) ;
60+ } catch ( e ) {
61+ console . error ( `⚠️ 벨로그에서 글을 가져오는데 실패했습니다. \n error = ${ e } ` ) ;
62+ process . exit ( 1 ) ;
63+ }
64+
65+ return response . data . data . post ;
66+ }
67+
68+ async writePost ( post ) {
69+ const path = join ( './backup' , `${ post . title } .md` ) ;
70+
71+ post . body = '---\n'
72+ + `title: "${ post . title } "\n`
73+ + `description: "${ post . short_description . replace ( / \n / g, ' ' ) } "\n`
74+ + `date: ${ post . released_at } \n`
75+ + `tags: ${ JSON . stringify ( post . tags ) } \n`
76+ + '---\n' + post . body ;
77+
78+ await fs . writeFile ( path , post . body , 'utf8' ) ;
79+ }
80+
81+
4282} ;
4383
4484module . exports = Crawler ;
0 commit comments