Skip to content

Commit

Permalink
Merge pull request #68 from jphacks/feat/harata/add-rate-schema
Browse files Browse the repository at this point in the history
rate shema, userRate shema, API の作成
  • Loading branch information
hikahana authored Nov 16, 2024
2 parents 746e204 + 857854c commit 03ba2b7
Show file tree
Hide file tree
Showing 5 changed files with 207 additions and 88 deletions.
17 changes: 16 additions & 1 deletion app/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement())
uid String @unique
Expand All @@ -21,10 +20,15 @@ model User {
photoUrl String
scores Score[]
experiencePoint ExperiencePoint? @relation()
rateId Int @default(1)
ratePoint Int
// todo メール受信のフラグを追記。APIは別で作成する
isReceivedMail Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
@@index([uid])
rate Rate @relation(fields: [rateId], references: [id])
}

model Score {
Expand Down Expand Up @@ -76,3 +80,14 @@ model ExperiencePoint {
user User @relation(fields: [userId], references: [id])
}

model Rate {
id Int @id @default(autoincrement())
name String
minRange Int
maxRange Int
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
user User[]
}
208 changes: 124 additions & 84 deletions app/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,90 +1,130 @@
import { PrismaClient } from '@prisma/client';
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

async function main() {
// Word データの投入
const words = await prisma.word.createMany({
data: [
{ english: 'apple', japanese: 'リンゴ', difficulty: 1 },
{ english: 'banana', japanese: 'バナナ', difficulty: 1 },
{ english: 'galaxy', japanese: '銀河', difficulty: 3 },
{ english: 'computer', japanese: 'コンピュータ', difficulty: 2 },
{ english: 'ocean', japanese: '海', difficulty: 2 },
],
});

console.log('Inserted Words:', words);

// Words の ID を取得
const allWords = await prisma.word.findMany();

// Assignment データの投入
const assignments = await Promise.all(
allWords.map((word) =>
prisma.assignment.create({
data: {
wordId: word.id,
date: new Date(`2024-10-${Math.floor(Math.random() * 30) + 1}`),
},
})
)
);

console.log('Inserted Assignments:', assignments);

// User データの投入
const users = await prisma.user.createMany({
data: [
{
uid: 'user123',
name: 'Alice',
email: '[email protected]',
photoUrl: 'https://example.com/photos/alice.jpg',
},
{
uid: 'user456',
name: 'Bob',
email: '[email protected]',
photoUrl: 'https://example.com/photos/bob.jpg',
},
{
uid: 'user789',
name: 'Charlie',
email: '[email protected]',
photoUrl: 'https://example.com/photos/charlie.jpg',
},
],
});

console.log('Inserted Users:', users);

// Users の ID を取得
const allUsers = await prisma.user.findMany();

// Score データの投入
for (const user of allUsers) {
for (const assignment of assignments) {
await prisma.score.create({
data: {
point: Math.floor(Math.random() * 100),
similarity: parseFloat((Math.random()).toFixed(2)),
assignmentId: assignment.id,
userId: user.id,
imageUrl: `https://example.com/scores/${user.name.toLowerCase()}_${assignment.id}.jpg`,
},
});
}
}

console.log('Inserted Scores');
// Word データの投入
const words = await prisma.word.createMany({
data: [
{ english: "apple", japanese: "リンゴ", difficulty: 1 },
{ english: "banana", japanese: "バナナ", difficulty: 1 },
{ english: "galaxy", japanese: "銀河", difficulty: 3 },
{ english: "computer", japanese: "コンピュータ", difficulty: 2 },
{ english: "ocean", japanese: "海", difficulty: 2 },
],
});

console.log("Inserted Words:", words);

// Words の ID を取得
const allWords = await prisma.word.findMany();

// Assignment データの投入
const assignments = await Promise.all(
allWords.map((word) =>
prisma.assignment.create({
data: {
wordId: word.id,
date: new Date(`2024-10-${Math.floor(Math.random() * 30) + 1}`),
},
}),
),
);

console.log("Inserted Assignments:", assignments);

// Rate データの投入
const rateData = [
{ name: "ブロンズ", minRange: 0, maxRange: 199 },
{ name: "シルバー", minRange: 200, maxRange: 399 },
{ name: "ゴールド", minRange: 400, maxRange: 599 },
{ name: "プラチナ", minRange: 600, maxRange: 699 },
{ name: "ダイヤモンド", minRange: 700, maxRange: 799 },
{ name: "マスター", minRange: 800, maxRange: 899 },
{ name: "プレデター", minRange: 900, maxRange: 999 },
];

const rates = await prisma.rate.createMany({
data: rateData,
});

console.log("Inserted Rates:", rates);

const allRates = await prisma.rate.findMany();

// User データの投入
const users = await prisma.user.createMany({
data: [
{
uid: "user123",
name: "Alice",
email: "[email protected]",
photoUrl: "https://example.com/photos/alice.jpg",
rateId: allRates[4]?.id || 1, // ダイヤモンドのレート
ratePoint: 750,
},
{
uid: "user456",
name: "Bob",
email: "[email protected]",
photoUrl: "https://example.com/photos/bob.jpg",
rateId: allRates[6]?.id || 1, // プレデターのレート
ratePoint: 950,
},
{
uid: "user789",
name: "Charlie",
email: "[email protected]",
photoUrl: "https://example.com/photos/charlie.jpg",
rateId: allRates[0]?.id || 1, // ブロンズのレート
ratePoint: 0,
},
],
});

console.log("Inserted Users:", users);

// Users の ID を取得
const allUsers = await prisma.user.findMany();

// Score データの投入
for (const user of allUsers) {
for (const assignment of assignments) {
await prisma.score.create({
data: {
point: Math.floor(Math.random() * 100),
similarity: Number.parseFloat(Math.random().toFixed(2)),
assignmentId: assignment.id,
userId: user.id,
imageUrl: `https://example.com/scores/${user.name.toLowerCase()}_${assignment.id}.jpg`,
},
});
}
}

console.log("Inserted Scores");

// ExperiencePoint データの投入
for (const user of allUsers) {
await prisma.experiencePoint.create({
data: {
speedPoint: Math.floor(Math.random() * 100),
similarityPoint: Math.floor(Math.random() * 100),
totalPoint: Math.floor(Math.random() * 200),
continuationDay: Math.floor(Math.random() * 365),
userId: user.id,
},
});
}

console.log("Inserted ExperiencePoints");
}

main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
64 changes: 64 additions & 0 deletions app/src/app/api/rate/user/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { prisma } from "@lib/prisma";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

// ratePointの取得
export async function GET(req: NextRequest) {
const { pathname } = new URL(req.url || "");
const id = Number(pathname.split("/").pop());

if (!id) {
return NextResponse.json(
{ error: "Invalid or missing ID" },
{ status: 400 },
);
}

try {
const user = await prisma.user.findUnique({
where: { id },
include: {
rate: {
select: {
name: true,
minRange: true,
maxRange: true,
},
},
},
});

if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}

const nextRate = await prisma.rate.findFirst({
where: { minRange: { gt: user.rate.maxRange } },
orderBy: { minRange: "asc" },
select: { name: true, minRange: true },
});

const nextRateName = nextRate ? nextRate.name : "";
const pointsToNextRate = nextRate
? nextRate.minRange - user.ratePoint
: user.rate.maxRange - user.ratePoint;

const result = {
ratePoint: user.ratePoint,
rate: {
name: user.rate.name,
minRange: user.rate.minRange,
maxRange: user.rate.maxRange,
nextRateName,
pointsToNextRate,
},
};

return NextResponse.json(result, { status: 200 });
} catch (error) {
return NextResponse.json(
{ error: "Failed to get ratePoint", details: error },
{ status: 500 },
);
}
}
4 changes: 2 additions & 2 deletions app/src/app/api/user/new/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { DBUser as User } from "@/types";
import { prisma } from "@lib/prisma";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { type NextRequest, NextResponse } from "next/server";

type ResponseData = {
message: string;
Expand Down Expand Up @@ -38,6 +37,7 @@ export async function POST(req: NextRequest) {
name: user.displayName,
email: user.email,
photoUrl: user.photoURL,
ratePoint: 0,
experiencePoint: {
create: {
speedPoint: 0,
Expand Down
2 changes: 1 addition & 1 deletion compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ services:
- "5555:5555"
volumes:
- ./app:/app
command: sh -c "npm i && npx prisma db push && npx prisma generate && npm run dev"
command: sh -c "npm i && npx prisma db push && npx prisma generate && npx prisma db seed && npm run dev"
tty: true

db:
Expand Down

0 comments on commit 03ba2b7

Please sign in to comment.