feathersjs / feathers

The API and real-time application framework
https://feathersjs.com
MIT License
15.02k stars 745 forks source link

Expose parsed files to hooks and services #3187

Closed Bomberus closed 1 year ago

Bomberus commented 1 year ago

When using the koa-body body parser it will create an additional property (files) in the request object. This property is not exposed to feather services / hooks which make it tedious to work with file uploads directly in the services itself.

This field will only be filled when multipart is activated and a binary file is sent. Otherwise it will be undefined.

Usage:

Hooks:

export const uploadFiles = async ({ arguments: args }: HookContext) => {
  console.log(args[1].files)
}

Services:

export class MessagesService<ServiceParams extends Params = MessagesParams> extends KnexService<
  Messages,
  MessagesData,
  MessagesParams,
  MessagesPatch
> {
  create(data: { text: string; }, params?: MessagesParams | undefined): Promise<{ id: number; text: string; files: string[]; }>;
  create(data: { text: string; }[], params?: MessagesParams | undefined): Promise<{ id: number; text: string; files: string[]; }[]>;
  create(data: { text: string; } | { text: string; }[], params?: MessagesParams | undefined): Promise<{ id: number; text: string; files: string[]; } | { id: number; text: string; files: string[]; }[]>;
  create(data: unknown, params?: unknown): Promise<{ id: number; text: string; files: string[]; }[]> | Promise<{ id: number; text: string; files: string[]; }> | Promise<{ id: number; text: string; files: string[]; } | { id: number; text: string; files: string[]; }[]> {
    const { files } = params as any
    console.log(files)
  }
}
Bomberus commented 1 year ago

Using koa.before hook I was able to cleanly implement this. Can be closed: https://feathersjs.com/api/koa.html