Coded Geekery

BlogAboutContact
BlogAboutContact

Hasura

Quickly query your hasura database.

Hasura
// nextjs api to store or retrieve views per page const { hasuraRequest } = require('../../lib/hasura'); export default async (req, res) => { const slug = req.query.slug; let views = 0; const data = await hasuraRequest({ query: ` query getViews($slug: String!){ views_by_pk(slug: $slug ){ slug views } } `, variables: { slug }, }); if( data && data.views_by_pk ){ views = data.views_by_pk.views } return res.status(200).json({ total: views }); };
// lib/hasura.js const fetch = require('node-fetch'); exports.hasuraRequest = async function ({ query, variables }) { const result = await fetch(process.env.HASURA_URL, { method: 'POST', headers: { 'X-Hasura-Admin-Secret': process.env.HASURA_ADMIN_SECRET, }, body: JSON.stringify({ query, variables }), }).then((res) => res.json()); if (!result || !result.data) { console.error(result); return []; } return result.data; };

Usage

  • Set up Hasura

  • First, set up Hasura.

    You can self host Hasura on heroku, via docker or using their own Hasura Cloud service. I'll leave how you set this up to you.

  • Add Environment Variables

  • To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable. Learn how to add environment variables in Vercel.

    Coded Geekery

    © 2021 Roger Stringer. All rights reserved.

    TwitterGitHubInstagram

    Stuff

    HomeAbout MeContact Me

    Not Playing

    Spotify