From 2ccef4e28c5bb261d93c0459e578f0e99ff58b3f Mon Sep 17 00:00:00 2001 From: Sugui Date: Sat, 30 Mar 2024 12:58:22 +0100 Subject: [PATCH] Added base64 encoding for image content --- src/services/ImageService.ts | 16 ++++++++++++---- test/ImageService.test.ts | 11 +++++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/services/ImageService.ts b/src/services/ImageService.ts index 2b8ca37..d511775 100644 --- a/src/services/ImageService.ts +++ b/src/services/ImageService.ts @@ -5,7 +5,7 @@ import GelbooruApiService from "./GelbooruApiService"; class ImageService { postsQueue: Image[] = []; - + async get(): Promise { while (this.postsQueue.length === 0) { const validPosts = await this.getNewValidImages(); @@ -21,12 +21,20 @@ class ImageService { const botResponse = await BotApiService.getAll(); const imagesUrls = botResponse.images.map(image => image.url); - const validPosts = posts + const validPosts = Promise.all(posts .filter(post => !imagesUrls.some(url => url === post.url)) - .map(post => ({ url: post.url, tags: post.tags, content: "TODO" })); - + .map(async (post): Promise => { + const encodedImage = await this.imageUrlToBase64(post.url); + return { url: post.url, tags: post.tags, content: encodedImage }; + })); + return validPosts; } + + private async imageUrlToBase64(url: string): Promise { + const data = await (await fetch(url)).text(); + return Buffer.from(data, "base64").toString("binary"); + } } export default new ImageService(); \ No newline at end of file diff --git a/test/ImageService.test.ts b/test/ImageService.test.ts index 6b9381a..1d6a60a 100644 --- a/test/ImageService.test.ts +++ b/test/ImageService.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, mock } from "bun:test"; +import { describe, expect, it, mock, spyOn } from "bun:test"; import Image from "../src/types/Image"; import ImageService from "../src/services/ImageService"; import GelbooruApiResponse from "../src/types/GelbooruServiceResponse"; @@ -6,8 +6,8 @@ import { BotApiResponse } from "../src/types/BotApiResponse"; describe("endpoint gets a non repeated image", () => { it("should return an image that is not in the response of the /images endpoint of the bot API", async () => { - const REPEATED_URL = "image.com/1"; - const UNIQUE_URL = "image.com/2"; + const REPEATED_URL = "https://fastly.picsum.photos/id/1/10/20.jpg?hmac=gY6PvUXFacKfYpBpTTVcNLxumpyMmoCamM-J5DOPwNc"; + const UNIQUE_URL = "https://fastly.picsum.photos/id/2/10/20.jpg?hmac=zy6lz21CuRIstr9ETx9h5AuoH50s_L2uIEct3dROpY8"; mock.module("../src/services/GelbooruApiService", () => { let alreadyCalled = false; @@ -35,7 +35,10 @@ describe("endpoint gets a non repeated image", () => { } })); + const imageUrlToBase64Spy = spyOn(ImageService as any, 'imageUrlToBase64'); + const image: Image = await ImageService.get(); expect(image.url).not.toBe(REPEATED_URL); - }) + expect(imageUrlToBase64Spy).toHaveBeenCalledTimes(1); + }); }) \ No newline at end of file