【发布时间】:2021-07-30 04:13:03
【问题描述】:
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();
};
这样做是正确的做法吗?
【问题讨论】:
标签: typescript express orm prisma