-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathdiscourse.ts
72 lines (70 loc) · 2.32 KB
/
discourse.ts
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
namespace pxt.discourse {
interface DiscoursePostResponse {
featured_link?: string;
post_stream?: DiscoursePostStream;
}
interface DiscoursePostStream {
posts?: DiscoursePost[];
}
interface DiscoursePost {
link_counts?: DiscourseLinkCount[];
}
interface DiscourseLinkCount {
url?: string;
}
interface TagTopic {
id: string;
title: string;
image_url: string;
slug: string;
views: number;
like_count: number;
posters: {
user_id: string;
}[];
}
interface TagUser {
id: number;
username: string;
name: string;
avatar_template: string;
}
interface TagsResponse {
users: TagUser[];
topic_list: {
topics: TagTopic[];
}
}
export function extractSharedIdFromPostUrl(url: string): Promise<string> {
// https://docs.discourse.org/#tag/Posts%2Fpaths%2F~1posts~1%7Bid%7D.json%2Fget
return pxt.Util.httpGetJsonAsync(url + ".json")
.then((json: DiscoursePostResponse) => {
// extract from post_stream
let projectId = json.post_stream
&& json.post_stream.posts
&& json.post_stream.posts[0]
&& json.post_stream.posts[0].link_counts
.map(link => pxt.Cloud.parseScriptId(link.url))
.filter(id => !!id)[0];
return projectId;
});
}
export function topicsByTag(apiUrl: string, tag: string): Promise<pxt.CodeCard[]> {
apiUrl = apiUrl.replace(/\/$/, '');
const q = `${apiUrl}/tag/${tag}.json`;
return pxt.Util.httpGetJsonAsync(q)
.then((json: TagsResponse) => {
const users = pxt.Util.toDictionary(json.users, u => u.id.toString());
return json.topic_list.topics.map(t => {
return <pxt.CodeCard>{
id: t.id,
title: t.title,
url: `${apiUrl}/t/${t.slug}/${t.id}`,
imageUrl: t.image_url,
author: users[t.posters[0].user_id].username,
cardType: "forumUrl"
}
});
});
}
}