summaryrefslogtreecommitdiff
path: root/src/routes/api/mastodon.json/+server.ts
blob: 72cbd3812fe6bf070841387dcc77fbb2542e36a4 (plain) (blame)
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
/*** IMPORT ------------------------------------------- ***/

import { error, json } from "@sveltejs/kit";

/*** EXPORT ------------------------------------------- ***/

export const POST = async({ fetch }) => {
  try {
    const response = await fetch("https://social.coop/users/netopwibby/outbox?page=true", {
      headers: { "Content-Type": "application/json" },
      method: "GET"
    });

    const { orderedItems } = await response.json();
    const { object } = findCreateType(orderedItems);

    return json({
      created: object.published,
      content: object.content,
      link: object.url,
      media: processAttachments(object.attachment)
    });
  } catch(welp) {
    console.error(`Error fetching latest Mastodon post: ${String(welp)}`);
    return error(500);
  }
};

/*** HELPER ------------------------------------------- ***/

function findCreateType(arr: Array<{ [key: string]: any }>): { [key: string]: any } | undefined {
  return arr.find(obj => obj.type === "Create");
}

function processAttachments(attachments: Array<{ [key: string]: any }>): Array<string> {
  const media = [];

  if (attachments) {
    for (const attachment of attachments) {
      // TODO
      // : use blurhash given to us by mastodon
      // : https://github.com/woltapp/blurhash/tree/master/TypeScript#example
      // : `attachment` comes with blurhash, height, mediaType, width
      // if (attachment && attachment.url)

      // @ts-ignore | Argument of type "any" is not assignable to parameter of type "never".
      media.push(attachment.url);
    }
  }

  return media;
}