teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

回答の追加

2021/08/14 08:42

投稿

k_a
k_a

スコア983

answer CHANGED
@@ -23,4 +23,66 @@
23
23
  const hoge = await fuga()
24
24
  ...
25
25
  })
26
+ ```
27
+
28
+ ## 追記
29
+ `const allPostsData = fileNames.map(async (fileName) => {...})`のpromiseが解決できていません。
30
+ ※エラーハンドリングの追加と、関数の分割をしています。
31
+ ```
32
+ export async function getSortedPostsData() {
33
+ const url = 'https://api.github.com/repos/satorun082/article/contents'
34
+ let files
35
+ // Error Handling
36
+ try {
37
+ files = await requestGithubApi(url)
38
+ } catch (error) {
39
+ return [errorObject(error)]
40
+ }
41
+
42
+ const fileNames = files.map((file) => file.name)
43
+
44
+ // Get Posts Promises
45
+ const allPostsPromise = fileNames.map((fileName) => getPostsData(fileName))
46
+
47
+ // Resolve Posts Promises
48
+ const allPostsData = await Promise.all(allPostsPromise)
49
+
50
+ // Sort posts by date
51
+ return allPostsData.sort(({ date: a }, { date: b }) => {
52
+ if (a < b) return 1
53
+ if (a > b) return -1
54
+ return 0
55
+ })
56
+ }
57
+
58
+ async function requestGithubApi(url) {
59
+ const response = await fetch(url)
60
+ if (response.status != 200) throw new Error(response.statusText)
61
+ return await response.json()
62
+ }
63
+
64
+ async function getPostsData(fileName) {
65
+ // Remove ".md" from file name to get id
66
+ const id = fileName.replace(/.md$/, '')
67
+ const url = `https://api.github.com/repos/satorun082/article/contents/${id}.md`
68
+ let content
69
+ try {
70
+ content = await requestGithubApi(url)
71
+ } catch (error) {
72
+ return errorObject(error)
73
+ }
74
+
75
+ // Use gray-matter to parse the post metadata section
76
+ const matterResult = matter(base64.decode(content.content))
77
+
78
+ // Combine the data with the id
79
+ return {
80
+ id,
81
+ ...matterResult.data,
82
+ }
83
+ }
84
+
85
+ function errorObject(error) {
86
+ return { id: 'api error', date: '', title: error.message }
87
+ }
26
88
  ```