refactor(rest): rename attachment to file (#7199)

This commit is contained in:
ckohen
2022-01-07 15:49:34 -08:00
committed by GitHub
parent 3872acfeb8
commit c969cbf652
8 changed files with 48 additions and 48 deletions

View File

@@ -8,7 +8,7 @@ test('Unauthorized', () => {
'PATCH', 'PATCH',
'https://discord.com/api/v9/guilds/:id', 'https://discord.com/api/v9/guilds/:id',
{ {
attachments: undefined, files: undefined,
body: undefined, body: undefined,
}, },
); );
@@ -19,7 +19,7 @@ test('Unauthorized', () => {
expect(error.name).toBe('DiscordAPIError[0]'); expect(error.name).toBe('DiscordAPIError[0]');
expect(error.status).toBe(401); expect(error.status).toBe(401);
expect(error.url).toBe('https://discord.com/api/v9/guilds/:id'); expect(error.url).toBe('https://discord.com/api/v9/guilds/:id');
expect(error.requestBody.attachments).toBe(undefined); expect(error.requestBody.files).toBe(undefined);
expect(error.requestBody.json).toBe(undefined); expect(error.requestBody.json).toBe(undefined);
}); });
@@ -37,7 +37,7 @@ test('Invalid Form Body Error (error.{property}._errors.{index})', () => {
'PATCH', 'PATCH',
'https://discord.com/api/v9/users/@me', 'https://discord.com/api/v9/users/@me',
{ {
attachments: undefined, files: undefined,
body: { body: {
username: 'a', username: 'a',
}, },
@@ -52,7 +52,7 @@ test('Invalid Form Body Error (error.{property}._errors.{index})', () => {
expect(error.name).toBe('DiscordAPIError[50035]'); expect(error.name).toBe('DiscordAPIError[50035]');
expect(error.status).toBe(400); expect(error.status).toBe(400);
expect(error.url).toBe('https://discord.com/api/v9/users/@me'); expect(error.url).toBe('https://discord.com/api/v9/users/@me');
expect(error.requestBody.attachments).toBe(undefined); expect(error.requestBody.files).toBe(undefined);
expect(error.requestBody.json).toStrictEqual({ username: 'a' }); expect(error.requestBody.json).toStrictEqual({ username: 'a' });
}); });

View File

@@ -38,7 +38,7 @@ nock(`${DefaultRestOptions.api}/v${DefaultRestOptions.version}`)
.reply(200, (_, body) => body) .reply(200, (_, body) => body)
.post('/postEcho') .post('/postEcho')
.reply(200, (_, body) => body) .reply(200, (_, body) => body)
.post('/postAttachment') .post('/postFile')
.times(5) .times(5)
.reply(200, (_, body) => ({ .reply(200, (_, body) => ({
body: body body: body
@@ -109,16 +109,16 @@ test('getReason encoded', async () => {
expect(await api.get('/getReason', { reason: '😄' })).toStrictEqual({ reason: '%F0%9F%98%84' }); expect(await api.get('/getReason', { reason: '😄' })).toStrictEqual({ reason: '%F0%9F%98%84' });
}); });
test('postAttachment empty', async () => { test('postFile empty', async () => {
expect(await api.post('/postAttachment', { attachments: [] })).toStrictEqual({ expect(await api.post('/postFile', { files: [] })).toStrictEqual({
body: '', body: '',
}); });
}); });
test('postAttachment attachment', async () => { test('postFile file', async () => {
expect( expect(
await api.post('/postAttachment', { await api.post('/postFile', {
attachments: [{ fileName: 'out.txt', rawBuffer: Buffer.from('Hello') }], files: [{ fileName: 'out.txt', rawBuffer: Buffer.from('Hello') }],
}), }),
).toStrictEqual({ ).toStrictEqual({
body: [ body: [
@@ -130,10 +130,10 @@ test('postAttachment attachment', async () => {
}); });
}); });
test('postAttachment attachment and JSON', async () => { test('postFile file and JSON', async () => {
expect( expect(
await api.post('/postAttachment', { await api.post('/postFile', {
attachments: [{ fileName: 'out.txt', rawBuffer: Buffer.from('Hello') }], files: [{ fileName: 'out.txt', rawBuffer: Buffer.from('Hello') }],
body: { foo: 'bar' }, body: { foo: 'bar' },
}), }),
).toStrictEqual({ ).toStrictEqual({
@@ -149,14 +149,14 @@ test('postAttachment attachment and JSON', async () => {
}); });
}); });
test('postAttachment attachments and JSON', async () => { test('postFile files and JSON', async () => {
expect( expect(
await api.post('/postAttachment', { await api.post('/postFile', {
attachments: [ files: [
{ fileName: 'out.txt', rawBuffer: Buffer.from('Hello') }, { fileName: 'out.txt', rawBuffer: Buffer.from('Hello') },
{ fileName: 'out.txt', rawBuffer: Buffer.from('Hi') }, { fileName: 'out.txt', rawBuffer: Buffer.from('Hi') },
], ],
body: { attachments: [{ id: 0, description: 'test' }] }, body: { files: [{ id: 0, description: 'test' }] },
}), }),
).toStrictEqual({ ).toStrictEqual({
body: [ body: [
@@ -170,15 +170,15 @@ test('postAttachment attachments and JSON', async () => {
'Hi', 'Hi',
'Content-Disposition: form-data; name="payload_json"', 'Content-Disposition: form-data; name="payload_json"',
'', '',
'{"attachments":[{"id":0,"description":"test"}]}', '{"files":[{"id":0,"description":"test"}]}',
].join('\n'), ].join('\n'),
}); });
}); });
test('postAttachment sticker and JSON', async () => { test('postFile sticker and JSON', async () => {
expect( expect(
await api.post('/postAttachment', { await api.post('/postFile', {
attachments: [{ key: 'file', fileName: 'sticker.png', rawBuffer: Buffer.from('Sticker') }], files: [{ key: 'file', fileName: 'sticker.png', rawBuffer: Buffer.from('Sticker') }],
body: { foo: 'bar' }, body: { foo: 'bar' },
appendToFormData: true, appendToFormData: true,
}), }),
@@ -242,7 +242,7 @@ test('Request and Response Events', async () => {
method: 'get', method: 'get',
path: '/request', path: '/request',
route: '/request', route: '/request',
data: { attachments: undefined, body: undefined }, data: { files: undefined, body: undefined },
retries: 0, retries: 0,
}) as APIRequest, }) as APIRequest,
); );
@@ -251,7 +251,7 @@ test('Request and Response Events', async () => {
method: 'get', method: 'get',
path: '/request', path: '/request',
route: '/request', route: '/request',
data: { attachments: undefined, body: undefined }, data: { files: undefined, body: undefined },
retries: 0, retries: 0,
}) as APIRequest, }) as APIRequest,
expect.objectContaining({ status: 200, statusText: 'OK' }) as Response, expect.objectContaining({ status: 200, statusText: 'OK' }) as Response,

View File

@@ -142,7 +142,7 @@ export interface APIRequest {
/** /**
* The data that was used to form the body of this request * The data that was used to form the body of this request
*/ */
data: Pick<InternalRequest, 'attachments' | 'body'>; data: Pick<InternalRequest, 'files' | 'body'>;
/** /**
* The number of times this request has been attempted * The number of times this request has been attempted
*/ */

View File

@@ -12,21 +12,21 @@ import { DefaultRestOptions, DefaultUserAgent } from './utils/constants';
let agent: Agent | null = null; let agent: Agent | null = null;
/** /**
* Represents an attachment to be added to the request * Represents a file to be added to the request
*/ */
export interface RawAttachment { export interface RawFile {
/** /**
* The name of the file * The name of the file
*/ */
fileName: string; fileName: string;
/** /**
* An explicit key to use for key of the formdata field for this attachment. * An explicit key to use for key of the formdata field for this file.
* When not provided, the index of the file in the attachments array is used in the form `files[${index}]`. * When not provided, the index of the file in the files array is used in the form `files[${index}]`.
* If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`) * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)
*/ */
key?: string; key?: string;
/** /**
* The actual data for the attachment * The actual data for the file
*/ */
rawBuffer: Buffer; rawBuffer: Buffer;
} }
@@ -36,13 +36,9 @@ export interface RawAttachment {
*/ */
export interface RequestData { export interface RequestData {
/** /**
* Whether to append JSON data to form data instead of `payload_json` when sending attachments * Whether to append JSON data to form data instead of `payload_json` when sending files
*/ */
appendToFormData?: boolean; appendToFormData?: boolean;
/**
* Files to be attached to this request
*/
attachments?: RawAttachment[] | undefined;
/** /**
* If this request needs the `Authorization` header * If this request needs the `Authorization` header
* @default true * @default true
@@ -58,13 +54,17 @@ export interface RequestData {
* If providing as BodyInit, set `passThroughBody: true` * If providing as BodyInit, set `passThroughBody: true`
*/ */
body?: BodyInit | unknown; body?: BodyInit | unknown;
/**
* Files to be attached to this request
*/
files?: RawFile[] | undefined;
/** /**
* Additional headers to add to this request * Additional headers to add to this request
*/ */
headers?: Record<string, string>; headers?: Record<string, string>;
/** /**
* Whether to pass-through the body property directly to `fetch()`. * Whether to pass-through the body property directly to `fetch()`.
* <warn>This only applies when attachments is NOT present</warn> * <warn>This only applies when files is NOT present</warn>
*/ */
passThroughBody?: boolean; passThroughBody?: boolean;
/** /**
@@ -212,7 +212,7 @@ export class RequestManager extends EventEmitter {
const { url, fetchOptions } = this.resolveRequest(request); const { url, fetchOptions } = this.resolveRequest(request);
// Queue the request // Queue the request
return handler.queueRequest(routeId, url, fetchOptions, { body: request.body, attachments: request.attachments }); return handler.queueRequest(routeId, url, fetchOptions, { body: request.body, files: request.files });
} }
/** /**
@@ -275,12 +275,12 @@ export class RequestManager extends EventEmitter {
let finalBody: RequestInit['body']; let finalBody: RequestInit['body'];
let additionalHeaders: Record<string, string> = {}; let additionalHeaders: Record<string, string> = {};
if (request.attachments?.length) { if (request.files?.length) {
const formData = new FormData(); const formData = new FormData();
// Attach all files to the request // Attach all files to the request
for (const [index, attachment] of request.attachments.entries()) { for (const [index, file] of request.files.entries()) {
formData.append(attachment.key ?? `files[${index}]`, attachment.rawBuffer, attachment.fileName); formData.append(file.key ?? `files[${index}]`, file.rawBuffer, file.fileName);
} }
// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified // If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified

View File

@@ -1,4 +1,4 @@
import type { InternalRequest, RawAttachment } from '../RequestManager'; import type { InternalRequest, RawFile } from '../RequestManager';
interface DiscordErrorFieldInformation { interface DiscordErrorFieldInformation {
code: string; code: string;
@@ -23,7 +23,7 @@ export interface OAuthErrorData {
} }
export interface RequestBody { export interface RequestBody {
attachments: RawAttachment[] | undefined; files: RawFile[] | undefined;
json: unknown | undefined; json: unknown | undefined;
} }
@@ -56,11 +56,11 @@ export class DiscordAPIError extends Error {
public status: number, public status: number,
public method: string, public method: string,
public url: string, public url: string,
bodyData: Pick<InternalRequest, 'attachments' | 'body'>, bodyData: Pick<InternalRequest, 'files' | 'body'>,
) { ) {
super(DiscordAPIError.getMessage(rawError)); super(DiscordAPIError.getMessage(rawError));
this.requestBody = { attachments: bodyData.attachments, json: bodyData.body }; this.requestBody = { files: bodyData.files, json: bodyData.body };
} }
/** /**

View File

@@ -21,10 +21,10 @@ export class HTTPError extends Error {
public status: number, public status: number,
public method: string, public method: string,
public url: string, public url: string,
bodyData: Pick<InternalRequest, 'attachments' | 'body'>, bodyData: Pick<InternalRequest, 'files' | 'body'>,
) { ) {
super(message); super(message);
this.requestBody = { attachments: bodyData.attachments, json: bodyData.body }; this.requestBody = { files: bodyData.files, json: bodyData.body };
} }
} }

View File

@@ -6,6 +6,6 @@ export interface IHandler {
routeId: RouteData, routeId: RouteData,
url: string, url: string,
options: RequestInit, options: RequestInit,
bodyData: Pick<InternalRequest, 'attachments' | 'body'>, bodyData: Pick<InternalRequest, 'files' | 'body'>,
): Promise<unknown>; ): Promise<unknown>;
} }

View File

@@ -168,7 +168,7 @@ export class SequentialHandler {
routeId: RouteData, routeId: RouteData,
url: string, url: string,
options: RequestInit, options: RequestInit,
bodyData: Pick<InternalRequest, 'attachments' | 'body'>, bodyData: Pick<InternalRequest, 'files' | 'body'>,
): Promise<unknown> { ): Promise<unknown> {
let queue = this.#asyncQueue; let queue = this.#asyncQueue;
let queueType = QueueType.Standard; let queueType = QueueType.Standard;
@@ -225,7 +225,7 @@ export class SequentialHandler {
routeId: RouteData, routeId: RouteData,
url: string, url: string,
options: RequestInit, options: RequestInit,
bodyData: Pick<InternalRequest, 'attachments' | 'body'>, bodyData: Pick<InternalRequest, 'files' | 'body'>,
retries = 0, retries = 0,
): Promise<unknown> { ): Promise<unknown> {
/* /*