Coded Geekery

BlogWritingAboutContact
BlogWritingAboutContact

Hasura

Quickly query your hasura database.

// 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.

    Remember: never commit secrets to git. Thus, we should use an environment variable.

    Not Playing

    Spotify

    Coded Geekery

    TwitterGitHubInstagramgumroadbuymeacoffee

    Stuff

    HomeAbout MeContact Me

    © 2022 Roger Stringer. All rights reserved.