From 08cd425e00817697fe9d06424a00cf328057ddc3 Mon Sep 17 00:00:00 2001 From: Mattias Runge-Broberg Date: Mon, 22 Jan 2024 09:32:32 +0100 Subject: [PATCH] @tus/server: add possibility to have an async namingFunction (#563) --- packages/server/README.md | 2 +- packages/server/src/handlers/PostHandler.ts | 2 +- packages/server/src/types.ts | 2 +- packages/server/test/PostHandler.test.ts | 14 ++++++++++++++ 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/server/README.md b/packages/server/README.md index 4f9c8834..dd6c626d 100644 --- a/packages/server/README.md +++ b/packages/server/README.md @@ -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`) 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 diff --git a/packages/server/src/handlers/PostHandler.ts b/packages/server/src/handlers/PostHandler.ts index 7d51e25e..413e1023 100644 --- a/packages/server/src/handlers/PostHandler.ts +++ b/packages/server/src/handlers/PostHandler.ts @@ -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 diff --git a/packages/server/src/types.ts b/packages/server/src/types.ts index 652629a8..7477bc54 100644 --- a/packages/server/src/types.ts +++ b/packages/server/src/types.ts @@ -60,7 +60,7 @@ export type ServerOptions = { namingFunction?: ( req: http.IncomingMessage, metadata?: Record - ) => string + ) => string | Promise /** * The Lock interface defines methods for implementing a locking mechanism. diff --git a/packages/server/test/PostHandler.test.ts b/packages/server/test/PostHandler.test.ts index 0838a51c..56b72c8d 100644 --- a/packages/server/test/PostHandler.test.ts +++ b/packages/server/test/PostHandler.test.ts @@ -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})