11import EventEmitter from 'node:events'
2+ import stream from 'node:stream/promises'
3+ import { addAbortSignal , PassThrough } from 'node:stream'
4+ import type http from 'node:http'
25
36import type { ServerOptions } from '../types'
47import type { DataStore , CancellationContext } from '@tus/utils'
5- import type http from 'node:http'
6- import { ERRORS , Upload , StreamLimiter } from '@tus/utils'
7- import stream from 'node:stream/promises'
8- import { addAbortSignal , PassThrough } from 'stream'
8+ import { ERRORS , Upload , StreamLimiter , EVENTS } from '@tus/utils'
9+ import throttle from 'lodash.throttle'
910
1011const reExtractFileID = / ( [ ^ / ] + ) \/ ? $ /
1112const reForwardedHost = / h o s t = " ? ( [ ^ " ; ] + ) /
@@ -127,8 +128,7 @@ export class BaseHandler extends EventEmitter {
127128
128129 protected writeToStore (
129130 req : http . IncomingMessage ,
130- id : string ,
131- offset : number ,
131+ upload : Upload ,
132132 maxFileSize : number ,
133133 context : CancellationContext
134134 ) {
@@ -149,6 +149,20 @@ export class BaseHandler extends EventEmitter {
149149 reject ( err . name === 'AbortError' ? ERRORS . ABORTED : err )
150150 } )
151151
152+ const postReceive = throttle (
153+ ( offset : number ) => {
154+ this . emit ( EVENTS . POST_RECEIVE_V2 , req , { ...upload , offset} )
155+ } ,
156+ this . options . postReceiveInterval ,
157+ { leading : false }
158+ )
159+
160+ let tempOffset = upload . offset
161+ proxy . on ( 'data' , ( chunk : Buffer ) => {
162+ tempOffset += chunk . byteLength
163+ postReceive ( tempOffset )
164+ } )
165+
152166 req . on ( 'error' , ( ) => {
153167 if ( ! proxy . closed ) {
154168 // we end the stream gracefully here so that we can upload the remaining bytes to the store
@@ -162,7 +176,7 @@ export class BaseHandler extends EventEmitter {
162176 // which would result in a socket hangup error for the client.
163177 stream
164178 . pipeline ( req . pipe ( proxy ) , new StreamLimiter ( maxFileSize ) , async ( stream ) => {
165- return this . store . write ( stream as StreamLimiter , id , offset )
179+ return this . store . write ( stream as StreamLimiter , upload . id , upload . offset )
166180 } )
167181 . then ( resolve )
168182 . catch ( reject )
0 commit comments