masto: add fetchStatus

* also add types RemoteServer and AccountKey
This commit is contained in:
thislight 2024-12-26 20:05:41 +08:00
parent 97bd6da9ac
commit 5ab0d4d0a2
No known key found for this signature in database
GPG key ID: FCFE5192241CCD4E
3 changed files with 68 additions and 2 deletions

View file

@ -6,10 +6,19 @@ import {
} from "masto";
import { createMastoClientFor } from "../masto/clients";
export type Account = {
export type RemoteServer = {
site: string;
accessToken: string;
};
export type AccountKey = RemoteServer & {
accessToken: string;
};
export function isAccountKey(object: RemoteServer): object is AccountKey {
return !!(object as Record<string, unknown>)["accessToken"];
}
export type Account = AccountKey & {
tokenType: string;
scope: string;
createdAt: number;
@ -17,6 +26,10 @@ export type Account = {
inf?: mastodon.v1.AccountCredentials;
};
export function isAccount(object: AccountKey) {
return !!(object as Record<string, unknown>)["tokenType"];
}
export const $accounts = persistentAtom<Account[]>("accounts", [], {
encode: JSON.stringify,
decode: JSON.parse,

23
src/masto/base.ts Normal file
View file

@ -0,0 +1,23 @@
import { createCacheBucket } from "~platform/cache";
export const cacheBucket = /* @__PURE__ */ createCacheBucket("mastodon");
export function toSmallCamelCase<T>(object: T) :T {
if (!object || typeof object !== "object") {
return object;
} else if (Array.isArray(object)) {
return object.map(toSmallCamelCase) as T
}
const result = {} as Record<keyof any, unknown>;
for (const k in object) {
const value = toSmallCamelCase(object[k])
const nk =
typeof k === "string"
? k.replace(/_(.)/g, (_, match) => match.toUpperCase())
: k;
result[nk] = value;
}
return result as T;
}

30
src/masto/statuses.ts Normal file
View file

@ -0,0 +1,30 @@
import { CachedFetch } from "~platform/cache";
import { cacheBucket, toSmallCamelCase } from "./base";
import {
isAccountKey,
type RemoteServer,
} from "../accounts/stores";
import type { mastodon } from "masto";
export const fetchStatus = /* @__PURE__ */ new CachedFetch(
cacheBucket,
(session: RemoteServer, id: string) => {
const headers = new Headers({
Accept: "application/json",
});
if (isAccountKey(session)) {
headers.set("Authorization", `Bearer ${session.accessToken}`);
}
return {
url: new URL(`./api/v1/statuses/${id}`, session.site).toString(),
headers,
};
},
async (response) => {
return toSmallCamelCase(
await response.json(),
) as unknown as mastodon.v1.Status;
},
);