fix(next): upload handlers can stop the next ones
What ?
This PR fix the uploads handlers to work accordingly to the documentation.
See packages/payload/src/uploads/types.ts:144 :
/**
* Custom handlers to run when a file is fetched.
*
* - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.
* - If a handler returns null, the next handler will be run.
* - If no handlers return a response the file will be returned by default.
*
* @default undefined
*/
handlers?: ((
req: PayloadRequest,
args: {
doc: TypeWithID
params: { collection: string; filename: string }
},
) => Promise<Response> | Promise<void> | Response | void)[]
https://github.com/payloadcms/payload/blob/76428373e4ad94ec29dd58ee293a68b0b67429dc/packages/payload/src/uploads/types.ts#L144C1-L159C62
Why ?
Currently, the customResponse instanceof Response check is done only after the whole for loop, so there's no way to prevent the other handlers to run by returning a response.
How ?
The proposed fix just make it works as the documentation says. It also allows for returning null in the handler. By moving the conditional check inside the for loop we avoid running the whole loop if we have any significant result
Example
In my implementation, I have a field on a collection called "location" with value "gcp" and "local". I created a handler that checks this field, and stream the file it it's local. Otherwise, the GCP storage plugin handles it. But with the current code, the GCP handler is always running and returns a 404, as it's the last registered #handler.