GraphQLGuide / apollo-datasource-mongodb

Apollo data source for MongoDB
MIT License
285 stars 64 forks source link

How to use other Model in data source? #24

Closed thearabbit closed 4 years ago

thearabbit commented 4 years ago

I tried to use mongoose

// Model
const Model1 = mongoose.model('col1', Schema1)
const Model2 = mongoose.model('col2', Schema2)

// Data source
export default class Data1 extends MongoDataSource {
  getData1(name) {
    // How to use `Model2`
    return this.model.findOne({ name: name })
  }
}
........................

// Apollo server
...........
dataSources: () => ({
    data1: new Data1(Model1),
    data2: new Data2(Model2),
  }),

How to use Model2 in DataSource1 (Data1)?

lorensr commented 4 years ago

For model methods, feel free to just import Model2. For data source methods (like data2.findOneById()), I'm not sure! Haven't seen an established best practice for this. The two solutions that come to mind are:

  1. Moving logic to the resolver, which can call methods on both data1 and data2
  2. Passing data2 as an argument to a data1 method, like in the resolver: data1.getData1('rabbit', data2)
thearabbit commented 4 years ago

Thanks for your reply. Excuse me, which one better for ???

1- Use Logic API directly on the resolver (Import ....) 2- Use Logic API from data source (Apollo Server

lorensr commented 4 years ago

Of the two solutions I mentioned, I'm not sure which is better.

9at8 commented 4 years ago

You might be able to use context inside the getData method in the Data1 class.

class Data1 extends DataSource {
  getData(x) {
    this.context.dataSources.data2.getData(x)
  }
}
lorensr commented 4 years ago

Oh yeah! That seems better ☺️

thearabbit commented 4 years ago

Very thanks again 👍