Google App Engine + GraphQL으로 스팀잇 API 서버 만들기

in #whan5 years ago (edited)


Design by @imrahelk


안녕하세요. 안피곤입니다.

바로 이전글 ⌈🚀5분 안에 Google App Engine에 Apollo GraphQL 서버 구성하기!⌋에서 GAE에 GraphQL 서버를 구성했습니다.

이제 이 API 서버를 이용하여 태그별 피드 검색, 저자 명성도 순, 댓글 순, 보상금액 순, 보팅 순 등의 데이터를 조회할 용도로 사용할 것입니다.

사실 API 서버를 Prisma로 구성하고 싶었습니다. 그런데 Prisma는 기능이 아직 많이 부족하다고 생각합니다. 제가 원하는 서비스를 구현하기에 매우 힘들었습니다.😥 결국 MongoDB를 사용하였습니다. 혹시라도 Prisma에 관심있으면 ⌈프리즈마(Prisma) 사용하기⌋ 시리즈 글을 읽어주세요~!


*

MongoDB + GraphQL + Google App Engine 조합으로 API 서버를 구성하였습니다. 그리고 MongoDB는 mlab.com 서비스를 이용하고 있습니다. DB 무료 제공 용량이 500MB라서 아껴서 써야 할 것 같습니다. 10만 건의 데이터를 저장했더니, 벌써 50%를 사용해버렸습니다. ㅠㅠ

그리고 코드를 전부 공개하기는 좀 그렇고, 일부 핵심 코드만 공개합니다. 앞으로 댓글 순, 보팅 순, 보상금액 순, 저자 명성도 순으로 조회하는 기능을 추가할 예정입니다.


index.js

import Storage from './storage'

const typeDefs = `
  type Query {
    getPosts(
      tags: [String]
    ): [Post!]!
  }
`;

const resolvers = {
  Query: {
    getPosts: async (_, args, { storage }) => {
      const { tags } = args;
      return await storage.getPosts(tags);
    }
  }
}

const storage = new Storage();

const server = new GraphQLServer({ 
    schema, 
    context: ({ request }) => ({ 
        request, 
        storage
    })
});
server.express.use(logger('dev'));
server.start({ port: PORT }, () => {
    console.log(`Server running on http://localhost:${PORT}`)
});


storage.js

import { MongoClient } from 'mongodb';

const collections = {
  POSTS: 'posts',
}

export default class Storage {
  constructor() {
    MongoClient.connect(process.env.MONGO_URI, { useNewUrlParser: true })
    .then(client => {
      this.db = client.db();
    });
  }

  getPosts(tags=["kr"], limit=10) {
    return this.db.collection(collections.POSTS)
      .find({
        $or: tags.map(tags => ({ tags }))
      }, { 
        limit 
      })
      .sort({ post_id: -1 })
      .toArray();
  }
}

태그(tag)를 or 조건으로 검색합니다. 만약, ["kr-book", "booksteem"]으로 검색한다면, 두 태그 중 하나라도 포함된 피드를 모두 조회합니다.




아래는 구글 앱 엔진에서 실행한 화면입니다.

이제 #bootsteem #kr-boot 태그에 올라온 피드를 조회하여, 최신순으로 받아 볼 수 있습니다. 이제 GraphQL 서버와 크롤링 데몬, 그리고 Front-End 페이지까지 개발완료되면 완성된 앱을 볼 수 있을 것 같습니다.


해피 코딩하세요~!




Sponsored ( Powered by dclick )

dclick-imagead

Sort:  

blockchainstudio님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
blockchainstudio님의 Steemitblog에 제가 한 일들이 소개되었습니다 + NextColony API 공개

이ㅎㅎ
근데 그리고보니 bluengel님과 anpigon 둘다 개발자시면서ㅠㅠ 스팀잇도 좀 고쳐주세요ㅠㅠ 요새 분위기가 왠만하면 다 받아줄 기세입니다. 헛수고 하진 않을 것 같아요. 다운보팅 버튼부터 누가 좀 옮겨줬으면ㅠㅠ

!dramatoken
우와 너무 멋집니다!! 역시 안피곤님.
#futsal 도 만들어주세요 ㅎㅎㅎㅎ

뽀돌님 드라마 토큰 감사합니다. #futsal은 포스팅 갯수가 많아지면 생각해볼께요. ㅎㅎ


@anpigon님 곰돌이가 1.6배로 보팅해드리고 가요~! 영차~

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

You received more than 8000 upvotes. Your next target is to reach 9000 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

해피베리 코딩하세요~~ ㅋㅋ
따라해봐야겠다..!!

Posted using Partiko iOS

해피코딩보이님 감사합니다.
해피 해피 코딩하세요.

앞으로도 유익한 포스팅 부탁 드려요.
!dramatoken


There's not enough DRAMA to go around.

To view or trade DRAMA go to steem-engine.com.

도리안님도 즐거운 코딩 하세요.
그리고 드! 라! 마! 토! 큰! 감사합니다~!
갑자기 이짤이 생각나네요. ㅋㅋ

토큰 발행이 실패할 때도 있어요. ㅠㅠ
이따 다시 보내 드릴께요.


DRAMATIC ERROR WHILE PARSING DRAMATIC ERROR

To view or trade DRAMA go to steem-engine.com.

항상 앞서나가시는군요.
스팀은 graphql 지원하는지 아시나요? 찾아봐도 별로 자료가 안나오네요.

steem은 graphql를 지원하지 않는 것으로 알고 있어요.
직접 구현해야할것 같아요..


You've got DRAMA!

To view or trade DRAMA go to steem-engine.com.

Hi @anpigon!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 2.270 which ranks you at #20831 across all Steem accounts.
Your rank has improved 200 places in the last three days (old rank 21031).

In our last Algorithmic Curation Round, consisting of 197 contributions, your post is ranked at #144.

Evaluation of your UA score:
  • Only a few people are following you, try to convince more people with good work.
  • The readers like your work!
  • You have already shown user engagement, try to improve it further.

Feel free to join our @steem-ua Discord server

나중 저녁에 따라해야겠어요.
잠깐 일하면서 눈팅만 하고 갑니다.

서버 쪽에도 관심이 많으시군요. ㅎㅎ
코딩은 항상 재미있습니다. ㅋ

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.032
BTC 66167.71
ETH 3014.78
USDT 1.00
SBD 3.73