kriasoft / react-starter-kit

The web's most popular Jamstack front-end template (boilerplate) for building web applications with React
https://reactstarter.com
MIT License
22.75k stars 4.16k forks source link

Query example accessing a db table (react-starter-kit/src/data/queries) #969

Closed buildbreakdo closed 3 years ago

buildbreakdo commented 8 years ago

Would like to see an example where a database value is queried and injected into the page. Current understanding is that this project does not have an example like this.

We have fetch examples hitting an external API (google feeds) but nothing leveraging the generated sqlite3 db, would also mean we need a seed script which seems like a reasonable addition to the data folder.

Have spent a few days trying to figure out how to make a query to the sqlite3 db (to no avail) after setting up some seed values. Simple example would go a long way in helping.

koistya commented 8 years ago

The idea is to provide database client utility as a context variable to the GraphQL middleware:

// server.js
app.use('/graphql', graphQL(req => ({
  schema: require('./data/schema').default,
  context: {
    user: req.user,
    db: new Database(config.db.connection), // Your database client /w connection pooling
  },
  graphiql: true,
}));

...then inside the resolver functions in your GraphQL types you would use that db client as follows:

export default new GraphQLObjectType({
  name: 'User',
  fields: {
     ...
  },
  resolve(parent, arts, { db }) {
    return db.loadUserById(parent.authorId);
  },
});
koistya commented 8 years ago

@buildbreakdo it's essential to understand how to use batching and caching when fetching data inside the resolver functions, it's a very simple pattern that's based on Node.js process.nextTick(..) and ES6 promises. Here is an example library implementing that pattern:

https://github.com/facebook/dataloader

ulani commented 3 years ago

@buildbreakdo thank you very much for crating this issue! Unfortunately, we have close it due to inactivity. Feel free to re-open it or join our Discord channel for discussion.

NOTE: The main branch has been updated with React Starter Kit v2, using JAM-style architecture.