Apollo-server: [apollo-datasource-rest] - Reuse classes outside of Apollo Server context

Created on 11 Apr 2019  路  6Comments  路  Source: apollographql/apollo-server

I'm using the package apollo-datasource-rest alongside Apollo Server to manage external REST requests and its working fine.

module.exports = class AuthenticationAPI extends RESTDataSource {
  constructor() {
    super()
    this.baseURL = REST_ENDPOINT
  }

  async login(args) {
    return this.post('/FormLogin/login', args)
  }

}

I would like to call those same class methods on server init before actually launching the Apollo Server. Naively I tried to instanciate the class with new and then call methods on the instance but at the moment I'm getting this error when class is instantiated outside the apollo server "context".

// from anywhere, executed outside of apollo server context
const authenticationAPI = new AuthenticationAPI()
this.authenticationAPI.login(data)
-------
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetch' of undefined
    at AuthenticationAPI.<anonymous> (/<folder>/node_modules/apollo-datasource-rest/dist/RESTDataSource.js:151:63)

Is there a way to archieve this or will I have to duplicate same fetching methods?

Most helpful comment

Actually relates to this https://github.com/apollographql/apollo-server/issues/2240

Calling initialize() function with empty object fixed my problem.

this.authenticationAPI = new AuthenticationAPI()
this.authenticationAPI.initialize({})
const token = await this.authenticationAPI.login(credentials)

All 6 comments

Actually relates to this https://github.com/apollographql/apollo-server/issues/2240

Calling initialize() function with empty object fixed my problem.

this.authenticationAPI = new AuthenticationAPI()
this.authenticationAPI.initialize({})
const token = await this.authenticationAPI.login(credentials)

i have the same issue

As mentioned above, data sources are automatically initialized by Apollo Server with the context, so you'll need to do this manually when using them separately.

@martijnwalraven do you plan having a clean support for using datasources in subscriptions?

@quentinus95 Yes, but not until Apollo Server 3 unfortunately. Subscriptions are currently implemented as a completely separate server that doesn't share the request pipeline with the regular server.

I had the same problem with apollo-datasource-rest combined with graphql-yoga, but with the clue of @Renaud009, now it works.

You can see my comments about it here

Was this page helpful?
0 / 5 - 0 ratings

Related issues

leinue picture leinue  路  3Comments

bryanerayner picture bryanerayner  路  3Comments

jpcbarros picture jpcbarros  路  3Comments

dupski picture dupski  路  3Comments

deathg0d picture deathg0d  路  3Comments