refactor: use link preview from nostr-services api

This commit is contained in:
Kieran 2024-01-15 11:16:28 +00:00
parent ad79091356
commit 21d7df0eac
Signed by: Kieran
GPG Key ID: DE71CEB3925BE941
4 changed files with 59 additions and 13 deletions

View File

@ -5,11 +5,11 @@ import { LRUCache } from "typescript-lru-cache";
import { MediaElement } from "@/Components/Embed/MediaElement";
import Spinner from "@/Components/Icons/Spinner";
import SnortApi, { LinkPreviewData } from "@/External/SnortApi";
import { LinkPreviewData, NostrServices } from "@/External/NostrServices";
import useImgProxy from "@/Hooks/useImgProxy";
async function fetchUrlPreviewInfo(url: string) {
const api = new SnortApi();
const api = new NostrServices("https://nostr.api.v0l.io");
try {
return await api.linkPreview(url.endsWith(")") ? url.slice(0, -1) : url);
} catch (e) {

View File

@ -0,0 +1,19 @@
import { JsonApi } from ".";
export interface LinkPreviewData {
title?: string;
description?: string;
image?: string;
og_tags?: Array<[name: string, value: string]>;
}
export class NostrServices extends JsonApi {
constructor(readonly url: string) {
super();
url = url.endsWith("/") ? url.slice(0, -1) : url;
}
linkPreview(url: string) {
return this.getJson<LinkPreviewData>(`/api/v1/preview?url=${encodeURIComponent(url)}`);
}
}

View File

@ -43,13 +43,6 @@ export class SubscriptionError extends Error {
}
}
export interface LinkPreviewData {
title?: string;
description?: string;
image?: string;
og_tags?: Array<[name: string, value: string]>;
}
export interface PushNotifications {
endpoint: string;
p256dh: string;
@ -119,10 +112,6 @@ export default class SnortApi {
return this.#getJsonAuthd<Array<Subscription>>("api/v1/subscription");
}
linkPreview(url: string) {
return this.#getJson<LinkPreviewData>(`api/v1/preview?url=${encodeURIComponent(url)}`);
}
onChainDonation() {
return this.#getJson<{ address: string }>("p/on-chain");
}

View File

@ -1,2 +1,40 @@
import { throwIfOffline, unwrap } from "@snort/shared";
export * from "./NostrBand";
export * from "./SemisolDev";
export abstract class JsonApi {
abstract url: string;
protected async getJson<T>(
path: string,
method?: "GET" | string,
body?: object,
headers?: { [key: string]: string },
): Promise<T> {
throwIfOffline();
const rsp = await fetch(`${this.url}${path}`, {
method: method,
body: body ? JSON.stringify(body) : undefined,
headers: {
accept: "application/json",
...(body ? { "content-type": "application/json" } : {}),
...headers,
},
});
if (rsp.ok) {
const text = (await rsp.text()) as string | null;
if ((text?.length ?? 0) > 0) {
const obj = JSON.parse(unwrap(text));
if ("error" in obj) {
throw new Error(obj.error, obj.code);
}
return obj as T;
} else {
return {} as T;
}
} else {
throw new Error("Invalid response");
}
}
}