check-work-cover-cache.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import assert from 'node:assert/strict';
  2. import { createServer } from 'node:http';
  3. import { mkdtemp, readFile, rm } from 'node:fs/promises';
  4. import os from 'node:os';
  5. import path from 'node:path';
  6. const tempUploadPath = await mkdtemp(path.join(os.tmpdir(), 'work-cover-cache-'));
  7. process.env.UPLOAD_PATH = tempUploadPath;
  8. const { cacheRemoteWorkCoverUrl, isLocalUploadUrl } = await import('../server/src/utils/workCoverCache.js');
  9. const png = Buffer.from(
  10. 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAoMBgB6WJ6sAAAAASUVORK5CYII=',
  11. 'base64'
  12. );
  13. const server = createServer((req, res) => {
  14. if (req.url === '/cover.png') {
  15. res.writeHead(200, {
  16. 'content-type': 'image/png',
  17. 'content-length': String(png.length),
  18. });
  19. res.end(png);
  20. return;
  21. }
  22. res.writeHead(404, { 'content-type': 'text/plain' });
  23. res.end('not found');
  24. });
  25. await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  26. try {
  27. const address = server.address();
  28. assert.ok(address && typeof address === 'object');
  29. const remoteUrl = `http://127.0.0.1:${address.port}/cover.png`;
  30. const cachedUrl = await cacheRemoteWorkCoverUrl({
  31. url: remoteUrl,
  32. platform: 'weixin_video',
  33. accountId: 123,
  34. platformVideoId: 'export/test-video-id',
  35. });
  36. assert.match(cachedUrl, /^\/uploads\/covers\/synced\/weixin_video\/123\/[a-f0-9]{32}\.png$/);
  37. assert.equal(isLocalUploadUrl(cachedUrl), true);
  38. const diskPath = path.join(tempUploadPath, ...cachedUrl.replace('/uploads/', '').split('/'));
  39. assert.deepEqual(await readFile(diskPath), png);
  40. const cachedAgain = await cacheRemoteWorkCoverUrl({
  41. url: remoteUrl,
  42. platform: 'weixin_video',
  43. accountId: 123,
  44. platformVideoId: 'export/test-video-id',
  45. });
  46. assert.equal(cachedAgain, cachedUrl);
  47. console.log('work cover cache checks passed');
  48. } finally {
  49. server.close();
  50. await rm(tempUploadPath, { recursive: true, force: true });
  51. }