Skip to content

Hook into multipart form field parsing #147

@katywings

Description

@katywings

Assume a multipart form with the following fields:

  • csrf
  • projectId
  • files

With the current @hattip/multipart parsing you have no way to check the csrf, before processing the files. You also have no way to access the projectId in the handleFile function, which is tedious when you wanna include that projectId in the resulting file path. Currently the only way is to either provide csrf and projectId via headers or query parameters, or to store the files in a temporary directory.

Idea: add options to control the order of the parsing and to hook into fields. Also add the already processed fields as a second parameter of handleFile.

let projectId = '';
const formData = await parseMultipartFormData(request, {
  // not all fields have to be in the order, missing fields will be processed at the end
  order: ["csrf", "projectId"],
  async handleField(name, value) {
    if (name === 'csrf' && value !== PROPER_CSRF) {
       throw new Error("Access denied");
    }

    if (name === 'projectId') {
       projectId = value;
    }

    return value;
  },
  async handleFile(info, fields) {
    // access projectId via "fields", or via the "projectId" variable from above
    ...upload things 
  }
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions