Skip to content

Commit

Permalink
feat(tRPC): add paged smart trades
Browse files Browse the repository at this point in the history
  • Loading branch information
bludnic committed Dec 21, 2024
1 parent 7cbe6da commit 176e2aa
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { xprisma, toSmartTradeEntity } from "@opentrader/db";
import type { TGetInfiniteSmartTradesSchema } from "./schema.js";
import type { Context } from "../../../../utils/context.js";

type Options = {
ctx: {
user: NonNullable<Context["user"]>;
};
input: TGetInfiniteSmartTradesSchema;
};

export async function getInfiniteSmartTrades({ ctx, input }: Options) {
const { cursor } = input;
const limit = input.limit ?? 50;
const items = await xprisma.smartTrade.findMany({
take: limit + 1, // get an extra item at the end which we'll use as next cursor
cursor: cursor ? { id: cursor } : undefined,
orderBy: {
updatedAt: "desc",
},
where: {
owner: { id: ctx.user.id },
bot: { id: input.botId },
},
include: {
orders: true,
exchangeAccount: true,
},
});

let nextCursor: typeof cursor | undefined = undefined;
if (items.length > limit) {
const nextItem = items.pop();
nextCursor = nextItem!.id;
}

return {
items: items.map((smartTrade) => toSmartTradeEntity(smartTrade)),
nextCursor,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { z } from "zod";

export const ZGetInfiniteSmartTradesSchema = z.object({
botId: z.number().optional(),
limit: z.number().min(1).max(100).nullish(),
cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type
});

export type TGetInfiniteSmartTradesSchema = z.infer<typeof ZGetInfiniteSmartTradesSchema>;
7 changes: 4 additions & 3 deletions packages/trpc/src/routers/private/smart-trade/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { router } from "../../../trpc.js";
import { authorizedProcedure } from "../../../procedures.js";
import { getSmartTrades } from "./get-smart-trades/handler.js";
import { ZGetSmartTradesSchema } from "./get-smart-trades/schema.js";
import { getInfiniteSmartTrades } from "./get-infinite-smart-trades/handler.js";
import { ZGetInfiniteSmartTradesSchema } from "./get-infinite-smart-trades/schema.js";
import { getSmartTrade } from "./get-smart-trade/handler.js";
import { ZGetSmartTradeInputSchema } from "./get-smart-trade/schema.js";

export const smartTradeRouter = router({
list: authorizedProcedure.input(ZGetSmartTradesSchema).query(getSmartTrades),
getOne: authorizedProcedure
.input(ZGetSmartTradeInputSchema)
.query(getSmartTrade),
infiniteList: authorizedProcedure.input(ZGetInfiniteSmartTradesSchema).query(getInfiniteSmartTrades),
getOne: authorizedProcedure.input(ZGetSmartTradeInputSchema).query(getSmartTrade),
});

0 comments on commit 176e2aa

Please sign in to comment.