14.0 Upload Form
늘 하던 패턴의 반복.
Model -> Form(useForm()) -> useMutation() 
14.1 Detail Page
14.2 Send Message
14.3 See Message
14.4 Mutations and Refresh
14.5 Seeding - prisma의 seeding 가짜 데이트베이스 많이 생성 하는 법.

1. seed.ts파일 생성

seed.ts파일 생성

2. 한 유저가 많이 생성 한것처럼 코드짜고

import { PrismaClient } from "@prisma/client";
// next.js의 바깥쪽

const client = new PrismaClient();

async function main() {
  [...Array.from(Array(500).keys())].forEach(async (item) => {
    await client.stream.create({
      data: {
        name: String(item),
        description: String(item),
        price: item,
        user: {
          connect: {
            id: 13, //내 아이디
          },
        },
      },
    });
    console.log(`${item}/500`);
  });
}
main()
  .catch((e) => console.log(e))
  .finally(() => client.$disconnect());


3. npm i ts-node 설치(https://www.npmjs.com/package/ts-node)
이게 뭐냐? TypeScript execution and REPL for node.js, with source map and native ESM support.
REPL이란  : Node. js Read-Eval-Print-Loop (REPL) is an easy-to-use command-line tool, used for processing Node. js expressions. It captures the user's JavaScript code inputs, interprets, and evaluates the result of this code. It displays the result to the screen, and repeats the process till the user quits the shell.
브라우저 개발자 모드에 있는 console대신 쓸수 있는 듯

이거말하는듯

5. package.json맨 아래에 해당 명령어 추

6. 그리고 바로 npx prisma db seed 명령어 치면 에러 남.
SyntaxError: Cannot use import statement outside a module

7. 그럼 package.json에서 다음처럼 수정
참고: https://www.prisma.io/docs/guides/database/seed-database 

그리고 . npx prisma db seed다시 치면
데이터 400개쯤 만들다가 get kicked out 됨.
왜? planetscale은 무료로 1000개정도 커넥션 제공하는데 이건 문제가 안됨.
https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/connection-pool#external-connection-poolers

대신, pool time out 때문에 그렇다.
Pool은 데이터 모으는거고, pool timeout은 이게 정해진 시간 넘도록 특정 쿼리 처리 못하면 exception을 던지고 다음 쿼리로 감.
The default connection pool timeout is 10 seconds. If the query engine does not process a particular query within that time, it throws an exception and moves on to the next query in the queue.
근데 serverless가 아닌 일반 서버는 데이터베이스가 허용하는 연결의 수 제한이 매우 작음
근데 우리는 planetscale이 1000개의 동시연결이 가능하단걸 prisma에게 알려주지 않았다.
그래서 prisma에서 시간 초과가 되었다. 우린 일반 DB보다 훨씬 빨랐기 때문에!

연결 limit을 늘리거나, 커넥션이 더 길어져도 된다면 그걸 늘리면 됨.
schema.prisma 파일에  추가
https://www.prisma.io/docs/concepts/components/prisma-client/working-with-prismaclient/connection-pool#external-connection-poolers

 

datasource db { provider = "postgresql" url = "postgresql://johndoe:mypassword@localhost:5432/mydb?connection_limit=5&pool_timeout=2" }





14.6 Pagination
Try not to fry our database
아래처럼 포함하고 있는 관계에도 pagination할 수 있다. 
아니 무조건 해야 한다. 

다 돈이거든

 

prisma 로그 출력하는 방법


참고로 표준출력이란 stdout: https://ko.wikipedia.org/wiki/%ED%91%9C%EC%A4%80_%EC%8A%A4%ED%8A%B8%EB%A6%BC

SELECT `carrot-market`.`Stream`.`id`, `carrot-market`.`Stream`.`created`, `carrot-market`.`Stream`.`updated`, `carrot-market`.`Stream`.`name`, `carrot-market`.`Stream`.`description`, `carrot-market`.`Stream`.`price`, `carrot-market`.`Stream`.`userId` FROM `carrot-market`.`Stream` WHERE 1=1 ORDER BY `carrot-market`.`Stream`.`id` ASC LIMIT ? OFFSET ?

 

'클론코딩-캐럿마켓 > 전반' 카테고리의 다른 글

16 NEXTJS IMAGES  (0) 2023.01.12
15 CLOUDFLARE IMAGES - 사진 다루기  (0) 2023.01.11
13 Profile  (0) 2023.01.09
12 동네생활  (0) 2023.01.06
11 Products  (0) 2023.01.04

+ Recent posts