diff --git a/packages/rest/__tests__/REST.test.ts b/packages/rest/__tests__/REST.test.ts index 939cc51..cd51254 100644 --- a/packages/rest/__tests__/REST.test.ts +++ b/packages/rest/__tests__/REST.test.ts @@ -36,7 +36,7 @@ nock(`${DefaultRestOptions.api}/v${DefaultRestOptions.version}`) .post('/postEcho') .reply(200, (_, body) => body) .post('/postAttachment') - .times(3) + .times(4) .reply(200, (_, body) => ({ body: body .replace(/\r\n/g, '\n') @@ -143,6 +143,26 @@ test('postAttachment attachment and JSON', async () => { }); }); +test('postAttachment sticker and JSON', async () => { + expect( + await api.post('/postAttachment', { + attachments: [{ key: 'file', fileName: 'sticker.png', rawBuffer: Buffer.from('Sticker') }], + body: { foo: 'bar' }, + dontUsePayloadJSON: true, + }), + ).toStrictEqual({ + body: [ + 'Content-Disposition: form-data; name="file"; filename="sticker.png"', + 'Content-Type: image/png', + '', + 'Sticker', + 'Content-Disposition: form-data; name="foo"', + '', + 'bar', + ].join('\n'), + }); +}); + test('postEcho', async () => { expect(await api.post('/postEcho', { body: { foo: 'bar' } })).toStrictEqual({ foo: 'bar' }); }); diff --git a/packages/rest/src/lib/RequestManager.ts b/packages/rest/src/lib/RequestManager.ts index 747649f..874527d 100644 --- a/packages/rest/src/lib/RequestManager.ts +++ b/packages/rest/src/lib/RequestManager.ts @@ -16,6 +16,7 @@ const agent = new Agent({ keepAlive: true }); */ export interface RawAttachment { fileName: string; + key?: string; rawBuffer: Buffer; } @@ -41,6 +42,10 @@ export interface RequestData { * The body to send to this request */ body?: unknown; + /** + * Whether to append JSON data to form data isntead of `payload_json` when sending attachments + */ + dontUsePayloadJSON?: boolean; /** * Additional headers to add to this request */ @@ -239,13 +244,17 @@ export class RequestManager extends EventEmitter { // Attach all files to the request for (const attachment of request.attachments) { - formData.append(attachment.fileName, attachment.rawBuffer, attachment.fileName); + formData.append(attachment.key ?? attachment.fileName, attachment.rawBuffer, attachment.fileName); } - // If a JSON body was added as well, attach it to the form data + // If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified // eslint-disable-next-line no-eq-null if (request.body != null) { - formData.append('payload_json', JSON.stringify(request.body)); + if (request.dontUsePayloadJSON) { + for (const [key, value] of Object.entries(request.body as any)) formData.append(key, value); + } else { + formData.append('payload_json', JSON.stringify(request.body)); + } } // Set the final body to the form data