블록체인에서 친구 추가 기능의 구현

in #kr-dev6 years ago

안녕하세요. 오늘은 블록체인 기반 Dapp에서 친구 추가 기능에 대해서 이야기 해보려고 합니다.

편의상 문체가 제 자신에게 편하게 하는 것이라, 경어가 없는 부분은 이해 부탁 드립니다.

사실 친구 추가는 굉장히 쉬운 기능이라고 생각이 되지만, 문제는 그 뒤에 딸린 것이다. 친구의 글을 어떻게 화면에 보여줄지, 그리고 어떤 순서로 보여줄지 등등..이 어려운 부분은 UX engineer에게 맡기기로 하고..

우선 오늘은 친구 추가에 대해서 구현을 해보려고 한다.

Interface

Web쪽에 계신 분들이 CRUD이야기를 많이 하셔서 오늘의 명칭은 이것에 따라 보려고 한다.

createfriend
readfriends 이것만 복수임의 유의!
update는..없으니 생략
deletefriend

각각의 parameter는..

createfriend
input : account (친구의 account정보)
return : success or fail

readfriends
input : N/A (session정보를 기반으로 자동으로 account를 추출)
return :
result : data : friend account array

deletefriend : create friend와 동일.

DB구조

account를 key로 하고, 여기에 friend를 pair로 묶는 구조로, 친구가 3명이면...
account friend pair가 3개가 되는 단순한 형태이다.

DB 이름 : follower

Operation

createfriend

follower DB에 account, friend pair를 기록. 만약 기존에 같은 값이 있으면 fail을 return

readfriends

account를 key로 하여 읽은 값을 그대로 return, data라는 이름의 array + result

delete friend

account, friend pair로 찾은 값을 삭제하고 결과를 return

coding


아래는 실제 code입니다.

CRUD method들...DB읽기 실패 처리는 있으나..fail return은 없음..!

const mongo = require('mongodb');
const ObjectId = require('mongodb').ObjectId;
const MongoClient = require('mongodb').MongoClient;
const url = process.env.MONGODB_URI;


exports.createFriend = function(account, friend, callback){
  MongoClient.connect(url, function(err, db) {
      const dbo = db.db("heroku_dg3d93pq");
      const myObj = {account : account, follower : friend};
      dbo.collection("board").insertOne(myobj, function(err, res){
          if (err) throw err;
          console.log("1 follower inserted", account, friend);
          callback("OK");
          db.close();
      });
  });  
}

exports.readFriends = function(account, friend, callback){
    MongoClient.connect(url, function(err, db) {
      const dbo = db.db("heroku_dg3d93pq");
      const findQuery = {account : account};
      dbo.collection("board").find(findQuery).toArray(function(err, res){
          if (err) throw err;
          console.log("reading follower", res.length);
          //make body
          var body = [];
          for(i = 0;i < res.length; i++){
              body.push({ data : res[i].friend });
          }       
          callback(body);
          db.close();
      });
  });  
}

exports.deleteFriend = function(account, callback){
    MongoClient.connect(url, function(err, db) {
        const dbo = db.db("heroku_dg3d93pq");
        const deleteQuery = {account : account, follower : friend};
        dbo.collection("board").deleteOne(deleteQuery, function(err, res){
            if (err) throw err;
            console.log("1 follower deleted", account, friend);
            callback("OK");
            db.close();
        });
    });
}

이건 Post method의 routing처리..
모두 callback type으로 맞추니 copy & paste수준으로 처리 가능함.

  app.post("/createfriend", function(req, res) { 
      const friend = req.body.account;
      console.log("createfriend event", friend);
      follower.createFriend(req.session.account, friend, (result)=>{
          res.send(result);
      });
  });

  app.post("/deletefriend", function(req, res) { 
      const friend = req.body.account;
      console.log("deletefriend event", friend);
      follower.deleteFriend(req.session.account, friend, (result)=>{
          res.send(result);
      });
  });

  app.post("/readfriends", function(req, res) { 
      console.log("readfriends event");
      follower.readFriends(req.session.account,(result)=>{
          res.send(result);
      });
  });

보시기에 어려운 부분은 없을것으로 생각되지만..혹시나 궁금하신 것이 있으시면 댓글을 달아주세요.

Sort:  

(jjangjjangman 태그 사용시 댓글을 남깁니다.)
[제 0회 짱짱맨배 42일장]5주차 보상글추천, 1,2,3,4주차 보상지급을 발표합니다.(계속 리스팅 할 예정)
https://steemit.com/kr/@virus707/0-42-5-1-2-3-4

5주차에 도전하세요

그리고 즐거운 스티밋하세요!

ID를 포함하여 search를 하는 것이 필요함.

내가 follow한 사람과, 나를 follow한 사람의 숫자를 구하는 interface가 필요함. 이건 나중에~~~?

문과생은 오늘도 한글이 한글같지 않습니다.ㅠㅠ

Congratulations @dabble! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of comments

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @dabble! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.17
TRX 0.15
JST 0.029
BTC 61320.84
ETH 2394.93
USDT 1.00
SBD 2.56