jnk1m
Foliage IT
jnk1m
전체 방문자
오늘
어제
  • 분류 전체보기 (209)
    • Today I Learned (34)
    • Java (47)
    • Database (15)
    • [NHN Academy] (27)
    • Spring (47)
    • HTML + CSS + JavaScript (11)
    • JSP (3)
    • Node.js (10)
    • React Native (2)
    • 기타 (8)
    • 스크랩 (5)

인기 글

최근 글

티스토리

hELLO · Designed By 정상우.
글쓰기 / 관리자
jnk1m

Foliage IT

기타

[Node.js] Day 09: 데이터 가져와서 출력하기3

2022. 5. 18. 00:40

2022/05/13

 

11.models 디렉토리의 index.js 파일에 새로 추가한 매핑 파일에 대한 설정을 추가

const Sequelize = require('sequelize');
const Item = require('./item')

const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env];
const db = {};

let sequelize = new Sequelize(config.database, config.username,
  config.password, config);

db.sequelize = sequelize;

db.Sequelize = Sequelize

db.Item = Item
Item.init(sequelize)


module.exports = db;




12.index.js 파일에 모델을 가져오는 코드를 추가

//모델 가져오기
const {Item} = require('./models')


13.index.js 파일의 데이터 삽입 처리 함수를 수정

//데이터 삽입 요청: 하나의 파일 업로드
app.post('/item/insert', upload.single('pictureurl'), 
    async(req, res, next) => {
    //클라이언트가 전송한 데이터를 가져오기
    const itemname = req.body.itemname;
    const description = req.body.description;
    const price = req.body.price;

    //파일 파라미터 읽기
    var pictureurl;
    if(req.file){
        pictureurl = req.file.filename;
    }else{
        pictureurl = "default.png"
    }

    //가장 큰 itemid를 조회해서 다음 itemid를 생성
    var itemid = 1;
    try{
        var x = await Item.max('itemid');
        itemid = x + 1;
    }catch(err){
        console.log(err)
    }

    //삽입하는 날짜(현재 날짜 및 시간)를 생성
    var date = new Date();

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = month >= 10 ? month : '0' + month;

    var day = date.getDate();
    day = day >= 10 ? day : '0' + day

    var hour = date.getHours();
    hour = hour >= 10 ? hour : '0' + hour;

    var minute = date.getMinutes();
    minute = minute >= 10 ? minute : '0' + minute;

    var second = date.getSeconds();
    second = second >= 10 ? second : '0' + second;

    Item.create({
        itemid:itemid,
        itemname:itemname,
        price:price,
        description:description,
        pictureurl:pictureurl,
        updatedate:year+'-'+month+'-'+day
    })
    
    //데이터를 삽입한 시간을 update.txt에 기록
    const writeStream = fs.createWriteStream('./update.txt');
    writeStream.write(year + '-' + month + '-' + day + ' ' + 
    hour + ':' + minute + ':' + second);
    writeStream.end();

    res.json({'result': true})
})



14.index.js 파일에서 전체 데이터 가져오기 수정

//전체 데이터 가져오기 요청을 처리하는 라우팅 함수
app.get('/item/all', async(req, res, next) => {
    try{
        //전체 데이터 와 전체 데이터 개수를 가져와서 출력
        var list = await Item.findAll()
        var count = await Item.count(); 
        res.json({'count':count, 'list':list})
    }catch(err){
        console.log(err)
    }
})



15.index.js 파일에서 데이터 일부분 가져오기 수정

//데이터 일부분 가져오기
app.get('/item/list', async (req, res, next) => {
    //파라미터 가져오기: 일부분 가져오는 경우는 데이터 개수 와 페이지 번호 필요
    //get 방식에서 pageno 와 count 파라미터 가져오기
    const pageno = req.query.pageno;
    const count = req.query.count;

    //일부분 가져오기 위한 변수를 선언
    var start = 0;
    var size = 5;

    if(count != undefined){
        size = parseInt(count);
    }
    if(pageno != undefined){
        start = (parseInt(pageno) - 1) * size;
    }

    try{
        //start 부터 size 만큼 가져오기
        //itemid 의 내림차순 정렬
        var list = await Item.findAll({
            offset:start,
            limit:size,
            order:[
                ['itemid', 'DESC']
            ],
            
        });
        var cnt = await Item.count()

        res.json({'count': cnt, 'list':list})
    }catch(err){
        console.log(err)
    }
 

})



16.index.js 파일에서 상세보기 처리 코드를 수정

//상세보기 - 데이터 1개와서 리턴
app.get('/item/detail', async(req, res, next) => {
    //1개의 데이터를 찾아오기 위한 primary key 값 가져오기
    var itemid = req.query.itemid;
    if(itemid == undefined){
        itemid=1;
    }

    try{
        var item = await Item.findOne({
            where:{itemid:itemid}
        });
        res.json({'result':true, 'item':item})
    }catch(err){
        console.log(err);
        res.json({'result':false})
    }

})



17.index.js 파일에서 데이터 삭제 요청 수정

app.post('/item/delete', async(req, res, next) => {
    //파라미터 읽어오기: 삭제는 기본키 만을 읽어옵니다.
    //클라이언트에서는 itemid 라는 이름으로 itemid를 post 방식으로 전송
    const itemid = req.body.itemid;

    //삭제하는 날짜(현재 날짜 및 시간)를 생성
    var date = new Date();

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = month >= 10 ? month : '0' + month;

    var day = date.getDate();
    day = day >= 10 ? day : '0' + day

    var hour = date.getHours();
    hour = hour >= 10 ? hour : '0' + hour;

    var minute = date.getMinutes();
    minute = minute >= 10 ? minute : '0' + minute;

    var second = date.getSeconds();
    second = second >= 10 ? second : '0' + second;

    try{
        var item = await Item.destroy({
            where:{itemid:itemid}
        })
        //데이터를 삭제한 시간을 update.txt에 기록
        const writeStream = fs.createWriteStream('./update.txt');
        writeStream.write(year + '-' + month + '-' + day + ' ' + 
            hour + ':' + minute + ':' + second);
        writeStream.end();
        res.json({"result":true})
    }catch(err){
        console.log(err)
        res.json({"result":false})
    }
})


18.index.js 파일에서 데이터 수정 처리 코드를 수정

app.post("/item/update", 
    upload.single('pictureurl'), async(req, res, next) => {
        //파라미터 읽어오기
        const itemid = req.body.itemid;
        const itemname = req.body.itemname;
        const description = req.body.description;
        const price = req.body.price;
        const oldpictureurl = req.body.oldpictureurl;
        
        var pictureurl;
        if(req.file){
            pictureurl = req.file.filename;
        }else{
            pictureurl = oldpictureurl;
        }

         //삭제하는 날짜(현재 날짜 및 시간)를 생성
        var date = new Date();

        var year = date.getFullYear();

        var month = date.getMonth() + 1;
        month = month >= 10 ? month : '0' + month;

        var day = date.getDate();
        day = day >= 10 ? day : '0' + day

        var hour = date.getHours();
        hour = hour >= 10 ? hour : '0' + hour;

        var minute = date.getMinutes();
        minute = minute >= 10 ? minute : '0' + minute;

        var second = date.getSeconds();
        second = second >= 10 ? second : '0' + second;

        try{

            var item = await Item.update({
                itemname:itemname,
                price:price,
                description:description,
                pictureurl:pictureurl,
                updatedate:year + '-' + month + '-' + day
            }, {where:{itemid:itemid}})

            //데이터를 수정한 시간을 update.txt에 기록
            const writeStream = fs.createWriteStream('./update.txt');
            writeStream.write(year + '-' + month + '-' + day + ' ' + 
                hour + ':' + minute + ':' + second);
            writeStream.end();

            res.json({"result":true})
        }catch(err){
            console.log(err)
            res.json({"result":false})
        }

})
    '기타' 카테고리의 다른 글
    • [Git] 명령어 정리: 커밋 이후의 저장소 반영 내용 수정부터 원격 저장소와 로컬 연결 및 병합까지
    • [Git] 명령어 정리: 설치 및 초기 설정, 저장소 생성, 파일 추가와 커밋, 원격 저장소 업로드 + 에러 해결
    • 한글 2 byte의 기준은 무엇인가?
    • ToyStory.java

    티스토리툴바