graphql mysql 데이터 호출 및 저장 방법

MINK·2022년 11월 11일
2

graphql mysql 데이터 호출 및 저장 방법

1. index.ts

import {ApolloServer} from "@apollo/server";
import {startStandaloneServer} from "@apollo/server/standalone";
import {item} from "./db/Item.js";
import {content, contents} from "./db/contents.js";
import {comments} from "./db/comment.js";
import {user} from "./db/user.js";
import {review} from "./db/review.js";

const typeDefs = `#graphql
  type Item {
    sId: Int!
    sName: String!
    sTitle: String!
    sContents: String!
    sPrice: Int!
    sLike: Int!
    sView: Int!
    sHalf_title:String!
    sCategory:String!
    slideImg: [String]!
    mainTopImg: [String]!
    mainMidImg: [String]!
    mainBottomImg: [String]!
  }
  
   type User{
    user_code : Int
    kakao_id : String
    kakao_profile_img : String
    kakao_nickname : String
    kakao_email : String
    user_role : String
    create_time : Date
  }
 
  type Contents {
    cId : Int!
    cWriter : String!
    cProfileImg : String!
    cImage : String!
    cTitle : String!
    cContent : String!
    cDate : String!
    cLike : Int!
  }
  
   type Comment {
    tId : Int!
    cId : Int!
    user_code : Int!
    comment : String!
    co_date : Date
  }
  
   type Review {
    rId : Int!
    sId : Int!
    user_code : Int!
    rReview : String!
    rDate : Date
  }
  
  type Query {
    item : [Item]
    contents : [Contents]!
    comments : [Comment]
    user : [User]
    review : [Review]
  }
    scalar Date

    type Mutation{
        addContent( cId : Int!, cWriter : String!, cProfileImg : String!, cImage : String!
        ,cTitle : String!
        ,cContent : String!
        ,cDate : String!
        ,cLike : Int!) :Boolean
}

`;

const resolvers = {
    Query: {
        item:() => item(),
        contents:() => contents(),
        comments:() => comments(),
        user:() => user(),
        review:() => review()
    },
    Mutation : {
        addContent : async (_, {cId, cWriter, cProfileImg,cImage, cTitle, cContent, cDate, cLike}) =>
    {
        const result = await content.insert(cId, cWriter, cProfileImg,cImage, cTitle, cContent, cDate, cLike);
        return result.code
    },
},

};

// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.

const server = new ApolloServer({
    typeDefs,
    resolvers,
});
(async () => {
    const {url} = await startStandaloneServer(server, {
        listen: {port: 4000},
    });
    console.log(`🚀 Server listening at: ${url}`);
})();




2. comment.ts

import mysql from "mysql2/promise";
import poolPromise, {dbConfig} from "./db.config.js";
import statusUtil from "./statusUtil";

const pool1 = mysql.createPool({
  host : dbConfig.host,
  user : dbConfig.user,
  password : dbConfig.password,
  database : dbConfig.database,
  waitForConnections : true,
  connectionLimit : 10,
  queueLimit : 0
}) ;



export const comments = async () => {
  const [rows] = await pool1.query("select * from comment");
  return rows;
}

3. user.ts

import mysql from "mysql2/promise";
import {dbConfig} from "./db.config.js";

const pool1 = mysql.createPool({
    host : dbConfig.host,
    user : dbConfig.user,
    password : dbConfig.password,
    database : dbConfig.database,
    waitForConnections : true,
    connectionLimit : 10,
    queueLimit : 0
}) ;


export const user = async () => {
    const [rows] = await pool1.query("select * from user_master");
    return rows;
}

4. review.ts

import mysql from "mysql2/promise";
import {dbConfig} from "./db.config.js";

const pool1 = mysql.createPool({
    host : dbConfig.host,
    user : dbConfig.user,
    password : dbConfig.password,
    database : dbConfig.database,
    waitForConnections : true,
    connectionLimit : 10,
    queueLimit : 0
}) ;


export const review = async () => {
    const [rows] = await pool1.query("select * from review");
    return rows;
}

5. contents.ts

import poolPromise, {dbConfig} from "./db.config.js";
import mysql from "mysql2/promise";
import statusUtil from "./statusUtil.js";

const pool1 = mysql.createPool({
  host : dbConfig.host,
  user : dbConfig.user,
  password : dbConfig.password,
  database : dbConfig.database,
  waitForConnections : true,
  connectionLimit : 10,
  queueLimit : 0
}) ;
const tableName = "contents"
const pool = {
    query: async (query, value) => {
        let result;
        const pool = await poolPromise;
        try {
            var connection = await pool.getConnection();
            result = value
                ? await connection.query(query, value)
                : (await connection.query(query)) || null;
        } catch (err) {
            console.log(err);
            connection.rollback();
        } finally {
            // @ts-ignore
            connection.release();
            return result;
        }
    },
};
export const content =
    {
      insert: async (cId, cWriter, cProfileImg,cImage, cTitle, cContent, cDate, cLike) => {
        const query = `INSERT INTO ${tableName} (cId, cWriter, cProfileImg, cImage, cTitle, cContent, cDate, cLike) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
        const result = await pool.query(query, [cId, cWriter, cProfileImg, cImage, cTitle, cContent, cDate, cLike]);

        return result ? statusUtil.success(result) : statusUtil.false();
      },
    };

export const contents = async () => {
  const [rows] = await pool1.query("select * from contents");
  return rows;
}

6. item.ts

import mysql from "mysql2/promise";
import {dbConfig} from "./db.config.js";

const pool1 = mysql.createPool({
    host: dbConfig.host,
    user: dbConfig.user,
    password: dbConfig.password,
    database: dbConfig.database,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});


export const item = async () => {
    const [rows] = await pool1.query("select * from shop");
    return rows;
}


// https://blog.naver.com/PostView.naver?blogId=kangminser88&logNo=221484949494&parentCategoryNo=&categoryNo=22&viewDate=&isShowPopularPosts=false&from=postView

7. db.config.ts

import mysql from "promise-mysql";

export const dbConfig = {
    host : "엔드포인트",
    user : "마스터 사용자 이름",
    password : "마스터 사용자 비밀번호",
    database : "데이터베이스",
    charset : 'utf8mb4'
}
export default mysql.createPool(dbConfig);

8. statusCode.ts

const statusCode = {
    OK: 200
};

export default statusCode;

9. statusUtil.ts

import StatusCode from "./statusCode.js";

const statusUtil = {
    success: (data) => {
        return { code: StatusCode.OK, data: data };
    },
    false: () => {
        return { code: StatusCode};
    },
};

export default statusUtil;
profile
parkminkyu velog

2개의 댓글

comment-user-thumbnail
2023년 2월 15일

잘 보고 갑니다👍

1개의 답글