처음 앱을 시작할 때 관리자계정 같은 초기 데이터를 넣어주고 싶었다.
Seeding, 말 그대로 씨앗을 처음 심어주는거다.
노드 환경에서 Prisma를 이용하여 진행하였다.
공식문서에 친절하게 잘 나와있다.
package.json에 다음의 데이터를 추가한다."prisma": {
"seed": "ts-node prisma/seed.ts"
},
seed.ts의 경로를 올바르게 작성해주어야 한다.
seed.ts를 작성해준다. seed.ts는 데이터를 생성하는 스크립트다.import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
/*
To resolve json file
-> tsconfig.json
"esModuleInterop": true,
"resolveJsonModule": true
*/
import categoryData from '../data/category.json';
const prisma = new PrismaClient();
async function hash(text: string) {
const saltOrRounds = 10;
const hashedToken = await bcrypt.hash(text, saltOrRounds);
return hashedToken;
}
async function main() {
return prisma.$transaction(async (tx) => {
// seed admin user
const hashedPassword = await hash(process.env.ADMIN_PASSWORD);
await tx.user.upsert({
where: {
id: 1,
},
update: {},
create: {
id: 1,
email: 'admin',
nickname: 'admin',
password: hashedPassword,
},
});
// seed categories
const categories = Object.values(categoryData);
for (const category of categories) {
await tx.category.upsert({
where: {
id: category.id,
},
update: {},
create: {
id: category.id,
title: category.label,
},
});
}
});
}
main()
.catch((e) => console.error(e))
.finally(() => prisma.$disconnect());
upsert를 사용했는데 앱을 실행할 때마다 Seed를 하도록 설정해 놨기 때문이다.tsconfig를 주석처럼 설정해줬다. (혹은 fs의 readFile등을 이용할 수도 있다.)npx prisma db seed 명령어를 실행한다.ts-node prisma/seed.ts가 실행된다.