hattipjs / hattip

Like Express, but for the future
MIT License
1.28k stars 18 forks source link

Hook into multipart form field parsing #147

Open katywings opened 5 months ago

katywings commented 5 months ago

Assume a multipart form with the following fields:

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 
  }
})
cyco130 commented 3 months ago

Hi! This is a very good idea and you already seem to have the implementation. Would you like to send a PR?