Skip to content

Commit

Permalink
@tus/server: add possibility to have an async namingFunction (#563)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattiasrunge authored Jan 22, 2024
1 parent b4fb15a commit 08cd425
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ By default, it expects everything in the path after the last `/` to be the uploa
#### `options.namingFunction`

Control how you want to name files (`(req, metadata) => string`)
Control how you want to name files (`(req, metadata) => string | Promise<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
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/handlers/PostHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class PostHandler extends BaseHandler {

let id
try {
id = this.options.namingFunction(req, metadata)
id = await this.options.namingFunction(req, metadata)
} catch (error) {
log('create: check your `namingFunction`. Error', error)
throw error
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 @@ -60,7 +60,7 @@ export type ServerOptions = {
namingFunction?: (
req: http.IncomingMessage,
metadata?: Record<string, string | null>
) => string
) => string | Promise<string>

/**
* The Lock interface defines methods for implementing a locking mechanism.
Expand Down
14 changes: 14 additions & 0 deletions packages/server/test/PostHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,20 @@ describe('PostHandler', () => {
assert.equal(namingFunction.calledOnce, true)
})

it('should call custom async namingFunction', async () => {
const fake_store = sinon.createStubInstance(DataStore)
const namingFunction = sinon.stub().resolves('1234')
const handler = new PostHandler(fake_store, {
path: '/test/',
namingFunction,
locker: new MemoryLocker(),
})

req.headers = {'upload-length': '1000'}
await handler.send(req, res, context)
assert.equal(namingFunction.calledOnce, true)
})

it('should send error when store rejects', () => {
const fake_store = sinon.createStubInstance(DataStore)
fake_store.create.rejects({status_code: 500})
Expand Down

0 comments on commit 08cd425

Please sign in to comment.