Handle non-string image content types
This commit is contained in:
1 parent
51438aa5db
commit
271f2d1fb5
2 files changed
+19
-3
No files matched your search
+8
-2
@@ -16,14 +16,20 @@ export async function downloadImage(url: string, userAgent: string): Promise<Dow
|
|||||||
maxRedirects: 5,
|
maxRedirects: 5,
|
||||||
});
|
});
|
||||||
|
|
||||||
const contentType = response.headers['content-type'] || 'image/jpeg';
|
const contentType = normalizeContentType(response.headers['content-type']);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
buffer: Buffer.from(response.data),
|
buffer: Buffer.from(response.data),
|
||||||
mimeType: contentType.split(';')[0].trim(),
|
mimeType: contentType,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Axios permits non-string header values, but media processing needs a MIME string. */
|
||||||
|
export function normalizeContentType(contentType: unknown): string {
|
||||||
|
if (typeof contentType !== 'string') return 'image/jpeg';
|
||||||
|
return contentType.split(';', 1)[0].trim() || 'image/jpeg';
|
||||||
|
}
|
||||||
|
|
||||||
export function bufferToBase64(buffer: Buffer): string {
|
export function bufferToBase64(buffer: Buffer): string {
|
||||||
return buffer.toString('base64');
|
return buffer.toString('base64');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { isValidImageMimeType, bufferToBase64 } from '../src/utils/image.js';
|
import { isValidImageMimeType, bufferToBase64, normalizeContentType } from '../src/utils/image.js';
|
||||||
|
|
||||||
describe('isValidImageMimeType', () => {
|
describe('isValidImageMimeType', () => {
|
||||||
it('accepts valid image MIME types', () => {
|
it('accepts valid image MIME types', () => {
|
||||||
@@ -72,3 +72,13 @@ describe('bufferToBase64', () => {
|
|||||||
expect(result).toMatch(/^[A-Za-z0-9+/]+=*$/);
|
expect(result).toMatch(/^[A-Za-z0-9+/]+=*$/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('normalizeContentType', () => {
|
||||||
|
it('uses the fallback when Axios exposes a non-string header value', () => {
|
||||||
|
expect(normalizeContentType(['image/png'])).toBe('image/jpeg');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes header parameters from a string content type', () => {
|
||||||
|
expect(normalizeContentType('image/webp; charset=binary')).toBe('image/webp');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user