Skip to content

Commit

Permalink
Improve RPC route response serialization
Browse files Browse the repository at this point in the history
This change serializes Blob data for API routes
and creates a JSON object from form responses,
although these are rare cases.
  • Loading branch information
blomqma committed Mar 26, 2024
1 parent 81e2aa6 commit 56e4721
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 14 deletions.
8 changes: 8 additions & 0 deletions apps/example/src/pages/api/v1/rpc/[operationId].ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ import {
} from '@/actions';
import { rpcApiRoute } from 'next-rest-framework';

// Body parser must be disabled when parsing multipart/form-data requests with pages router.
// A recommended way is to create a separate RPC API route for multipart/form-data requests.
// export const config = {
// api: {
// bodyParser: false
// }
// };

const handler = rpcApiRoute({
getTodos,
getTodoById,
Expand Down
20 changes: 9 additions & 11 deletions packages/next-rest-framework/src/app-router/rpc-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
import {
validateSchema,
logNextRestFrameworkError,
type RpcOperationDefinition
type RpcOperationDefinition,
parseRpcOperationResponseJson
} from '../shared';
import {
type FormDataContentType,
Expand Down Expand Up @@ -194,21 +195,18 @@ export const rpcRoute = <
);
}

const parseRes = (res: unknown): BodyInit => {
if (
res instanceof ReadableStream ||
res instanceof ArrayBuffer ||
res instanceof Blob ||
res instanceof FormData ||
res instanceof URLSearchParams
) {
const parseRes = async (res: unknown): Promise<BodyInit> => {
if (res instanceof ReadableStream || res instanceof Blob) {
return res;
}

return JSON.stringify(res);
const parsed = await parseRpcOperationResponseJson(res);
return JSON.stringify(parsed);
};

return new NextResponse(parseRes(res), {
const json = await parseRes(res);

return new NextResponse(json, {
status: 200,
headers: {
'Content-Type': 'application/json'
Expand Down
32 changes: 29 additions & 3 deletions packages/next-rest-framework/src/pages-router/rpc-api-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
validateSchema,
logNextRestFrameworkError,
type RpcOperationDefinition,
logPagesEdgeRuntimeErrorForRoute
logPagesEdgeRuntimeErrorForRoute,
parseRpcOperationResponseJson
} from '../shared';
import { type NextApiRequest, type NextApiResponse } from 'next/types';
import {
Expand Down Expand Up @@ -117,7 +118,7 @@ export const rpcApiRoute = <
// Parse multipart/form-data into a FormData object.
try {
req.body = await parseMultiPartFormData(req);
} catch (e) {
} catch {
res.status(400).json({
message: `${DEFAULT_ERRORS.invalidRequestBody} Failed to parse form data.`
});
Expand Down Expand Up @@ -166,7 +167,32 @@ export const rpcApiRoute = <
return;
}

res.status(200).json(_res);
if (_res instanceof Blob) {
const reader = _res.stream().getReader();
res.setHeader('Content-Type', 'application/octet-stream');

res.setHeader(
'Content-Disposition',
`attachment; filename="${_res.name}"`
);

const pump = async () => {
await reader.read().then(async ({ done, value }) => {
if (done) {
res.end();
return;
}

res.write(value);
await pump();
});
};

await pump();
}

const json = await parseRpcOperationResponseJson(_res);
res.status(200).json(json);
} catch (error) {
logNextRestFrameworkError(error);
res.status(400).json({ message: DEFAULT_ERRORS.unexpectedError });
Expand Down
14 changes: 14 additions & 0 deletions packages/next-rest-framework/src/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,17 @@ export const isValidMethod = (x: unknown): x is ValidMethod =>

export const capitalizeFirstLetter = (str: string) =>
str[0]?.toUpperCase() + str.slice(1);

export const parseRpcOperationResponseJson = async (res: unknown) => {
if (res instanceof FormData || res instanceof URLSearchParams) {
const body: Record<string, FormDataEntryValue> = {};

for (const [key, value] of res.entries()) {
body[key] = value;
}

return body;
}

return res;
};

0 comments on commit 56e4721

Please sign in to comment.