Prisma2 ORM
你好,有什么办法我不能把它缩短吗?看起来真的很糟..。我试过用圈,但它坏了。
产生卡片的随机指标
export const getRandomCards = (cards: any) => {
let randomCards: number[] = [];
while (randomCards.length < 5) {
let card = Math.floor(Math.random() * cards.length);
if (!randomCards.includes(card)) randomCards.push(card);
}
return randomCards;
};然后,我想根据以前从数组中生成的索引发送卡片。
import express, { Request, Response, NextFunction } from "express";
import { getRandomCards } from "./../../../util";
import prisma from "../../../client";
export const getEvents = async (
_req: Request,
res: Response,
next: NextFunction
) => {
const cards = await prisma.event.findMany();
if (!cards) throw new Error();
const randomCards = getRandomCards(cards);
try {
const firstCard = await prisma.event.findUnique({
where: {
id: randomCards[0],
},
});
const secondCard = await prisma.event.findUnique({
where: {
id: randomCards[1],
},
});
const thirdCard = await prisma.event.findUnique({
where: {
id: randomCards[2],
},
});
const fourthCard = await prisma.event.findUnique({
where: {
id: randomCards[3],
},
});
const fifthCard = await prisma.event.findUnique({
where: {
id: randomCards[4],
},
});
res.send({
cards: { firstCard, secondCard, thirdCard, fourthCard, fifthCard },
});
} catch (err) {
throw new Error(err);
}
next();
};这样做是正确的做法吗?
发布于 2021-05-08 23:05:43
我建议您在查询中使用in运算符。
您目前的方法的问题是,它是“非常手动”。如果你想查询20张随机卡片怎么办?你不能写20个案子..。(请记住,开发人员是懒惰的)
const cards = await prisma.event.findMany({
where: {
id: { in: randomCards },
},
})你为什么要这么做?
const cards = await prisma.event.findMany();
if (!cards) throw new Error();我想你可以跳过它。如果你有200 K的记录会发生什么?你会查询整张表.丢弃数据,然后重新运行5次查询?
只需运行我在上面给您的查询,也许您可以执行"if cards.length === 0“这样的检查,然后抛出一个错误。
此外,我建议你:
randomCards by randomCardIds,对于getRandomCards -> getRandomCardIds也是如此(否则会假设变量包含一个卡片对象,而它只包含ids。event实体重命名为card可能吗?)读起来有点违背直觉:const cards = await prisma.event.XXX。是event还是cards ?参考资料:
https://stackoverflow.com/questions/67441956
复制相似问题