PronounsPage/server/imageCopy.ts
Adaline Simonian 23a3862ca0
test: introduce snapshot-based smoke tests
- Adds a new test suite with Docker-based smoke tests for all locales.
  Can be run using the ./smoketest.sh script.
- Replaces all calls to Math.random() with a new helper that returns 0.5
  in snapshot testing mode, ensuring deterministic snapshots.
- Similarly replaces all calls to new Date() and Date.now() with new
  helpers that return a fixed date in snapshot testing mode.
- Replaces checks against NODE_ENV with APP_ENV, to ensure that the
  bundles can be built with Nuxt for testing without losing code that
  would otherwise be stripped out by production optimizations.
- Adds a database init script that can be used to initialize the
  database with a single admin user and a long-lived JWT token for use
  in automation tests.
- Adds a JWT decoding/encoding CLI tool for debugging JWTs.

Note: Snapshots are not checked in, and must be generated manually. See
test/__snapshots__/.gitignore for more information.
2025-02-02 23:11:19 -08:00

63 lines
1.7 KiB
TypeScript

import { S3 } from '@aws-sdk/client-s3';
import { loadImage, createCanvas } from 'canvas';
import md5 from 'js-md5';
import { newDate } from '../src/helpers.ts';
import { awsConfig, awsParams } from './aws.ts';
const s3 = new S3(awsConfig);
const convertToPng = async (original: Buffer): Promise<Buffer> => {
const image = await loadImage(original);
const canvas = createCanvas(image.width, image.height);
canvas.getContext('2d').drawImage(image, 0, 0);
return canvas.toBuffer('image/png');
};
export default async (prefix: string, url: string, ttlDays: number | null = null): Promise<string | null> => {
if (!url) {
return null;
}
const isSvg = url.toLowerCase().endsWith('.svg');
const key = `${prefix}/${md5(url)}.${isSvg ? 'svg' : 'png'}`;
try {
const metadata = await s3.headObject({ Key: key, ...awsParams });
if (
ttlDays !== null &&
metadata.LastModified! < new Date(
newDate().setDate(newDate().getDate() - ttlDays),
)
) {
throw 'force refresh';
}
return `${process.env.CLOUDFRONT}/${key}`;
} catch {
try {
const originalBuffer = Buffer.from(await (await fetch(url)).arrayBuffer());
await s3.putObject({
Key: key,
Body: isSvg
? originalBuffer
: await convertToPng(originalBuffer),
ContentType: isSvg
? 'image/svg+xml'
: 'image/png',
ACL: 'public-read',
...awsParams,
});
return `${process.env.CLOUDFRONT}/${key}`;
} catch (e) {
return null;
}
}
};