1. prisma 생성하기

 

npx prisma init 명령어로 prisma 를 생성한다

 

그후 env파일은 전에했던건 처럼 database와 user이름을 잘 맞춰준다.

 

 

 

1. model 을 만든다

 

Schema.prisma 파일

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

model User {
  id Int @id @default(autoincrement())
  firstName String
  lastName String?
  userName String @unique
  email String @unique
  password String
}

 

 

2.   users 폴더,  mutation, queries, typeDefs 파일들을 만든다.

 

 

 

 

3. typeDefs의 타입과 위에서 설정해준 model과 일치시킨다.

 

 

 

4. 한번더 migrate시킨다. 

 

* prisma schema 를 update 할경우에는

항상 migrate 를 시켜줘야한다.

 

 

 

4.  계정생성과, 프로필보기위한  mutation, query 설정

 

import { gql } from "apollo-server";

export default gql`
  type User {
    id: String!
    firstName: String!
    lastName: String
    username: String!
    email: String!
    createAt: String!
    updatedAt: String!
  }

  type Mutation {
    createAccount(
      firstName: String!
      lastName: String
      username: String!
      email: String!
      password: String!
    ): User
  }

  type Query {
    seeProfile(username: String): User
  }
`;

 

 

2.. Mutation 설정하기

 

import client from "../client";

export default {
  Mutation: {
    createAccount: async (
      _,
      { firstName, lastName, userName, email, password }
    ) => {
      // check if username or email are already on DB.
      const existingUser = await client.user.findFirst({
        where: {
          OR: [
            {
              userName,
            },
            {
              email,
            },
          ],
        },
      });
      console.log(existingUser); //체크용
      // hash password
      // save and return the user
    },
  },
};

 

여기서주의해야할점은 

첫번째 생성할 user가 userName과 email이 반드시 중복되면안되고

두번째 await 와 async 를 같이사용해서 비동기적으로 처리해 ( 실패에대한 처리를해야햔다.)

 

또한 prisma의 filter 기능도 알아보면 좋을거같다.

 

 

 

3. 비밀번호 HASH 처리하기

 

비밀번호를 그대로 저장하는건 있을수없는일이다.

그렇기때문에  hasing 처리를 해줘야한다.

 

사용자가로그인한 비밀번호 => return hashing처리한 패스워드 == DB에있는 비밀번호 처리를해줘야한다.

 

npm i bcrypt 

 

 

우선  설치해준다.

 

 

https://www.npmjs.com/package/bcrypt

 

bcrypt

A bcrypt library for NodeJS.. Latest version: 5.0.1, last published: a year ago. Start using bcrypt in your project by running `npm i bcrypt`. There are 3429 other projects in the npm registry using bcrypt.

www.npmjs.com

이문서를 참고해서 구현해주었다

 

 

import bycrpt from "bcrypt";
import client from "../client";

export default {
  Mutation: {
    createAccount: async (
      _,
      { firstName, lastName, userName, email, password }
    ) => {
      // 1. check if username or email are already on DB.
      const existingUser = await client.user.findFirst({
        where: {
          OR: [
            {
              userName,
            },
            {
              email,
            },
          ],
        },
      });
      console.log(existingUser); //체크용
      
      
      // 2. hash password   									-->추가
      const uglyPassword = await bycrpt.hash(password, 10);
      console.log(uglyPassword);

      // save and return the user								-->추가 end
    },
  },
};

 

 

 

 

4. 사용자 계정 생성하기

 

import bycrpt from "bcrypt";
import client from "../client";

export default {
  Mutation: {
    createAccount: async (
      _,
      { firstName, lastName, userName, email, password }
    ) => {
      // 1. check if username or email are already on DB.
      const existingUser = await client.user.findFirst({
        where: {
          OR: [
            {
              userName,
            },
            {
              email,
            },
          ],
        },
      });
      console.log(existingUser); //체크용
      // 2. hash password
      const uglyPassword = await bycrpt.hash(password, 10);
      console.log(uglyPassword);
      return client.user.create({							--> 추가
        data: {
          userName,
          email,
          firstName,
          lastName,
          password: uglyPassword,
        },
      });													--> end 추가

      // save and return the user
    },
  },
};

 

이렇게 return 문으로  data라는 오브젝트에 담아서 return을 하면

 

 

 

mutation {
  createAccount(
    firstName:"yun"
    lastName:"yeji"
    email:"yun@las.com"
    password:"123"
    userName:"yunrap"
  ){
    userName
  }
}

 서버실행후  graphql 명령어를 입력해주면 계정이 들어감을 확인할수있다.

 

 

확인하기쉬운방법은 prisma studio 에서 하면 쉽게할수있다.

 

 

 

 

5. try catch 문 작성하기

 

 

async 사용에서는 try catch 문을 사용하는것이좋다

 

변경하기

import bycrpt from "bcrypt";
import client from "../client";

export default {
  Mutation: {
    createAccount: async (
      _,
      { firstName, lastName, userName, email, password }
    ) => {
      try {
        // 1. check if username or email are already on DB.
        const existingUser = await client.user.findFirst({
          where: {
            OR: [
              {
                userName,
              },
              {
                email,
              },
            ],
          },
        });
        console.log(existingUser); //체크용

        if (existingUser) {
          //유저가 존재할시 생성 x
          throw new Error("This username/password is already taken.");
        }

        // 2. hash password
        const uglyPassword = await bycrpt.hash(password, 10);
        console.log(uglyPassword);
        return client.user.create({
          data: {
            userName,
            email,
            firstName,
            lastName,
            password: uglyPassword,
          },
        });

        // save and return the user
      } catch (e) {
        return e;
      }
    },
  },
};

 

 

 

 

6. 프로필 보기

 

users.quries파일

import client from "../client";
export default {
  Query: {
    seeProfile: (_, { userName }) =>
      client.user.findUnique({
        where: {
          userName,
        },
      }),
  },
};

users  quries 파일에 QUERY 를 추가해준다.

 

 

type Query {
seeProfile(userName: String): User
}
 
 

그후 서버실행하면

 

 

이렇게 프로필보기를 할 수 있다.

+ Recent posts