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?
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.
Most helpful comment
Actually relates to this https://github.com/apollographql/apollo-server/issues/2240
Calling initialize() function with empty object fixed my problem.