/**
*  시작 화면을 위한 member.js 파일
*/

// 관련된 모듈을 로딩하는 코드(express 어쩌구 쓸때 나옴)
var express = require('express');
var db = require('../db');
var router = express.Router();

/** 회원 정보를 반환하는 라우트 함수
* 회원 정보를 요청하는 경로
* 안드로이드 : /member/{phone}
* 노드 : /member/:phone
app.js에서 /member를 이미 지정했기 때문에
/member를 빼고 member.js에 /:phone만 지정함.
경로에 포함된 매개변수라고 해서, 라우트 매개변수라고 부름.
라우트 매개변수로 넘어온 데이터는 반드시 req.params 객체에서 값을 가지고 와야 함.
따라서 :phone에 넘어온 값은 req.params.phone을 통해 값을 가지고 올 수 있음.
*/
router.get('/:phone', function(req, res, next){
  var phone = req.params.phone;
    
    var sql = "select * " + "from bestfood_member " + "where phone = ? limit 1;";
    console.log("sql : " + sql);
    
    //질의를 실행할 때, 다음 줄과 같은 형식을 가짐.
    //질의할 sql, sql문에 포함된 질의 매개변수 ?를 치환할 변수, 콜백함수로 구성됨.
    //만약 질의 매개변수(?)가 여러 개라면 배열 형식([phone, name])으로 작성해야 함.
    db.get().query(sql, phone, function (err, rows){
        console.log("rows : " + JSON.stringify(rows));
        console.log("row.length : " + rows.length);
        if(rows.length > 0) {
            res.json(rows[0]);
        } else {
            res.sendStatus(400);
        }
        if(err){
            console.log(err);
        }
    });
});

/**
*회원 전화번호를 저장하는 라우트 함수
*/
router.post('/phone', function(req,res){
    var phone = req.body.phone;
    
    var sql_count = "select count(*) as cnt " + 
        "from bestfood_member " + 
        "where phone = ?;";
    console.log("sql_count : " + sql_count);
    
    var sql_insert = "insert into bestfood_member (phone) values(?);";
    
    db.get().query(sql_count, phone, function(err, rows){
        console.log(rows);
        console.log(rows[0].cnt);
        
        if(rows[0].cnt>0){
            return res.sendStatus(400);
        }
            
        db.get().query(sql_insert, [phone, name, sextype, birthday], function(err,result){
            if(err) return res.sendStatus(400);
            res.status(200).send(''+result.insertId);            
        });
    });
});

/**
* 프로필에서 객체를 보내 정보를 업데이트할 때.
* 위에서 전화번호를 미리 저장했기 때문에,
* 전화번호 시퀀스를 얻어서 있으면 업데이트, 없으면 insert로 넘어가게 하는 과정 자체가 불필요하다.
* 그래서 한 부분이 주석처리.
*/
router.post('/info', function(req, res){
    var phone = req.body.phone;
    var name = req.body.name;
    var sextype = req.body.sextype;
    var birthday = req.body.birthday;
    
    console.log({name, sextype, birthday, phone});
    
    var sql_count = "select count(*) as cnt " + 
        "from bestfood_member " + 
        "where phone = ?;";
    console.log("sql_count : " + sql_count);
    
    var sql_insert = "insert into bestfood_member (phone, name, sextype, birthday), values(?, ?, ?, ?);";
    var sql_update = "update bestfood_member set name = ?, sextype = ?, birthday = ? where phone = ?; ";
    var sql_select = "select seq from bestfood_member where phone = ?; ";
    
    //쓸 데 없는 ... 폰 넘버가 같은 게 있는지 개수를 세는 건데 이미 프로필로 넘어왔으면 정해진 폰 번호가 이미 있을 것인데.. 한 번 더 체크를 하네.
//    db.get().query(sql_count, phone, function(err, rows){
//        if(rows[0].cnt > 0){
//            console.log("sql_update : " + sql_update);
//        
//        db.get().query(sql_update, [name, sextype, birthday, phone], function(err, result){
//            
//            if(err) return res.sendStatus(400);
//            console.log(result);
//            res.sendStatus(200);
//            
            //seq만 시퀀스만 베스트의 멤버 테이블로부터 받아오겠다. 조회 쿼리문을 날림.
//            db.get().query(sql_select, phone, function(err, rows){
//                if(err) return res.sendStatus(400);
                // res : 서버에서 사용자에게 보내겠다. 는  뜻. rows[0].seq를 response.body로 보냄.
                // 근데 이것도 또한 별 필요 없는 것 같음...
//                res.status(200).send('' + rows[0].seq);
//            });
//        });
//        
//    } else {
//        console.log("sql_insert : " + sql_insert);
//            
//            db.get().query(sql_insert, [phone, name, sextype, birthday], function(err,result){
//                
//                if(err) return res.sendStatus(400);
//                
//                res.status(200).send(''+result.insertId);
//            });
//        }
//    });

    /**
이 업데이트 쿼리문만 있어도 충분하긴 함. 대신 res.sendStatus(200)으로 성공 여부를 보내서
response.body에서 isSuccessful을 true로 통과.
*/
    db.get().query(sql_update, [name, sextype, birthday, phone], function(err, result){
            
            if(err) return res.sendStatus(400);
            console.log(result);
            res.sendStatus(200);
    });
});

//현재 작성한 함수를 외부에서 사용할 수 있도록 해주는 코드
module.exports = router;

member.js 전체 코드.

앞부분에서 전화번호를 저장하고, insertMemberPhone이 제대로 실행되지 않았을 시

경고문과 함께 정상 작동을 막는 코드를 자바에 추가해줘야 함.

밑의 코드를 보자.

/**
     * 사용자 정보를 조회하지 못했다면 insertMemberPhone() 메서드를 통해
     * 전화번호를 서버에 저장하고, MainActivity를 실행한 후에 ProfileActivity를 실행한다.
     * 그리고 현재 액티비티를 종료한다.
     * @param item 사용자 정보
     */
    private void goProfileActivity(MemberInfoItem item){
        if(item == null || item.seq <= 0){
            insertMemberPhone();
            Log.d("12345", "ffffffff");
        }

        Intent intent = new Intent(IndexActivity.this, MainActivity.class);
        startActivity(intent);

//        Intent intent2 = new Intent(this, ProfileActivity.class);
//        startActivity(intent2);

        finish();
    }

    /**
     * 폰의 전화번호를 서버에 저장한다.
     */
    private void insertMemberPhone(){
        String phone = EtcLib.getInstance().getPhoneNumber(context);
        RemoteService remoteService = ServiceGenerator.createService(RemoteService.class);

        Call<String> call = remoteService.insertMemberPhone(phone);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.isSuccessful()){
                    MyLog.d(TAG, "success insert id " + response.body().toString());
                } else { // reponse는 있는데 404가 뜬다거나 하는 에러 코드가 있는 경우 여기.
                    int statusCode = response.code();

                    ResponseBody errorBody = response.errorBody();

                    MyLog.d(TAG, "fail " + statusCode + errorBody.toString());
                }
            }
            @Override // response가 나올 수 없는(오류) 경우 throwable을 내보내게 되어 있는 듯.
            //보통 Log.d(TAG, t.toString() ) 해서 띄운다.
            public void onFailure(Call<String> call, Throwable t) {
                MyLog.d(TAG, "no internet connectivity");
                @@@@@@finish();@@@@@@@
            }
        });

    }

맨 아랫부분 onFailure에 finish()를  추가한 것처럼!!! 추가로 AlertDialog를 띄워 주어도 괜찮겠다.

 

 

또한, update 시퀀스에서

전화번호 조회, 저장 쿼리문은 필요 없다. 앞에서 제대로 작성했다면!

그러므로 아래 update 쿼리문만 있어도 된다.

/**
이 업데이트 쿼리문만 있어도 충분함. 대신 res.sendStatus(200)으로 성공 여부를 보내서
response.body에서 isSuccessful을 true로 통과하게 한다.
*/
db.get().query(sql_update, [name, sextype, birthday, phone], function(err, result){
            
            if(err) return res.sendStatus(400);
            console.log(result);
            res.sendStatus(200);

그에 따라 자바 코드에서도 시퀀스를 받아와 비교하는 코드(try-catch문)를 지운다.

만약 업데이트를 해서 성공(response.isSuccessful()를 통과, res.sendStatus(200)이 실행되어 200이 보내졌어야 함)하면

업데이트 됐겠지 믿고 newItem에 있는 정보들을 currentItem에 저장해서 출력해 보여준다.

		Call<String> call = remoteService.insertMemberInfo(newItem);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.isSuccessful()){
//                    String seq = response.body();
//                    try{
//                        currentItem.seq = Integer.parseInt(seq);
//                        if(currentItem.seq == 0){
//                            MyToast.s(context, R.string.member_insert_fail_message);
//                            return;
//                        }
//                    } catch (Exception e){
//                        MyToast.s(context, R.string.member_insert_fail_message);
//                        return;
//                    }
                    currentItem.name = newItem.name;
                    currentItem.name = newItem.name;
                    currentItem.sexType = newItem.sexType;
                    currentItem.birthday = newItem.birthday;
                    finish();
                }else {
                    Log.d(TAG, "실패니?" + response.errorBody());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d(TAG, "실패야?");
            }
        });