refactor(rest): add content-type(s) to uploads (#8290)

This commit is contained in:
DD
2022-07-17 19:55:25 +03:00
committed by GitHub
parent bf65b37d1a
commit 103a3584c9
6 changed files with 92 additions and 13 deletions

View File

@@ -255,8 +255,8 @@ class MessagePayload {
name = fileLike.name ?? findName(attachment);
}
const data = await DataResolver.resolveFile(attachment);
return { data, name };
const { data, contentType } = await DataResolver.resolveFile(attachment);
return { data, name, contentType };
}
/**

View File

@@ -100,32 +100,37 @@ class DataResolver extends null {
* @see {@link https://nodejs.org/api/stream.html}
*/
/**
* @typedef {Object} ResolvedFile
* @property {Buffer} data Buffer containing the file data
* @property {string} [contentType] Content type of the file
*/
/**
* Resolves a BufferResolvable to a Buffer.
* @param {BufferResolvable|Stream} resource The buffer or stream resolvable to resolve
* @returns {Promise<Buffer>}
* @returns {Promise<ResolvedFile>}
*/
static async resolveFile(resource) {
if (!resource) return null;
if (Buffer.isBuffer(resource)) return resource;
if (Buffer.isBuffer(resource)) return { data: resource };
if (typeof resource[Symbol.asyncIterator] === 'function') {
const buffers = [];
for await (const data of resource) buffers.push(data);
return Buffer.concat(buffers);
return { data: Buffer.concat(buffers) };
}
if (typeof resource === 'string') {
if (/^https?:\/\//.test(resource)) {
const res = await fetch(resource);
return Buffer.from(await res.arrayBuffer());
return { data: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get('content-type') };
}
const file = path.resolve(resource);
const stats = await fs.stat(file);
if (!stats.isFile()) throw new DiscordError(ErrorCodes.FileNotFound, file);
return fs.readFile(file);
return { data: await fs.readFile(file) };
}
throw new TypeError(ErrorCodes.ReqResourceType);

View File

@@ -1039,11 +1039,16 @@ export class ContextMenuCommandInteraction<Cached extends CacheType = CacheType>
private resolveContextMenuOptions(data: APIApplicationCommandInteractionData): CommandInteractionOption<Cached>[];
}
export interface ResolvedFile {
data: Buffer;
contentType?: string;
}
export class DataResolver extends null {
private constructor();
public static resolveBase64(data: Base64Resolvable): string;
public static resolveCode(data: string, regex: RegExp): string;
public static resolveFile(resource: BufferResolvable | Stream): Promise<Buffer>;
public static resolveFile(resource: BufferResolvable | Stream): Promise<ResolvedFile>;
public static resolveImage(resource: BufferResolvable | Base64Resolvable): Promise<string | null>;
public static resolveInviteCode(data: InviteResolvable): string;
public static resolveGuildTemplateCode(data: GuildTemplateResolvable): string;