Compare commits

..
2 changed files with 32 additions and 25 deletions
+14 -9
View File
@@ -1,9 +1,12 @@
import { getBaseUrl } from '@documenso/lib/universal/get-base-url';
import { createTRPCClient, httpBatchLink, httpLink, isNonJsonSerializable, splitLink } from '@trpc/client';
import { z } from 'zod';
import type { AppRouter } from '../server/router';
import { dataTransformer } from '../utils/data-transformer';
const ZTeamIdHeaderSchema = z.string().min(1);
export const trpc = createTRPCClient<AppRouter>({
links: [
splitLink({
@@ -12,9 +15,11 @@ export const trpc = createTRPCClient<AppRouter>({
url: `${getBaseUrl()}/api/trpc`,
transformer: dataTransformer,
headers: (opts) => {
if (typeof opts.op.context.teamId === 'string') {
const teamId = ZTeamIdHeaderSchema.safeParse(opts.op.context.teamId);
if (teamId.success) {
return {
'x-team-id': opts.op.context.teamId,
'x-team-id': teamId.data,
};
}
@@ -25,14 +30,14 @@ export const trpc = createTRPCClient<AppRouter>({
url: `${getBaseUrl()}/api/trpc`,
transformer: dataTransformer,
headers: (opts) => {
const operationWithTeamId = opts.opList.find(
(op) => op.context.teamId && typeof op.context.teamId === 'string',
);
for (const op of opts.opList) {
const teamId = ZTeamIdHeaderSchema.safeParse(op.context.teamId);
if (operationWithTeamId && typeof operationWithTeamId.context.teamId === 'string') {
return {
'x-team-id': operationWithTeamId.context.teamId,
};
if (teamId.success) {
return {
'x-team-id': teamId.data,
};
}
}
return {};
+18 -16
View File
@@ -29,7 +29,7 @@ export type TrpcRouteMeta = {
successDescription?: string;
errorResponses?: number[] | Record<number, string>;
};
};
} & Record<string, unknown>;
const t = initTRPC
.meta<TrpcRouteMeta>()
@@ -37,30 +37,32 @@ const t = initTRPC
.create({
transformer: dataTransformer,
errorFormatter(opts) {
const { shape: errorTemplate, error, ctx } = opts;
const { shape, error, ctx } = opts;
const originalError = error.cause;
if (!(originalError instanceof AppError)) {
return errorTemplate;
}
if (originalError.headers && ctx) {
for (const [headerKey, headerValue] of Object.entries(originalError.headers)) {
ctx.res.headers.append(headerKey, headerValue);
}
}
let data: Record<string, unknown> = shape.data;
// Default unknown errors to 400, since if you're throwing an AppError it is expected
// that you already know what you're doing.
return {
...errorTemplate,
data: {
...errorTemplate.data,
if (originalError instanceof AppError) {
if (originalError.headers && ctx) {
for (const [headerKey, headerValue] of Object.entries(originalError.headers)) {
ctx.res.headers.append(headerKey, headerValue);
}
}
data = {
...data,
appError: AppError.toJSON(originalError),
code: originalError.code,
httpStatus: originalError.statusCode ?? genericErrorCodeToTrpcErrorCodeMap[originalError.code]?.status ?? 400,
},
};
}
return {
...shape,
data,
};
},
});