728x90
반응형

전 포스트에서 클라이언트에서 쓰일 Create API를 만들었다. 

이번엔 나머지 findALL과 find메소드를 사용해서 전체조회, name에 따른 내용 조회를 구현해보겠다.

 

1. 이름은 같지만 나머지 내용이 다른 튜플을 하나 더 생성해준다.

 

이제 이름이 teepo인 튜플 2개가 생성되었다.

HeidiSQL 결과

 

2. 전체조회, 튜플 한 개 조회 라우터를 추가로 만들어준다.

 

routes/index.js

const express = require('express');
const router = express.Router();
const { Users } = require('../sequelize/models');

// 유저 생성 api
router.post('/create', async (req, res, next) => {
    const userbody = req.body; // 클라이언트로 부터 생성할 user 정보를 받는다.
    Users.create({
        email: userbody.email,
        password: userbody.password,
        name: userbody.name,
        phone: userbody.phone
    })
        .then((result) => {
            console.log("저장 성공: ", result);
            return res.send({ success: true, result });
        })
        .catch((err) => {
            console.log("저장 Error: ", err);
            return res.send({ success: false });
        });
});

// 유저 전체 조회 api
router.get('/findall', async (req, res, next) => {
    const query = req.query; // 클라이언트에서 보낸 query
    Users.findAll({ where: query }) // 검색 조건이 있을 경우 조건에 맞게 조회한다.
        .then((result) => {
            console.log("전체조회 성공: ", result);
            return res.send({ success: true, result });
        })
        .catch((err) => {
            console.log("전체조회 Error: ", err);
            return res.send({ success: false });
        });
});

// 유저 한 개 조회 api
router.get('/findone', async (req, res, next) => {
    const query = req.query; // 클라이언트에서 보낸 query
    Users.findOne({ where: query }) // 검색 조건이 있을 경우 조건에 맞게 제일 오래된 데이터를 조회한다.
        .then((result) => {
            console.log("조회 성공: ", result);
            return res.send({ success: true, result });
        })
        .catch((err) => {
            console.log("조회 Error: ", err);
            return res.send({ success: false });
        });
});


module.exports = router;

 

2-1. findall api로 먼저 조건없이 전체조회를 해본다.

 

2-2. findall api로 name이 teepo인 조건으로 조회한다.

 

2-3. findall api로 email이 teepo@co.kr인 조건으로 조회한다.

 

2-4. findone api로 조건없이 전체조회를 해본다.

 

2-5. findone api로 name이 teepo인 조건으로 조회한다.

 

2-6. findone api로 email이 teepo@co.kr인 조건으로 조회한다.

 

결과를 보면 알 수 있듯이 findAll 메소드로 검색을 하면 배열 안에 담기는 것을 볼 수 있고,

findOne 메소드로 검색을 하면 json형태로 한 개의 데이터만 담기는 것을 볼 수 있다.

 

 

728x90
반응형

+ Recent posts