回答編集履歴
1
回答の追加
test
CHANGED
@@ -49,3 +49,127 @@
|
|
49
49
|
})
|
50
50
|
|
51
51
|
```
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
## 追記
|
56
|
+
|
57
|
+
`const allPostsData = fileNames.map(async (fileName) => {...})`のpromiseが解決できていません。
|
58
|
+
|
59
|
+
※エラーハンドリングの追加と、関数の分割をしています。
|
60
|
+
|
61
|
+
```
|
62
|
+
|
63
|
+
export async function getSortedPostsData() {
|
64
|
+
|
65
|
+
const url = 'https://api.github.com/repos/satorun082/article/contents'
|
66
|
+
|
67
|
+
let files
|
68
|
+
|
69
|
+
// Error Handling
|
70
|
+
|
71
|
+
try {
|
72
|
+
|
73
|
+
files = await requestGithubApi(url)
|
74
|
+
|
75
|
+
} catch (error) {
|
76
|
+
|
77
|
+
return [errorObject(error)]
|
78
|
+
|
79
|
+
}
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
const fileNames = files.map((file) => file.name)
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
// Get Posts Promises
|
88
|
+
|
89
|
+
const allPostsPromise = fileNames.map((fileName) => getPostsData(fileName))
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
// Resolve Posts Promises
|
94
|
+
|
95
|
+
const allPostsData = await Promise.all(allPostsPromise)
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
// Sort posts by date
|
100
|
+
|
101
|
+
return allPostsData.sort(({ date: a }, { date: b }) => {
|
102
|
+
|
103
|
+
if (a < b) return 1
|
104
|
+
|
105
|
+
if (a > b) return -1
|
106
|
+
|
107
|
+
return 0
|
108
|
+
|
109
|
+
})
|
110
|
+
|
111
|
+
}
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
async function requestGithubApi(url) {
|
116
|
+
|
117
|
+
const response = await fetch(url)
|
118
|
+
|
119
|
+
if (response.status != 200) throw new Error(response.statusText)
|
120
|
+
|
121
|
+
return await response.json()
|
122
|
+
|
123
|
+
}
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
async function getPostsData(fileName) {
|
128
|
+
|
129
|
+
// Remove ".md" from file name to get id
|
130
|
+
|
131
|
+
const id = fileName.replace(/.md$/, '')
|
132
|
+
|
133
|
+
const url = `https://api.github.com/repos/satorun082/article/contents/${id}.md`
|
134
|
+
|
135
|
+
let content
|
136
|
+
|
137
|
+
try {
|
138
|
+
|
139
|
+
content = await requestGithubApi(url)
|
140
|
+
|
141
|
+
} catch (error) {
|
142
|
+
|
143
|
+
return errorObject(error)
|
144
|
+
|
145
|
+
}
|
146
|
+
|
147
|
+
|
148
|
+
|
149
|
+
// Use gray-matter to parse the post metadata section
|
150
|
+
|
151
|
+
const matterResult = matter(base64.decode(content.content))
|
152
|
+
|
153
|
+
|
154
|
+
|
155
|
+
// Combine the data with the id
|
156
|
+
|
157
|
+
return {
|
158
|
+
|
159
|
+
id,
|
160
|
+
|
161
|
+
...matterResult.data,
|
162
|
+
|
163
|
+
}
|
164
|
+
|
165
|
+
}
|
166
|
+
|
167
|
+
|
168
|
+
|
169
|
+
function errorObject(error) {
|
170
|
+
|
171
|
+
return { id: 'api error', date: '', title: error.message }
|
172
|
+
|
173
|
+
}
|
174
|
+
|
175
|
+
```
|