programing

Firebase 및 GraphQL?

nasanasas 2020. 10. 30. 08:12
반응형

Firebase 및 GraphQL?


두 사람을 함께 사용한 경험이 있습니까?

관련 필드의 리졸버에 firebase 호출을 배치하여 구성 요소 소품의 일부 변수를 쿼리의 인수에 전달한다고 생각합니다.

당신의 생각을 알려주세요!


귀하의 질문에 답하기 위해이를 처리 할 수 있는 세 가지 방법 이 있습니다.

1. Firebase 및 GraphQL

Firebase를 사용하도록 설정 한 경우 Firebase API를 GraphQL 쿼리 및 변형으로 일대일 매핑 할 수 있습니다.

Firebase API를 GraphQL 리졸버로 래핑하고 그런 식으로 호출 할 수 있습니다. 이것이 좋은 예입니다 .

const ref = path => firebase.database().ref(path)
const getValue = path => ref(path).once('value')
const mapSnapshotToEntities = snapshot => snapshot.val().map((value, id) => ({ id, ...value }))
const getEntities = path => getValue(path).then(mapSnapshotToEntities)

const resolvers = {
    Author: {
        posts(author) {
            return getEntities('posts').then(posts => filter(posts, { authorId: author.id }))
        },
    },

    Post: {
        author(post) {
            return getEntities('authors').then(posts => filter(authors, { id: authorId }))
        },
    },
};

기본적으로 여기서 수행하는 작업은 리졸버에서 관계형 방식으로 데이터를 쿼리 할 때까지 작동 하는 데이터베이스로 Firebase를 사용하는 것입니다 . 데이터 저장소 상단의 서버 측에서 조인을 수행하는 기능이 없으면 단일 요청 만 수행하기 위해 리졸버에서 Firebase에 수많은 왕복 요청을 할 수 있습니다.

대부분의 사람들이 Firebase를 사용하는 이유는 실시간 기능 때문이며,이 측면에서 데이터 관계형 모델링 도구가 상당히 부족하기 때문에 주로 데이터 저장소가 아닙니다. 이를 통해 다른 데이터 소스를 사용하여 GraphQL로 마이그레이션하는 것이 더 나을 것입니다.

2. 서비스로서의 GraphQL 백엔드

Firebase와 같은 BaaS 제품을 사용할 수 있다는 점을 고려할 때 GraphQL BaaS로 전환하는 것을 고려할 수 있습니다.

3. 자체 호스팅 GraphQL

자체 데이터 저장소를 사용하여 자체 호스팅 솔루션으로 전환 할 수있는 경우에도 많은 이점이 있습니다. 다음은 몇 가지 큰 타자입니다.

  • 고유 한 데이터 저장소를 사용할 수있는 유연성과 특정 앱의 요구 사항에 맞게 여러 개를 사용할 수 있습니다.

  • 사용자 지정 쿼리 및 변형

  • API의 웹 후크에 연결된 마이크로 서비스를 통하지 않고 기본적으로 사용자 지정 논리를 추가합니다.

  • 자체 인증 및 권한 부여 메커니즘 롤

  • 저비용 솔루션


여기에서 몇 가지 권장 사항에 강력히 동의하지 않습니다. GraphQL은 관계형으로 사용할 수 있지만 NoSQL 방식으로도 사용할 수 있습니다. RTD (실시간 데이터베이스) 및 Firestore가있는 Firebase는 NoSQL 데이터베이스이기 때문에 NoSQL 데이터베이스로 모델링해야합니다! 이 접근 방식에는 장단점이 있습니다.

1. 최적화 된 읽기 :

NoSQL 데이터베이스로서 컬렉션은 클라이언트 (모바일 또는 웹)에서 뷰로 모델링되어야합니다. 따라서 쿼리를 만들 때 모든 것이 이미 병합되고 클라이언트 나 Firebase 함수에서 계산 된 소품을 만들 필요가 없습니다. 이 접근 방식은 읽기를 정말 빠르게 만듭니다.

2. 최적화 해제 된 쓰기 :

여기서 주된 트레이드 오프는 관련 데이터 (사용자 이름, 프로필 사진 업데이트 등)를 터치하는 경우 데이터베이스의 모든 문서를 업데이트해야한다는 것입니다. 이 경우 데이터베이스에서 모든 문서 (예 : 게시물, 댓글 등)를 찾고 원 자성을 보장해야합니다. 이 접근 방식은 쓰기 작업보다 훨씬 더 많은 읽기 작업을 수행 할 앱이있는 경우에 권장됩니다 (예 : 블로그처럼 7000 읽기에서 1 쓰기).

3. 간편한 확장 :

컬렉션은 다른 문서와 밀접한 관계가 없기 때문에 하나의 서버에서만 전체 컬렉션을 보유하거나 여러 서버로 분할 할 수 있습니다. (그래서 Firebase는 DynamoDB처럼 확장 비용이 저렴합니다.)

GraphQL은 쿼리 언어 일뿐입니다. 쿼리가 쉬워야하지만 데이터베이스 모델링 방법을 지시해서는 안됩니다. 데이터베이스, 쿼리 및 변형을 모델링하는 방법을 지정해야합니다.


요약 : GraphQL은 Firebase가 부족한 부분에서 빛을 발합니다. 강력한 데이터 모델링, 유연하고 효율적인 쿼리 및 개방형 사양은 모두 Firebase에 부족한 GraphQL의 필수 부분입니다.

강력한 데이터 모델링

Firebase는 제한된 데이터 모델링으로 인해 많은 비판을 받았습니다. 기본적으로 데이터는 동일한 데이터를 여러 번 설명하는 하나의 거대한 JSON으로 구성됩니다. 처음에 편리해 보이는 것은 동일한 데이터에 대한 모든 참조를 수동으로 추적해야하므로 데이터를 업데이트해야 할 때마다 관리 할 수없는 클라이언트 코드가 발생합니다 .

반면 GraphQL에서 사용되는 데이터 구조는 그래프로 모델링되므로 매우 직관적이고 생각하기에 익숙합니다. IDL 구문사용하여 GraphQL 스키마라고하는 데이터 모델을 쉽게 설명 할 수 있습니다. Twitter 앱의 경우 스키마는 다음과 같습니다.

type Tweet {
  id: ID!
  title: String!
  author: User! @relation(name: "Tweets")
}

type User {
  id: ID!
  name: String!
  tweets: [Tweet!]! @relation(name: "Tweets")
}

Here we defined two types Tweet and User with some scalar properties and also a one-to-many relationship between User and Tweet. Single data items are referred to as nodes - and a user node can be connected to many tweet nodes. This data structure is both simple and flexible, other than the JSON approach from Firebase.

Flexible and Efficient Queries

The flexible query capabilities of GraphQL is one its main benefits. Queries are hierarchical, that means you can specify data requirements that mirror the graph structure. In our Twitter example, we might have a query to fetch all users and their tweets:

query {
  allUsers {
    id
    name
    tweets {
      title
    }
  }
}

Note that we can freely include or leave out fields that we want to query, and we can even query across relations. This means that we neither need to do multiple queries nor are we querying unneeded data - making GraphQL queries extremely efficient.

Adding query arguments to the mix we can add features like a custom order or filters to obtain a powerful GraphQL API.

All of that is simply not possible with Firebase.

Realtime Data

Firebase's realtime capabilities have made it so popular - but since the GraphQL community is about to reach a consensus regarding realtime, Firebase's biggest advantage is nullified as well. I recommend this video tutorial on GraphQL subscriptions to get a better understanding of underlying concepts

Conclusion

So, to answer your question: GraphQL surpasses Firebases in most aspects making it the preferred choice.

If you're interested in GraphQL, I encourage you to check out Graphcool that combines the strengths of GraphQL with powerful features like built-in authentication and flexible hooks to AWS Lambda or other serverless functions to implement custom business logic.

Disclaimer: I work at Graphcool :)


Do you have to use firebase? There are services more specific to GraphQL that may offer what you're looking for. https://scaphold.io is a YC Fellowship Company that looks particularly promising and gives you a firebase like experience but it is powered by GraphQL.


You can use graphql & firebase locally. All the heavy lifting can be done in a webworker to avoid blocking the UI when resolving the request.

One word about the "many roundtrips necessary to resolve the request" : if you don't mind about the data transferred, that's not so much of a big deal since all the "roundtrips" are merged in the same socket frame. But if you do want to avoid big frames, you just have to put a little dataloader in front of your firebase database.

For realtime updates, you only have to subscribe to realtime events from firebase and send them to the webworker to convert them into real graphql subscriptions that can be resolved through your schema.

You can find more information on this very issue on my medium post : “Client-side only” realtime web applications with Firebase, GraphQL and apollo-client 2.0

Hope that helps !

참고URL : https://stackoverflow.com/questions/37535374/firebase-graphql

반응형