From f5be341accd0e3cbfb7d5da113468b58947cfd1d Mon Sep 17 00:00:00 2001 From: Hazelnoot Date: Fri, 21 Mar 2025 22:50:28 -0400 Subject: [PATCH] normalize mastodon API query parameters to strip `[]` suffix --- .../api/mastodon/MastodonApiServerService.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts b/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts index 2735856139..c35f318ac7 100644 --- a/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts +++ b/packages/backend/src/server/api/mastodon/MastodonApiServerService.ts @@ -74,6 +74,50 @@ export class MastodonApiServerService { payload.on('error', done); }); + // Remove trailing "[]" from query params + fastify.addHook('preValidation', (request, _reply, done) => { + if (!request.query || typeof(request.query) !== 'object') { + return done(); + } + + // Same object aliased with a different type + const query = request.query as Record; + + for (const key of Object.keys(query)) { + if (!key.endsWith('[]')) { + continue; + } + if (query[key] == null) { + continue; + } + + const newKey = key.substring(0, key.length - 2); + const newValue = query[key]; + const oldValue = query[newKey]; + + // Move the value to the correct key + if (oldValue != null) { + if (Array.isArray(oldValue)) { + // Works for both array and single values + query[newKey] = oldValue.concat(newValue); + } else if (Array.isArray(newValue)) { + // Preserve order + query[newKey] = [oldValue, ...newValue]; + } else { + // Preserve order + query[newKey] = [oldValue, newValue]; + } + } else { + query[newKey] = newValue; + } + + // Remove the invalid key + delete query[key]; + } + + return done(); + }); + fastify.setErrorHandler((error, request, reply) => { const data = getErrorData(error); const status = getErrorStatus(error);