Skip to content

Commit

Permalink
migration
Browse files Browse the repository at this point in the history
  • Loading branch information
eomsung committed Dec 11, 2024
1 parent 500ed1a commit d2e68df
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 28 deletions.
30 changes: 14 additions & 16 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import express from "express";
import { Product } from "./models/product.js";
import mongoose from "mongoose";
import { PrismaClient, Prisma } from "@prisma/client";
import { assert } from "superstruct";
import * as dotenv from "dotenv";
import cors from "cors";

import { CreateProduct, PatchProdcut } from "./structs.js";
dotenv.config();

const prisma = new PrismaClient();
const app = express();

app.use(
Expand All @@ -16,6 +16,7 @@ app.use(
],
})
);
app.use(express.json());

const asyncHandler = (handler) => {
return async (req, res) => {
Expand All @@ -37,8 +38,6 @@ const asyncHandler = (handler) => {
};
};

app.use(express.json());

app.get(
"/products",
asyncHandler(async (req, res) => {
Expand Down Expand Up @@ -68,13 +67,14 @@ app.get(
}
: {};

const products = await Product.find(search)
const products = await prisma.product
.find(search)
.select("name price createdAt favoriteCount")
.sort(sortOption)
.skip(offset)
.limit(pageSize);

const totalCount = await Product.countDocuments(search);
const totalCount = await prisma.product.countDocuments(search);

res.send({ list: products, totalCount });
})
Expand All @@ -84,24 +84,26 @@ app.get(
"/products/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
const product = await Product.findById(id).select("-updatedAt");
const product = await prisma.product.findById(id).select("-updatedAt");
res.send(product);
})
);

app.post(
"/products",
asyncHandler(async (req, res) => {
const product = await Product.create(req.body);
assert(req.body, CreateProduct);
const product = await prisma.product.create(req.body);
res.status(201).send(product);
})
);

app.patch(
"/products/:id",
asyncHandler(async (req, res) => {
assert(req.body, PatchProdcut);
const id = req.params.id;
const product = await Product.findById(id);
const product = await prisma.product.findById(id);
Object.keys(req.body).forEach((key) => {
product[key] = req.body[key];
});
Expand All @@ -116,15 +118,11 @@ app.delete(
"/products/:id",
asyncHandler(async (req, res) => {
const id = req.params.id;
await Product.findByIdAndDelete(id);
await prisma.product.findByIdAndDelete(id);
res.sendStatus(204);
})
);

mongoose
.connect(process.env.DATABASE_URL)
.then(() => console.log("Connected to DB"));

app.listen(process.env.PORT || 3000, () => {
console.log(`Server started`);
});
28 changes: 19 additions & 9 deletions data/seed.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import mongoose from "mongoose";
import products from "./mock.js";
import { Product } from "../models/product.js";
import { config } from "dotenv";
import { PrismaClient } from "@prisma/client";

config();
const prisma = new PrismaClient();

await mongoose.connect(process.env.DATABASE_URL);
async function main() {
try {
await prisma.product.deleteMany({});
await prisma.product.createMany({
data: products,
skipDuplicates: true,
});
} catch (e) {
throw e;
} finally {
await prisma.$disconnect();
}
}

await Product.deleteMany({});
await Product.insertMany(products);

mongoose.connection.close();
// 실행
main().catch((e) => {
process.exit(1);
});
111 changes: 109 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@
"license": "ISC",
"description": "",
"dependencies": {
"@prisma/client": "^6.0.1",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"mongoose": "^7.8.3"
"is-email": "^1.0.2",
"is-uuid": "^1.0.2",
"mongoose": "^7.8.3",
"prisma": "^6.0.1",
"superstruct": "^2.0.2"
},
"devDependencies": {
"nodemon": "^3.1.7"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- CreateTable
CREATE TABLE "Product" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,
"price" INTEGER NOT NULL,
"tags" TEXT[],
"favoriteCount" INTEGER NOT NULL,
"images" TEXT[],
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Product_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "Article" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"content" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Article_pkey" PRIMARY KEY ("id")
);
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
34 changes: 34 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Product {
id String @id @default(uuid())
name String
description String
price Int
tags String[]
favoriteCount Int
images String[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

model Article {
id String @id @default(uuid())
title String
content String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
14 changes: 14 additions & 0 deletions structs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import * as s from "superstruct";
import isEmail from "is-email";
import isUuid from "is-uuid";

export const CreateProduct = s.object({
name: s.size(s.string(), 1, 10),
description: s.size(s.string(), 10, 100),
price: s.min(s.number(), 0),
tags: s.array(s.size(s.string(), 1, 5)),
favoriteCount: s.optional(s.min(s.number(), 0)),
images: s.optional(s.array(s.string())),
});

const PatchProdcut = s.partial(CreateProduct);

0 comments on commit d2e68df

Please sign in to comment.