Home >Web Front-end >JS Tutorial >How to Build Your Backend with Hasura and PostgreSQL

How to Build Your Backend with Hasura and PostgreSQL

William Shakespeare
William ShakespeareOriginal
2025-02-09 09:22:13867browse

How to Build Your Backend with Hasura and PostgreSQL

Building robust backends often involves extensive coding for CRUD operations, authorization, and business logic—a time-consuming process. This article explores how Hasura and PostgreSQL streamline backend development, enabling faster app launches with minimal coding effort.

Hasura, an open-source GraphQL engine, automatically generates GraphQL and REST APIs from your database schema. It supports data modeling, real-time queries, event programming, role-based authorization, and custom business logic execution via GraphQL actions.

PostgreSQL, a powerful open-source relational database, offers enterprise-level features comparable to Oracle and Microsoft SQL Server, making it a reliable choice for large-scale applications. Its use by companies like Netflix and Spotify underscores its capabilities. While Hasura supports other databases, this article focuses on PostgreSQL due to its accessibility and open-source nature. MySQL support is planned.

This guide highlights Hasura's features for building scalable backends for web and mobile apps. It also demonstrates how PostgreSQL's capabilities, accessed via SQL, can perform complex computations and analytics, reducing the need for custom server-side code.

Key Advantages:

  • Rapid Backend Development: Hasura's auto-generated APIs significantly reduce coding time.
  • PostgreSQL Power: Leverage PostgreSQL's advanced features (table inheritance, concurrency control, JSON/Spatial data types) for enhanced data integrity and performance.
  • Real-time Capabilities: Hasura's real-time querying, event programming, and role-based authorization create highly responsive applications.
  • Easy Deployment: Deploy Hasura using Docker for local development or Hasura Cloud for scalable, secure, globally distributed applications with features like monitoring and caching.
  • Comprehensive Web Console: Manage data modeling, CRUD operations, and complex queries within Hasura's intuitive web console. Integrate with authentication and file storage providers.
  • Streamlined Workflows: Utilize Hasura's migration tools and environment staging for seamless transitions between development and production, supporting CI/CD.

Why Choose PostgreSQL?

Relational databases like PostgreSQL offer advantages over other database types, including schema modeling, JOIN operations, and ACID transactions—crucial for data integrity. PostgreSQL further excels with:

  • Table Inheritance: Efficient data modeling.
  • Advanced Concurrency Control: Handles high-volume data writes effectively in multi-user environments.
  • Fault Tolerance and Data Integrity: Reduces data corruption risks.
  • Unique Data Types: Supports JSON and Spatial data types, beneficial for various applications.

PostgreSQL also acts as a computation server, executing custom functions and triggers for analytical tasks, eliminating the need for separate server-side code. This is achieved using:

  • Views: Simplify complex queries.
  • Functions & Operators: Perform date formatting, pattern matching, and arithmetic operations.
  • Extensions: Extend PostgreSQL's functionality (e.g., PostGIS).
  • Procedural Languages: Write user-defined functions and stored procedures (e.g., PL/pgSQL).

Hasura exposes this PostgreSQL logic via GraphQL, making it readily accessible to frontend applications.

How to Build Your Backend with Hasura and PostgreSQL

PostgreSQL Examples:

  • Example 1 (Online Users View): A view to retrieve currently active users:
<code class="language-sql">CREATE OR REPLACE VIEW "public"."online_users" AS
 SELECT users.id, users.last_seen
   FROM users
  WHERE (users.last_seen >= (now() - '00:00:30'::interval));</code>
  • Example 2 (Geolocation with PostGIS): Find stores within a 1000-meter radius:
<code class="language-sql">SELECT id, name, address, geom
FROM Seattle_Starbucks
WHERE ST_DWithin(geom, ST_MakePoint(-122.325959,47.625138)::geography, 1000);</code>

What is Hasura?

Hasura is an open-source, real-time GraphQL engine that generates APIs for your database. Its web console allows for:

  • Schema Modeling: Create tables, define relationships, and manage data.
  • CRUD Operations: Perform create, read, update, and delete actions.
  • Role-Based Access Control: Implement granular permissions.
  • GraphQL/REST Endpoint Creation: Generate APIs for your data.
  • SQL Execution: Run custom SQL queries.
  • Action & Trigger Definition: Automate tasks and handle events.

How to Build Your Backend with Hasura and PostgreSQL

Note: Hasura requires integration with a separate authentication provider (e.g., Auth0, Firebase) and file storage service. NHost offers an integrated solution.

Launching Hasura:

  • Docker: Recommended for local development, offering easy setup and no rate limiting.
  • Hasura Cloud: Simplifies deployment with scalability, security, and global distribution, including monitoring and caching features. A free tier is available with limitations.

How to Build Your Backend with Hasura and PostgreSQL

Hasura Features (Detailed Overview):

  • Data Manager: Visual schema designer for creating tables, defining relationships, and managing data types (including JSON and custom types). How to Build Your Backend with Hasura and PostgreSQL
  • Authorization: Role-based access control with granular permissions for insert, select, update, and delete operations. How to Build Your Backend with Hasura and PostgreSQL
  • Queries: Execute various GraphQL queries (simple, nested, aggregation, filtering) directly within the console. How to Build Your Backend with Hasura and PostgreSQL
  • Mutations: Perform INSERT, UPSERT, UPDATE, and DELETE operations with support for transactions.
  • Subscriptions: Implement real-time data updates using GraphQL subscriptions over WebSockets.
  • Remote Schemas: Integrate with third-party APIs for data and logic.
  • Actions: Execute custom business logic via webhooks using any programming language.
  • Event Triggers: Invoke webhooks based on database events (INSERT, UPDATE, DELETE). Supports manual invocation.
  • Scheduled Triggers: Run tasks periodically (CRON) or once (one-off) via webhooks. How to Build Your Backend with Hasura and PostgreSQL
  • Migrations and Environments: Manage schema changes using migration files for database and Hasura metadata, supporting CI/CD workflows.

Deployment Options:

  • Hasura Cloud: Easiest production deployment.
  • External Hosting: Heroku, Digital Ocean, Render, Azure, Kubernetes, AWS (more complex).
  • NHost: All-in-one BaaS solution including PostgreSQL, Hasura, authentication, and storage.

Summary:

Hasura and PostgreSQL offer a powerful combination for rapid backend development. The reduced coding effort, real-time capabilities, and robust features make it a compelling solution for building scalable and maintainable applications. While not as feature-rich as some alternatives in every aspect, its ease of use, focus on performance, and open-source nature are significant advantages.

Frequently Asked Questions (FAQs): (The provided FAQs are already comprehensive and well-written; no modification needed.)

The above is the detailed content of How to Build Your Backend with Hasura and PostgreSQL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn