theMostCuriousHomunculus
theMostCuriousHomunculus
TtRPC
Created by DrizzyDrake on 6/24/2024 in #❓-help
Brainstorming how to convert REST api to tRPC
create a stores router with different procedures, items being one of them, and then pass :store and :item as fields on your input object, so something like:
// ...
.input(z.object({ storeId: z.string(), itemId: z.string() }))
// ...
// ...
.input(z.object({ storeId: z.string(), itemId: z.string() }))
// ...
let me know if you need more details!
3 replies
TtRPC
Created by theMostCuriousHomunculus on 6/24/2024 in #❓-help
rate limiting with @fastify/rate-limit
// server/middleware/rate-limited.ts
import { TRPCError } from '@trpc/server';
import type { RateLimitOptions } from '@fastify/rate-limit';

import { middleware } from '../constants/trpc.js';

const rateLimited = (options: RateLimitOptions) => middleware(
async ({
ctx,
next,
}) => {
try {
await new Promise(
(
resolve,
reject,
) => {
ctx
.app
.rateLimit(options)
.bind(ctx.app)(ctx.req, ctx.res)
.then(resolve)
.catch((error) => {
reject(new TRPCError({
code: 'TOO_MANY_REQUESTS',
message: (error as Error).message,
}));
});
},
);

return next();
} catch (error) {
ctx.app.log.error(error);

if (error instanceof TRPCError) throw error;

throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: (error as Error).message,
});
}
},
);

export default rateLimited;
// server/middleware/rate-limited.ts
import { TRPCError } from '@trpc/server';
import type { RateLimitOptions } from '@fastify/rate-limit';

import { middleware } from '../constants/trpc.js';

const rateLimited = (options: RateLimitOptions) => middleware(
async ({
ctx,
next,
}) => {
try {
await new Promise(
(
resolve,
reject,
) => {
ctx
.app
.rateLimit(options)
.bind(ctx.app)(ctx.req, ctx.res)
.then(resolve)
.catch((error) => {
reject(new TRPCError({
code: 'TOO_MANY_REQUESTS',
message: (error as Error).message,
}));
});
},
);

return next();
} catch (error) {
ctx.app.log.error(error);

if (error instanceof TRPCError) throw error;

throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: (error as Error).message,
});
}
},
);

export default rateLimited;
2 replies