tus / tus-node-server

Node.js tus server, standalone or integrable in any framework, with disk, S3, and GGC stores.
https://tus.io/
MIT License
795 stars 197 forks source link

@tus/server: add `lastPath` arg to `getFileIdFromRequest` #626

Closed Murderlon closed 2 months ago

Murderlon commented 2 months ago

As soon as people want nested directories they have to implement namingFunction,generateUrl, and getFileIdFromRequest.

Almost always, the last part of the path (after last /) is the ID. It's therefor a little awkward to let users repeat our internal code in getFileIdFromRequest again.

const path = '/files'
const server = new Server({
  path,
  datastore: new FileStore({directory: './test/output'}),
  namingFunction(req) {
    const id = crypto.randomBytes(16).toString('hex')
    const folder = getFolderForUser(req) // your custom logic
    return `users/${folder}/${id}`
  },
  generateUrl(req, {proto, host, path, id}) {
    id = Buffer.from(id, 'utf-8').toString('base64url')
    return `${proto}://${host}${path}/${id}`
  },
  getFileIdFromRequest(req) {
    const reExtractFileID = /([^/]+)\/?$/
    const match = reExtractFileID.exec(req.url as string)

    if (!match || path.includes(match[1])) {
      return
    }

    return Buffer.from(match[1], 'base64url').toString('utf-8')
  },
})

Which can be simplified to this for most cases now:

const server = new Server({
  // ...
  getFileIdFromRequest(req, lastPath) {
    return Buffer.from(lastPath, 'base64url').toString('utf-8')
  },
})
changeset-bot[bot] commented 2 months ago

🦋 Changeset detected

Latest commit: 0fa15d6cb6da7b10979fd1c57556cda43b952ba7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package | Name | Type | | ----------- | ----- | | @tus/server | Minor |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR