feat: integrate Prisma for MongoDB with initial schema and seed data

This commit is contained in:
ngc2207 2024-11-21 14:35:31 +08:00
parent ff57a87de5
commit 7faa8237c7
4 changed files with 95 additions and 3 deletions

View File

@ -15,19 +15,21 @@
"lucide-react": "^0.460.0", "lucide-react": "^0.460.0",
"next": "15.0.3", "next": "15.0.3",
"next-themes": "^0.4.3", "next-themes": "^0.4.3",
"prisma": "^5.22.0",
"react": "19.0.0-rc-66855b96-20241106", "react": "19.0.0-rc-66855b96-20241106",
"react-dom": "19.0.0-rc-66855b96-20241106", "react-dom": "19.0.0-rc-66855b96-20241106",
"tailwind-merge": "^2.5.4", "tailwind-merge": "^2.5.4",
"tailwindcss-animate": "^1.0.7" "tailwindcss-animate": "^1.0.7"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5", "@prisma/client": "^5.22.0",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "15.0.3",
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.1",
"eslint": "^8", "typescript": "^5"
"eslint-config-next": "15.0.3"
} }
} }

18
prisma/schema.prisma Normal file
View File

@ -0,0 +1,18 @@
generator client {
provider = "prisma-client-js"
output = "../node_modules/.prisma/client"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model Snippet {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
language String
code String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

57
prisma/seed.ts Normal file
View File

@ -0,0 +1,57 @@
import prisma from "@/lib/prisma";
async function main() {
await prisma.snippet.createMany({
data: [
{
title: "Hello World in JavaScript",
language: "JavaScript",
code: `console.log("Hello, World!");
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Prisma"));`,
},
{
title: "Hello World in Python",
language: "Python",
code: `print("Hello, World!")
def greet(name):
return f"Hello, {name}!"
print(greet("Prisma"))`,
},
{
title: "Hello World in Java",
language: "Java",
code: `public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
public static String greet(String name) {
return "Hello, " + name + "!";
}
public static void main(String[] args) {
System.out.println(greet("Prisma"));
}
}`,
},
],
});
console.log("Seeding completed.");
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});

15
src/lib/prisma.ts Normal file
View File

@ -0,0 +1,15 @@
import { PrismaClient } from "@prisma/client";
const prismaClientSingleton = () => {
return new PrismaClient();
};
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();
export default prisma;
if (process.env.NODE_ENV !== "production") globalThis.prismaGlobal = prisma;