Use Grafbase Edge Resolvers with Neon
Learn how to build and deploy serverless GraphQL backends with Grafbase and Neon
This guide was contributed by Josep Vidal from Grafbase
Grafbase allows you to combine your data sources into a centralized GraphQL endpoint and deploy a serverless GraphQL backend.
The example project in this guide simulates a marketplace of products, where the product price is dynamically calculated based on data retrieved from your Neon database.
Create a backend with Grafbase
Create a directory and initialize your Grafbase project by running the following commands:
In your project directory, open the
grafbase/schema.graphqlfile and replace the existing content with the following schema:
Create the schema in Neon
Navigate to the Neon Console and select your project.
Open the Neon SQL Editor and run the following
product_visitstable stores product page view data that the application uses to dynamically calculate a product price.
Create the resolver files
The schema includes an
addProductVisit query and
prodcut/price field. Create resolvers for those by creating the following files in your project directory:
You can use the following commands to create the files:
You will add code to these files in a later step.
Install the Neon serverless driver
grafbase directory in your project, run the following commands to install the Neon serverless driver:
Retrieve your Neon connection string
A database connection string is required to forward queries to your Neon database. To retrieve the connection string for your database:
Navigate to the Neon Dashboard.
Copy the connection string for your database from the Connection Details widget. The connection string should appear similar to the following:
DATABASE_URLenvironment variable to your
grafbase/.envfile and set the value to your connection string. For example:
Add code to the resolvers
resolvers/product/add-product-visitresolver, add the following code, which inserts a new record in the
product_visitstable with a
productIdeach time the resolver is queried.
grafbase/resolvers/product/price.jsresolver, add the following code, which calculates the product price based on the number of product visits (the number of visits represents customer interest in the product).
Test the resolvers
To test the resolvers with Neon, perform the following steps:
Start the Grafbase CLI:
Go to http://localhost:4000 and execute the following GraphQL mutation, which creates a new product:
Use the product
idto execute the following mutation, which adds a row to the database table in Neon:
Query the same product, and check the price:
Run the query several more times and watch how the price increases as "interest" in the product increases.
Last updated on