Skip to content

Commit d3b50a5

Browse files
committed
✨ Implement wrappers of /api/embed-text/twitter
1 parent acb4707 commit d3b50a5

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

rest/getTweetInfo.ts

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import type {
2+
BadRequestError,
3+
InvalidURLError,
4+
SessionError,
5+
TweetInfo,
6+
} from "../deps/scrapbox.ts";
7+
import { cookie, getCSRFToken } from "./auth.ts";
8+
import { UnexpectedResponseError } from "./error.ts";
9+
import { tryToErrorLike } from "../is.ts";
10+
import { ExtendedOptions, Result, setDefaults } from "./util.ts";
11+
12+
/** 指定したTweetの情報を取得する
13+
*
14+
* @param url 取得したいTweetのURL
15+
* @param init connect.sidなど
16+
* @return tweetの中身とか
17+
*/
18+
export const getTweetInfo = async (
19+
url: string | URL,
20+
init?: ExtendedOptions,
21+
): Promise<
22+
Result<
23+
TweetInfo,
24+
| SessionError
25+
| InvalidURLError
26+
| BadRequestError
27+
>
28+
> => {
29+
const { sid, hostName, fetch, csrf } = setDefaults(init ?? {});
30+
const path = `https://${hostName}/api/embed-text/twitter?url=${
31+
encodeURIComponent(url.toString())
32+
}`;
33+
34+
const res = await fetch(
35+
path,
36+
{
37+
method: "POST",
38+
headers: {
39+
"Content-Type": "application/json;charset=utf-8",
40+
"X-CSRF-TOKEN": csrf ?? await getCSRFToken(init),
41+
...(sid ? { Cookie: cookie(sid) } : {}),
42+
},
43+
body: JSON.stringify({ timeout: 3000 }),
44+
},
45+
);
46+
47+
if (!res.ok) {
48+
if (res.status === 422) {
49+
return {
50+
ok: false,
51+
value: {
52+
name: "InvalidURLError",
53+
message: (await res.json()).message as string,
54+
},
55+
};
56+
}
57+
const text = await res.json();
58+
const value = tryToErrorLike(text);
59+
if (!value) {
60+
throw new UnexpectedResponseError({
61+
path: new URL(path),
62+
...res,
63+
body: await res.text(),
64+
});
65+
}
66+
return {
67+
ok: false,
68+
value: value as
69+
| SessionError
70+
| BadRequestError,
71+
};
72+
}
73+
74+
const tweet = (await res.json()) as TweetInfo;
75+
return { ok: true, value: tweet };
76+
};

0 commit comments

Comments
 (0)