Extract `Message.loadWithObjectURL`
parent
45d89d1e44
commit
4ce0472b9f
@ -1,15 +1,45 @@
|
|||||||
/**
|
/**
|
||||||
* @prettier
|
* @prettier
|
||||||
*/
|
*/
|
||||||
export interface Message {
|
import is from '@sindresorhus/is';
|
||||||
body?: string;
|
|
||||||
|
import { arrayBufferToObjectURL } from '../../../../util/arrayBufferToObjectURL';
|
||||||
|
import { Attachment } from '../../../../types/Attachment';
|
||||||
|
import { MapAsync } from '../../../../types/MapAsync';
|
||||||
|
import { MIMEType } from '../../../../types/MIME';
|
||||||
|
|
||||||
|
export type Message = {
|
||||||
|
attachments: Array<Attachment>;
|
||||||
received_at: number;
|
received_at: number;
|
||||||
attachments: Array<{
|
} & { objectURL?: string };
|
||||||
data?: ArrayBuffer;
|
|
||||||
fileName?: string;
|
const DEFAULT_CONTENT_TYPE: MIMEType = 'application/octet-stream' as MIMEType;
|
||||||
size?: number;
|
|
||||||
}>;
|
export const loadWithObjectURL = (loadMessage: MapAsync<Message>) => async (
|
||||||
|
media: Array<Message>
|
||||||
// TODO: Revisit
|
): Promise<Array<Message>> => {
|
||||||
objectURL?: string;
|
if (!is.function_(loadMessage)) {
|
||||||
}
|
throw new TypeError("'loadMessage' must be a function");
|
||||||
|
}
|
||||||
|
if (!is.array(media)) {
|
||||||
|
throw new TypeError("'media' must be a function");
|
||||||
|
}
|
||||||
|
|
||||||
|
const mediaWithAttachmentData = await Promise.all(media.map(loadMessage));
|
||||||
|
return mediaWithAttachmentData.map(withObjectURL);
|
||||||
|
};
|
||||||
|
|
||||||
|
const withObjectURL = (message: Message): Message => {
|
||||||
|
if (message.attachments.length === 0) {
|
||||||
|
throw new TypeError('`message.attachments` cannot be empty');
|
||||||
|
}
|
||||||
|
const attachment = message.attachments[0];
|
||||||
|
const objectURL = arrayBufferToObjectURL({
|
||||||
|
data: attachment.data,
|
||||||
|
type: attachment.contentType || DEFAULT_CONTENT_TYPE,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...message,
|
||||||
|
objectURL,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
Loading…
Reference in New Issue