Query Speed Up
please how do I optimise this query, I feel like am not doing it the right way
export const list = query({
args: {},
handler: async (ctx) => {
await getUserId(ctx);
const users = await ctx.db.query("customers").collect();
const usersWithDownline = await Promise.all(
users.map(async (user) => {
const userDetail = await ctx.db.get(user.userId);
const downline = await ctx.db
.query("downlines")
.withIndex("customer", (q) => q.eq("leader", user._id))
.collect();
const downlineWithFollower = await Promise.all(
downline.map(async (dl) => {
const follower = await ctx.db.get(dl.follower);
const followerDetails = await ctx.db.get(follower!.userId);
return {
...dl,
followers: {
userId: followerDetails!._id,
id: follower!._id,
email: followerDetails!.email,
firstName: follower!.firstName,
lastName: follower!.lastName,
},
};
}),
);
const upline = await ctx.db.get(user.upline ?? "");
const uplineDetails = await ctx.db.get(upline!.userId);
const products =
user.products?.map(async (productId: Id<"products">) => {
return await ctx.db.get(productId);
}) ?? [];
return {
...user,
user: userDetail,
productsList: await Promise.all(products),
downline: downlineWithFollower,
upline: upline
? {
id: upline._id,
email: uplineDetails!.email,
name: uplineDetails!.name,
firstName: upline.firstName,
lastName: upline.lastName,
}
: null,
};
}),
);
return usersWithDownline;
},
});export const list = query({
args: {},
handler: async (ctx) => {
await getUserId(ctx);
const users = await ctx.db.query("customers").collect();
const usersWithDownline = await Promise.all(
users.map(async (user) => {
const userDetail = await ctx.db.get(user.userId);
const downline = await ctx.db
.query("downlines")
.withIndex("customer", (q) => q.eq("leader", user._id))
.collect();
const downlineWithFollower = await Promise.all(
downline.map(async (dl) => {
const follower = await ctx.db.get(dl.follower);
const followerDetails = await ctx.db.get(follower!.userId);
return {
...dl,
followers: {
userId: followerDetails!._id,
id: follower!._id,
email: followerDetails!.email,
firstName: follower!.firstName,
lastName: follower!.lastName,
},
};
}),
);
const upline = await ctx.db.get(user.upline ?? "");
const uplineDetails = await ctx.db.get(upline!.userId);
const products =
user.products?.map(async (productId: Id<"products">) => {
return await ctx.db.get(productId);
}) ?? [];
return {
...user,
user: userDetail,
productsList: await Promise.all(products),
downline: downlineWithFollower,
upline: upline
? {
id: upline._id,
email: uplineDetails!.email,
name: uplineDetails!.name,
firstName: upline.firstName,
lastName: upline.lastName,
}
: null,
};
}),
);
return usersWithDownline;
},
});