Added base64 encoding for image content

This commit is contained in:
Sugui 2024-03-30 12:58:22 +01:00
parent 0472cf24f1
commit 2ccef4e28c
2 changed files with 19 additions and 8 deletions

View File

@ -5,7 +5,7 @@ import GelbooruApiService from "./GelbooruApiService";
class ImageService {
postsQueue: Image[] = [];
async get(): Promise<Image> {
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<Image> => {
const encodedImage = await this.imageUrlToBase64(post.url);
return { url: post.url, tags: post.tags, content: encodedImage };
}));
return validPosts;
}
private async imageUrlToBase64(url: string): Promise<string> {
const data = await (await fetch(url)).text();
return Buffer.from(data, "base64").toString("binary");
}
}
export default new ImageService();

View File

@ -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);
});
})