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

Support nested directories with namingFunction & clarify docs #549

Merged
merged 6 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 38 additions & 8 deletions packages/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,49 @@ Allow `Forwarded`, `X-Forwarded-Proto`, and `X-Forwarded-Host` headers to overri
Additional headers sent in `Access-Control-Allow-Headers` (`string[]`).

#### `options.generateUrl`
Control how the upload url is generated (`(req, { proto, host, baseUrl, path, id }) => string)`)

Control how the upload URL is generated (`(req, { proto, host, path, id }) => string)`)

This only changes the upload URL (`Location` header).
Murderlon marked this conversation as resolved.
Show resolved Hide resolved
If you also want to change the file name in storage use `namingFunction`.
Returning `prefix-1234` in `namingFunction` means the `id` argument in `generateUrl` is `prefix-1234`.

```js
function generateUrl(req, {proto, host, path, id}) {
const prefix = getPrefixForUser(req) // your custom logic
return `${proto}://${host}${path}/${prefix}/${id}?query=param`
}
```

> [!NOTE]
> `@tus/server` expects everything after the last `/` to be the upload id.
Murderlon marked this conversation as resolved.
Show resolved Hide resolved
> If you change that you have to use `getFileIdFromRequest` as well.

#### `options.getFileIdFromRequest`

Control how the Upload-ID is extracted from the request (`(req) => string | void`)
Murderlon marked this conversation as resolved.
Show resolved Hide resolved

#### `options.namingFunction`

Control how you want to name files (`(req) => string`)

In `@tus/server`, the upload ID in the URL is the same as the file name.
This means using a custom `namingFunction` will return a different `Location` header for uploading
and result in a different file name in storage.

It is important to make these unique to prevent data loss. Only use it if you need to.
Default uses `crypto.randomBytes(16).toString('hex')`.

```js
function namingFunction(req) {
const prefix = getPrefixForUser(req) // your custom logic
return `${prefix}-${crypto.randomBytes(16).toString('hex')}`
}
```

> [!CAUTION]
> You can not use slashes (`/`) in your name.

#### `disableTerminationForFinishedUploads`

Disallow the [termination extension](https://tus.io/protocols/resumable-upload#termination) for finished uploads. (`boolean`)
Expand Down Expand Up @@ -358,31 +389,30 @@ Access control is opinionated and can be done in different ways.
This example is psuedo-code for what it could look like with JSON Web Tokens.

```js
const { Server } = require("@tus/server");
const {Server} = require('@tus/server')
// ...

const server = new Server({
// ..
async onIncomingRequest(req, res) {
const token = req.headers.authorization;
const token = req.headers.authorization

if (!token) {
throw { status_code: 401, body: 'Unauthorized' }
throw {status_code: 401, body: 'Unauthorized'}
}

try {
const decodedToken = await jwt.verify(token, 'your_secret_key')
req.user = decodedToken
} catch (error) {
throw { status_code: 401, body: 'Invalid token' }
throw {status_code: 401, body: 'Invalid token'}
}

if (req.user.role !== 'admin') {
throw { status_code: 403, body: 'Access denied' }
throw {status_code: 403, body: 'Access denied'}
}
},
});

})
```

## Types
Expand Down
8 changes: 2 additions & 6 deletions packages/server/src/handlers/BaseHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@ export class BaseHandler extends EventEmitter {
}

generateUrl(req: http.IncomingMessage, id: string) {
// @ts-expect-error req.baseUrl does exist
const baseUrl = req.baseUrl ?? ''
const path = this.options.path === '/' ? '' : this.options.path

if (this.options.generateUrl) {
Expand All @@ -50,21 +48,19 @@ export class BaseHandler extends EventEmitter {
return this.options.generateUrl(req, {
proto,
host,
// @ts-expect-error we can pass undefined
baseUrl: req.baseUrl,
path: path,
id,
})
}

// Default implementation
if (this.options.relativeLocation) {
return `${baseUrl}${path}/${id}`
return `${path}/${id}`
}

const {proto, host} = this.extractHostAndProto(req)

return `${proto}://${host}${baseUrl}${path}/${id}`
return `${proto}://${host}${path}/${id}`
}

getFileIdFromRequest(req: http.IncomingMessage) {
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export type ServerOptions = {
*/
generateUrl?: (
req: http.IncomingMessage,
options: {proto: string; host: string; baseUrl: string; path: string; id: string}
options: {proto: string; host: string; path: string; id: string}
) => string

/**
Expand Down
9 changes: 4 additions & 5 deletions packages/server/test/BaseHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,21 +74,20 @@ describe('BaseHandler', () => {
const handler = new BaseHandler(store, {
path: '/path',
locker: new MemoryLocker(),
generateUrl: (req: http.IncomingMessage, info) => {
const {proto, host, baseUrl, path, id} = info
return `${proto}://${host}${baseUrl}${path}/${id}?customParam=1`
generateUrl: (_, info) => {
const {proto, host, path, id} = info
return `${proto}://${host}${path}/${id}?customParam=1`
},
})

const req = httpMocks.createRequest({
headers: {
host: 'localhost',
},
url: '/upload',
})
const id = '123'
const url = handler.generateUrl(req, id)
assert.equal(url, `http://localhost/upload/path/123?customParam=1`)
assert.equal(url, `http://localhost/path/123?customParam=1`)
})

it('should allow extracting the request id with a custom function', () => {
Expand Down
Loading