@@ -5,10 +5,10 @@ import Layout from '../components/Layout';
55import Content from '../components/Content' ;
66
77function Index ( props ) {
8- const { content } = props ;
8+ const { content, paths } = props ;
99 return (
1010 < div >
11- < Layout >
11+ < Layout paths = { paths } >
1212 < Content content = { content } />
1313 </ Layout >
1414 </ div >
@@ -17,23 +17,68 @@ function Index(props) {
1717
1818Index . propTypes = {
1919 content : PropTypes . string . isRequired ,
20+ paths : PropTypes . arrayOf ( PropTypes . string ) . isRequired ,
2021} ;
2122
23+ async function getPage ( path ) {
24+ const uri = `https://api.github.com/repos/codebru/markdown-test-repo/contents/${ path } ` ;
25+ const res = await Fetch ( uri ) ;
26+ const data = await res . json ( ) ;
27+ if ( ! Object . prototype . hasOwnProperty . call ( data , 'content' ) ) {
28+ if ( Object . prototype . hasOwnProperty . call ( data , 'message' ) ) {
29+ // Error possibly
30+ return data . message ;
31+ }
32+ return false ;
33+ }
34+ const contentMd = Buffer . from ( data . content , data . encoding ) . toString ( ) ;
35+ const contentHTML = Marked ( contentMd ) ;
36+ return contentHTML ;
37+ }
38+
39+ async function getDirectory ( path ) {
40+ try {
41+ const uri = `https://api.github.com/repos/codebru/markdown-test-repo/contents/${ path } ` ;
42+ const res = await Fetch ( uri ) ;
43+ const data = await res . json ( ) ;
44+ if ( ! data || ! Array . isArray ( data ) || ! Object . prototype . hasOwnProperty . call ( data [ 0 ] , 'path' ) ) {
45+ throw new Error ( 'Failed to fetch tree.' ) ;
46+ }
47+ const pathArray = data . map ( entry => entry . path ) ;
48+ return pathArray ;
49+ } catch ( e ) {
50+ return `Unable to get data: ${ e } ` ;
51+ }
52+ }
53+
2254Index . getInitialProps = async ( { query } ) => {
55+ let pathArray = [ ] ;
56+ let contentHTML = null ;
2357 let uri = null ;
58+ let uri2 = null ;
59+
2460 if ( query . pathName && query . pathName !== '/' ) {
2561 uri = query . pathName ;
2662 } else {
2763 uri = 'README.md' ;
2864 }
2965
30- uri = `https://raw.githubusercontent.com/codebru/full-web-dev/master/${ uri } ` ;
31- const res = await Fetch ( uri ) ;
32- const data = await res . text ( ) ;
33- const contentMd = data ;
34- const contentHTML = Marked ( contentMd ) ;
66+ contentHTML = await getPage ( uri ) ;
67+
68+ if ( ! contentHTML ) {
69+ // This means that the content is a DIR
70+ contentHTML = 'This is a directory' ;
71+ // Now get directory info from the same URI
72+ pathArray = await getDirectory ( uri ) ;
73+ } else {
74+ // Remove the file from the path so we can get the DIR
75+ uri2 = uri . lastIndexOf ( '/' ) + 1 ;
76+ uri2 = uri . substring ( 0 , uri2 ) ;
77+
78+ pathArray = await getDirectory ( uri2 ) ;
79+ }
3580
36- return { content : contentHTML } ;
81+ return { content : contentHTML , paths : pathArray } ;
3782} ;
3883
3984export default Index ;
0 commit comments