Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(connect): add support for File type in requests #3189

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 57 additions & 3 deletions packages/ts/frontend/src/Connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ $wnd.Vaadin.registrations.push({
is: 'endpoint',
});

export const bodyPartName = 'hilla_body_part';

export type MaybePromise<T> = Promise<T> | T;

/**
Expand Down Expand Up @@ -187,6 +189,40 @@ function isFlowLoaded(): boolean {
return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;
}

/**
* Extracts file objects from the object that is used to build the request body.
*
* @param obj - The object to extract files from.
* @returns A tuple with the object without files and a map of files.
*/
function extractFiles(obj: Record<string, unknown>): [Record<string, unknown>, Map<string, File>] {
const fileMap = new Map<string, File>();

function recursiveExtract(prop: unknown, path: string): unknown {
if (prop !== null && typeof prop === 'object') {
if (prop instanceof File) {
fileMap.set(path, prop);
return null;
}
if (Array.isArray(prop)) {
return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));
}
return Object.entries(prop).reduce<Record<string, unknown>>((acc, [key, value]) => {
const newPath = `${path}/${key}`;
if (value instanceof File) {
fileMap.set(newPath, value);
} else {
acc[key] = recursiveExtract(value, newPath);
}
return acc;
}, {});
}
return prop;
}

return [recursiveExtract(obj, '') as Record<string, unknown>, fileMap];
}

/**
* A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.
*/
Expand Down Expand Up @@ -304,13 +340,31 @@ export class ConnectClient {
const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};
const headers: Record<string, string> = {
Accept: 'application/json',
'Content-Type': 'application/json',
...csrfHeaders,
};

const [paramsWithoutFiles, files] = extractFiles(params ?? {});
let body;

if (files.size > 0) {
// in this case params is not undefined, otherwise there would be no files
body = new FormData();
body.append(
bodyPartName,
JSON.stringify(paramsWithoutFiles, (_, value) => (value === undefined ? null : value)),
);

for (const [path, file] of files) {
body.append(path, file);
}
} else {
headers['Content-Type'] = 'application/json';
body =
params !== undefined ? JSON.stringify(params, (_, value) => (value === undefined ? null : value)) : undefined;
}

const request = new Request(`${this.prefix}/${endpoint}/${method}`, {
body:
params !== undefined ? JSON.stringify(params, (_, value) => (value === undefined ? null : value)) : undefined,
body, // automatically sets Content-Type header
headers,
method: 'POST',
});
Expand Down
55 changes: 55 additions & 0 deletions packages/ts/frontend/test/Connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
ForbiddenResponseError,
type MiddlewareFunction,
UnauthorizedResponseError,
bodyPartName,
} from '../src/index.js';
import type { Vaadin } from '../src/types.js';
import { subscribeStub } from './mocks/atmosphere.js';
Expand Down Expand Up @@ -492,6 +493,60 @@ describe('@vaadin/hilla-frontend', () => {
expect(await request?.json()).to.deep.equal({ fooParam: 'foo' });
});

it('should use multipart if a param is of File type', async () => {
const file = new File(['foo'], 'foo.txt', { type: 'text/plain' });
await client.call('FooEndpoint', 'fooMethod', { fooParam: file });

const request = fetchMock.callHistory.lastCall()?.request;
expect(request).to.exist;
expect(request?.headers.get('content-type')).to.match(/^multipart\/form-data;/u);
const formData = await request!.formData();

const uploadedFile = formData.get('/fooParam') as File | null;
expect(uploadedFile).to.be.instanceOf(File);
expect(uploadedFile!.name).to.equal('foo.txt');
expect(await uploadedFile!.text()).to.equal('foo');

const body = formData.get(bodyPartName);
expect(body).to.equal('{}');
});

it('should use multipart if a param has a property if File type', async () => {
const file = new File(['foo'], 'foo.txt', { type: 'text/plain' });
await client.call('FooEndpoint', 'fooMethod', { fooParam: { a: 'abc', b: file } });

const request = fetchMock.callHistory.lastCall()?.request;
expect(request).to.exist;
expect(request?.headers.get('content-type')).to.match(/^multipart\/form-data;/u);
const formData = await request!.formData();

const uploadedFile = formData.get('/fooParam/b') as File | null;
expect(uploadedFile).to.be.instanceOf(File);
expect(uploadedFile!.name).to.equal('foo.txt');
expect(await uploadedFile!.text()).to.equal('foo');

const body = formData.get(bodyPartName);
expect(body).to.equal('{"fooParam":{"a":"abc"}}');
});

it('should use multipart if a File is found in array', async () => {
const file = new File(['foo'], 'foo.txt', { type: 'text/plain' });
await client.call('FooEndpoint', 'fooMethod', { fooParam: ['a', file, 'c'], other: 'abc' });

const request = fetchMock.callHistory.lastCall()?.request;
expect(request).to.exist;
expect(request?.headers.get('content-type')).to.match(/^multipart\/form-data;/u);
const formData = await request!.formData();

const uploadedFile = formData.get('/fooParam/1') as File | null;
expect(uploadedFile).to.be.instanceOf(File);
expect(uploadedFile!.name).to.equal('foo.txt');
expect(await uploadedFile!.text()).to.equal('foo');

const body = formData.get(bodyPartName);
expect(body).to.equal('{"fooParam":["a",null,"c"],"other":"abc"}');
});

describe('middleware invocation', () => {
it('should not invoke middleware before call', () => {
const spyMiddleware = sinon.spy(async (context: MiddlewareContext, next: MiddlewareNext) => next(context));
Expand Down