Skip to content

Commit

Permalink
feat(Requests): add attachment keys and form data for stickers
Browse files Browse the repository at this point in the history
Ported from discordjs/discord.js#5867

Co-authored-by: Advaith <advaithj1@gmail.com>
  • Loading branch information
ckohen and advaith1 committed Nov 14, 2021
1 parent 6df603e commit 62843d6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
22 changes: 21 additions & 1 deletion packages/rest/__tests__/REST.test.ts
Expand Up @@ -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')
Expand Down Expand Up @@ -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' });
});
Expand Down
15 changes: 12 additions & 3 deletions packages/rest/src/lib/RequestManager.ts
Expand Up @@ -16,6 +16,7 @@ const agent = new Agent({ keepAlive: true });
*/
export interface RawAttachment {
fileName: string;
key?: string;
rawBuffer: Buffer;
}

Expand All @@ -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
*/
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 62843d6

Please sign in to comment.