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

form-data-parser needs a code example to take another parameter #40

Open
kenn opened this issue Jan 5, 2025 · 1 comment
Open

form-data-parser needs a code example to take another parameter #40

kenn opened this issue Jan 5, 2025 · 1 comment

Comments

@kenn
Copy link

kenn commented Jan 5, 2025

parseFormData takes uploadHandler at the second arg, but since the function only takes one arg which is (fileUpload: FileUpload), it's hard to make it reusable.

To pull it outside of action, we have to do a higher order function gymnastics like this:

async function uploadHandler(id: string) {
  return async (fileUpload: FileUpload) => {
    if (
      fileUpload.fieldName === 'file' &&
      fileUpload.type.startsWith('image/')
    ) {
      let storageKey = `upload-${id}`
      await fileStorage.set(storageKey, fileUpload)
      return fileStorage.get(storageKey) // => LazyFile
    }
  }
}

export async function action({ request, params }) {
  let formData = await parseFormData(request, await uploadHandler(params.id))
  // ...
}

This is fine, but I think it's unkind to less experienced users.

Until we figure out a better API, can we at least put this example in a visible place? The current README has a bug with referencing user.id.

If I should create a PR for this, let me know.

Thanks for this great library!

@kenn
Copy link
Author

kenn commented Jan 5, 2025

Also, it's not clear to me how I can return an extra value from uploadHandler.

For instance, I'm creating a DB record that keeps uploaded file's metadata, and would like to return upload.id which is only generated and accessible inside the handler function.

Also it can even receive multiple files in one request, which makes things even more complicated...

What is a suggested solution here?

export async function uploadHandler(id: string) {
  return async (fileUpload: FileUpload) => {
    let upload = await Upload.create({
      owner_id: id,
      name: fileUpload.name,
    })
    let storageKey = `image-${upload.id}`
    await FileStorage.set(storageKey, fileUpload)
    return FileStorage.get(storageKey)
  }
}

export async function action({ request, params }) {
  let formData = await parseFormData(request, await uploadHandler(params.id))
  // how can I access upload.id(s) just generated?
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant