Build and Deploy a GraphQL API to the Edge with MySQL and PlanetScale — Part 8

Build and Deploy a GraphQL API to the Edge with MySQL and PlanetScale — Part 8

Fetch all Products query

Now let's finish by implementing our final query that will be used to fetch all products from our database.

Inside the grafbase/grafbase.config.ts file you should add the following query definition:

g.query('products', {
  resolver: 'products/all',
  returns: g.ref(product).optional().list().optional()
})

Next finish by creating the file grafbase/resolvers/products/all.ts and add the following:

import { connect } from '@planetscale/database'
import { config, options } from '../../lib'

const conn = connect(config)

export default async function ProductsAll() {
  try {
    const results = await conn.execute(
      'SELECT * FROM Products',
      undefined,
      options
    )

    return results?.rows || []
  } catch (error) {
    return []
  }
}

That's it! You now have a GraphQL query to fetch everything from the database. Open Pathfinder and execute the following GraphQL operation:

{
  products {
    id
    name
    slug
    price
    onSale
  }
}

👉 Continue to Part 9