I'm creating a new GraphQL server with Apollo, and keep running into this issue.
The dataSources function keeps getting called over and over. I'm not sure what's causing this issue, but I have a couple of log points that indicate it is.
My server constructor (index.js) looks like this:
const schema = fs.readFileSync('path/to/schema.graphql', 'utf8');
const resolvers = require('path/to/resolvers.js');
const databaseDatasource = require('path/to/source.js');
const options = getOptionsFromCli(); // private function
const server = new Apollo({
typeDefs: schema,
resolvers: resolvers,
dataSources: () => ({
database: new databaseDatasource(options);
})
});
My database source
const db = require('path/to/db.js'); // returns a dictionary of Sequelize models
const DataSource = require('apollo-datasource').DataSource;
class DatabaseSource extends DataSource {
constructor(options) {
super();
this.db = db(options);
}
}
module.exports = DatabaseSource;
The db() function constructs and ties together multiple Sequelize models. No errors are being reported from it.
The console.log gets called multiple times, even though there are no requests being made of the server:
> node index.js
Server online
http://localhost:8080/graphql
Data imported
Data imported
Data imported
Data imported
Data imported
Data imported
Data imported
Data imported
Process finished with exit code 2
Any help would be appreciated
After doing some further digging, I've noticed that
constructor() for each data source is called, rather than just initialize(context), as was my previous understanding from other issuesI was initializing my database and models in constructor(), but have moved it to avoid constantly being re-initialized
Hey @MatrixSenpai apollo-server works as expected. You should declare your database as a local variable outside dataSources function:
const database = new databaseDatasource(options);
const server = new Apollo({
typeDefs: schema,
resolvers: resolvers,
dataSources: () => ({ database })
});
Sorry for digging up such an old issue, it was referenced here.
And it seems to be still open.. can be closed maybe?
I'll go ahead and close. I've learned since that the data source gets recreated every time a query is run, and I've since moved sequelize elsewhere. I honestly forgot this was open
Most helpful comment
After doing some further digging, I've noticed that
constructor()for each data source is called, rather than justinitialize(context), as was my previous understanding from other issuesI was initializing my database and models in
constructor(), but have moved it to avoid constantly being re-initialized